Programs & Examples On #Referer

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

"HTTP 415 Unsupported Media Type response" stems from Content-Type in header of your request. for example in javascript by axios:

Axios({
            method: 'post',
            headers: { 'Content-Type': 'application/json'},
            url: '/',
            data: data,  // an object u want to send
          }).then(function (response) {
            console.log(response);
          });

How to enable CORS in ASP.net Core WebAPI

Just to add to answer here, if you are using app.UseHttpsRedirection(), and you are hitting not SSL port consider commenting out this.

http post - how to send Authorization header?

you need RequestOptions

 let headers = new Headers({'Content-Type': 'application/json'});  
 headers.append('Authorization','Bearer ')
 let options = new RequestOptions({headers: headers});
 return this.http.post(APIname,body,options)
  .map(this.extractData)
  .catch(this.handleError);

for more check this link

Googlemaps API Key for Localhost

It didn't work for me when I used

http://localhost{port}/
http://localhost:{port}/something-else/here

However, removing the http did the trick for me. I just added localhost:8000 without prefixing it with the http.

Google Maps JavaScript API RefererNotAllowedMapError

Enable billing for Google project fixed the problem.

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

Your project supports .Net Framework 4.0 and .Net Framework 4.5. If you have upgrade issues

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

instead of can use;

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

Insert the image directly in the Jupyter notebook.

Note: You should have a local copy of the image on your computer

You can insert the image in the Jupyter notebook itself. This way you don't need to keep the image separately in the folder.

Steps:

  1. Convert the cell to markdown by:

    • pressing M on the selected cell
      OR
    • From menu bar, Cell > Cell Type > Markdown.
      (Note: It's important to convert the cell to Markdown, otherwise the "Insert Image" option in Step 2 will not be active)
  2. Now go to menu bar and select Edit -> Insert Image.

  3. Select image from your disk and upload.

  4. Press Ctrl+Enter or Shift+Enter.

This will make the image as part of the notebook and you don't need to upload in the directory or Github. I feel this looks more clean and not prone to broken URL issue.

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

Nginx:

location ~* \.(eot|ttf|woff)$ {
   add_header Access-Control-Allow-Origin '*';
}

AWS S3:

  1. Select your bucket
  2. Click properties on the right top
  3. Permisions => Edit Cors Configuration => Save
  4. Save

http://schock.net/articles/2013/07/03/hosting-web-fonts-on-a-cdn-youre-going-to-need-some-cors/

Apache Proxy: No protocol handler was valid

For me all above-mentioned answers was enabled on xampp still not working. Enabling below module made virtual host work again

LoadModule slotmem_shm_module modules/mod_slotmem_shm.so

How to avoid HTTP error 429 (Too Many Requests) python

In many cases, continuing to scrape data from a website even when the server is requesting you not to is unethical. However, in the cases where it isn't, you can utilize a list of public proxies in order to scrape a website with many different IP addresses.

Access-Control-Allow-Origin and Angular.js $http

I have found a way to use JSONP method in $http directly and with support of params in the config object:

params = {
  'a': b,
  'callback': 'JSON_CALLBACK'
};

$http({
  url: url,
  method: 'JSONP',
  params: params
})

how to delete a specific row in codeigniter?

It will come in the url so you can get it by two ways. Fist one

<td><?php echo anchor('textarea/delete_row', 'DELETE', 'id="$row->id"'); ?></td>
$id = $this->input->get('id');

2nd one.

$id = $this->uri->segment(3);

But in the second method you have to count the no. of segments in the url that on which no. your id come. 2,3,4 etc. then you have to pass. then in the ();

How to send and retrieve parameters using $state.go toParams and $stateParams?

Try With reload: true?

Couldn't figure out what was going on for the longest time -- turns out I was fooling myself. If you're certain that things are written correctly and you will to use the same state, try reload: true:

.state('status.item', {
    url: '/:id',
    views: {...}
}

$state.go('status.item', { id: $scope.id }, { reload: true });

Hope this saves you time!

How to simulate POST request?

Simple way is to use curl from command-line, for example:

DATA="foo=bar&baz=qux"
curl --data "$DATA" --request POST --header "Content-Type:application/x-www-form-urlencoded" http://example.com/api/callback | python -m json.tool

or here is example how to send raw POST request using Bash shell (JSON request):

exec 3<> /dev/tcp/example.com/80

DATA='{"email": "[email protected]"}'
LEN=$(printf "$DATA" | wc -c)

cat >&3 << EOF
POST /api/retrieveInfo HTTP/1.1
Host: example.com
User-Agent: Bash
Accept: */*
Content-Type:application/json
Content-Length: $LEN
Connection: close

$DATA
EOF

# Read response.
while read line <&3; do
   echo $line
done

How to send a correct authorization header for basic authentication

NodeJS answer:

In case you wanted to do it with NodeJS: make a GET to JSON endpoint with Authorization header and get a Promise back:

First

npm install --save request request-promise

(see on npm) and then in your .js file:

var requestPromise = require('request-promise');

var user = 'user';
var password = 'password';

var base64encodedData = Buffer.from(user + ':' + password).toString('base64');

requestPromise.get({
  uri: 'https://example.org/whatever',
  headers: {
    'Authorization': 'Basic ' + base64encodedData
  },
  json: true
})
.then(function ok(jsonData) {
  console.dir(jsonData);
})
.catch(function fail(error) {
  // handle error
});

Nginx not running with no error message

1. Check for your configuration files by running the aforementioned command: sudo nginx -t.

2. Check for port conflicts. For instance, if apache2 (ps waux | grep apache2) or any other service is using the same ports configured for nginx (say port 80) the service will not start and will fail silently (err... the cousin of my friend had this problem...)

Wampserver icon not going green fully, mysql services not starting up?

I was running on the same problem, wampmysqld64 did not start, so I checked the Mysql log which you should find it inside the main wamp64 folder, and I found all the details on why is not working. on my computer I found another mysql instance is running so it prevents the wampmysqld64 to start. I stopped the other instance, and everything works fine after.

Angular JS POST request not sending JSON data

I have tried your example and it works just fine:

var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();

$http({
    url: '/api/test',
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    data: {application: app, from: d1, to: d2}
});

Output:

Content-Length:91
Content-Type:application/json
Host:localhost:1234
Origin:http://localhost:1234
Referer:http://localhost:1234/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
{"application":"AirFare","from":"2013-10-10T11:47:50.681Z","to":"2013-10-10T11:47:50.681Z"}

Are you using the latest version of AngularJS?

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Here is a list of examples for sending cookies - https://github.com/andriichuk/php-curl-cookbook#cookies

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://httpbin.org/cookies',
CURLOPT_RETURNTRANSFER => true,

CURLOPT_COOKIEFILE  => $cookieFile,
CURLOPT_COOKIE => 'foo=bar;baz=foo',

/**
 * Or set header
 * CURLOPT_HTTPHEADER => [
       'Cookie: foo=bar;baz=foo',
   ]
 */
]);

$response = curl_exec($curlHandler);
curl_close($curlHandler);

echo $response;

The remote server returned an error: (403) Forbidden

Add the following line:

request.UseDefaultCredentials = true;

This will let the application use the credentials of the logged in user to access the site. If it's returning 403, clearly it's expecting authentication.

It's also possible that you (now?) have an authenticating proxy in between you and the remote site. In which case, try:

request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

Hope this helps.

PHP: How to get referrer URL?

Underscore. Not space.

$_SERVER['HTTP_REFERER']

Angular, content type is not being sent with $http

Great! The solution given above worked for me. Had the same problem with a GET call.

 method: 'GET',
 data: '',
 headers: {
        "Content-Type": "application/json"
 }

Request exceeded the limit of 10 internal redirects due to probable configuration error

This error occurred to me when I was debugging the PHP header() function:

header('Location: /aaa/bbb/ccc'); // error

If I use a relative path it works:

header('Location: aaa/bbb/ccc'); // success, but not what I wanted

However when I use an absolute path like /aaa/bbb/ccc, it gives the exact error:

Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

It appears the header function redirects internally without going HTTP at all which is weird. After some tests and trials, I found the solution of adding exit after header():

header('Location: /aaa/bbb/ccc');
exit;

And it works properly.

setting request headers in selenium

Webdriver doesn't contain an API to do it. See issue 141 from Selenium tracker for more info. The title of the issue says that it's about response headers but it was decided that Selenium won't contain API for request headers in scope of this issue. Several issues about adding API to set request headers have been marked as duplicates: first, second, third.

Here are a couple of possibilities that I can propose:

  1. Use another driver/library instead of selenium
  2. Write a browser-specific plugin (or find an existing one) that allows you to add header for request.
  3. Use browsermob-proxy or some other proxy.

I'd go with option 3 in most of cases. It's not hard.

Note that Ghostdriver has an API for it but it's not supported by other drivers.

Adding a custom header to HTTP request using angular.js

For me the following explanatory snippet worked. Perhaps you shouldn't use ' for header name?

{
   headers: { 
      Authorization: "Basic " + getAuthDigest(), 
      Accept: "text/plain" 
   }
}

I'm using $http.ajax(), though I wouldn't expect that to be a game changer.

Spring Security redirect to previous page after successful login

The following generic solution can be used with regular login, a Spring Social login, or most other Spring Security filters.

In your Spring MVC controller, when loading the product page, save the path to the product page in the session if user has not been logged in. In XML config, set the default target url. For example:

In your Spring MVC controller, the redirect method should read out the path from the session and return redirect:<my_saved_product_path>.

So, after user logs in, they'll be sent to /redirect page, which will promptly redirect them back to the product page that they last visited.

is there any PHP function for open page in new tab

You can simply use target="_blank" to open a page in a new tab

<a href="whatever.php" target="_blank">Opens On Another Tab</a>

Or you can simply use a javascript for onload

<body onload="window.open(url, '_blank');">

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

enabling cross-origin resource sharing on IIS7

One thing that has not been mentioned in these answers is that if you are using IIS and have sub applications with their own separate web.config, you may need to have a web.config in the parent directory containing the following code.

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type"/>
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS"/>
  </customHeaders>
</httpProtocol>

$_SERVER['HTTP_REFERER'] missing

When a web browser moves from one website to another and between pages of a website, it can optionally pass the URL it came from. This is called the HTTP_REFERER, So if you don't redirect from one page to another it might be missing

If the HTTP_REFERER has been set then it will be displayed. If it is not then you won't see anything. If it's not set and you have error reporting set to show notices, you'll see an error like this instead:

 Notice: Undefined index: HTTP_REFERER in /path/to/filename.php

To prevent this error when notices are on (I always develop with notices on), you can do this:

  if(isset($_SERVER['HTTP_REFERER'])) {
      echo $_SERVER['HTTP_REFERER'];
   }

OR

 echo isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';

It can be useful to use the HTTP_REFERER variable for logging etc purposes using the $_SERVER['HTTP_REFERER'] superglobal variable. However it is important to know it's not always set so if you program with notices on then you'll need to allow for this in your code

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

Not in this questions askers case but often:

What does the "premature end of script headers" error mean?

That error means that the FCGI call was exited unexpectedly.

In some cases it means that the script "backup.php" did crash.

How to fix this?

If the crash of a script was the cause, fix the script so that it does not crash. Then this error is fixed, too. To find out if and why a script crashes, you need to debug it. For example you can check the PHP error log. Errors logged to STDERR normally go into the error handler of the FCGI.

Error message "Forbidden You don't have permission to access / on this server"

If you are using a WAMP server then try this:

  • Single click on the WAMP server icon at the taskbar

  • Select the option put online

  • Your server will restart automatically

  • Then try to access your localwebsite

Python send POST with header

To make POST request instead of GET request using urllib2, you need to specify empty data, for example:

import urllib2
req = urllib2.Request("http://am.domain.com:8080/openam/json/realms/root/authenticate?authIndexType=Module&authIndexValue=LDAP")
req.add_header('X-OpenAM-Username', 'demo')
req.add_data('')
r = urllib2.urlopen(req)

HttpClient does not exist in .net 4.0: what can I do?

Here's a "translation" to HttpWebRequest (needed rather than WebClient in order to set the referrer). (Uses System.Net and System.IO):

    HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(requestUrl))
    http.Referer = referrer;
    HttpWebResponse response = (HttpWebResponse )http.GetResponse();
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        string responseJson = sr.ReadToEnd();
        // more stuff
    }

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Steps to start Apache httpd.exe (I am using x64 VC11 example here)

http://www.apachelounge.com/download/VC11/

Be sure that you have installed Visual C++ Redistributable for Visual Studio 2012 : VC11 vcredist_x64/86.exe

http://www.microsoft.com/en-us/download/details.aspx?id=30679

You may need to have Visual Studio 2012 Update 3 (VS2012.3)

http://www.microsoft.com/en-us/download/details.aspx?id=30679 (vcredirect.exe)
http://support.microsoft.com/kb/2835600

Unzip httpd-2.4.4-win64-VC11.zip and copy paste in

C:\Apache24

Unzip modules-2.4-win64-VC11.zip and copy paste them in

C:\Apache24\modules

http://www.apachelounge.com/viewtopic.php?p=25091

For further info on the modules see the Apache Lounge VC10 Win64 download page and/or the readme in the .zip's there.

http://www.apachelounge.com/download/win64/

In

C:\Apache24\conf\httpd.conf

un-comment (remove # sign) starting below this like copy pasted list in here

# Example:
# LoadModule foo_module modules/mod_foo.so

LoadModule access_compat_module modules/mod_access_compat.so
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule allowmethods_module modules/mod_allowmethods.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_socache_module modules/mod_authn_socache.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule authz_dbd_module modules/mod_authz_dbd.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule buffer_module modules/mod_buffer.so
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule charset_lite_module modules/mod_charset_lite.so
LoadModule data_module modules/mod_data.so
LoadModule dav_module modules/mod_dav.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule dav_lock_module modules/mod_dav_lock.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule dir_module modules/mod_dir.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule env_module modules/mod_env.so
LoadModule expires_module modules/mod_expires.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule filter_module modules/mod_filter.so
LoadModule headers_module modules/mod_headers.so
LoadModule heartbeat_module modules/mod_heartbeat.so
LoadModule heartmonitor_module modules/mod_heartmonitor.so
LoadModule ident_module modules/mod_ident.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule include_module modules/mod_include.so
LoadModule info_module modules/mod_info.so
LoadModule isapi_module modules/mod_isapi.so
LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
LoadModule ldap_module modules/mod_ldap.so
LoadModule logio_module modules/mod_logio.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_debug_module modules/mod_log_debug.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule lua_module modules/mod_lua.so
LoadModule mime_module modules/mod_mime.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_express_module modules/mod_proxy_express.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_html_module modules/mod_proxy_html.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
LoadModule ratelimit_module modules/mod_ratelimit.so
LoadModule reflector_module modules/mod_reflector.so
LoadModule remoteip_module modules/mod_remoteip.so
LoadModule request_module modules/mod_request.so
LoadModule reqtimeout_module modules/mod_reqtimeout.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule sed_module modules/mod_sed.so
LoadModule session_module modules/mod_session.so
LoadModule session_cookie_module modules/mod_session_cookie.so
LoadModule session_crypto_module modules/mod_session_crypto.so
LoadModule session_dbd_module modules/mod_session_dbd.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule slotmem_plain_module modules/mod_slotmem_plain.so
LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
LoadModule socache_dbm_module modules/mod_socache_dbm.so
LoadModule socache_memcache_module modules/mod_socache_memcache.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
LoadModule speling_module modules/mod_speling.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule status_module modules/mod_status.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule version_module modules/mod_version.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule watchdog_module modules/mod_watchdog.so
LoadModule xml2enc_module modules/mod_xml2enc.so

Then find

C:\Apache24\bin\ApacheMonitor.exe

and double click on it.

Then in Command Prompt (CMD.exe) type

C:\Apache24\bin\httpd.exe

and press enter. It shows any error remaining.

Build with the latest Update 3 Visual Studio® 2012 aka VC11. VC11 has improvements, fixes and optimizations over VC10 in areas like Performance, MemoryManagement and Stability. For example code quality tuning and improvements done across different code generation areas for "speed". And makes more use of modern processors and win7, win8, 2008 and Server 2012 internal features.

The VC11 binaries loads VC11, VC10 and VC9 modules, and does not run on XP and 2003. Minimum system required: Windows 7 SP1, Windows 8 / 8.1, Windows Vista SP2, Windows Server 2008 R2 SP1, Windows Server 2012 / R2

After you have downloaded and before you attempt to install it, you should make sure that it is intact and has not been tampered with. Use the PGP Signature and/or the SHA Checksums to verify the integrity.

Thank you

Nginx fails to load css files

I ran into this issue too. It confused me until I realized what was wrong:

You have this:

include       /etc/nginx/mime.types;
default_type  application/octet-stream;

You want this:

default_type  application/octet-stream;
include       /etc/nginx/mime.types;

there appears to either be a bug in nginx or a deficiency in the docs (this could be the intended behavior, but it is odd)

Is it possible to log all HTTP request headers with Apache?

In my case easiest way to get browser headers was to use php. It appends headers to file and prints them to test page.

<?php
$fp = fopen('m:/temp/requests.txt', 'a');
$time = $_SERVER['REQUEST_TIME'];
fwrite($fp, $time  "\n");
echo "$time.<br>";
foreach (getallheaders() as $name => $value) {
    $cur_hd = "$name: $value\n";
    fwrite($fp, $cur_hd);
    echo "$cur_hd.<br>";
}
fwrite($fp, "***\n");
fclose($fp);
?>

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Cannot set content-type to 'application/json' in jQuery.ajax

It would seem that removing http:// from the url option ensures the the correct HTTP POST header is sent.

I dont think you need to fully qualify the name of the host, just use a relative URL as below.

   $.ajax({
      type: "POST",
      contentType: "application/json",
      url: '/Hello',
      data: { name: 'norm' },
      dataType: "json"
   });

An example of mine that works:

        $.ajax({
            type: "POST",
            url: siteRoot + "api/SpaceGame/AddPlayer",
            async: false,
            data: JSON.stringify({ Name: playersShip.name, Credits: playersShip.credits }),
            contentType: "application/json",
            complete: function (data) {
            console.log(data);
            wait = false;
        }
    });

Possibly related: jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

Edit: After some more research I found out the OPTIONS header is used to find out if the request from the originating domain is allowed. Using fiddler, I added the following to the response headers from my server.

 Access-Control-Allow-Origin: *
 Access-Control-Allow-Headers: Content-Type
 Access-Control-Allow-Methods: POST, GET, OPTIONS

Once the browser received this response it then sent off the correct POST request with json data. It would seem that the default form-urlencoded content type is considered safe and so does not undergo the extra cross domain checks.

It looks like you will need to add the previously mentioned headers to your servers response to the OPTIONS request. You should of course configure them to allow requests from specific domains rather then all.

I used the following jQuery to test this.

$.ajax({
   type: "POST",
   url: "http://myDomain.com/path/AddPlayer",
   data: JSON.stringify({
      Name: "Test",
       Credits: 0
   }),
   //contentType: "application/json",
   dataType: 'json',
   complete: function(data) {
       $("content").html(data);
  }
});?

References:

Get protocol + host name from URL

This is a bit obtuse, but uses urlparse in both directions:

import urlparse
def uri2schemehostname(uri):
    urlparse.urlunparse(urlparse.urlparse(uri)[:2] + ("",) * 4)

that odd ("",) * 4 bit is because urlparse expects a sequence of exactly len(urlparse.ParseResult._fields) = 6

How to manually set REFERER header in Javascript?

You can not change the REFERRER property. What you are asking is to spoof the request.

Just in case you want the referrer to be set like you have opened a url directly or for the fist time{http referrer=null} then reload the page

location.reload();

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

json Uncaught SyntaxError: Unexpected token :

That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character

jQuery Ajax requests are getting cancelled without being sent

I had this issue with a particular 3G network.
It would always fail on DELETE requests with net_error = -101 in chrome://net-internals/#events.

Other networks worked just fine so I assume there was a faulty proxy server or something.

Spring JSON request getting 406 (not Acceptable)

I had the same problem, my controller method executes but response is Error 406. I debug AbstractMessageConverterMethodProcessor#writeWithMessageConverters and found that method ContentNegotiationManager#resolveMediaTypes always returns text/html which is not supported by MappingJacksonHttpMessageConverter. The problem is that the org.springframework.web.accept.ServletPathExtensionContentNegotiationStrategy works earlier than org.springframework.web.accept.HeaderContentNegotiationStrategy, and extension of my request /get-clients.html is the cause of my problem with Error 406. I just changed request url to /get-clients.

Spring MVC - HttpMediaTypeNotAcceptableException

Try to add "jackson-databind" jars to pom.xml

`<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.databind-version}</version>
</dependency>`

And produces ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} to @RequestMapping

Es. @RequestMapping(value = "/api/xxx/{akey}/{md5}", produces ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE} @RequestMapping(value = "/api/contrassegno/{akey}/{md5}", produces ={MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},...

In what cases will HTTP_REFERER be empty

It will also be empty if the new Referrer Policy standard draft is used to prevent that the referer header is sent to the request origin. Example:

<meta name="referrer" content="none">

Although Chrome and Firefox have already implemented a draft version of the Referrer Policy, you should be careful with it because for example Chrome expects no-referrer instead of none (and I have seen also never somewhere).

How to get a cross-origin resource sharing (CORS) post request working

If for some reasons while trying to add headers or set control policy you're still getting nowhere you may consider using apache ProxyPass…

For example in one <VirtualHost> that uses SSL add the two following directives:

SSLProxyEngine On
ProxyPass /oauth https://remote.tld/oauth

Make sure the following apache modules are loaded (load them using a2enmod):

  • proxy
  • proxy_connect
  • proxy_http

Obviously you'll have to change your AJAX requests url in order to use the apache proxy…

Showing all errors and warnings

PHP errors can be displayed by any of below methods:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

For more details:

Displaying PHP errors

How to pass extra variables in URL with WordPress

To make the round trip "The WordPress Way" on the "front-end" (doesn't work in the context of wp-admin), you need to use 3 WordPress functions:

  • add_query_arg() - to create the URL with your new query variable ('c' in your example)
  • the query_vars filter - to modify the list of public query variables that WordPress knows about (this only works on the front-end, because the WP Query is not used on the back end - wp-admin - so this will also not be available in admin-ajax)
  • get_query_var() - to retrieve the value of your custom query variable passed in your URL.

Note: there's no need to even touch the superglobals ($_GET) if you do it this way.

Example

On the page where you need to create the link / set the query variable:

if it's a link back to this page, just adding the query variable

<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c ) )?>">

if it's a link to some other page

<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c, site_url( '/some_other_page/' ) ) )?>">

In your functions.php, or some plugin file or custom class (front-end only):

function add_custom_query_var( $vars ){
  $vars[] = "c";
  return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );

On the page / function where you wish to retrieve and work with the query var set in your URL:

$my_c = get_query_var( 'c' );

On the Back End (wp-admin)

On the back end we don't ever run wp(), so the main WP Query does not get run. As a result, there are no query vars and the query_vars hook is not run.

In this case, you'll need to revert to the more standard approach of examining your $_GET superglobal. The best way to do this is probably:

$my_c = filter_input( INPUT_GET, "c", FILTER_SANITIZE_STRING );

though in a pinch you could do the tried and true

$my_c = isset( $_GET['c'] ? $_GET['c'] : "";

or some variant thereof.

PHP CURL & HTTPS

Another option like Gavin Palmer answer is to use the .pem file but with a curl option

  1. download the last updated .pem file from https://curl.haxx.se/docs/caextract.html and save it somewhere on your server(outside the public folder)

  2. set the option in your code instead of the php.ini file.

In your code

curl_setopt($ch, CURLOPT_CAINFO, $_SERVER['DOCUMENT_ROOT'] .  "/../cacert-2017-09-20.pem");

NOTE: setting the cainfo in the php.ini like @Gavin Palmer did is better than setting it in your code like I did, because it will save a disk IO every time the function is called, I just make it like this in case you want to test the cainfo file on the fly instead of changing the php.ini while testing your function.

How can I find where I will be redirected using cURL?

Add this line to curl inizialization

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

and use getinfo before curl_close

$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL );

es:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$html = curl_exec($ch);
$redirectURL = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL );
curl_close($ch);

Login to remote site with PHP cURL

This is how I solved this in ImpressPages:

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

Just pressing F5 is not always working.

why?

Because your ISP is also caching web data for you.

Solution: Force Refresh.

Force refresh your browser by pressing CTRL + F5 in Firefox or Chrome to clear ISP cache too, instead of just pressing F5

You then can see 200 response instead of 304 in the browser F12 developer tools network tab.

Another trick is to add question mark ? at the end of the URL string of the requested page:

http://localhost:52199/Customers/Create?

The question mark will ensure that the browser refresh the request without caching any previous requests.

Additionally in Visual Studio you can set the default browser to Chrome in Incognito mode to avoid cache issues while developing, by adding Chrome in Incognito mode as default browser, see the steps (self illustrated):

Go to browsers list Select browse with... Click Add... Point to the chrome.exe on your platform, add argument "Incognito" Choose the browser you just added and set as default, then click browse

Get original URL referer with PHP?

As Johnathan Suggested, you would either want to save it in a cookie or a session.

The easier way would be to use a Session variable.

session_start();
if(!isset($_SESSION['org_referer']))
{
    $_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}

Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.

How long will my session last?

In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data (not the last time session_start was called!). But PHP’s session handling is a little bit more complicated.

Because the session data is removed by a garbage collector that is only called by session_start with a probability of session.gc_probability devided by session.gc_divisor. The default values are 1 and 100, so the garbage collector is only started in only 1% of all session_start calls. That means even if the the session is already timed out in theory (the session data had been changed more than session.gc_maxlifetime seconds ago), the session data can be used longer than that.

Because of that fact I recommend you to implement your own session timeout mechanism. See my answer to How do I expire a PHP session after 30 minutes? for more details.

Set a request header in JavaScript

@gnarf answer is right . wanted to add more information .

Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Terminate these steps if header is a case-insensitive match for one of the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

Cannot set some HTTP headers when using System.Net.WebRequest

Basically, no. That is an http header, so it is reasonable to cast to HttpWebRequest and set the .Referer (as you indicate in the question):

HttpWebRequest req = ...
req.Referer = "your url";

How do I access the HTTP request header fields via JavaScript?

One way to obtain the headers from JavaScript is using the WebRequest API, which allows us to access the different events that originate from http or websockets, the life cycle that follows is this: WebRequest Lifecycle

So in order to access the headers of a page it would be like this:

    browser.webRequest.onHeadersReceived.addListener(
     (headersDetails)=> {
      console.log("Request: " + headersDetails);
    },
    {urls: ["*://hostName/*"]}
    );`

The issue is that in order to use this API, it must be executed from the browser, that is, the browser object refers to the browser itself (tabs, icons, configuration), and the browser does have access to all the Request and Reponse of any page , so you will have to ask the user for permissions to be able to do this (The permissions will have to be declared in the manifest for the browser to execute them)

And also being part of the browser you lose control over the pages, that is, you can no longer manipulate the DOM, (not directly) so to control the DOM again it would be done as follows:

    browser.webRequest.onHeadersReceived.addListener(
        browser.tabs.executeScript({
        code: 'console.log("Headers success")',
    });
});

or if you want to run a lot of code

    browser.webRequest.onHeadersReceived.addListener(
        browser.tabs.executeScript({
        file: './headersReveiced.js',
    });
});

Also by having control over the browser we can inject CSS and images

Documentation: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onHeadersReceived

Determining Referer in PHP

The REFERER is sent by the client's browser as part of the HTTP protocol, and is therefore unreliable indeed. It might not be there, it might be forged, you just can't trust it if it's for security reasons.

If you want to verify if a request is coming from your site, well you can't, but you can verify the user has been to your site and/or is authenticated. Cookies are sent in AJAX requests so you can rely on that.

Laravel: Get Object From Collection By Attribute

As the question above when you are using the where clause you also need to use the get Or first method to get the result.

/**
*Get all food
*
*/

$foods = Food::all();

/**
*Get green food 
*
*/

$green_foods = Food::where('color', 'green')->get();

How can I access and process nested objects, arrays or JSON?

If you are looking for one or more objects that meets certain criteria you have a few options using query-js

//will return all elements with an id larger than 1
data.items.where(function(e){return e.id > 1;});
//will return the first element with an id larger than 1
data.items.first(function(e){return e.id > 1;});
//will return the first element with an id larger than 1 
//or the second argument if non are found
data.items.first(function(e){return e.id > 1;},{id:-1,name:""});

There's also a single and a singleOrDefault they work much like firstand firstOrDefaultrespectively. The only difference is that they will throw if more than one match is found.

for further explanation of query-js you can start with this post

Programmatically get the version number of a DLL

Here's a nice way using a bit of reflection to get a version of a DLL containing a particular class:

var ver = System.Reflection.Assembly.GetAssembly(typeof(!Class!)).GetName().Version;

Just replace !Class! with the name of a class which is defined in the DLL you wish to get the version of.

This is my preferred method because if I move the DLLs around for different deploys I don't have to change the filepath.

DELETE ... FROM ... WHERE ... IN

The canonical T-SQL (SqlServer) answer is to use a DELETE with JOIN as such

DELETE o
FROM Orders o
INNER JOIN Customers c
    ON o.CustomerId = c.CustomerId
WHERE c.FirstName = 'sklivvz'

This will delete all orders which have a customer with first name Sklivvz.

Check if a row exists using old mysql_* API

function checkLectureStatus($lectureName) {
  global $con;
  $lectureName = mysql_real_escape_string($lectureName);
  $sql = "SELECT 1 FROM preditors_assigned WHERE lecture_name='$lectureName'";
  $result = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
  if (mysql_fetch_row($result)) {
    return 'Assigned';
  }
  return 'Available';
}

however you have to use some abstraction library for the database access.
the code would become

function checkLectureStatus($lectureName) {
  $res = db::getOne("SELECT 1 FROM preditors_assigned WHERE lecture_name=?",$lectureName);
  if($res) {
    return 'Assigned';
  }
  return 'Available';
}

How to read value of a registry key c#

You need to first add using Microsoft.Win32; to your code page.

Then you can begin to use the Registry classes:

try
{
    using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
    {
        if (key != null)
        {
            Object o = key.GetValue("Version");
            if (o != null)
            {
                Version version = new Version(o as String);  //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
                //do what you like with version
            }
        }
    }
}
catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
{
    //react appropriately
}

BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE. Sometimes even reading values can be a suspect operation without admin rights.

MVC Razor view nested foreach's model

You can simply use EditorTemplates to do that, you need to create a directory named "EditorTemplates" in your controller's view folder and place a seperate view for each of your nested entities (named as entity class name)

Main view :

@model ViewModels.MyViewModels.Theme

@Html.LabelFor(Model.Theme.name)
@Html.EditorFor(Model.Theme.Categories)

Category view (/MyController/EditorTemplates/Category.cshtml) :

@model ViewModels.MyViewModels.Category

@Html.LabelFor(Model.Name)
@Html.EditorFor(Model.Products)

Product view (/MyController/EditorTemplates/Product.cshtml) :

@model ViewModels.MyViewModels.Product

@Html.LabelFor(Model.Name)
@Html.EditorFor(Model.Orders)

and so on

this way Html.EditorFor helper will generate element's names in an ordered manner and therefore you won't have any further problem for retrieving the posted Theme entity as a whole

How do you declare string constants in C?

There's one more (at least) road to Rome:

static const char HELLO3[] = "Howdy";

(static — optional — is to prevent it from conflicting with other files). I'd prefer this one over const char*, because then you'll be able to use sizeof(HELLO3) and therefore you don't have to postpone till runtime what you can do at compile time.

The define has an advantage of compile-time concatenation, though (think HELLO ", World!") and you can sizeof(HELLO) as well.

But then you can also prefer const char* and use it across multiple files, which would save you a morsel of memory.

In short — it depends.

Vue - Deep watching an array of objects and calculating the change?

Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.

The best way is to create a person-component and watch every person separately inside its own component, as shown below:

<person-component :person="person" v-for="person in people"></person-component>

Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit to send an event upwards, containing the id of modified person.

_x000D_
_x000D_
Vue.component('person-component', {_x000D_
    props: ["person"],_x000D_
    template: `_x000D_
        <div class="person">_x000D_
            {{person.name}}_x000D_
            <input type='text' v-model='person.age'/>_x000D_
        </div>`,_x000D_
    watch: {_x000D_
        person: {_x000D_
            handler: function(newValue) {_x000D_
                console.log("Person with ID:" + newValue.id + " modified")_x000D_
                console.log("New age: " + newValue.age)_x000D_
            },_x000D_
            deep: true_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
    el: '#app',_x000D_
    data: {_x000D_
        people: [_x000D_
          {id: 0, name: 'Bob', age: 27},_x000D_
          {id: 1, name: 'Frank', age: 32},_x000D_
          {id: 2, name: 'Joe', age: 38}_x000D_
        ]_x000D_
    }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<body>_x000D_
    <div id="app">_x000D_
        <p>List of people:</p>_x000D_
        <person-component :person="person" v-for="person in people"></person-component>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Seeking useful Eclipse Java code templates

Invoke code on the GUI thread

I bind the following template to the shortcut slater to quickly dispatch code on the GUI thread.

${:import(javax.swing.SwingUtilities)}
SwingUtilities.invokeLater(new Runnable() {      
      @Override
      public void run() {
        ${cursor}
      }
    });

Bootstrap 4 - Inline List?

Bootstrap4

Remove a list’s bullets and apply some light margin with a combination of two classes, .list-inline and .list-inline-item.

<ul class="list-inline">
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
   <li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>

Transfer data between databases with PostgreSQL

  1. If your source and target database resides in the same local machine, you can use:

Note:- Sourcedb already exists in your database.

CREATE DATABASE targetdb WITH TEMPLATE sourcedb;

This statement copies the sourcedb to the targetdb.

  1. If your source and target databases resides on different servers, you can use following steps:

Step 1:- Dump the source database to a file.

pg_dump -U postgres -O sourcedb sourcedb.sql

Note:- Here postgres is the username so change the name accordingly.

Step 2:- Copy the dump file to the remote server.

Step 3:- Create a new database in the remote server

CREATE DATABASE targetdb;

Step 4:- Restore the dump file on the remote server

psql -U postgres -d targetdb -f sourcedb.sql

(pg_dump is a standalone application (i.e., something you run in a shell/command-line) and not an Postgres/SQL command.)

This should do it.

Adding two Java 8 streams, or an extra element to a stream

If you don't mind using 3rd Party Libraries cyclops-react has an extended Stream type that will allow you to do just that via the append / prepend operators.

Individual values, arrays, iterables, Streams or reactive-streams Publishers can be appended and prepended as instance methods.

Stream stream = ReactiveSeq.of(1,2)
                           .filter(x -> x!=0)
                           .append(ReactiveSeq.of(3,4))
                           .filter(x -> x!=1)
                           .append(5)
                           .filter(x -> x!=2);

[Disclosure I am the lead developer of cyclops-react]

Handling Dialogs in WPF with MVVM

EDIT: yes I agree this is not a correct MVVM approach and I am now using something similar to what is suggested by blindmeis.

One of the way you could to this is

In your Main View Model (where you open the modal):

void OpenModal()
{
    ModalWindowViewModel mwvm = new ModalWindowViewModel();
    Window mw = new Window();
    mw.content = mwvm;
    mw.ShowDialog()
    if(mw.DialogResult == true)
    { 
        // Your Code, you can access property in mwvm if you need.
    }
}

And in your Modal Window View/ViewModel:

XAML:

<Button Name="okButton" Command="{Binding OkCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">OK</Button>
<Button Margin="2" VerticalAlignment="Center" Name="cancelButton" IsCancel="True">Cancel</Button>

ViewModel:

public ICommand OkCommand
{
    get
    {
        if (_okCommand == null)
        {
            _okCommand = new ActionCommand<Window>(DoOk, CanDoOk);
        }
        return _okCommand ;
    }
}

void DoOk(Window win)
{
    <!--Your Code-->
    win.DialogResult = true;
    win.Close();
}

bool CanDoOk(Window win) { return true; }

or similar to what is posted here WPF MVVM: How to close a window

Apache server keeps crashing, "caught SIGTERM, shutting down"

I had mysterious SIGTERM shutdowns in our L.A.M.P. server, and it turned out to be an error in a custom PHP module, which was caused by mismatched versions. It was found by looking in the apache access/error logs at the time of malfunction. Don't forget to turn error logging on.

Only on Firefox "Loading failed for the <script> with source"

VPNs can sometimes cause this error as well, if they provide some type of auto-blocking. Disabling the VPN worked for my case.

Adding rows to dataset

DataSet myDataset = new DataSet();

DataTable customers = myDataset.Tables.Add("Customers");

customers.Columns.Add("Name");
customers.Columns.Add("Age");

customers.Rows.Add("Chris", "25");

//Get data
DataTable myCustomers = myDataset.Tables["Customers"];
DataRow currentRow = null;
for (int i = 0; i < myCustomers.Rows.Count; i++)
{
    currentRow = myCustomers.Rows[i];
    listBox1.Items.Add(string.Format("{0} is {1} YEARS OLD", currentRow["Name"], currentRow["Age"]));    
}

How to programmatically click a button in WPF?

Like JaredPar said you can refer to Josh Smith's article towards Automation. However if you look through comments to his article you will find more elegant way of raising events against WPF controls

someButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));

I personally prefer the one above instead of automation peers.

how to use javascript Object.defineProperty

get is a function that is called when you try to read the value player.health, like in:

console.log(player.health);

It's effectively not much different than:

player.getHealth = function(){
  return 10 + this.level*15;
}
console.log(player.getHealth());

The opposite of get is set, which would be used when you assign to the value. Since there is no setter, it seems that assigning to the player's health is not intended:

player.health = 5; // Doesn't do anything, since there is no set function defined

A very simple example:

_x000D_
_x000D_
var player = {_x000D_
  level: 5_x000D_
};_x000D_
_x000D_
Object.defineProperty(player, "health", {_x000D_
  get: function() {_x000D_
    return 10 + (player.level * 15);_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log(player.health); // 85_x000D_
player.level++;_x000D_
console.log(player.health); // 100_x000D_
_x000D_
player.health = 5; // Does nothing_x000D_
console.log(player.health); // 100
_x000D_
_x000D_
_x000D_

What is the apply function in Scala?

1 - Treat functions as objects.

2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

This will work definitely.....

Add the below lines in the POM file and give a build.

<plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.19.1</version>
          <configuration>
            <trimStackTrace>false</trimStackTrace>
            <includes>
              <include>**/*Test.class</include>
            </includes>
          </configuration>
        </plugin>

LINQ order by null column where order is ascending and nulls should be last

Try putting both columns in the same orderby.

orderby p.LowestPrice.HasValue descending, p.LowestPrice

Otherwise each orderby is a separate operation on the collection re-ordering it each time.

This should order the ones with a value first, "then" the order of the value.

Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

i had similar issues after upgrading my project to java 11, then what fixed it was upgrading to spring boot 2.1.1 which apparently has support for java 11, this helped

Windows Task Scheduler doesn't start batch file task

Had the same issue, make sure you check "Run only when user is logged on" at least that is what made my bat file alive again.

Drawing Isometric game worlds

Either way gets the job done. I assume that by zigzag you mean something like this: (numbers are order of rendering)

..  ..  01  ..  ..
  ..  06  02  ..
..  11  07  03  ..
  16  12  08  04
21  17  13  09  05
  22  18  14  10
..  23  19  15  ..
  ..  24  20  ..
..  ..  25  ..  ..

And by diamond you mean:

..  ..  ..  ..  ..
  01  02  03  04
..  05  06  07  ..
  08  09  10  11
..  12  13  14  ..
  15  16  17  18
..  19  20  21  ..
  22  23  24  25
..  ..  ..  ..  ..

The first method needs more tiles rendered so that the full screen is drawn, but you can easily make a boundary check and skip any tiles fully off-screen. Both methods will require some number crunching to find out what is the location of tile 01. In the end, both methods are roughly equal in terms of math required for a certain level of efficiency.

How to convert java.lang.Object to ArrayList?

You can create a util method that converts any collection to a java list

public static List<?> convertObjectToList(Object obj) {
    List<?> list = new ArrayList<>();
    if (obj.getClass().isArray()) {
        list = Arrays.asList((Object[])obj);
    } else if (obj instanceof Collection) {
        list = new ArrayList<>((Collection<?>)obj);
    }
    return list;
}

you can also mix with this validation below:

public static boolean isCollection(Object obj) {
  return obj.getClass().isArray() || obj instanceof Collection;
}

Count all occurrences of a string in lots of files with grep

This works for multiple occurrences per line:

grep -o string * | wc -l

How to create an instance of System.IO.Stream stream

System.IO.Stream stream = new System.IO.MemoryStream();

Format certain floating dataframe columns into percentage in pandas

style.format is vectorized, so we can simply apply it to the entire df (or just its numerical columns):

df[num_cols].style.format('{:,.3f}')

Batchfile to create backup and rename with timestamp

Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.

You can also run your batch script through a vbs script like this:

'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True

This will execute your batch file with no cmd window shown.

How to push to History in React Router v4?

If you want to use history while passing a function as a value to a Component's prop, with react-router 4 you can simply destructure the history prop in the render attribute of the <Route/> Component and then use history.push()

    <Route path='/create' render={({history}) => (
      <YourComponent
        YourProp={() => {
          this.YourClassMethod()
          history.push('/')
        }}>
      </YourComponent>
    )} />

Note: For this to work you should wrap React Router's BrowserRouter Component around your root component (eg. which might be in index.js)

How do I set/unset a cookie with jQuery?

$.cookie("test", 1); //set cookie
$.cookie("test"); //get cookie
$.cookie('test', null); //delete cookie

How to retrieve records for last 30 minutes in MS SQL?

DATEADD only returned Function does not exist on MySQL 5.5.53 (I know it's old)

Instead, I found DatePlayed > DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 30 minute) to produce the desired result

In Angular, how do you determine the active route?

in 2020 if you want to set active class on element which has no [routerLink] - you can do simply:

<a
  (click)="bookmarks()"
  [class.active]="router.isActive('/string/path/'+you+'/need', false)" // <== you need this one. second argument 'false' - exact: true/false
  routerLinkActive="active"
  [routerLinkActiveOptions]="{ exact: true }"
>
  bookmarks
</a>

How to transform currentTimeMillis to a readable date format?

It will work.

long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");    
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

Do you have an Interface that your "UserService" class implements.

Your endpoints should specify an interface for the contract attribute:

contract="UserService.IUserService"

jQuery click not working for dynamically created items

Using .click will only attach events to elements that already exist.

You need to use a function which monitors for dynamically created events - in older versions of JQuery this was .live(), but this has been superceded by .on()

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

On top of what @wisekiddo said, you can also modify your build settings in the project.pbxproj file by setting the Swift 3 @obj Inference to default like SWIFT_SWIFT3_OBJC_INFERENCE = Default; for your build flavors (i.e. debug and release), especially if you're coming from some other environment besides Xcode

Oracle Partition - Error ORA14400 - inserted partition key does not map to any partition

select partition_name,column_name,high_value,partition_position
from ALL_TAB_PARTITIONS a , ALL_PART_KEY_COLUMNS b 
where table_name='YOUR_TABLE' and a.table_name = b.name;

This query lists the column name used as key and the allowed values. make sure, you insert the allowed values(high_value). Else, if default partition is defined, it would go there.


EDIT:

I presume, your TABLE DDL would be like this.

CREATE TABLE HE0_DT_INF_INTERFAZ_MES
  (
    COD_PAIS NUMBER,
    FEC_DATA NUMBER,
    INTERFAZ VARCHAR2(100)
  )
  partition BY RANGE(COD_PAIS, FEC_DATA)
  (
    PARTITION PDIA_98_20091023 VALUES LESS THAN (98,20091024)
  );

Which means I had created a partition with multiple columns which holds value less than the composite range (98,20091024);

That is first COD_PAIS <= 98 and Also FEC_DATA < 20091024

Combinations And Result:

98, 20091024     FAIL
98, 20091023     PASS
99, ********     FAIL
97, ********     PASS
 < 98, ********     PASS

So the below INSERT fails with ORA-14400; because (98,20091024) in INSERT is EQUAL to the one in DDL but NOT less than it.

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
                                  VALUES(98, 20091024, 'CTA');  2
INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
            *
ERROR at line 1:
ORA-14400: inserted partition key does not map to any partition

But, we I attempt (97,20091024), it goes through

SQL> INSERT INTO HE0_DT_INF_INTERFAZ_MES(COD_PAIS, FEC_DATA, INTERFAZ)
  2                                    VALUES(97, 20091024, 'CTA');

1 row created.

Checking for NULL pointer in C/C++

Personally I've always used if (ptr == NULL) because it makes my intent explicit, but at this point it's just a habit.

Using = in place of == will be caught by any competent compiler with the correct warning settings.

The important point is to pick a consistent style for your group and stick to it. No matter which way you go, you'll eventually get used to it, and the loss of friction when working in other people's code will be welcome.

Build Error - missing required architecture i386 in file

I had this same problem, and the solution turned out to be an easy fix. Backup then open project.pbxproj (located inside your project file bundle) in TextMate or TextEdit and search for the section titled "/* Begin XCBuildConfiguration section */". Look for a key named FRAMEWORK_SEARCH_PATHS and delete it and it's contents (once per build configuration, so I removed it in two places). Here is an example of what I deleted:

FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"\"$(DEVELOPER_DIR)/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.1.sdk/System/Library/Frameworks\"",);

My project now build for both the iPhone device and the iPhoneSimulator.

Darken background image on hover

you can use this:

box-shadow: inset 0 0 0 1000px rgba(0,0,0,.2);

as seen on: https://stackoverflow.com/a/24084708/8953378

What is the python "with" statement designed for?

In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.

General form of with:

with open(“file name”, “mode”) as file-var:
    processing statements

note: no need to close the file by calling close() upon file-var.close()

Oracle SQL - select within a select (on the same table!)

Basically, all you have to do is

select ..., (select ... from ... where ...) as ..., ..., from ... where ...

For exemple. You can insert the (select ... from ... where) wherever you want it will be replaced by the corresponding data.

I know that the others exemple (even if each of them are really great :) ) are a bit complicated to understand for the newbies (like me :p) so i hope this "simple" exemple will help some of you guys :)

Defining and using a variable in batch file

The spaces are significant. You created a variable named 'location ' with a value of
' "bob"'. Note - enclosing single quotes were added to show location of space.

If you want quotes in your value, then your code should look like

set location="bob"

If you don't want quotes, then your code should look like

set location=bob

Or better yet

set "location=bob"

The last syntax prevents inadvertent trailing spaces from getting in the value, and also protects against special characters like & | etc.

VBA: How to display an error message just like the standard error message which has a "Debug" button?

There is a simpler way simply disable the error handler in your error handler if it does not match the error types you are doing and resume.

The handler below checks agains each error type and if none are a match it returns error resume to normal VBA ie GoTo 0 and resumes the code which then tries to rerun the code and the normal error block pops up.

On Error GoTo ErrorHandler

x = 1/0

ErrorHandler:
if Err.Number = 13 then ' 13 is Type mismatch (only used as an example)

'error handling code for this

end if

If err.Number = 1004 then ' 1004 is Too Large (only used as an example)

'error handling code for this

end if

On Error GoTo 0
Resume

How to use the switch statement in R functions?

I hope this example helps. You ca use the curly braces to make sure you've got everything enclosed in the switcher changer guy (sorry don't know the technical term but the term that precedes the = sign that changes what happens). I think of switch as a more controlled bunch of if () {} else {} statements.

Each time the switch function is the same but the command we supply changes.

do.this <- "T1"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)
#########################################################
do.this <- "T2"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)
########################################################
do.this <- "T3"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)

Here it is inside a function:

FUN <- function(df, do.this){
    switch(do.this,
        T1={X <- t(df)
            P <- colSums(df)%*%X
        },
        T2={X <- colMeans(df)
            P <- outer(X, X)
        },
        stop("Enter something that switches me!")
    )
    return(P)
}

FUN(mtcars, "T1")
FUN(mtcars, "T2")
FUN(mtcars, "T3")

Mapping object to dictionary and vice versa

Reflection can take you from an object to a dictionary by iterating over the properties.

To go the other way, you'll have to use a dynamic ExpandoObject (which, in fact, already inherits from IDictionary, and so has done this for you) in C#, unless you can infer the type from the collection of entries in the dictionary somehow.

So, if you're in .NET 4.0 land, use an ExpandoObject, otherwise you've got a lot of work to do...

Turning off eslint rule for a specific line

You can add the files which give error to .eslintignore file in your project.Like for all the .vue files just add /*.vue

How can I disable ReSharper in Visual Studio and enable it again?

Now Resharper supports Suspend & Resume argument at devenv.exe

(ReSharper 2019.2.3)

Run VS & Suspend R#:

devenv.exe /ReSharper.Suspend

Run VS & Resume R#:

devenv.exe /ReSharper.Resume

Here's an example usage:

enter image description here

Lombok is not generating getter and setter

For Spring ToolSuite 4 on Mac, they renamed the ini to SpringToolSuite4.ini.

You can either rename or copy it to STS.ini to be recognized by lombok. Then copy it back to the original name to be read by the IDE. (Haven't tried if symbolic links work though.)

Difference between matches() and find() in Java Regex

matches(); does not buffer, but find() buffers. find() searches to the end of the string first, indexes the result, and return the boolean value and corresponding index.

That is why when you have a code like

1:Pattern.compile("[a-z]");

2:Pattern.matcher("0a1b1c3d4");

3:int count = 0;

4:while(matcher.find()){

5:count++: }

At 4: The regex engine using the pattern structure will read through the whole of your code (index to index as specified by the regex[single character] to find at least one match. If such match is found, it will be indexed then the loop will execute based on the indexed result else if it didn't do ahead calculation like which matches(); does not. The while statement would never execute since the first character of the matched string is not an alphabet.

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

The situation you describe is pretty fishy. Whenever you close your program's startup form, the entire application should quit automatically, including closing all other open forms. Make sure that you're closing the correct form, and you should not experience any problems.

The other possibility is that you've changed your project (using its Properties page) not to close until all open windows have been closed. In this mode, your application will not exit until the last remaining open form has been closed. If you've chosen this setting, you have to make sure that you call the Close method of all forms that you've shown during the course of application, not just the startup/main form.

The first setting is the default for a reason, and if you've changed it, you probably want to go fix it back.
It is by far the most intuitive model for normal applications, and it prevents exactly the situation you describe. For it to work properly, make sure that you have specified your main form as the "Startup form" (rather than a splash screen or log-in form).

The settings I'm talking about are highlighted here:

   Visual Studio Project Properties

But primarily, note that you should never have to call Application.Exit in a properly-designed application. If you find yourself having to do this in order for your program to close completely, then you are doing something wrong. Doing it is not a bad practice in itself, as long as you have a good reason. The other two answers fail to explain that, and thus I feel are incomplete at best.

How to get english language word database?

You may check *spell en-GB dictionary used by Mozilla, OpenOffice, plenty of other software.

How to compare two maps by their values

I don't think there is a "apache-common-like" tool to compare maps since the equality of 2 maps is very ambiguous and depends on the developer needs and the map implementation...

For exemple if you compare two hashmaps in java: - You may want to just compare key/values are the same - You may also want to compare if the keys are ordered the same way - You may also want to compare if the remaining capacity is the same ... You can compare a lot of things!

What such a tool would do when comparing 2 different map implementations such that: - One map allow null keys - The other throw runtime exception on map2.get(null)

You'd better to implement your own solution according to what you really need to do, and i think you already got some answers above :)

how to get the value of a textarea in jquery?

You can directly use

var message = $.trim($("#message").val());

Read more @ Get the Value of TextArea using the jQuery Val () Method

Sequel Pro Alternative for Windows

You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.

But if you want alternative suggestions, here are a few that I know of and have used:

MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.

Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.

(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)

Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.

How to declare an array inside MS SQL Server Stored Procedure?

Is there a reason why you aren't using a table variable and the aggregate SUM operator, instead of a cursor? SQL excels at set-oriented operations. 99.87% of the time that you find yourself using a cursor, there's a set-oriented alternative that's more efficient:

declare @MonthsSale table
(
MonthNumber int,
MonthName varchar(9),
MonthSale decimal(18,2)
)

insert into @MonthsSale
select
    1, 'January', 100.00
union select    
    2, 'February', 200.00
union select    
    3, 'March', 300.00
union select    
    4, 'April', 400.00
union select    
    5, 'May', 500.00
union select    
    6, 'June', 600.00
union select    
    7, 'July', 700.00
union select    
    8, 'August', 800.00
union select    
    9, 'September', 900.00
union select    
    10, 'October', 1000.00
union select    
    11, 'November', 1100.00
union select    
    12, 'December', 1200.00

select * from @MonthsSale   
select SUM(MonthSale) as [TotalSales] from @MonthsSale

How to code a BAT file to always run as admin mode?

  1. My experimenting indicates that the runas command must include the admin user's domain (at least it does in my organization's environmental setup):

    runas /user:AdminDomain\AdminUserName ExampleScript.bat
    

    If you don’t already know the admin user's domain, run an instance of Command Prompt as the admin user, and enter the following command:

    echo %userdomain%
    
  2. The answers provided by both Kerrek SB and Ed Greaves will execute the target file under the admin user but, if the file is a Command script (.bat file) or VB script (.vbs file) which attempts to operate on the normal-login user’s environment (such as changing registry entries), you may not get the desired results because the environment under which the script actually runs will be that of the admin user, not the normal-login user! For example, if the file is a script that operates on the registry’s HKEY_CURRENT_USER hive, the affected “current-user” will be the admin user, not the normal-login user.

Space between border and content? / Border distance from content?

You could try adding an<hr>and styling that. Its a minimal markup change but seems to need less css so that might do the trick.

fiddle:

http://jsfiddle.net/BhxsZ/

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

CLOCK_REALTIME represents the machine's best-guess as to the current wall-clock, time-of-day time. As Ignacio and MarkR say, this means that CLOCK_REALTIME can jump forwards and backwards as the system time-of-day clock is changed, including by NTP.

CLOCK_MONOTONIC represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past. It isn't affected by changes in the system time-of-day clock.

If you want to compute the elapsed time between two events observed on the one machine without an intervening reboot, CLOCK_MONOTONIC is the best option.

Note that on Linux, CLOCK_MONOTONIC does not measure time spent in suspend, although by the POSIX definition it should. You can use the Linux-specific CLOCK_BOOTTIME for a monotonic clock that keeps running during suspend.

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

If you don't need the code to be portable to old unices, you can use clock_gettime(), which will give you the time in nanoseconds (if your processor supports that resolution). It's POSIX, but from 2001.

Convert object string to JSON

A solution with one regex and not using eval:

str.replace(/([\s\S]*?)(')(.+?)(')([\s\S]*?)/g, "$1\"$3\"$5")

This I believe should work for multiple lines and all possible occurrences (/g flag) of single-quote 'string' replaced with double-quote "string".

How to run TestNG from command line

Ok after 2 days of trying to figure out why I couldn't run the example from

http://www.tutorialspoint.com/testng/testng_environment.htm the following code did not work for me

C:\TestNG_WORKSPACE>java -cp "C:\TestNG_WORKSPACE" org.testng.TestNG testng.xml

The fix for it is as follows: I came to the following conclusion: First off install eclipse, and download the TestNG plugin. After that follow the instructions from the tutorial to create and compile the test class from cmd using javac, and add the testng.xml. To run the testng.xml on windows 10 cmd run the following line:

java -cp C:\Users\Lenovo\Desktop\eclipse\plugins\org.testng.eclipse_6.9.12.201607091356\lib\*;C:\Test org.testng.TestNG testng.xml

to clarify: C:\Users\Lenovo\Desktop\eclipse\plugins\org.testng.eclipse_6.9.12.201607091356\lib\* The path above represents the location of jcommander.jar and testng.jar that you downloaded by installing the TESTNG plugin for eclipse. The path may vary so to be sure just open the installation location of eclipse, go to plugins and search for jcommander.jar. Then copy that location and after that add * to select all the necessary .jars.

C:\Test  

The path above represents the location of the testing.xml in your project. After getting all the necessary paths, append them by using ";".

I hope I have been helpful to some of you guys :)

Objective-C and Swift URL encoding

//use NSString instance method like this:

+ (NSString *)encodeURIComponent:(NSString *)string
{
NSString *s = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return s;
}

+ (NSString *)decodeURIComponent:(NSString *)string
{
NSString *s = [string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return s;
}

remember,you should only do encode or decode for your parameter value, not all the url you request.

HttpServletRequest get JSON POST data

Are you posting from a different source (so different port, or hostname)? If so, this very very recent topic I just answered might be helpful.

The problem was the XHR Cross Domain Policy, and a useful tip on how to get around it by using a technique called JSONP. The big downside is that JSONP does not support POST requests.

I know in the original post there is no mention of JavaScript, however JSON is usually used for JavaScript so that's why I jumped to that conclusion

How to remove non-alphanumeric characters?

For unicode characters, it is :

preg_replace("/[^[:alnum:][:space:]]/u", '', $string);

Move the most recent commit(s) to a new branch with Git

1) Create a new branch, which moves all your changes to new_branch.

git checkout -b new_branch

2) Then go back to old branch.

git checkout master

3) Do git rebase

git rebase -i <short-hash-of-B-commit>

4) Then the opened editor contains last 3 commit information.

...
pick <C's hash> C
pick <D's hash> D
pick <E's hash> E
...

5) Change pick to drop in all those 3 commits. Then save and close the editor.

...
drop <C's hash> C
drop <D's hash> D
drop <E's hash> E
...

6) Now last 3 commits are removed from current branch (master). Now push the branch forcefully, with + sign before branch name.

git push origin +master

What does it mean by command cd /d %~dp0 in Windows

~dp0 : d=drive, p=path, %0=full path\name of this batch-file.

cd /d %~dp0 will change the path to the same, where the batch file resides.

See for /? or call / for more details about the %~... modifiers.
See cd /? about the /d switch.

How to get the sizes of the tables of a MySQL database?

Calculate the total size of the database at the end:

(SELECT 
  table_name AS `Table`, 
  round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` 
  FROM information_schema.TABLES 
  WHERE table_schema = "$DB_NAME"
)
UNION ALL
(SELECT 
  'TOTAL:',
  SUM(round(((data_length + index_length) / 1024 / 1024), 2) )
  FROM information_schema.TABLES 
  WHERE table_schema = "$DB_NAME"
)

jQuery Validate Required Select

You can write your own rule!

 // add the rule here
 $.validator.addMethod("valueNotEquals", function(value, element, arg){
  return arg !== value;
 }, "Value must not equal arg.");

 // configure your validation
 $("form").validate({
  rules: {
   SelectName: { valueNotEquals: "default" }
  },
  messages: {
   SelectName: { valueNotEquals: "Please select an item!" }
  }  
 });

IE 8: background-size fix

I created jquery.backgroundSize.js: a 1.5K jquery plugin that can be used as a IE8 fallback for "cover" and "contain" values. Have a look at the demo.

Solving your problem could be as simple as:

$("h2#news").css({backgroundSize: "cover"});

How do I add FTP support to Eclipse?

I'm not sure if this works for you, but when I do small solo PHP projects with Eclipse, the first thing I set up is an Ant script for deploying the project to a remote testing environment. I code away locally, and whenever I want to test it, I just hit the shortcut which updates the remote site.

Eclipse has good Ant support out of the box, and the scripts aren't hard to make.

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

How to save a data.frame in R?

Let us say you have a data frame you created and named "Data_output", you can simply export it to same directory by using the following syntax.

write.csv(Data_output, "output.csv", row.names = F, quote = F)

credit to Peter and Ilja, UMCG, the Netherlands

Microsoft Web API: How do you do a Server.MapPath?

You can use HostingEnvironment.MapPath in any context where System.Web objects like HttpContext.Current are not available (e.g also from a static method).

var mappedPath = System.Web.Hosting.HostingEnvironment.MapPath("~/SomePath");

See also What is the difference between Server.MapPath and HostingEnvironment.MapPath?

How to grep a text file which contains some binary data?

Starting with Grep 2.21, binary files are treated differently:

When searching binary data, grep now may treat non-text bytes as line terminators. This can boost performance significantly.

So what happens now is that with binary data, all non-text bytes (including newlines) are treated as line terminators. If you want to change this behavior, you can:

  • use --text. This will ensure that only newlines are line terminators

  • use --null-data. This will ensure that only null bytes are line terminators

How to convert a string to integer in C?

In C++, you can use a such function:

template <typename T>
T to(const std::string & s)
{
    std::istringstream stm(s);
    T result;
    stm >> result;

    if(stm.tellg() != s.size())
        throw error;

    return result;
}

This can help you to convert any string to any type such as float, int, double...

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

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

read_csv(..., nrows=999999)

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

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

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

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

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

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

Is there a way to create key-value pairs in Bash script?

In bash, we use

declare -A name_of_dictonary_variable

so that Bash understands it is a dictionary.

For e.g. you want to create sounds dictionary then,

declare -A sounds

sounds[dog]="Bark"

sounds[wolf]="Howl"

where dog and wolf are "keys", and Bark and Howl are "values".

You can access all values using : echo ${sounds[@]} OR echo ${sounds[*]}

You can access all keys only using: echo ${!sounds[@]}

And if you want any value for a particular key, you can use:

${sounds[dog]}

this will give you value (Bark) for key (Dog).

Giving UIView rounded corners

set cornerRadious Property for round View

set masksToBounds Boolean Value for image will not still be drawn outside the corner radius boundary

view.layer.cornerRadius = 5;

view.layer.masksToBounds = YES;

MySQL and PHP - insert NULL rather than empty string

To pass a NULL to MySQL, you do just that.

INSERT INTO table (field,field2) VALUES (NULL,3)

So, in your code, check if $intLat, $intLng are empty, if they are, use NULL instead of '$intLat' or '$intLng'.

$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
          VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long', 
                  $intLat, $intLng)";

How do I add all new files to SVN

Among bash one-liner I think this is the prettiest:

svn status | tee >(awk '/^?/{print $2}' | xargs -r svn add >&2) | awk '/^!/{print $2}' | xargs -r svn delete

It will add all new files and delete all missing files. Use with caution, possibly set an alias for quick access.

NOTE for Macs: in xargs -r is a GNU extension: it might not be supported. In that case just remove it and ignore warnings when there are no files to add or to delete

MongoDb query condition on comparing 2 fields

If your query consists only of the $where operator, you can pass in just the JavaScript expression:

db.T.find("this.Grade1 > this.Grade2");

For greater performance, run an aggregate operation that has a $redact pipeline to filter the documents which satisfy the given condition.

The $redact pipeline incorporates the functionality of $project and $match to implement field level redaction where it will return all documents matching the condition using $$KEEP and removes from the pipeline results those that don't match using the $$PRUNE variable.


Running the following aggregate operation filter the documents more efficiently than using $where for large collections as this uses a single pipeline and native MongoDB operators, rather than JavaScript evaluations with $where, which can slow down the query:

db.T.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$gt": [ "$Grade1", "$Grade2" ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

which is a more simplified version of incorporating the two pipelines $project and $match:

db.T.aggregate([
    {
        "$project": {
            "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] },
            "Grade1": 1,
            "Grade2": 1,
            "OtherFields": 1,
            ...
        }
    },
    { "$match": { "isGrade1Greater": 1 } }
])

With MongoDB 3.4 and newer:

db.T.aggregate([
    {
        "$addFields": {
            "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] }
        }
    },
    { "$match": { "isGrade1Greater": 1 } }
])

Difference between jQuery parent(), parents() and closest() functions

parent() method returns the direct parent element of the selected one. This method only traverse a single level up the DOM tree.

parents() method allows us to search through the ancestors of these elements in the DOM tree. Begin from given selector and move up.

The **.parents()** and **.parent()** methods are almost similar, except that the latter only travels a single level up the DOM tree. Also, **$( "html" ).parent()** method returns a set containing document whereas **$( "html" ).parents()** returns an empty set.

[closest()][3]method returns the first ancestor of the selected element.An ancestor is a parent, grandparent, great-grandparent, and so on.

This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.

According to docs:

**closest()** method is similar to **parents()**, in that they both traverse up the DOM tree. The differences are as follows:

**closest()**

Begins with the current element
Travels up the DOM tree and returns the first (single) ancestor that matches the passed expression
The returned jQuery object contains zero or one element

**parents()**

Begins with the parent element
Travels up the DOM tree and returns all ancestors that matches the passed expression
The returned jQuery object contains zero or more than one element





 

How to make an array of arrays in Java

Like this:

String[][] arrays = { array1, array2, array3, array4, array5 };

or

String[][] arrays = new String[][] { array1, array2, array3, array4, array5 };

(The latter syntax can be used in assignments other than at the point of the variable declaration, whereas the shorter syntax only works with declarations.)

Why should we typedef a struct so often in C?

From an old article by Dan Saks (http://www.ddj.com/cpp/184403396?pgno=3):


The C language rules for naming structs are a little eccentric, but they're pretty harmless. However, when extended to classes in C++, those same rules open little cracks for bugs to crawl through.

In C, the name s appearing in

struct s
    {
    ...
    };

is a tag. A tag name is not a type name. Given the definition above, declarations such as

s x;    /* error in C */
s *p;   /* error in C */

are errors in C. You must write them as

struct s x;     /* OK */
struct s *p;    /* OK */

The names of unions and enumerations are also tags rather than types.

In C, tags are distinct from all other names (for functions, types, variables, and enumeration constants). C compilers maintain tags in a symbol table that's conceptually if not physically separate from the table that holds all other names. Thus, it is possible for a C program to have both a tag and an another name with the same spelling in the same scope. For example,

struct s s;

is a valid declaration which declares variable s of type struct s. It may not be good practice, but C compilers must accept it. I have never seen a rationale for why C was designed this way. I have always thought it was a mistake, but there it is.

Many programmers (including yours truly) prefer to think of struct names as type names, so they define an alias for the tag using a typedef. For example, defining

struct s
    {
    ...
    };
typedef struct s S;

lets you use S in place of struct s, as in

S x;
S *p;

A program cannot use S as the name of both a type and a variable (or function or enumeration constant):

S S;    // error

This is good.

The tag name in a struct, union, or enum definition is optional. Many programmers fold the struct definition into the typedef and dispense with the tag altogether, as in:

typedef struct
    {
    ...
    } S;

The linked article also has a discussion about how the C++ behavior of not requireing a typedef can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.

angularjs: ng-src equivalent for background-image:url(...)

This one works for me

<li ng-style="{'background-image':'url(/static/'+imgURL+')'}">...</li>

Is there 'byte' data type in C++?

namespace std
{
  // define std::byte
  enum class byte : unsigned char {};

};

This if your C++ version does not have std::byte will define a byte type in namespace std. Normally you don't want to add things to std, but in this case it is a standard thing that is missing.

std::byte from the STL does much more operations.

How to open a new file in vim in a new window

from inside vim, use one of the following

open a new window below the current one:

:new filename.ext

open a new window beside the current one:

:vert new filename.ext

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

Regular expression for checking if capital letters are found consecutively in a string?

Aside from tchrists excellent post concerning unicode, I think you don't need the complex solution with a negative lookahead... Your definition requires an Uppercase-letter followed by at least one group of (a lowercase letter optionally followed by an Uppercase-letter)

^
[A-Z]    // Start with an uppercase Letter
(        // A Group of:
  [a-z]  // mandatory lowercase letter
  [A-Z]? // an optional Uppercase Letter at the end
         // or in between lowercase letters
)+       // This group at least one time
$

Just a bit more compact and easier to read I think...

What do $? $0 $1 $2 mean in shell script?

These are positional arguments of the script.

Executing

./script.sh Hello World

Will make

$0 = ./script.sh
$1 = Hello
$2 = World

Note

If you execute ./script.sh, $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh.

How to return rows from left table not found in right table?

This page gives a decent breakdown of the different join types, as well as venn diagram visualizations to help... well... visualize the difference in the joins.

As the comments said this is a quite basic query from the sounds of it, so you should try to understand the differences between the joins and what they actually mean.

Check out http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

You're looking for a query such as:

DECLARE @table1 TABLE (test int)
DECLARE @table2 TABLE (test int)

INSERT INTO @table1
(
    test
)
SELECT 1
UNION ALL SELECT 2

INSERT INTO @table2
(
    test
)
SELECT 1
UNION ALL SELECT 3

-- Here's the important part
SELECT  a.*
FROM    @table1 a
LEFT    join @table2 b on a.test = b.test -- this will return all rows from a
WHERE   b.test IS null -- this then excludes that which exist in both a and b

-- Returned results:

2

Thread-safe List<T> property

Even accepted answer is ConcurrentBag, I don't think it's real replacement of list in all cases, as Radek's comment to the answer says: "ConcurrentBag is unordered collection, so unlike List it does not guarantee ordering. Also you cannot access items by index".

So if you use .NET 4.0 or higher, a workaround could be to use ConcurrentDictionary with integer TKey as array index and TValue as array value. This is recommended way of replacing list in Pluralsight's C# Concurrent Collections course. ConcurrentDictionary solves both problems mentioned above: index accessing and ordering (we can not rely on ordering as it's hash table under the hood, but current .NET implementation saves order of elements adding).

How can I list the scheduled jobs running in my database?

I think you need the SCHEDULER_ADMIN role to see the dba_scheduler tables (however this may grant you too may rights)

see: http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/schedadmin001.htm

Java : Cannot format given Object as a Date

java.time

I should like to contribute the modern answer. The SimpleDateFormat class is notoriously troublesome, and while it was reasonable to fight one’s way through with it when this question was asked six and a half years ago, today we have much better in java.time, the modern Java date and time API. SimpleDateFormat and its friend Date are now considered long outdated, so don’t use them anymore.

    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MM/uuuu");
    String dateformat = "2012-11-17T00:00:00.000-05:00";
    OffsetDateTime dateTime = OffsetDateTime.parse(dateformat);
    String monthYear = dateTime.format(monthFormatter);
    System.out.println(monthYear);

Output:

11/2012

I am exploiting the fact that your string is in ISO 8601 format, the international standard, and that the classes of java.time parse this format as their default, that is, without any explicit formatter. It’s stil true what the other answers say, you need to parse the original string first, then format the resulting date-time object into a new string. Usually this requires two formatters, only in this case we’re lucky and can do with just one formatter.

What went wrong in your code

  • As others have said, SimpleDateFormat.format cannot accept a String argument, also when the parameter type is declared to be Object.
  • Because of the exception you didn’t get around to discovering: there is also a bug in your format pattern string, mm/yyyy. Lowercase mm os for minute of the hour. You need uppercase MM for month.
  • Finally the Java naming conventions say to use a lowercase first letter in variable names, so use lowercase m in monthYear (also because java.time includes a MonthYear class with uppercase M, so to avoid confusion).

Links

Open multiple Projects/Folders in Visual Studio Code

To run one project at a time in same solution

Open Solution explorer window -> Open Solution for Project -> Right click on it -> Select Properties from drop down list (Alt+Enter)-> Common Properties -> select Startup Project you will see "current selection,single selection and multiple selection from that select "Current Selection" this will help you to run one project at a time in same solution workspace having different coding.

How to set JAVA_HOME for multiple Tomcat instances?

In UNIX I had this problem, I edited catalina.sh manually and entered

export JAVA_HOME=/usr/lib/jvm/java-6-sun-1.6.0.24
echo "Using JAVA_HOME:       $JAVA_HOME"

as the first 2 lines. I tried setting the JAVA_HOME in /etc/profile but it did not help.

This worked finally.

Executing periodic actions in Python

This will insert a 10 second sleep in between every call to foo(), which is approximately what you asked for should the call complete quickly.

import time

while True:
    foo()
    time.sleep(10)

To do other things while your foo() is being called in a background thread

import time
import sys
import threading

def foo():
    sys.stdout.write('({}) foo\n'.format(time.ctime()))

def foo_target():
    while True:
        foo()
        time.sleep(10)

t = threading.Thread(target=foo_target)
t.daemon = True
t.start()
print('doing other things...')

How do I create a new user in a SQL Azure database?

You can simply create a contained user in SQL DB V12.

Create user containeduser with password = 'Password'

Contained user login is more efficient than login to the database using the login created by master. You can find more details @ http://www.sqlindepth.com/contained-users-in-sql-azure-db-v12/

Webpack how to build production code and how to use it

If you have a lot of duplicate code in your webpack.dev.config and your webpack.prod.config, you could use a boolean isProd to activate certain features only in certain situations and only have a single webpack.config.js file.

const isProd = (process.env.NODE_ENV === 'production');

 if (isProd) {
     plugins.push(new AotPlugin({
      "mainPath": "main.ts",
      "hostReplacementPaths": {
        "environments/index.ts": "environments/index.prod.ts"
      },
      "exclude": [],
      "tsConfigPath": "src/tsconfig.app.json"
    }));
    plugins.push(new UglifyJsPlugin({
      "mangle": {
        "screw_ie8": true
      },
      "compress": {
        "screw_ie8": true,
        "warnings": false
      },
      "sourceMap": false
    }));
  }

By the way: The DedupePlugin plugin was removed from Webpack. You should remove it from your configuration.

UPDATE:

In addition to my previous answer:

If you want to hide your code for release, try enclosejs.com. It allows you to:

  • make a release version of your application without sources
  • create a self-extracting archive or installer
  • Make a closed source GUI application
  • Put your assets inside the executable

You can install it with npm install -g enclose

Angular + Material - How to refresh a data source (mat-table)

I did some more research and found this place to give me what I needed - feels clean and relates to update data when refreshed from server: https://blog.angular-university.io/angular-material-data-table/

Most credits to the page above. Below is a sample of how a mat-selector can be used to update a mat-table bound to a datasource on change of selection. I am using Angular 7. Sorry for being extensive, trying to be complete but concise - I have ripped out as many non-needed parts as possible. With this hoping to help someone else getting forward faster!

organization.model.ts:

export class Organization {
    id: number;
    name: String;
}

organization.service.ts:

import { Observable, empty } from 'rxjs';
import { of } from 'rxjs';

import { Organization } from './organization.model';

export class OrganizationService {
  getConstantOrganizations(filter: String): Observable<Organization[]> {
    if (filter === "All") {
      let Organizations: Organization[] = [
        { id: 1234, name: 'Some data' }
      ];
      return of(Organizations);
     } else {
       let Organizations: Organization[] = [
         { id: 5678, name: 'Some other data' }
       ];
     return of(Organizations);
  }

  // ...just a sample, other filterings would go here - and of course data instead fetched from server.
}

organizationdatasource.model.ts:

import { CollectionViewer, DataSource } from '@angular/cdk/collections';
import { Observable, BehaviorSubject, of } from 'rxjs';
import { catchError, finalize } from "rxjs/operators";

import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';

export class OrganizationDataSource extends DataSource<Organization> {
  private organizationsSubject = new BehaviorSubject<Organization[]>([]);

  private loadingSubject = new BehaviorSubject<boolean>(false);

  public loading$ = this.loadingSubject.asObservable();

  constructor(private organizationService: OrganizationService, ) {
    super();
  }

  loadOrganizations(filter: String) {
    this.loadingSubject.next(true);

    return this.organizationService.getOrganizations(filter).pipe(
      catchError(() => of([])),
      finalize(() => this.loadingSubject.next(false))
    ).subscribe(organization => this.organizationsSubject.next(organization));
  }

  connect(collectionViewer: CollectionViewer): Observable<Organization[]> {
    return this.organizationsSubject.asObservable();
  }

  disconnect(collectionViewer: CollectionViewer): void {
    this.organizationsSubject.complete();
    this.loadingSubject.complete();
  }
}

organizations.component.html:

<div class="spinner-container" *ngIf="organizationDataSource.loading$ | async">
    <mat-spinner></mat-spinner>
</div>

<div>
  <form [formGroup]="formGroup">
    <mat-form-field fxAuto>
      <div fxLayout="row">
        <mat-select formControlName="organizationSelectionControl" (selectionChange)="updateOrganizationSelection()">
          <mat-option *ngFor="let organizationSelectionAlternative of organizationSelectionAlternatives"
            [value]="organizationSelectionAlternative">
            {{organizationSelectionAlternative.name}}
          </mat-option>
        </mat-select>
      </div>
    </mat-form-field>
  </form>
</div>

<mat-table fxLayout="column" [dataSource]="organizationDataSource">
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
    <mat-cell *matCellDef="let organization">{{organization.name}}</mat-cell>
  </ng-container>

  <ng-container matColumnDef="number">
    <mat-header-cell *matHeaderCellDef>Number</mat-header-cell>
    <mat-cell *matCellDef="let organization">{{organization.number}}</mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>

organizations.component.scss:

.spinner-container {
    height: 360px;
    width: 390px;
    position: fixed;
}

organization.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs';

import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';
import { OrganizationDataSource } from './organizationdatasource.model';

@Component({
  selector: 'organizations',
  templateUrl: './organizations.component.html',
  styleUrls: ['./organizations.component.scss']
})
export class OrganizationsComponent implements OnInit {
  public displayedColumns: string[];
  public organizationDataSource: OrganizationDataSource;
  public formGroup: FormGroup;

  public organizationSelectionAlternatives = [{
    id: 1,
    name: 'All'
  }, {
    id: 2,
    name: 'With organization update requests'
  }, {
    id: 3,
    name: 'With contact update requests'
  }, {
    id: 4,
    name: 'With order requests'
  }]

  constructor(
    private formBuilder: FormBuilder,
    private organizationService: OrganizationService) { }

  ngOnInit() {
    this.formGroup = this.formBuilder.group({
      'organizationSelectionControl': []
    })

    const toSelect = this.organizationSelectionAlternatives.find(c => c.id == 1);
    this.formGroup.get('organizationSelectionControl').setValue(toSelect);

    this.organizationDataSource = new OrganizationDataSource(this.organizationService);
    this.displayedColumns = ['name', 'number' ];
    this.updateOrganizationSelection();
  }

  updateOrganizationSelection() {
    this.organizationDataSource.loadOrganizations(this.formGroup.get('organizationSelectionControl').value.name);
  }
}

How to error handle 1004 Error with WorksheetFunction.VLookup?

From my limited experience, this happens for two main reasons:

  1. The lookup_value (arg1) is not present in the table_array (arg2)

The simple solution here is to use an error handler ending with Resume Next

  1. The formats of arg1 and arg2 are not interpreted correctly

If your lookup_value is a variable you can enclose it with TRIM()

cellNum = wsFunc.VLookup(TRIM(currName), rngLook, 13, False)

Should operator<< be implemented as a friend or as a member function?

You can not do it as a member function, because the implicit this parameter is the left hand side of the <<-operator. (Hence, you would need to add it as a member function to the ostream-class. Not good :)

Could you do it as a free function without friending it? That's what I prefer, because it makes it clear that this is an integration with ostream, and not a core functionality of your class.

How can I trigger a Bootstrap modal programmatically?

I wanted to do this the angular (2/4) way, here is what I did:

<div [class.show]="visible" [class.in]="visible" class="modal fade" id="confirm-dialog-modal" role="dialog">
..
</div>`

Important things to note:

  • visible is a variable (boolean) in the component which governs modal's visibility.
  • show and in are bootstrap classes.

An example component & html

Component

@ViewChild('rsvpModal', { static: false }) rsvpModal: ElementRef;
..
@HostListener('document:keydown.escape', ['$event'])
  onEscapeKey(event: KeyboardEvent) {
    this.hideRsvpModal();
  }
..
  hideRsvpModal(event?: Event) {
    if (!event || (event.target as Element).classList.contains('modal')) {
      this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'none');
      this.renderer.removeClass(this.rsvpModal.nativeElement, 'show');
      this.renderer.addClass(document.body, 'modal-open');
    }
  }
  showRsvpModal() {
    this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'block');
    this.renderer.addClass(this.rsvpModal.nativeElement, 'show');
    this.renderer.removeClass(document.body, 'modal-open');
  }

Html

<!--S:RSVP-->
<div class="modal fade" #rsvpModal role="dialog" aria-labelledby="niviteRsvpModalTitle" (click)="hideRsvpModal($event)">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="niviteRsvpModalTitle">

                </h5>
                <button type="button" class="close" (click)="hideRsvpModal()" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary bg-white text-dark"
                    (click)="hideRsvpModal()">Close</button>
            </div>
        </div>
    </div>
</div>
<!--E:RSVP-->

What is 'Currying'?

Here you can find a simple explanation of currying implementation in C#. In the comments, I have tried to show how currying can be useful:

public static class FuncExtensions {
    public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func)
    {
        return x1 => x2 => func(x1, x2);
    }
}

//Usage
var add = new Func<int, int, int>((x, y) => x + y).Curry();
var func = add(1);

//Obtaining the next parameter here, calling later the func with next parameter.
//Or you can prepare some base calculations at the previous step and then
//use the result of those calculations when calling the func multiple times 
//with different input parameters.

int result = func(1);

Set markers for individual points on a line in Matplotlib

You can do:

import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [2,1,3,6,7]

plt.plot(x, y, style='.-')
plt.show()

This will return a graph with the data points marked with a dot

How to use filter, map, and reduce in Python 3

As an addendum to the other answers, this sounds like a fine use-case for a context manager that will re-map the names of these functions to ones which return a list and introduce reduce in the global namespace.

A quick implementation might look like this:

from contextlib import contextmanager    

@contextmanager
def noiters(*funcs):
    if not funcs: 
        funcs = [map, filter, zip] # etc
    from functools import reduce
    globals()[reduce.__name__] = reduce
    for func in funcs:
        globals()[func.__name__] = lambda *ar, func = func, **kwar: list(func(*ar, **kwar))
    try:
        yield
    finally:
        del globals()[reduce.__name__]
        for func in funcs: globals()[func.__name__] = func

With a usage that looks like this:

with noiters(map):
    from operator import add
    print(reduce(add, range(1, 20)))
    print(map(int, ['1', '2']))

Which prints:

190
[1, 2]

Just my 2 cents :-)

How to represent multiple conditions in a shell if statement?

Using /bin/bash the following will work:

if [ "$option" = "Y" ] || [ "$option" = "y" ]; then
    echo "Entered $option"
fi

Find size and free space of the filesystem containing a given file

The simplest way to find out it.

import os
from collections import namedtuple

DiskUsage = namedtuple('DiskUsage', 'total used free')

def disk_usage(path):
    """Return disk usage statistics about the given path.

    Will return the namedtuple with attributes: 'total', 'used' and 'free',
    which are the amount of total, used and free space, in bytes.
    """
    st = os.statvfs(path)
    free = st.f_bavail * st.f_frsize
    total = st.f_blocks * st.f_frsize
    used = (st.f_blocks - st.f_bfree) * st.f_frsize
    return DiskUsage(total, used, free)

ssh "permissions are too open" error

0600 is what mine is set at (and it's working)

How to install Intellij IDEA on Ubuntu?

Note: This answer covers the installation of IntelliJ IDEA. For an extended script, that covers more JetBrains IDEs, as well as help for font rendering issues, please see this link provided by brendan.
Furthermore, a manual Desktop Entry creation is optional, as newer versions of IntelliJ offer to create it on first startup.


I have my intellij int /opt folder. So what I do is:

  • Download Intellij
  • Extract intellij to /opt-folder: sudo tar -xvf <intellij.tar> -C /opt/ (the -C option extracts the tar to the folder /opt/)
  • Create a Desktop Entry File called idea.desktop (see example file below) and store it anywhere you want (let's assume in your home directory)
  • Move the idea.desktop from your home directory to /usr/share/applications: sudo mv ~/idea.desktop /usr/share/applications/

Now (in a lot) Ubuntu versions you can start the application after the GUI is restarted. If you don't know how to do that, you can restart your PC..

idea.desktop (this is for community edition version 14.1.2, you have to change the paths in Exec= and Icon= lines if the path is different for you):

[Desktop Entry]                                                                 
Encoding=UTF-8
Name=IntelliJ IDEA
Comment=IntelliJ IDEA
Exec=/opt/ideaIC-14.1.2/bin/idea.sh
Icon=/opt/ideaIC-14.1.2/bin/idea.png
Terminal=false
StartupNotify=true
Type=Application

Edit
I also found a shell script that does this for you, here. The given script in the link installs Oracle Java 7 for you and gives you the choice between Community and Ultimate Edition. It then automatically downloads the newest version for you, extracts it and creates a desktop entry.
I have modified the scripts to fulfill my needs. It does not install java 8 and it does not ask you for the version you want to install (but the version is kept in a variable to easily change that). You can also update Intellij with it. But then you have to (so far) manually remove the old folder! This is what i got:

Edit2
Here is the new version of the script. As mentioned in the comments, breandan has updated the script to be more stable (the jetbrains website changed its behavior). Thanks for the update, breandan.

#!/bin/sh

echo "Installing IntelliJ IDEA..."

# We need root to install
[ $(id -u) != "0" ] && exec sudo "$0" "$@"

# Attempt to install a JDK
# apt-get install openjdk-8-jdk
# add-apt-repository ppa:webupd8team/java && apt-get update && apt-get install oracle-java8-installer

# Prompt for edition
#while true; do
#    read -p "Enter 'U' for Ultimate or 'C' for Community: " ed 
#    case $ed in
#        [Uu]* ) ed=U; break;;
#        [Cc]* ) ed=C; break;;
#    esac
#done
ed=C

# Fetch the most recent version
VERSION=$(wget "https://www.jetbrains.com/intellij-repository/releases" -qO- | grep -P -o -m 1 "(?<=https://www.jetbrains.com/intellij-repository/releases/com/jetbrains/intellij/idea/BUILD/)[^/]+(?=/)")

# Prepend base URL for download
URL="https://download.jetbrains.com/idea/ideaI$ed-$VERSION.tar.gz"

echo $URL

# Truncate filename
FILE=$(basename ${URL})

# Set download directory
DEST=~/Downloads/$FILE

echo "Downloading idea-I$ed-$VERSION to $DEST..."

# Download binary
wget -cO ${DEST} ${URL} --read-timeout=5 --tries=0

echo "Download complete!"

# Set directory name
DIR="/opt/idea-I$ed-$VERSION"

echo "Installing to $DIR"

# Untar file
if mkdir ${DIR}; then
    tar -xzf ${DEST} -C ${DIR} --strip-components=1
fi

# Grab executable folder
BIN="$DIR/bin"

# Add permissions to install directory
chmod -R +rwx ${DIR}

# Set desktop shortcut path
DESK=/usr/share/applications/IDEA.desktop

# Add desktop shortcut
echo -e "[Desktop Entry]\nEncoding=UTF-8\nName=IntelliJ IDEA\nComment=IntelliJ IDEA\nExec=${BIN}/idea.sh\nIcon=${BIN}/idea.png\nTerminal=false\nStartupNotify=true\nType=Application" -e > ${DESK}

# Create symlink entry
ln -s ${BIN}/idea.sh /usr/local/bin/idea

echo "Done."  

Old Version

#!/bin/sh                                                                                                                                   

echo "Installing IntelliJ IDEA..."

# We need root to install
[ $(id -u) != "0" ] && exec sudo "$0" "$@"

# define version (ultimate. change to 'C' for Community)
ed='U'

# Fetch the most recent community edition URL
URL=$(wget "https://www.jetbrains.com/idea/download/download_thanks.jsp?edition=I${ed}&os=linux" -qO- | grep -o -m 1 "https://download.jetbrains.com/idea/.*gz")

echo "URL: ${URL}"
echo "basename(url): $(basename ${URL})"

# Truncate filename
FILE=$(basename ${URL})

echo "File: ${FILE}"

# Download binary
wget -cO /tmp/${FILE} ${URL} --read-timeout=5 --tries=0

# Set directory name
DIR="${FILE%\.tar\.gz}"

# Untar file
if mkdir /opt/${DIR}; then
    tar -xvzf /tmp/${FILE} -C /opt/${DIR} --strip-components=1
fi

# Grab executable folder
BIN="/opt/$DIR/bin"

# Add permissions to install directory
chmod 755 ${BIN}/idea.sh

# Set desktop shortcut path
DESK=/usr/share/applications/IDEA.desktop

# Add desktop shortcut                     
echo -e "[Desktop Entry]\nEncoding=UTF-8\nName=IntelliJ IDEA\nComment=IntelliJ IDEA\nExec=${BIN}/idea.sh\nIcon=${BIN}/idea.png\nTerminal=false\nStartupNotify=true\nType=Application" > ${DESK}

echo "Done."    

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

I got this warning in Visual Studio 2012 when compiling a SQL Server 2012 SP1 SSIS pipeline script task - until I installed SQL Server 2012 SP2.

How to add anything in <head> through jquery/javascript?

jQuery

$('head').append( ... );

JavaScript:

document.getElementsByTagName('head')[0].appendChild( ... );

Identify if a string is a number

I guess this answer will just be lost in between all the other ones, but anyway, here goes.

I ended up on this question via Google because I wanted to check if a string was numeric so that I could just use double.Parse("123") instead of the TryParse() method.

Why? Because it's annoying to have to declare an out variable and check the result of TryParse() before you know if the parse failed or not. I want to use the ternary operator to check if the string is numerical and then just parse it in the first ternary expression or provide a default value in the second ternary expression.

Like this:

var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;

It's just a lot cleaner than:

var doubleValue = 0;
if (double.TryParse(numberAsString, out doubleValue)) {
    //whatever you want to do with doubleValue
}

I made a couple extension methods for these cases:


Extension method one

public static bool IsParseableAs<TInput>(this string value) {
    var type = typeof(TInput);

    var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
        new[] { typeof(string), type.MakeByRefType() }, null);
    if (tryParseMethod == null) return false;

    var arguments = new[] { value, Activator.CreateInstance(type) };
    return (bool) tryParseMethod.Invoke(null, arguments);
}

Example:

"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;

Because IsParseableAs() tries to parse the string as the appropriate type instead of just checking if the string is "numeric" it should be pretty safe. And you can even use it for non numeric types that have a TryParse() method, like DateTime.

The method uses reflection and you end up calling the TryParse() method twice which, of course, isn't as efficient, but not everything has to be fully optimized, sometimes convenience is just more important.

This method can also be used to easily parse a list of numeric strings into a list of double or some other type with a default value without having to catch any exceptions:

var sNumbers = new[] {"10", "20", "30"};
var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);

Extension method two

public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) {
    var type = typeof(TOutput);

    var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
        new[] { typeof(string), type.MakeByRefType() }, null);
    if (tryParseMethod == null) return defaultValue;

    var arguments = new object[] { value, null };
    return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue;
}

This extension method lets you parse a string as any type that has a TryParse() method and it also lets you specify a default value to return if the conversion fails.

This is better than using the ternary operator with the extension method above as it only does the conversion once. It still uses reflection though...

Examples:

"123".ParseAs<int>(10);
"abc".ParseAs<int>(25);
"123,78".ParseAs<double>(10);
"abc".ParseAs<double>(107.4);
"2014-10-28".ParseAs<DateTime>(DateTime.MinValue);
"monday".ParseAs<DateTime>(DateTime.MinValue);

Outputs:

123
25
123,78
107,4
28.10.2014 00:00:00
01.01.0001 00:00:00

How to build a Horizontal ListView with RecyclerView?

It's for both for Horizontal and for Vertical.

RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_recycler);
    recyclerView = (RecyclerView)findViewById(R.id.recyclerViewId);

    RecyclAdapter adapter = new RecyclAdapter();

    //Vertical RecyclerView
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);

    //Horizontal RecyclerView
    //recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));

    recyclerView.setAdapter(adapter);

}

How to delete file from public folder in laravel 5.1

Its a very old thread, but I don't see that the solution is here or the this thread is marked as solved. I have also stuck into the same problem I solved it like this

  $path = public_path('../storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME');
  if (!File::exists($path)) 
  {
    File::delete(public_path('storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME'));
  }

The key is that you need to remove '..' from the delete method. Keep in mind that this goes true if you are using Storage as well, whether you are using Storage of File don't for get to use them like

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use File; // For File
use Storage; // For Storage

Hope that it will help someone.

Simulate low network connectivity for Android

for and mac OS user you can use Network Link Conditioner which could be downloaded from apple. set it as a AP on mac and any divices could connected it.

you can either use facebook open source tools ATC http://facebook.github.io/augmented-traffic-control/

Best way to get hostname with php

I am running PHP version 5.4 on shared hosting and both of these both successfully return the same results:

php_uname('n');

gethostname();

correct way to use super (argument passing)

As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object, all arguments have been eaten, and object.__init__ will be called without arguments (as it expects). So your code should look like this:

class A(object):
    def __init__(self, *args, **kwargs):
        print "A"
        super(A, self).__init__(*args, **kwargs)

class B(object):
    def __init__(self, *args, **kwargs):
        print "B"
        super(B, self).__init__(*args, **kwargs)

class C(A):
    def __init__(self, arg, *args, **kwargs):
        print "C","arg=",arg
        super(C, self).__init__(*args, **kwargs)

class D(B):
    def __init__(self, arg, *args, **kwargs):
        print "D", "arg=",arg
        super(D, self).__init__(*args, **kwargs)

class E(C,D):
    def __init__(self, arg, *args, **kwargs):
        print "E", "arg=",arg
        super(E, self).__init__(*args, **kwargs)

print "MRO:", [x.__name__ for x in E.__mro__]
E(10, 20, 30)

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

I used a list in my controller class to set data into grid view. The code works fine for me:

public ActionResult ExpExcl()
{
  List<PersonModel> person= new List<PersonModel>
   { 
    new PersonModel() {FirstName= "Jenny", LastName="Mathew", Age= 23},
    new PersonModel() {FirstName= "Paul", LastName="Meehan", Age=25}
   };
   var grid= new GridView();
   grid.DataSource= person;
   grid.DataBind();

   Response.ClearContent();
   Response.AddHeader("content-disposition","attachement; filename=data.xls");
   Response.ContentType="application/excel";
   StringWriter sw= new StringWriter();
   HtmlTextWriter htw= new HtmlTextWriter(sw); 
   grid.RenderControl(htw);
   Response.Output.Write(sw.ToString());
   Response.Flush();
   Response.End();
   return View();
 }

Array of char* should end at '\0' or "\0"?

I would end it with NULL. Why? Because you can't do either of these:

array[index] == '\0'
array[index] == "\0"

The first one is comparing a char * to a char, which is not what you want. You would have to do this:

array[index][0] == '\0'

The second one doesn't even work. You're comparing a char * to a char *, yes, but this comparison is meaningless. It passes if the two pointers point to the same piece of memory. You can't use == to compare two strings, you have to use the strcmp() function, because C has no built-in support for strings outside of a few (and I mean few) syntactic niceties. Whereas the following:

array[index] == NULL

Works just fine and conveys your point.

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

You can also just copy the file to GAC using a command prompt. I use the following batch script to copy the DLL and restart IIS.

copy /b/v/y "PathToAssembly\MyAssembly.dll" "C:\Windows\assembly\" 
iisreset /noforce
pause

Saves the need to use or install gacutil

Tracking the script execution time in PHP

Shorter version of talal7860's answer

<?php
// At start of script
$time_start = microtime(true); 

// Anywhere else in the script
echo 'Total execution time in seconds: ' . (microtime(true) - $time_start);

As pointed out, this is 'wallclock time' not 'cpu time'

What is the difference between ports 465 and 587?

SMTP protocol: smtps (port 465) v. msa (port 587)

Ports 465 and 587 are intended for email client to email server communication - sending out email using SMTP protocol.

Port 465 is for smtps
SSL encryption is started automatically before any SMTP level communication.

Port 587 is for msa
It is almost like standard SMTP port. MSA should accept email after authentication (e.g. after SMTP AUTH). It helps to stop outgoing spam when netmasters of DUL ranges can block outgoing connections to SMTP port (port 25).
SSL encryption may be started by STARTTLS command at SMTP level if server supports it and your ISP does not filter server's EHLO reply (reported 2014).


Port 25 is used by MTA to MTA communication (mail server to mail server). It may be used for client to server communication but it is not currently the most recommended. Standard SMTP port accepts email from other mail servers to its "internal" mailboxes without authentication.

excel formula to subtract number of days from a date

Assuming the original date is in cell A1:

=DATE(YEAR(A1), MONTH(A1), DAY(A1)-180)

How to find first element of array matching a boolean condition in JavaScript?

foundElement = myArray[myArray.findIndex(element => //condition here)];

Best way to center a <div> on a page vertically and horizontally?

Using Flex-box in my opinion:

_x000D_
_x000D_
#parent {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}
_x000D_
<div id="parent">_x000D_
  <div id="child">Hello World!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You see there are only three CSS properties that you have to use to center the child element vertically and horizontally. display: center; Do the main part by just activating Flex-box display, justify-content: center; center the child element vertically and align-items: center; center it horizontally. To see the best result I just add some extra styles :

_x000D_
_x000D_
#parent {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  height: 500px;_x000D_
  width: 500px;_x000D_
  background: yellow;_x000D_
}_x000D_
_x000D_
#child {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: silver;_x000D_
}
_x000D_
<div id="parent">_x000D_
  <div id="child">Hello World!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you want to learn more about Flex-box you can visit W3Schools, MDN or CSS-Tricks for more information.

How to refresh materialized view in oracle

try this:

DBMS_SNAPSHOT.REFRESH( 'v_materialized_foo_tbl','f'); 

first parameter is name of mat_view and second defines type of refresh. f denotes fast refresh. but keep this thing in mind it will override any any other refresh timing options.

What is the difference between iterator and iterable and how to use them?

If a collection is iterable, then it can be iterated using an iterator (and consequently can be used in a for each loop.) The iterator is the actual object that will iterate through the collection.

Why can't I display a pound (£) symbol in HTML?

Or for other code equivalents try:

&#163;
&pound;

Redirect with CodeIgniter

If your directory structure is like this,

site
  application
         controller
                folder_1
                   first_controller.php
                   second_controller.php
                folder_2
                   first_controller.php
                   second_controller.php

And when you are going to redirect it in same controller in which you are working then just write the following code.

 $this->load->helper('url');
    if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
    {
         redirect('same_controller/method', 'refresh');
    }

And if you want to redirect to another control then use the following code.

$this->load->helper('url');
if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
{
     redirect('folder_name/any_controller_name/method', 'refresh');
}

Generate an integer sequence in MySQL

If you were using Oracle, 'pipelined functions' would be the way to go. Unfortunately, MySQL has no such construct.

Depending on the scale of the numbers you want sets of, I see two simple ways to go : you either populate a temporary table with just the numbers you need (possibly using memory tables populated by a stored procedure) for a single query or, up front, you build a big table that counts from 1 to 1,000,000 and select bounded regions of it.

const char* concatenation

Connecting two constant char pointer without using strcpy command in the dynamic allocation of memory:

const char* one = "Hello ";
const char* two = "World!";

char* three = new char[strlen(one) + strlen(two) + 1] {'\0'};

strcat_s(three, strlen(one) + 1, one);
strcat_s(three, strlen(one) + strlen(two) + 1, two);

cout << three << endl;

delete[] three;
three = nullptr;

How and when to use ‘async’ and ‘await’

See this fiddle https://dotnetfiddle.net/VhZdLU (and improve it if possible) for running a simple console application which shows usages of Task, Task.WaitAll(), async and await operators in the same program.

This fiddle should clear your execution cycle concept.

Here is the sample code

using System;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {               
        var a = MyMethodAsync(); //Task started for Execution and immediately goes to Line 19 of the code. Cursor will come back as soon as await operator is met       
        Console.WriteLine("Cursor Moved to Next Line Without Waiting for MyMethodAsync() completion");
        Console.WriteLine("Now Waiting for Task to be Finished");       
        Task.WaitAll(a); //Now Waiting      
        Console.WriteLine("Exiting CommandLine");       
    }

    public static async Task MyMethodAsync()
    {
        Task<int> longRunningTask = LongRunningOperation();
        // independent work which doesn't need the result of LongRunningOperationAsync can be done here
        Console.WriteLine("Independent Works of now executes in MyMethodAsync()");
        //and now we call await on the task 
        int result = await longRunningTask;
        //use the result 
        Console.WriteLine("Result of LongRunningOperation() is " + result);
    }

    public static async Task<int> LongRunningOperation() // assume we return an int from this long running operation 
    {
        Console.WriteLine("LongRunningOperation() Started");
        await Task.Delay(2000); // 2 second delay
        Console.WriteLine("LongRunningOperation() Finished after 2 Seconds");
        return 1;
    }   

}

Trace coming from Output Window: enter image description here

How to include External CSS and JS file in Laravel 5

Place your assets in public directory and use the following

URL::to()

example

<link rel="stylesheet" type="text/css" href="{{ URL::to('css/style.css') }}">
<script type="text/javascript" src="{{ URL::to('js/jquery.min.js') }}"></script>

'sprintf': double precision in C

You need to write it like sprintf(aa, "%9.7lf", a)

Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.

Append key/value pair to hash with << in Ruby

I had to do a similar thing but I needed to add values with same keys. When I use merge or update I can't push values with same keys. So I had to use array of hashes.

    my_hash_static = {:header =>{:company => 'xx', :usercode => 'xx', :password => 'xx',
                      :type=> 'n:n', :msgheader => from}, :body=>[]}
    my_hash_dynamic = {:mp=>{:msg=>message, :no=>phones} }        
    my_hash_full = my_hash_static[:body].push my_hash_dynamic

Argparse: Required arguments listed under "optional arguments"?

Since I prefer to list required arguments before optional, I hack around it via:

    parser = argparse.ArgumentParser()
    parser._action_groups.pop()
    required = parser.add_argument_group('required arguments')
    optional = parser.add_argument_group('optional arguments')
    required.add_argument('--required_arg', required=True)
    optional.add_argument('--optional_arg')
    return parser.parse_args()

and this outputs:

usage: main.py [-h] [--required_arg REQUIRED_ARG]
               [--optional_arg OPTIONAL_ARG]

required arguments:
  --required_arg REQUIRED_ARG

optional arguments:
  --optional_arg OPTIONAL_ARG

I can live without 'help' showing up in the optional arguments group.

Number of days between past date and current date in Google spreadsheet

I used your idea, and found the difference and then just divided by 365 days. Worked a treat.

=MINUS(F2,TODAY())/365

Then I shifted my cell properties to not display decimals.

How do I add a ToolTip to a control?

ToolTip in C# is very easy to add to almost all UI controls. You don't need to add any MouseHover event for this.

This is how to do it-

  1. Add a ToolTip object to your form. One object is enough for the entire form. ToolTip toolTip = new ToolTip();

  2. Add the control to the tooltip with the desired text.

    toolTip.SetToolTip(Button1,"Click here");

How can I set selected option selected in vue.js 2?

Handling the errors

You are binding properties to nothing. :required in

<select class="form-control" v-model="selected" :required @change="changeLocation">

and :selected in

<option :selected>Choose Province</option>

If you set the code like so, your errors should be gone:

<template>
  <select class="form-control" v-model="selected" :required @change="changeLocation">
    <option>Choose Province</option>
    <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
 </select>
</template>

Getting the select tags to have a default value

  1. you would now need to have a data property called selected so that v-model works. So,

    {
      data () {
        return {
          selected: "Choose Province"
        }
      }
    }
    
  2. If that seems like too much work, you can also do it like:

    <template>
      <select class="form-control" :required="true" @change="changeLocation">
       <option :selected="true">Choose Province</option>
       <option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>
      </select>
    </template>
    

When to use which method?

  1. You can use the v-model approach if your default value depends on some data property.

  2. You can go for the second method if your default selected value happens to be the first option.

  3. You can also handle it programmatically by doing so:

    <select class="form-control" :required="true">
      <option 
       v-for="option in options" 
       v-bind:value="option.id"
       :selected="option == '<the default value you want>'"
      >{{ option }}</option>
    </select>
    

Make Frequency Histogram for Factor Variables

Country is a categorical variable and I want to see how many occurences of country exist in the data set. In other words, how many records/attendees are from each Country

barplot(summary(df$Country))

How to paste into a terminal?

In Konsole (KDE terminal) is the same, Ctrl + Shift + V

How to convert float value to integer in php?

Use round()

$float_val = 4.5;

echo round($float_val);

You can also set param for precision and rounding mode, for more info

Update (According to your updated question):

$float_val = 1.0000124668092E+14;
printf('%.0f', $float_val / 1E+14); //Output Rounds Of To 1000012466809201

How can I get date and time formats based on Culture Info?

You can retrieve the format strings from the CultureInfo DateTimeFormat property, which is a DateTimeFormatInfo instance. This in turn has properties like ShortDatePattern and ShortTimePattern, containing the format strings:

CultureInfo us = new CultureInfo("en-US");
string shortUsDateFormatString = us.DateTimeFormat.ShortDatePattern;
string shortUsTimeFormatString = us.DateTimeFormat.ShortTimePattern;

CultureInfo uk = new CultureInfo("en-GB");
string shortUkDateFormatString = uk.DateTimeFormat.ShortDatePattern;
string shortUkTimeFormatString = uk.DateTimeFormat.ShortTimePattern;

If you simply want to format the date/time using the CultureInfo, pass it in as your IFormatter when converting the DateTime to a string, using the ToString method:

string us = myDate.ToString(new CultureInfo("en-US"));
string uk = myDate.ToString(new CultureInfo("en-GB"));

Recreate the default website in IIS

You can try to restore your previous state by doing the following:

  1. Go to IIS Manager
  2. Right-click on your Local Computer.
  3. Point to All Tasks
  4. Point to Backup/Restore Configuration
  5. Select the configuration you want to restore
  6. Wait untill configuration applies

how to set radio option checked onload with jQuery

 $("form input:[name=gender]").filter('[value=Male]').attr('checked', true);

How to hide form code from view code/inspect element browser?

you can not stop user from seeing our code but you can avoid it by disabling some keys

simply you can do <body oncontextmenu="return false" onkeydown="return false;" onmousedown="return false;"><!--Your body context--> </body>

After doing this following keys get disabled automatically

1. Ctrl + Shift + U 2. Ctrl + Shift + C 3. Ctrl + Shift + I 4. Right Click of mouse 5. F12 Key

How should a model be structured in MVC?

Disclaimer: the following is a description of how I understand MVC-like patterns in the context of PHP-based web applications. All the external links that are used in the content are there to explain terms and concepts, and not to imply my own credibility on the subject.

The first thing that I must clear up is: the model is a layer.

Second: there is a difference between classical MVC and what we use in web development. Here's a bit of an older answer I wrote, which briefly describes how they are different.

What a model is NOT:

The model is not a class or any single object. It is a very common mistake to make (I did too, though the original answer was written when I began to learn otherwise), because most frameworks perpetuate this misconception.

Neither is it an Object-Relational Mapping technique (ORM) nor an abstraction of database tables. Anyone who tells you otherwise is most likely trying to 'sell' another brand-new ORM or a whole framework.

What a model is:

In proper MVC adaptation, the M contains all the domain business logic and the Model Layer is mostly made from three types of structures:

  • Domain Objects

    A domain object is a logical container of purely domain information; it usually represents a logical entity in the problem domain space. Commonly referred to as business logic.

    This would be where you define how to validate data before sending an invoice, or to compute the total cost of an order. At the same time, Domain Objects are completely unaware of storage - neither from where (SQL database, REST API, text file, etc.) nor even if they get saved or retrieved.

  • Data Mappers

    These objects are only responsible for the storage. If you store information in a database, this would be where the SQL lives. Or maybe you use an XML file to store data, and your Data Mappers are parsing from and to XML files.

  • Services

    You can think of them as "higher level Domain Objects", but instead of business logic, Services are responsible for interaction between Domain Objects and Mappers. These structures end up creating a "public" interface for interacting with the domain business logic. You can avoid them, but at the penalty of leaking some domain logic into Controllers.

    There is a related answer to this subject in the ACL implementation question - it might be useful.

The communication between the model layer and other parts of the MVC triad should happen only through Services. The clear separation has a few additional benefits:

  • it helps to enforce the single responsibility principle (SRP)
  • provides additional 'wiggle room' in case the logic changes
  • keeps the controller as simple as possible
  • gives a clear blueprint, if you ever need an external API

 

How to interact with a model?

Prerequisites: watch lectures "Global State and Singletons" and "Don't Look For Things!" from the Clean Code Talks.

Gaining access to service instances

For both the View and Controller instances (what you could call: "UI layer") to have access these services, there are two general approaches:

  1. You can inject the required services in the constructors of your views and controllers directly, preferably using a DI container.
  2. Using a factory for services as a mandatory dependency for all of your views and controllers.

As you might suspect, the DI container is a lot more elegant solution (while not being the easiest for a beginner). The two libraries, that I recommend considering for this functionality would be Syfmony's standalone DependencyInjection component or Auryn.

Both the solutions using a factory and a DI container would let you also share the instances of various servers to be shared between the selected controller and view for a given request-response cycle.

Alteration of model's state

Now that you can access to the model layer in the controllers, you need to start actually using them:

public function postLogin(Request $request)
{
    $email = $request->get('email');
    $identity = $this->identification->findIdentityByEmailAddress($email);
    $this->identification->loginWithPassword(
        $identity,
        $request->get('password')
    );
}

Your controllers have a very clear task: take the user input and, based on this input, change the current state of business logic. In this example the states that are changed between are "anonymous user" and "logged in user".

Controller is not responsible for validating user's input, because that is part of business rules and controller is definitely not calling SQL queries, like what you would see here or here (please don't hate on them, they are misguided, not evil).

Showing user the state-change.

Ok, user has logged in (or failed). Now what? Said user is still unaware of it. So you need to actually produce a response and that is the responsibility of a view.

public function postLogin()
{
    $path = '/login';
    if ($this->identification->isUserLoggedIn()) {
        $path = '/dashboard';
    }
    return new RedirectResponse($path); 
}

In this case, the view produced one of two possible responses, based on the current state of model layer. For a different use-case you would have the view picking different templates to render, based on something like "current selected of article" .

The presentation layer can actually get quite elaborate, as described here: Understanding MVC Views in PHP.

But I am just making a REST API!

Of course, there are situations, when this is a overkill.

MVC is just a concrete solution for Separation of Concerns principle. MVC separates user interface from the business logic, and it in the UI it separated handling of user input and the presentation. This is crucial. While often people describe it as a "triad", it's not actually made up from three independent parts. The structure is more like this:

MVC separation

It means, that, when your presentation layer's logic is close to none-existent, the pragmatic approach is to keep them as single layer. It also can substantially simplify some aspects of model layer.

Using this approach the login example (for an API) can be written as:

public function postLogin(Request $request)
{
    $email = $request->get('email');
    $data = [
        'status' => 'ok',
    ];
    try {
        $identity = $this->identification->findIdentityByEmailAddress($email);
        $token = $this->identification->loginWithPassword(
            $identity,
            $request->get('password')
        );
    } catch (FailedIdentification $exception) {
        $data = [
            'status' => 'error',
            'message' => 'Login failed!',
        ]
    }

    return new JsonResponse($data);
}

While this is not sustainable, when you have complicate logic for rendering a response body, this simplification is very useful for more trivial scenarios. But be warned, this approach will become a nightmare, when attempting to use in large codebases with complex presentation logic.

 

How to build the model?

Since there is not a single "Model" class (as explained above), you really do not "build the model". Instead you start from making Services, which are able to perform certain methods. And then implement Domain Objects and Mappers.

An example of a service method:

In the both approaches above there was this login method for the identification service. What would it actually look like. I am using a slightly modified version of the same functionality from a library, that I wrote .. because I am lazy:

public function loginWithPassword(Identity $identity, string $password): string
{
    if ($identity->matchPassword($password) === false) {
        $this->logWrongPasswordNotice($identity, [
            'email' => $identity->getEmailAddress(),
            'key' => $password, // this is the wrong password
        ]);

        throw new PasswordMismatch;
    }

    $identity->setPassword($password);
    $this->updateIdentityOnUse($identity);
    $cookie = $this->createCookieIdentity($identity);

    $this->logger->info('login successful', [
        'input' => [
            'email' => $identity->getEmailAddress(),
        ],
        'user' => [
            'account' => $identity->getAccountId(),
            'identity' => $identity->getId(),
        ],
    ]);

    return $cookie->getToken();
}

As you can see, at this level of abstraction, there is no indication of where the data was fetched from. It might be a database, but it also might be just a mock object for testing purposes. Even the data mappers, that are actually used for it, are hidden away in the private methods of this service.

private function changeIdentityStatus(Entity\Identity $identity, int $status)
{
    $identity->setStatus($status);
    $identity->setLastUsed(time());
    $mapper = $this->mapperFactory->create(Mapper\Identity::class);
    $mapper->store($identity);
}

Ways of creating mappers

To implement an abstraction of persistence, on the most flexible approaches is to create custom data mappers.

Mapper diagram

From: PoEAA book

In practice they are implemented for interaction with specific classes or superclasses. Lets say you have Customer and Admin in your code (both inheriting from a User superclass). Both would probably end up having a separate matching mapper, since they contain different fields. But you will also end up with shared and commonly used operations. For example: updating the "last seen online" time. And instead of making the existing mappers more convoluted, the more pragmatic approach is to have a general "User Mapper", which only update that timestamp.

Some additional comments:

  1. Database tables and model

    While sometimes there is a direct 1:1:1 relationship between a database table, Domain Object, and Mapper, in larger projects it might be less common than you expect:

    • Information used by a single Domain Object might be mapped from different tables, while the object itself has no persistence in the database.

      Example: if you are generating a monthly report. This would collect information from different of tables, but there is no magical MonthlyReport table in the database.

    • A single Mapper can affect multiple tables.

      Example: when you are storing data from the User object, this Domain Object could contain collection of other domain objects - Group instances. If you alter them and store the User, the Data Mapper will have to update and/or insert entries in multiple tables.

    • Data from a single Domain Object is stored in more than one table.

      Example: in large systems (think: a medium-sized social network), it might be pragmatic to store user authentication data and often-accessed data separately from larger chunks of content, which is rarely required. In that case you might still have a single User class, but the information it contains would depend of whether full details were fetched.

    • For every Domain Object there can be more than one mapper

      Example: you have a news site with a shared codebased for both public-facing and the management software. But, while both interfaces use the same Article class, the management needs a lot more info populated in it. In this case you would have two separate mappers: "internal" and "external". Each performing different queries, or even use different databases (as in master or slave).

  2. A view is not a template

    View instances in MVC (if you are not using the MVP variation of the pattern) are responsible for the presentational logic. This means that each View will usually juggle at least a few templates. It acquires data from the Model Layer and then, based on the received information, chooses a template and sets values.

    One of the benefits you gain from this is re-usability. If you create a ListView class, then, with well-written code, you can have the same class handing the presentation of user-list and comments below an article. Because they both have the same presentation logic. You just switch templates.

    You can use either native PHP templates or use some third-party templating engine. There also might be some third-party libraries, which are able to fully replace View instances.

  3. What about the old version of the answer?

    The only major change is that, what is called Model in the old version, is actually a Service. The rest of the "library analogy" keeps up pretty well.

    The only flaw that I see is that this would be a really strange library, because it would return you information from the book, but not let you touch the book itself, because otherwise the abstraction would start to "leak". I might have to think of a more fitting analogy.

  4. What is the relationship between View and Controller instances?

    The MVC structure is composed of two layers: ui and model. The main structures in the UI layer are views and controller.

    When you are dealing with websites that use MVC design pattern, the best way is to have 1:1 relation between views and controllers. Each view represents a whole page in your website and it has a dedicated controller to handle all the incoming requests for that particular view.

    For example, to represent an opened article, you would have \Application\Controller\Document and \Application\View\Document. This would contain all the main functionality for UI layer, when it comes to dealing with articles (of course you might have some XHR components that are not directly related to articles).

Quicksort with Python

def sort(array=[12,4,5,6,7,3,1,15]):
    """Sort the array by using quicksort."""

    less = []
    equal = []
    greater = []

    if len(array) > 1:
        pivot = array[0]
        for x in array:
            if x < pivot:
                less.append(x)
            elif x == pivot:
                equal.append(x)
            elif x > pivot:
                greater.append(x)
        # Don't forget to return something!
        return sort(less)+equal+sort(greater)  # Just use the + operator to join lists
    # Note that you want equal ^^^^^ not pivot
    else:  # You need to handle the part at the end of the recursion - when you only have one element in your array, just return the array.
        return array

How to change line width in ggplot?

It also looks like if you just put the size argument in the geom_line() portion but without the aes() it will scale appropriately. At least it works this way with geom_density and I had the same problem.

How to start nginx via different port(other than 80)

If you are on windows then below port related server settings are present in file nginx.conf at < nginx installation path >/conf folder.

server {
    listen       80;
    server_name  localhost;
....

Change the port number and restart the instance.

How to convert a column of DataTable to a List

I do just like below, after you set your column AsEnumarable you can sort, order or how you want.

 _dataTable.AsEnumerable().Select(p => p.Field<string>("ColumnName")).ToList();

How to work on UAC when installing XAMPP

This is a specific issue for Windows Vista, 7, 8 (and presumably newer).

User Account Control (UAC) is a feature in Windows that can help you stay in control of your computer by informing you when a program makes a change that requires administrator-level permission. UAC works by adjusting the permission level of your user account.

This is applied mostly to C:\Program Files. You may have noticed sometimes, that some applications can see files in C:\Program Files that does not exist there. You know why? Windows now tend to have "C:\Program Files" folder customized for every user. For example, old applications store config files (like .ini) in the same folder where the executable files are stored. In the good old days all users had the same configurations for such apps. In nowadays Windows stores configs in the special folder tied to the user account. Thus, now different users may have different configs while application still think that config files are in the same folder with the executables.

XAMPP does not like to have different config for different users. In fact it is not a config file for XAMPP, it is folders where you keep your projects and databases. The idea of XAMPP is to make projects same for all users. This is a source of a conflict with Windows.

All you need is to avoid installing XAMPP into C:\Program Files. Thus XAMPP will always use the original files for all users and there would be no confusion.

I recommend to install XAMPP into the special folder in root directory like in C:\XAMPP. But before you choose the folder you need to click on this warning message.

ASP.Net which user account running Web Service on IIS 7?

Look at the Identity of the Application Pool that's running your application. By default it will be the Network Service account, but you can change this.

At least that's how it works on 2003 server, don't know if some details have changed for 2008 server.

What does $(function() {} ); do?

The following is a jQuery function call:

$(...);

Which is the "jQuery function." $ is a function, and $(...) is you calling that function.

The first parameter you've supplied is the following:

function() {}

The parameter is a function that you specified, and the $ function will call the supplied method when the DOM finishes loading.

Positive Number to Negative Number in JavaScript?

Javascript has a dedicated operator for this: unary negation.

TL;DR: It's the minus sign!

To negate a number, simply prefix it with - in the most intuitive possible way. No need to write a function, use Math.abs() multiply by -1 or use the bitwise operator.

Unary negation works on number literals:

let a = 10;  // a is `10`
let b = -10; // b is `-10`

It works with variables too:

let x = 50;
x = -x;      // x is now `-50`

let y = -6;
y = -y;      // y is now `6`

You can even use it multiple times if you use the grouping operator (a.k.a. parentheses:

l = 10;       // l is `10`
m = -10;      // m is `-10`
n = -(10);    // n is `-10`
o = -(-(10)); // o is `10`
p = -(-10);   // p is `10` (double negative makes a positive)

All of the above works with a variable as well.

How to delete the contents of a folder?

Using rmtree and recreating the folder could work, but I have run into errors when deleting and immediately recreating folders on network drives.

The proposed solution using walk does not work as it uses rmtree to remove folders and then may attempt to use os.unlink on the files that were previously in those folders. This causes an error.

The posted glob solution will also attempt to delete non-empty folders, causing errors.

I suggest you use:

folder_path = '/path/to/folder'
for file_object in os.listdir(folder_path):
    file_object_path = os.path.join(folder_path, file_object)
    if os.path.isfile(file_object_path) or os.path.islink(file_object_path):
        os.unlink(file_object_path)
    else:
        shutil.rmtree(file_object_path)

How can I sort a List alphabetically?

Use the two argument for of Collections.sort. You will want a suitable Comparator that treats case appropriate (i.e. does lexical, not UTF16 ordering), such as that obtainable through java.text.Collator.getInstance.

How to change SmartGit's licensing option after 30 days of commercial use on ubuntu?

on Mac:

  • First goto ~/Library/Preferences/SmartGit/19.1
  • Second goto preferences.yml file and just comment listx line
  • Third open smart git

When to use Comparable and Comparator

I have been asked sorting of a definite range of numbers in better than nlogn time in one of interview. (Not using Counting sort)

Implementing Comparable interface over an object allows implicit sorting algos to use overridden compareTo method to order sort elements and that would be linear time.

What does "Table does not support optimize, doing recreate + analyze instead" mean?

The better option is create a new table copy the rows to the destination table, drop the actual table and rename the newly created table . This method is good for small tables,

Add/remove HTML inside div using JavaScript

Add HTML inside div using JavaScript

Syntax:

element.innerHTML += "additional HTML code"

or

element.innerHTML = element.innerHTML + "additional HTML code"

Remove HTML inside div using JavaScript

elementChild.remove();

Failed to build gem native extension — Rails install

mkmf is part of the ruby1.9.1-dev package. This package contains the header files needed for extension libraries for Ruby 1.9.1. You need to install the ruby1.9.1-dev package by doing:

sudo apt-get install ruby1.9.1-dev

Then you can install Rails as per normal.

Generally it's easier to just do:

sudo apt-get install ruby-dev

jQuery Event Keypress: Which key was pressed?

$(document).bind('keypress', function (e) {
    console.log(e.which);  //or alert(e.which);

});

you should have firbug to see a result in console

Reduce git repository size

This should not affect everyone, but one of the semi-hidden reasons of the repository size being large could be Git submodules.

You might have added one or more submodules, but stopped using it at some time, and some files remained in .git/modules directory. To make redundant submodule files gone away, see this question.

However, just like the main repository, the other way is to navigate to the submodule directory in .git/modules, and do a, for example, git gc --aggressive --prune.

These should have a good impact in the repository size, but as long as you use Git submodules, e.g. especially with large libraries, your repository size should not change drastically.

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

There is a special security expression in spring security:

hasAnyRole(list of roles) - true if the user has been granted any of the roles specified (given as a comma-separated list of strings).

I have never used it but I think it is exactly what you are looking for.

Example usage:

<security:authorize access="hasAnyRole('ADMIN', 'DEVELOPER')">
    ...
</security:authorize>

Here is a link to the reference documentation where the standard spring security expressions are described. Also, here is a discussion where I described how to create custom expression if you need it.

Android draw a Horizontal line between views

If you does not want to use an extra view just for underlines. Add this style on your textView.

style="?android:listSeparatorTextViewStyle"

Just down side is it will add extra properties like

android:textStyle="bold"
android:textAllCaps="true"

which you can easily override.

How to submit form on change of dropdown list?

Just ask assistance of JavaScript.

<select onchange="this.form.submit()">
    ...
</select>

See also:

Send email with PHPMailer - embed image in body

According to PHPMailer Manual, full answer would be :

$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg '); 

Use Case :

$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';

If you want to display an image with a remote URL :

$mail->addStringAttachment(file_get_contents("url"), "filename");

Oracle SQL, concatenate multiple columns + add text

The Oracle/PLSQL CONCAT function allows to concatenate two strings together.

CONCAT( string1, string2 )

string1

The first string to concatenate.

string2

The second string to concatenate.

E.g.

SELECT 'I like ' || type_column_name || ' cake with ' || 
icing_column_name || ' and a ' fruit_column_name || '.' 
AS Cake FROM table;

how to start stop tomcat server using CMD?

I have just downloaded Tomcat and want to stop it (Windows).

  1. To stop tomcat

    • run cmd as administrator (I used Cmder)

    • find process ID

tasklist /fi "Imagename eq tomcat*"

C:\Users\Admin
tasklist /fi "Imagename eq tomcat*"

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
Tomcat8aaw.exe                6376 Console                    1      7,300 K
Tomcat8aa.exe                 5352 Services                   0    124,748 K
  • stop prosess with pid 6376

C:\Users\Admin

taskkill /f /pid 6376

SUCCESS: The process with PID 6376 has been terminated.

  • stop process with pid 5352

C:\Users\Admin

taskkill /f /pid 5352

SUCCESS: The process with PID 5352 has been terminated.

Remap values in pandas column with a dict

Given map is faster than replace (@JohnE's solution) you need to be careful with Non-Exhaustive mappings where you intend to map specific values to NaN. The proper method in this case requires that you mask the Series when you .fillna, else you undo the mapping to NaN.

import pandas as pd
import numpy as np

d = {'m': 'Male', 'f': 'Female', 'missing': np.NaN}
df = pd.DataFrame({'gender': ['m', 'f', 'missing', 'Male', 'U']})

keep_nan = [k for k,v in d.items() if pd.isnull(v)]
s = df['gender']

df['mapped'] = s.map(d).fillna(s.mask(s.isin(keep_nan)))

    gender  mapped
0        m    Male
1        f  Female
2  missing     NaN
3     Male    Male
4        U       U

Dynamic creation of table with DOM

var html = "";
    for (var i = 0; i < data.length; i++){
    html +="<tr>"+
            "<td>"+ (i+1) + "</td>"+
            "<td>"+ data[i].name + "</td>"+
            "<td>"+ data[i].number + "</td>"+
            "<td>"+ data[i].city + "</td>"+
            "<td>"+ data[i].hobby + "</td>"+
            "<td>"+ data[i].birthdate + "</td>"+"<td><button data-arrayIndex='"+ i +"' onclick='editData(this)'>Edit</button><button data-arrayIndex='"+ i +"' onclick='deleteData()'>Delete</button></td>"+"</tr>";
}
$("#tableHtml").html(html);

Just disable scroll not hide it?

I had a similar problem: a left-hand menu that, when it appears, prevents scrolling. As soon as height was set to 100vh, the scrollbar disappeared and the content jerked to the right.

So if you don't mind keeping the scrollbar enabled (but setting the window to full height so it won't actually scroll anywhere) then another possibility is setting a tiny bottom margin, which will keep the scroll bars showing:

body {
    height: 100vh;
    overflow: hidden;
    margin: 0 0 1px;
}

Scala best way of turning a Collection into a Map-by-key?

This can be implemented immutably and with a single traversal by folding through the collection as follows.

val map = c.foldLeft(Map[P, T]()) { (m, t) => m + (t.getP -> t) }

The solution works because adding to an immutable Map returns a new immutable Map with the additional entry and this value serves as the accumulator through the fold operation.

The tradeoff here is the simplicity of the code versus its efficiency. So, for large collections, this approach may be more suitable than using 2 traversal implementations such as applying map and toMap.

Alert handling in Selenium WebDriver (selenium 2) with Java

Write the following method:

public boolean isAlertPresent() {
    try {
        driver.switchTo().alert();
        return true;
    } // try
    catch (Exception e) {
        return false;
    } // catch
}

Now, you can check whether alert is present or not by using the method written above as below:

if (isAlertPresent()) {
    driver.switchTo().alert();
    driver.switchTo().alert().accept();
    driver.switchTo().defaultContent();
}

Finding all objects that have a given property inside a collection

Just FYI there are 3 other answers given to this question that use Guava, but none answer the question. The asker has said he wishes to find all Cats with a matching property, e.g. age of 3. Iterables.find will only match one, if any exist. You would need to use Iterables.filter to achieve this if using Guava, for example:

Iterable<Cat> matches = Iterables.filter(cats, new Predicate<Cat>() {
    @Override
    public boolean apply(Cat input) {
        return input.getAge() == 3;
    }
});

What is the right way to check for a null string in Objective-C?

I have found that in order to really do it right you end up having to do something similar to

if ( ( ![myString isEqual:[NSNull null]] ) && ( [myString length] != 0 ) ) {
}

Otherwise you get weird situations where control will still bypass your check. I haven't come across one that makes it past the isEqual and length checks.

Call to undefined method mysqli_stmt::get_result

I was getting this same error on my server - PHP 7.0 with the mysqlnd extension already enabled.

Solution was for me (thanks to this page) was to deselect the mysqli extension and select nd_mysqli instead.

NB - You may be able to access the extensions selector in your cPanel. (I access mine via the Select PHP Version option.)

Responsive image map

Similar to Orland's answer here: https://stackoverflow.com/a/32870380/462781

Combined with Chris' code here: https://stackoverflow.com/a/12121309/462781

If the areas fit in a grid you can overlay the areas by transparent pictures using a width in % that keep their aspect ratio.

_x000D_
_x000D_
    .wrapperspace {_x000D_
      width: 100%;_x000D_
      display: inline-block;_x000D_
      position: relative;_x000D_
    }_x000D_
    .mainspace {_x000D_
      position: absolute;_x000D_
      top: 0;_x000D_
      bottom: 0;_x000D_
      right: 0;_x000D_
      left: 0;_x000D_
    }
_x000D_
<div class="wrapperspace">_x000D_
 <img style="float: left;" title="" src="background-image.png" width="100%" />_x000D_
 <div class="mainspace">_x000D_
     <div>_x000D_
         <img src="space-top.png" style="margin-left:6%;width:15%;"/>_x000D_
     </div>_x000D_
     <div>_x000D_
       <a href="http://www.example.com"><img src="space-company.png" style="margin-left:6%;width:15%;"></a>_x000D_
     </div>_x000D_
  <div>_x000D_
   <a href="http://www.example.com"><img src="space-company.png" style="margin-left:6%;width:10%;"></a>_x000D_
   <a href="http://www.example.com"><img src="space-company.png" style="width:20%;"></a>_x000D_
  </div>_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can use a margin in %. Additionally "space" images can be placed next to each other inside a 3rd level div.

How to generate a git patch for a specific commit?

Say you have commit id 2 after commit 1 you would be able to run:

git diff 2 1 > mypatch.diff

where 2 and 1 are SHA hashes.

Can we update primary key values of a table?

From a relational database theory point of view, there should be absolutely no problem on updating the primary key of a table, provided that there are no duplicates among the primary keys and that you do not try to put a NULL value in any of the primary key columns.

How to view the current heap size that an application is using?

public class CheckHeapSize {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        long heapSize = Runtime.getRuntime().totalMemory(); 

        // Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
        long heapMaxSize = Runtime.getRuntime().maxMemory();

         // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
        long heapFreeSize = Runtime.getRuntime().freeMemory(); 

        System.out.println("heapsize"+formatSize(heapSize));
        System.out.println("heapmaxsize"+formatSize(heapMaxSize));
        System.out.println("heapFreesize"+formatSize(heapFreeSize));

    }
    public static String formatSize(long v) {
        if (v < 1024) return v + " B";
        int z = (63 - Long.numberOfLeadingZeros(v)) / 10;
        return String.format("%.1f %sB", (double)v / (1L << (z*10)), " KMGTPE".charAt(z));
    }
}

CertificateException: No name matching ssl.someUrl.de found

In Java 8 you can skip server name checking with the following code:

HttpsURLConnection.setDefaultHostnameVerifier ((hostname, session) -> true);

However this should be used only in development!

clear table jquery

Use .remove()

$("#yourtableid tr").remove();

If you want to keep the data for future use even after removing it then you can use .detach()

$("#yourtableid tr").detach();

If the rows are children of the table then you can use child selector instead of descendant selector, like

$("#yourtableid > tr").remove();

How to delete from multiple tables in MySQL?

The syntax looks right to me ... try to change it to use INNER JOIN ...

Have a look at this.

ImportError: No module named MySQLdb

Or try this:

apt-get install python-mysqldb

SQL Case Sensitive String Compare

Select * from a_table where attribute = 'k' COLLATE Latin1_General_CS_AS 

Did the trick.

MySQL Multiple Where Clause

select unique red24.image_id from 
( 
    select image_id from `list` where style_id = 24 and style_value = 'red' 
) red24
inner join 
( 
    select image_id from `list` where style_id = 25 and style_value = 'big' 
) big25
on red24.image_id = big25.image_id
inner join 
( 
    select image_id from `list` where style_id = 27 and style_value = 'round' 
) round27
on red24.image_id = round27.image_id

UICollectionView spacing margins

You can use the collectionView:layout:insetForSectionAtIndex: method for your UICollectionView or set the sectionInset property of the UICollectionViewFlowLayout object attached to your UICollectionView:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(top, left, bottom, right);
}

or

UICollectionViewFlowLayout *aFlowLayout = [[UICollectionViewFlowLayout alloc] init];
[aFlowLayout setSectionInset:UIEdgeInsetsMake(top, left, bottom, right)];

Updated for Swift 5

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
       return UIEdgeInsets(top: 25, left: 15, bottom: 0, right: 5)
    }

Unable to import a module that is definitely installed

As a friend did for me today, here is what helped me (I am using Windows):

Press 'Setting' -> 'Project' -> 'Project Interpreter'. Here in the window on the right, there is a line with the title 'Project Interpreter' on it's left. Click this line and it will open several additional lines.

Now press the 'Show All' line. A window will open. In this window press the small '+' sign in the upper right corner.

A new window will open. On the left there are 4 tabs, press the most upper one, which says 'Virtualenv Environment'. Now, in the window on the right, mark the 'Existing Environment' option. The 'Interpreter' line will become well visible. Press the '...' button on the right of the line.

Now, a browsing window will open. Browse to the directory that you installed Python itself in. Not the one with PyCharm. When you get there, choose the 'python.exe' file and press OK (the window will disappear).

Press OK again (this window will disappear too).

Now in this window make sure the new line you created is marked, and press OK again.

Now, all the installed packages should be visible in the project interpreter, and are read by your program.

Specifying a custom DateTime format when serializing with Json.Net

There is another solution I've been using. Just create a string property and use it for json. This property wil return date properly formatted.

class JSonModel {
    ...

    [JsonIgnore]
    public DateTime MyDate { get; set; }

    [JsonProperty("date")]
    public string CustomDate {
        get { return MyDate.ToString("ddMMyyyy"); }
        // set { MyDate = DateTime.Parse(value); }
        set { MyDate = DateTime.ParseExact(value, "ddMMyyyy", null); }
    }

    ...
}

This way you don't have to create extra classes. Also, it allows you to create diferent data formats. e.g, you can easily create another Property for Hour using the same DateTime.

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

How to increase editor font size?

By default, Android Studio doesn't allow the normal CTRL + Mouse scroll to zoom in or out. You can enable it in the settings, though it seems its location has changed over time. Mac users are well documented in other answers, but I use Windows.

For Windows users in Android Studio 3.4, you go to File -> Settings -> General, then check the box Change font size (Zoom) with Ctrl+Mouse Wheel. See below:

enter image description here