Programs & Examples On #Sonatype

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

Running ./gradlew assembleDebug command on Android Studio Terminal had solved my problem.

Why am I getting a "401 Unauthorized" error in Maven?

Failed to transfer file:
http://mcpappxxxp.dev.chx.s.com:18080/artifactory/mcprepo-release-local/Shop/loyalty-telluride/01.16.03/loyalty-tell-01.16.03.jar.
Return code is: 401, ReasonPhrase: Unauthorized. -> [Help 1]

Solution:

In this case you need to change the version in the pom file, and try to use a new version.

Here 01.16.03 already exist so it was failing and when i have tried with the 01.16.04 version the job went successful.

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

  • Download maven compiler plugin jar from your central repositoy n try
  • If it is still failing check your jdk version, it is because of your application is built on diff jdk version

Hosting a Maven repository on github

Another alternative is to use any web hosting with webdav support. You will need some space for this somewhere of course but it is straightforward to set up and a good alternative to running a full blown nexus server.

add this to your build section

     <extensions>
        <extension>
        <artifactId>wagon-webdav-jackrabbit</artifactId>
        <groupId>org.apache.maven.wagon</groupId>
        <version>2.2</version>
        </extension>
    </extensions>

Add something like this to your distributionManagement section

<repository>
    <id>release.repo</id>
    <url>dav:http://repo.jillesvangurp.com/releases/</url>
</repository>

Finally make sure to setup the repository access in your settings.xml

add this to your servers section

    <server>
        <id>release.repo</id>
        <username>xxxx</username>
        <password>xxxx</password>
    </server>

and a definition to your repositories section

            <repository>
                <id>release.repo</id>
                <url>http://repo.jillesvangurp.com/releases</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>

Finally, if you have any standard php hosting, you can use something like sabredav to add webdav capabilities.

Advantages: you have your own maven repository Downsides: you don't have any of the management capabilities in nexus; you need some webdav setup somewhere

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

As Nayan said the Path has to updated properly in my case the apache-maven was installed in C:\apache-maven and settings.xml was found inside C:\apache-maven\conf\settings.xml

if this doesn't work go to your local repos
in my case C:\Users\<<"name">>.m2\
and search for .lastUpdated and delete them
then build the maven

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

Right Click on Project -> Maven -> Update Project -> Select Force update of snapshot

Or

Navigate to project root folder and use following commands :

mvn clean install -U or mvn clean install --update-snapshots

Here -U will Forces a check for missing releases and updated snapshots on remote repositories

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

Make sure you have settings.xml. I had the same problem when I've deleted it by mistake.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

I was getting the same issue.

I just installed the m2e (Maven2Eclipse)plugin from below site:

http://www.eclipse.org/m2e/

Eclipse>Help>Install New Software>Available Software Sites>Add

Name: m2e (any name is OK)
Location:m2e - http://download.eclipse.org/technology/m2e/releases/

Under Install Window> Work with:

Select this new location and Add all the plugins that appear. Eclipse restart and it was running properly with no previous errors.

Installing Apache Maven Plugin for Eclipse

Installing m2eclipse

All downloads are provided under the terms and conditions of the Eclipse Foundation Software User Agreement unless otherwise specified.

m2e is tested against Eclipse 4.2 (Juno) and 4.3 (Kepler).

See http://wiki.eclipse.org/M2E_updatesite_and_gittags for detailed information about available builds and m2e build repository layout.

m2e 1.3 and earlier version have been removed from the main m2e update site. These old releases are still available and can be installed from repositories documented in http://wiki.eclipse.org/M2E_updatesite_and_gittags

Please note that links below point at Eclipse p2 repositories; you must access them from Eclipse (see how). Update Sites Latest m2e release (recommended) http://download.eclipse.org/technology/m2e/releases m2e milestone builds towards version 1.5 http://download.eclipse.org/technology/m2e/milestones/1.5 Latest m2e 1.5 SNAPSHOT build (not tested, not hosted at eclipse.org) http://repository.takari.io:8081/nexus/content/sites/m2e.extras/m2e/1.5.0/N/LATEST/

Maven: The packaging for this project did not assign a file to the build artifact

This error shows up when using the maven-install-plugin version 3.0.0-M1 (or similar)

As already mentioned above and also here the following plug-in version works:

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.5.2</version>
    </plugin>

Maven: repository element was not specified in the POM inside distributionManagement?

The ID of the two repos are both localSnap; that's probably not what you want and it might confuse Maven.

If that's not it: There might be more repository elements in your POM. Search the output of mvn help:effective-pom for repository to make sure the number and place of them is what you expect.

How to update maven repository in Eclipse?

In newer versions of Eclipse that use the M2E plugin it is:

Right-click on your project(s) --> Maven --> Update Project...

In the following dialog is a checkbox for forcing the update ("Force Update of Snapshots/Releases")

How can the default node version be set using NVM?

Lets say to want to make default version as 10.19.0.

nvm alias default v10.19.0

But it will give following error

! WARNING: Version 'v10.19.0' does not exist.
default -> v10.19.0 (-> N/A)

In That case you need to run two commands in the following order

# Install the version that you would like 
nvm install 10.19.0

# Set 10.19.0 (or another version) as default
nvm alias default 10.19.0

Toggle show/hide on click with jQuery

The toggle-event is deprecated in version 1.8, and removed in version 1.9

Try this...

$('#myelement').toggle(
   function () {
      $('#another-element').show("slide", {
          direction: "right"
      }, 1000);
   },
   function () {
      $('#another-element').hide("slide", {
          direction: "right"
      }, 1000);
});

Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed, jQuery docs.

The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element, jQuery docs

You toggle between visibility using show and hide with click. You can put condition on visibility if element is visible then hide else show it. Note you will need jQuery UI to use addition effects with show / hide like direction.

Live Demo

$( "#myelement" ).click(function() {     
    if($('#another-element:visible').length)
        $('#another-element').hide("slide", { direction: "right" }, 1000);
    else
        $('#another-element').show("slide", { direction: "right" }, 1000);        
});

Or, simply use toggle instead of click. By using toggle you wont need a condition (if-else) statement. as suggested by T.J.Crowder.

Live Demo

$( "#myelement" ).click(function() {     
   $('#another-element').toggle("slide", { direction: "right" }, 1000);
});

Get size of an Iterable in Java

You can cast your iterable to a list then use .size() on it.

Lists.newArrayList(iterable).size();

For the sake of clarity, the above method will require the following import:

import com.google.common.collect.Lists;

node.js vs. meteor.js what's the difference?

Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.

Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).

So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...

Best way to resolve file path too long exception

this may be also possibly solution.It some times also occurs when you keep your Development project into too deep, means may be possible project directory may have too many directories so please don't make too many directories keep it in a simple folder inside the drives. For Example- I was also getting this error when my project was kept like this-

D:\Sharad\LatestWorkings\GenericSurveyApplication020120\GenericSurveyApplication\GenericSurveyApplication

then I simply Pasted my project inside

D:\Sharad\LatestWorkings\GenericSurveyApplication

And Problem was solved.

Javascript Print iframe contents only

I had issues with all of the above solutions in IE8, have found a decent workaround that is tested in IE 8+9, Chrome, Safari and Firefox. For my situation i needed to print a report that was generated dynamically:

// create content of iframe
var content = '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'+
'<head><link href="/css/print.css" media="all" rel="stylesheet" type="text/css"></head>'+
'<body>(rest of body content)'+
'<script type="text/javascript">function printPage() { window.focus(); window.print();return; }</script>'+
'</body></html>';

Note the printPage() javascript method before the body close tag.

Next create the iframe and append it to the parent body so its contentWindow is available:

var newIframe = document.createElement('iframe');
newIframe.width = '0';
newIframe.height = '0';
newIframe.src = 'about:blank';
document.body.appendChild(newIframe);

Next set the content:

newIframe.contentWindow.contents = content;
newIframe.src = 'javascript:window["contents"]';

Here we are setting the dynamic content variable to the iframe's window object then invoking it via the javascript: scheme.

Finally to print; focus the iframe and call the javascript printPage() function within the iframe content:

newIframe.focus();
setTimeout(function() {
  newIframe.contentWindow.printPage();
}, 200);
return;

The setTimeout is not necessarily needed, however if you're loading large amounts of content i found Chrome occasionally failed to print without it so this step is recommended. The alternative is to wrap 'newIframe.contentWindow.printPage();' in a try catch and place the setTimeout wrapped version in the catch block.

Hope this helps someone as i spent a lot of time finding a solution that worked well across multiple browsers. Thanks to SpareCycles.

EDIT:

Instead of using setTimeout to call the printPage function use the following:

newIframe.onload = function() {
    newIframe.contentWindow.printPage();
}

EOFError: end of file reached issue with Net::HTTP

I had a similar problem with a request to a non-SSL service.

This blog suggested vaguely to try URI encoding the URL that is passed to 'get': http://www.loudthinking.org/2010/02/ruby-eoferror-end-of-file-reached.html

I took a shot at it, based on desperation, and in my limiting testing this seems to have fixed it for me. My new code is:

@http = Net::HTTP.new('domain.com')  
@http = @http.start    
url = 'http://domain.com/requested_url?blah=blah&etc=1'
req = Net::HTTP::Get.new(URI.encode(url))
req.basic_auth USERNAME, API_KEY
res = @http.request(req) 

Note that I use @http.start as I want to maintain the HTTP session over multiple requests. Other than that, you might like to try the most relevant part which is: URI.encode(url) inside the get call

Fatal error: Out of memory, but I do have plenty of memory (PHP)

this happened to me a few days ago. I did a fresh installation and it still happened. as far as everyone sees and based on your server specs. most likely it is an infinite loop. it could be not on the PHP code itself but on the requests made to Apache.

lets say when you access this url http://localhost/mysite/page_with_multiple_requests

Check your Apache's access log if it receives multiple requests. trace that request and check out the code that might cause a 'bottleneck' to the system (mine's exec() when using sendmail). The bottleneck im talking about doesn't need to be an 'infinite loop'. It could be a function that takes sometime to finish. or maybe some of php's 'program execution functions'

You might need to check ajax requests too (the ones that execute when the page loads). if that ajax request redirects to the same url

e.g. httpx://localhost/mysite/page_with_multiple_requests

it would 'redo' the requests all over again

it would help if you post the random lines or the code itself where the script ends maybe there is a 'loop' code somewhere there. imho php won't just call random lines for nothing.

http://blog.piratelufi.com/2012/08/browser-sending-multiple-requests-at-once/

Cannot read property 'length' of null (javascript)

I tried this:

if(capital !== null){ 
//Capital has something 
}

How to import a module given the full path?

you can do this using __ import __ and chdir

def import_file(full_path_to_module):
    try:
        import os
        module_dir, module_file = os.path.split(full_path_to_module)
        module_name, module_ext = os.path.splitext(module_file)
        save_cwd = os.getcwd()
        os.chdir(module_dir)
        module_obj = __import__(module_name)
        module_obj.__file__ = full_path_to_module
        globals()[module_name] = module_obj
        os.chdir(save_cwd)
    except Exception as e:
        raise ImportError(e)
    return module_obj


import_file('/home/somebody/somemodule.py')

Find size of an array in Perl

As numerous answers pointed out, the first and third way are the correct methods to get the array size, and the second way is not.

Here I expand on these answers with some usage examples.

@array_name evaluates to the length of the array = the size of the array = the number of elements in the array, when used in a scalar context.

Below are some examples of a scalar context, such as @array_name by itself inside if or unless, of in arithmetic comparisons such as == or !=.

All of these examples will work if you change @array_name to scalar(@array_name). This would make the code more explicit, but also longer and slightly less readable. Therefore, more idiomatic usage omitting scalar() is preferred here.

my @a = (undef, q{}, 0, 1);

# All of these test whether 'array' has four elements:
print q{array has four elements} if @a == 4;
print q{array has four elements} unless @a != 4;
@a == 4 and print q{array has four elements};
!(@a != 4) and print q{array has four elements};

# All of the above print:
# array has four elements

# All of these test whether array is not empty:
print q{array is not empty} if @a;
print q{array is not empty} unless !@a;
@a and print q{array is not empty};
!(!@a) and print q{array is not empty};

# All of the above print:
# array is not empty

javascript get child by id

document.getElementById('child') should return you the correct element - remember that id's need to be unique across a document to make it valid anyway.

edit : see this page - ids MUST be unique.

edit edit : alternate way to solve the problem :

<div onclick="test('child1')">
    Test
    <div id="child1">child</div>
</div>

then you just need the test() function to look up the element by id that you passed in.

How to pass boolean parameter value in pipeline to downstream jobs?

Assuming

value: update_composer

was the issue, try

value: Boolean.valueOf(update_composer)

is there a less cumbersome way in which I can just pass ALL the pipeline parameters to the downstream job

Not that I know of, at least not without using Jenkins API calls and disabling the Groovy sandbox.

Convert IQueryable<> type object to List<T> type?

Add the following:

using System.Linq

...and call ToList() on the IQueryable<>.

How to create radio buttons and checkbox in swift (iOS)?

A very simple checkbox control.

 @IBAction func btn_box(sender: UIButton) {
    if (btn_box.selected == true)
    {
        btn_box.setBackgroundImage(UIImage(named: "box"), forState: UIControlState.Normal)

            btn_box.selected = false;
    }
    else
    {
        btn_box.setBackgroundImage(UIImage(named: "checkBox"), forState: UIControlState.Normal)

        btn_box.selected = true;
    }
}

How to convert Calendar to java.sql.Date in Java?

Did you try cal.getTime()? This gets the date representation.

You might also want to look at the javadoc.

How can I add new item to the String array?

String a []=new String[1];

  a[0].add("kk" );
  a[1].add("pp");

Try this one...

How do you compare structs for equality in C?

You can't use memcmp to compare structs for equality due to potential random padding characters between field in structs.

  // bad
  memcmp(&struct1, &struct2, sizeof(struct1));

The above would fail for a struct like this:

typedef struct Foo {
  char a;
  /* padding */
  double d;
  /* padding */
  char e;
  /* padding */
  int f;
} Foo ;

You have to use member-wise comparison to be safe.

CSS image resize percentage of itself?

Try zoom property

<img src="..." style="zoom: 0.5" />

Edit: Apparently, FireFox doesn't support zoom property. You should use;

-moz-transform: scale(0.5);

for FireFox.

Facebook Like-Button - hide count?

It is now officially supported by Facebook. Just select the 'Button' layout.

https://developers.facebook.com/docs/plugins/like-button/

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

GO ends a batch, you would only very rarely need to use it in code. Be aware that if you use it in a stored proc, no code after the GO will be executed when you execute the proc.

BEGIN and END are needed for any procedural type statements with multipe lines of code to process. You will need them for WHILE loops and cursors (which you will avoid if at all possible of course) and IF statements (well techincally you don't need them for an IF statment that only has one line of code, but it is easier to maintain the code if you always put them in after an IF). CASE statements also use an END but do not have a BEGIN.

How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

How to call a PHP file from HTML or Javascript


How to make a button call PHP?

I don't care if the page reloads or displays the results immediately;

Good!

Note: If you don't want to refresh the page see "Ok... but how do I Use Ajax anyway?" below.

I just want to have a button on my website make a PHP file run.

That can be done with a form with a single button:

<form action="">
  <input type="submit" value="my button"/>
</form>

That's it.

Pretty much. Also note that there are cases where ajax is really the way to go.

That depends on what you want. In general terms you only need ajax when you want to avoid realoading the page. Still you have said that you don't care about that.


Why I cannot call PHP directly from JavaScript?

If I can write the code inside HTML just fine, why can't I just reference the file for it in there or make a simple call for it in Javascript?

Because the PHP code is not in the HTML just fine. That's an illusion created by the way most server side scripting languages works (including PHP, JSP, and ASP). That code only exists on the server, and it is no reachable form the client (the browser) without a remote call of some sort.

You can see evidence of this if you ask your browser to show the source code of the page. There you will not see the PHP code, that is because the PHP code is not send to the client, therefore it cannot be executed from the client. That's why you need to do a remote call to be able to have the client trigger the execution of PHP code.

If you don't use a form (as shown above) you can do that remote call from JavaScript with a little thing called Ajax. You may also want to consider if what you want to do in PHP can be done directly in JavaScript.


How to call another PHP file?

Use a form to do the call. You can have it to direct the user to a particlar file:

<form action="myphpfile.php">
  <input type="submit" value="click on me!">
</form>

The user will end up in the page myphpfile.php. To make it work for the current page, set action to an empty string (which is what I did in the example I gave you early).

I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

You want to make an operation on the server, you should make your form have the fields you need (even if type="hidden" and use POST):

<form action="" method="POST">
  <input type="text" value="default value, you can edit it" name="myfield">
  <input type="submit" value = "post">
</form>

What do I need to know about it to call a PHP file that will create a text file on a button press?

see: How to write into a file in PHP.


How do you recieve the data from the POST in the server?

I'm glad you ask... Since you are a newb begginer, I'll give you a little template you can follow:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        //Ok we got a POST, probably from a FORM, read from $_POST.
        var_dump($_PSOT); //Use this to see what info we got!
    }
    else
    {
       //You could assume you got a GET
       var_dump($_GET); //Use this to see what info we got!
    }
 ?>
 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta char-set="utf-8">
     <title>Page title</title>
   </head>
   <body>
     <form action="" method="POST">
       <input type="text" value="default value, you can edit it" name="myfield">
       <input type="submit" value = "post">
     </form>
   </body>
 </html>

Note: you can remove var_dump, it is just for debugging purposes.


How do I...

I know the next stage, you will be asking how to:

  1. how to pass variables form a PHP file to another?
  2. how to remember the user / make a login?
  3. how to avoid that anoying message the appears when you reload the page?

There is a single answer for that: Sessions.

I'll give a more extensive template for Post-Redirect-Get

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        //Do stuff...
        //Write results to session
        session_start();
        $_SESSION['stuff'] = $something;
        //You can store stuff such as the user ID, so you can remeember him.
        //redirect:
        header('Location: ', true, 303);
        //The redirection will cause the browser to request with GET
        //The results of the operation are in the session variable
        //It has empty location because we are redirecting to the same page
        //Otherwise use `header('Location: anotherpage.php', true, 303);`
        exit();
    }
    else
    {
        //You could assume you got a GET
        var_dump($_GET); //Use this to see what info we got!
        //Get stuff from session
        session_start();
        if (array_key_exists('stuff', $_SESSION))
        {
           $something = $_SESSION['stuff'];
           //we got stuff
           //later use present the results of the operation to the user.
        }
        //clear stuff from session:
        unset($_SESSION['stuff']);
        //set headers
        header('Content-Type: text/html; charset=utf-8');
        //This header is telling the browser what are we sending.
        //And it says we are sending HTML in UTF-8 encoding
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
  </head>
  <body>
    <?php if (isset($something)){ echo '<span>'.$something.'</span>'}?>;
    <form action="" method="POST">
      <input type="text" value="default value, you can edit it" name="myfield">
      <input type="submit" value = "post">
    </form>
  </body>
</html>

Please look at php.net for any function call you don't recognize. Also - if you don't have already - get a good tutorial on HTML5.

Also, use UTF-8 because UTF-8!


Notes:

I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately.

If are you using a CMS (Codepress, Joomla, Drupal... etc)? That make put some contraints on how you got to do things.

Also, if you are using a framework, you should look at their documentation or ask at their forum/mailing list/discussion page/contact or try to ask the authors.


Ok... but how do I Use Ajax anyway?

Well... Ajax is made easy by some JavaScript libraries. Since you are a begginer, I'll recomend jQuery.

So, let's send something to the server via Ajax with jQuery, I'll use $.post instead of $.ajax for this example.

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        var_dump($_PSOT);
        header('Location: ', true, 303);
        exit();
    }
    else
    {
        var_dump($_GET);
        header('Content-Type: text/html; charset=utf-8');
    }
 ?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta char-set="utf-8">
    <title>Page title</title>
    <script>
        function ajaxmagic()
        {
            $.post(                             //call the server
                "test.php",                     //At this url
                {
                    field: "value",
                    name: "John"
                }                               //And send this data to it
            ).done(                             //And when it's done
                function(data)
                {
                    $('#fromAjax').html(data);  //Update here with the response
                }
            );
        }
    </script>
  </head>
  <body>
    <input type="button" value = "use ajax", onclick="ajaxmagic()">
    <span id="fromAjax"></span>
  </body>
</html>

The above code will send a POST request to the page test.php.

Note: You can mix sessions with ajax and stuff if you want.


How do I...

  1. How do I connect to the database?
  2. How do I prevent SQL injection?
  3. Why shouldn't I use Mysql_* functions?

... for these or any other, please make another questions. That's too much for this one.

GitHub: invalid username or password

  1. Control panel
  2. Credential manager
  3. Look for options webcredentials and windows credentials
  4. in either one you will find github credentials fix it with correct credentials
  5. open new instance of git bash you should be able to perform your git commands.

This worked for me, I was able to pull and push into my remote repo.

When to use AtomicReference in Java?

You can use AtomicReference when applying optimistic locks. You have a shared object and you want to change it from more than 1 thread.

  1. You can create a copy of the shared object
  2. Modify the shared object
  3. You need to check that the shared object is still the same as before - if yes, then update with the reference of the modified copy.

As other thread might have modified it and/can modify between these 2 steps. You need to do it in an atomic operation. this is where AtomicReference can help

'do...while' vs. 'while'

I can't imagine how you've gone this long without using a do...while loop.

There's one on another monitor right now and there are multiple such loops in that program. They're all of the form:

do
{
    GetProspectiveResult();
}
while (!ProspectIsGood());

Loading/Downloading image from URL on Swift

Xcode 8 or later • Swift 3 or later

Synchronously:

if let filePath = Bundle.main.path(forResource: "imageName", ofType: "jpg"), let image = UIImage(contentsOfFile: filePath) {
    imageView.contentMode = .scaleAspectFit
    imageView.image = image
}

Asynchronously:

Create a method with a completion handler to get the image data from your url

func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
    URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}

Create a method to download the image (start the task)

func downloadImage(from url: URL) {
    print("Download Started")
    getData(from: url) { data, response, error in
        guard let data = data, error == nil else { return }
        print(response?.suggestedFilename ?? url.lastPathComponent)
        print("Download Finished")
        DispatchQueue.main.async() { [weak self] in
            self?.imageView.image = UIImage(data: data)
        }
    }
}

Usage:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    print("Begin of code")
    let url = URL(string: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")! 
    downloadImage(from: url)
    print("End of code. The image will continue downloading in the background and it will be loaded when it ends.")
}

Extension:

extension UIImageView {
    func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
        contentMode = mode
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data)
                else { return }
            DispatchQueue.main.async() { [weak self] in
                self?.image = image
            }
        }.resume()
    }
    func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) { 
        guard let url = URL(string: link) else { return }
        downloaded(from: url, contentMode: mode)
    }
}

Usage:

imageView.downloaded(from: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")

MySQL: Insert datetime into other datetime field

Try

    UPDATE products SET former_date=20111218131717 WHERE id=1

Alternatively, you might want to look at using the STR_TO_DATE (see STR_TO_DATE(str,format)) function.

Use multiple css stylesheets in the same html page

You can't. The last stylesheet you specify will be the one html page will use. Think of it as a big single .css document.

Difference between "process.stdout.write" and "console.log" in node.js?

The Simple Difference is: console.log() methods automatically append new line character. It means if we are looping through and printing the result, each result get printed in new line.

process.stdout.write() methods don't append new line character. useful for printing patterns.

How to calculate md5 hash of a file using javascript

The following snippet shows an example, which can archive a throughput of 400 MB/s while reading and hashing the file.

It is using a library called hash-wasm, which is based on WebAssembly and calculates the hash faster than js-only libraries. As of 2020, all modern browsers support WebAssembly.

_x000D_
_x000D_
const chunkSize = 64 * 1024 * 1024;
const fileReader = new FileReader();
let hasher = null;

function hashChunk(chunk) {
  return new Promise((resolve, reject) => {
    fileReader.onload = async(e) => {
      const view = new Uint8Array(e.target.result);
      hasher.update(view);
      resolve();
    };

    fileReader.readAsArrayBuffer(chunk);
  });
}

const readFile = async(file) => {
  if (hasher) {
    hasher.init();
  } else {
    hasher = await hashwasm.createMD5();
  }

  const chunkNumber = Math.floor(file.size / chunkSize);

  for (let i = 0; i <= chunkNumber; i++) {
    const chunk = file.slice(
      chunkSize * i,
      Math.min(chunkSize * (i + 1), file.size)
    );
    await hashChunk(chunk);
  }

  const hash = hasher.digest();
  return Promise.resolve(hash);
};

const fileSelector = document.getElementById("file-input");
const resultElement = document.getElementById("result");

fileSelector.addEventListener("change", async(event) => {
  const file = event.target.files[0];

  resultElement.innerHTML = "Loading...";
  const start = Date.now();
  const hash = await readFile(file);
  const end = Date.now();
  const duration = end - start;
  const fileSizeMB = file.size / 1024 / 1024;
  const throughput = fileSizeMB / (duration / 1000);
  resultElement.innerHTML = `
    Hash: ${hash}<br>
    Duration: ${duration} ms<br>
    Throughput: ${throughput.toFixed(2)} MB/s
  `;
});
_x000D_
<script src="https://cdn.jsdelivr.net/npm/hash-wasm"></script>
<!-- defines the global `hashwasm` variable -->

<input type="file" id="file-input">
<div id="result"></div>
_x000D_
_x000D_
_x000D_

Error: getaddrinfo ENOTFOUND in nodejs for get call

getaddrinfo ENOTFOUND means client was not able to connect to given address. Please try specifying host without http:

var optionsget = {
    host : 'localhost',
    port : 3010,
    path : '/quote/random', // the rest of the url with parameters if needed
    method : 'GET' // do GET
};

Regarding learning resources, you won't go wrong if you start with http://www.nodebeginner.org/ and then go through some good book to get more in-depth knowledge - I recommend Professional Node.js , but there's many out there.

See full command of running/stopped container in Docker

Moving Dylan's comment into a full-blown answer because TOO USEFUL:

docker run --rm -v /var/run/docker.sock:/var/run/docker.sock assaflavie/runlike YOUR-CONTAINER

What does it do? Runs https://github.com/lavie/runlike inside a container, gets you the complete docker run command, then removes the container for you.

Current time formatting with Javascript

ISO8601 (eg: HH:MM:SS , 07:55:55 , or 18:50:30) on chrome :

new Date(Date.now()).toTimeString().substr(0,8);

on edge :

new Date(Date.now()).toLocaleTimeString();

Node.js + Nginx - What now?

answering your question 2:

I would use option b simply because it consumes much less resources. with option 'a', every client will cause the server to consume a lot of memory, loading all the files you need (even though i like php, this is one of the problems with it). With option 'b' you can load your libraries (reusable code) and share them among all client requests.

But be ware that if you have multiple cores you should tweak node.js to use all of them.

How do I style (css) radio buttons and labels?

For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels

input:checked + label {
    color: white;
}  

MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.

phpMyAdmin says no privilege to create database, despite logged in as root user

login in the terminal as a root and execute this command:

mysql_secure_installation

Type n in order to not change root password and hit enter, then type y to remove anonymous users and hit enter. Type n if you want to disallow root login remotely and hit enter. Now type y to remove test tables and databases and hit enter, then type y again and hit enter.

and you are good to go :)

PHP Warning: Division by zero

You need to wrap your form processing code in a conditional so it doesn't run when you first open the page. Something like so:

if($_POST['num1'] > 0 && $_POST['num2'] > 0 && $_POST['num3'] > 0 && $_POST['num4'] > 0){

  $itemQty = $_POST['num1'];
  $itemCost = $_POST['num2'];
  $itemSale = $_POST['num3'];
  $shipMat = $_POST['num4'];

  $diffPrice = $itemSale - $itemCost;
  $actual = ($diffPrice - $shipMat) * $itemQty;
  $diffPricePercent = (($actual * 100) / $itemCost) / $itemQty ;
}

Get the current first responder without using a private API

For a Swift 3 & 4 version of nevyn's answer:

UIApplication.shared.sendAction(#selector(UIView.resignFirstResponder), to: nil, from: nil, for: nil)

Import a custom class in Java

According Oracle and Sun doc, a class can use all classes from its own package and all public classes from other packages. You can access the public classes in another package in two ways.

  • The first is simply to add the full package name in front of every class name. For example:

    java.util.Date today = new java.util.Date();

  • The simpler, and more common, approach is to use the import statement. The point of the import statement is to give you a shorthand to refer to the classes in the package. Once you use import, you no longer have to give the classes their full names. You can import a specific class or the whole package. You place import statements at the top of your source files (but below any package statements). For example, you can import all classes in the java.util package with the statement Then you can use without a package prefix.

    import java.util.*;

    // Use class in your code with this manner

    Date today = new Date();

As you mentioned in your question that your classes are under the same package, you should not have any problem, it is better just to use class name.

How to delete multiple files at once in Bash on Linux?

A wild card would work nicely for this, although to be safe it would be best to make the use of the wild card as minimal as possible, so something along the lines of this:

rm -rf abc.log.2012-*

Although from the looks of it, are those just single files? The recursive option should not be necessary if none of those items are directories, so best to not use that, just for safety.

How to change the decimal separator of DecimalFormat from comma to dot/point?

You can change the separator either by setting a locale or using the DecimalFormatSymbols.

If you want the grouping separator to be a point, you can use an european locale:

NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;

Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others:

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.'); 
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);

currentLocale can be obtained from Locale.getDefault() i.e.:

Locale currentLocale = Locale.getDefault();

Get file version in PowerShell

Nowadays you can get the FileVersionInfo from Get-Item or Get-ChildItem, but it will show the original FileVersion from the shipped product, and not the updated version. For instance:

(Get-Item C:\Windows\System32\Lsasrv.dll).VersionInfo.FileVersion

Interestingly, you can get the updated (patched) ProductVersion by using this:

(Get-Command C:\Windows\System32\Lsasrv.dll).Version

The distinction I'm making between "original" and "patched" is basically due to the way the FileVersion is calculated (see the docs here). Basically ever since Vista, the Windows API GetFileVersionInfo is querying part of the version information from the language neutral file (exe/dll) and the non-fixed part from a language-specific mui file (which isn't updated every time the files change).

So with a file like lsasrv (which got replaced due to security problems in SSL/TLS/RDS in November 2014) the versions reported by these two commands (at least for a while after that date) were different, and the second one is the more "correct" version.

However, although it's correct in LSASrv, it's possible for the ProductVersion and FileVersion to be different (it's common, in fact). So the only way to get the updated Fileversion straight from the assembly file is to build it up yourself from the parts, something like this:

Get-Item C:\Windows\System32\Lsasrv.dll | ft FileName, File*Part

Or by pulling the data from this:

[System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName)

You can easily add this to all FileInfo objects by updating the TypeData in PowerShell:

Update-TypeData -TypeName System.IO.FileInfo -MemberName FileVersion -MemberType ScriptProperty -Value {
   [System.Diagnostics.FileVersionInfo]::GetVersionInfo($this.FullName) | % {
      [Version](($_.FileMajorPart, $_.FileMinorPart, $_.FileBuildPart, $_.FilePrivatePart)-join".") 
   }
}

Now every time you do Get-ChildItem or Get-Item you'll have a FileVersion property that shows the updated FileVersion ...

Change all files and folders permissions of a directory to 644/755

This worked for me:

find /A -type d -exec chmod 0755 {} \;
find /A -type f -exec chmod 0644 {} \;

How can I change the Java Runtime Version on Windows (7)?

For Java applications, i.e. programs that are delivered (usually) as .jar files and started with java -jar xxx.jar or via a shortcut that does the same, the JRE that will be launched will be the first one found on the PATH.

If you installed a JRE or JDK, the likely places to find the .exes are below directories like C:\Program Files\JavaSoft\JRE\x.y.z. However, I've found some "out of the box" Windows installations to (also?) have copies of java.exe and javaw.exe in C:\winnt\system32 (NT and 2000) or C:\windows\system (Windows 95, 98). This is usually a pretty elderly version of Java: 1.3, maybe? You'll want to do java -version in a command window to check that you're not running some antiquated version of Java.

You can of course override the PATH setting or even do without it by explicitly stating the path to java.exe / javaw.exe in your command line or shortcut definition.


If you're running applets from the browser, or possibly also Java Web Start applications (they look like applications insofar as they have their own window, but you start them from the browser), the choice of JRE is determined by a set of registry settings:

Key: HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment
Name: CurrentVersion
Value: (e.g.) 1.3

More registry keys are created using this scheme:

(e.g.) 
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.3   
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.3.1

i.e. one for the major and one including the minor version number. Each of these keys has values like these (examples shown):

JavaHome    : C:\program Files\JavaSoft\JRE\1.3.1
RuntimeLib  : C:\Program Files\JavaSoft\JRE\1.3.1\bin\hotspot\jvm.dll
MicroVersion: 1

... and your browser will look to these settings to determine which JRE to fire up.

Since Java versions are changing pretty frequently, there's now a "wizard" called the "Java Control Panel" for manually switching your browser's Java version. This works for IE, Firefox and probably others like Opera and Chrome as well: It's the 'Java' applet in Windows' System Settings app. You get to pick any one of the installed JREs. I believe that wizard fiddles with those registry entries.

If you're like me and have "uninstalled" old Java versions by simply wiping out directories, you'll find these "ghosts" among the choices too; so make sure the JRE you choose corresponds to an intact Java installation!


Some other answers are recommending setting the environment variable JAVA_HOME. This is meanwhile outdated advice. Sun came to realize, around Java 2, that this environment setting is

  1. unreliable, as users often set it incorrectly, and
  2. unnecessary, as it's easy enough for the runtime to find the Java library directories, knowing they're in a fixed path relative to the path from which java.exe or javaw.exe was launched.

There's hardly any modern Java software left that needs or respects the JAVA_HOME environment variable.


More Information:

...and some useful information on multi-version support:

Total number of items defined in an enum

If you find yourself writing the above solution as often as I do then you could implement it as a generic:

public static int GetEnumEntries<T>() where T : struct, IConvertible 
{
    if (!typeof(T).IsEnum)
        throw new ArgumentException("T must be an enumerated type");

    return Enum.GetNames(typeof(T)).Length;
}

HTTPS connections over proxy servers

I don't think "have HTTPS connections over proxy servers" means the Man-in-the-Middle attack type of proxy server. I think it's asking whether one can connect to a http proxy server over TLS. And the answer is yes.


Is it possible to have HTTPS connections over proxy servers?

Yes, see my question and answer here. HTTPs proxy server only works in SwitchOmega

If yes, what kind of proxy server allows this?

The kind of proxy server deploys SSL certificates, like how ordinary websites do. But you need a pac file for the brower to configure proxy connection over SSL.

How to specify in crontab by what user to run script?

You can also try using runuser (as root) to run a command as a different user

*/1 * * * * runuser php5 \
            --command="/var/www/web/includes/crontab/queue_process.php \
                       >> /var/www/web/includes/crontab/queue.log 2>&1"

See also: man runuser

Label points in geom_point

Instead of using the ifelse as in the above example, one can also prefilter the data prior to labeling based on some threshold values, this saves a lot of work for the plotting device:

xlimit <- 36
ylimit <- 24
ggplot(myData)+geom_point(aes(myX,myY))+
    geom_label(data=myData[myData$myX > xlimit & myData$myY> ylimit,], aes(myX,myY,myLabel))

Encrypt and decrypt a String in java

    public String encrypt(String str) {
        try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);

            // Encode bytes to base64 to get a string
            return new sun.misc.BASE64Encoder().encode(enc);
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }

    public String decrypt(String str) {
        try {
            // Decode base64 to get bytes
            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }
}

Here's an example that uses the class:

try {
    // Generate a temporary key. In practice, you would save this key.
    // See also Encrypting with DES Using a Pass Phrase.
    SecretKey key = KeyGenerator.getInstance("DES").generateKey();

    // Create encrypter/decrypter class
    DesEncrypter encrypter = new DesEncrypter(key);

    // Encrypt
    String encrypted = encrypter.encrypt("Don't tell anybody!");

    // Decrypt
    String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}

How to get first and last day of week in Oracle?

Assuming you mean weeks relative to the first day of the year ...

SELECT first_day_of_week, first_day_of_week+6 last_day_of_week
FROM (
  SELECT TO_DATE(YEAR||'0101','YYYYMMDD') + 7 * (week-1) first_day_of_week
  FROM (
    SELECT substr(yearweek,1,4) YEAR, to_number(substr(yearweek,5)) week
    FROM (
      SELECT '201118' yearweek FROM dual
    )
  )
)
;

Finding median of list in Python

The sorted() function is very helpful for this. Use the sorted function to order the list, then simply return the middle value (or average the two middle values if the list contains an even amount of elements).

def median(lst):
    sortedLst = sorted(lst)
    lstLen = len(lst)
    index = (lstLen - 1) // 2
   
    if (lstLen % 2):
        return sortedLst[index]
    else:
        return (sortedLst[index] + sortedLst[index + 1])/2.0

How do I insert an image in an activity with android studio?

I'll Explain how to add an image using Android studio(2.3.3). First you need to add the image into res/drawable folder in the project. Like below

enter image description here


Now in go to activity_main.xml (or any activity you need to add image) and select the Design view. There you can see your Palette tool box on left side. You need to drag and drop ImageView.

enter image description here

It will prompt you Resources dialog box. In there select Drawable under the project section you can see your image. Like below

enter image description here

Select the image you want press Ok you can see the image on the Design view. If you want it configure using xml it would look like below.

<ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/homepage"
        tools:layout_editor_absoluteX="55dp"
        tools:layout_editor_absoluteY="130dp" />

You need to give image location using

app:srcCompat="@drawable/imagename"

How to uninstall Eclipse?

The steps are very simple and it'll take just few mins. 1.Go to your C drive and in that go to the 'USER' section. 2.Under 'USER' section go to your 'name(e.g-'user1') and then find ".eclipse" folder and delete that folder 3.Along with that folder also delete "eclipse" folder and you can find that you're work has been done completely.

How to remove origin from git repository

Remove existing origin and add new origin to your project directory

>$ git remote show origin

>$ git remote rm origin

>$ git add .

>$ git commit -m "First commit"

>$ git remote add origin Copied_origin_url

>$ git remote show origin

>$ git push origin master

How to reload or re-render the entire page using AngularJS

Try one of the following:

$route.reload(); // don't forget to inject $route in your controller
$window.location.reload();
location.reload();

Vertically centering a div inside another div

You can do this with a simple javascript (jQuery) block.

CSS:

#outerDiv{
    height:100%;
}

Javascript:

<script type="text/javascript">
    $(document).ready(function () {
        $("#innerDiv").css('top', ($(window).height() - $("#content").height()) / 2);
    });
</script>

Dynamically update values of a chartjs chart

So simple, Just replace the chart canvas element.

$('#canvas').replaceWith(' id="canvas" height="200px" width="368px">');

height style property doesn't work in div elements

You try to set the height property of an inline element, which is not possible. You can try to make it a block element, or perhaps you meant to alter the line-height property?

How to set value of input text using jQuery

Using jQuery, we can use the following code:

Select by input name:

$('input[name="textboxname"]').val('some value')

Select by input class:

$('input[type=text].textboxclass').val('some value')

Select by input id:

$('#textboxid').val('some value')

How to change credentials for SVN repository in Eclipse?

On Mac OS X, go to folder /$HOME (/Users/{user home}/). You will see file '.eclipse_keyring'. Remove it. All saved credentials will be lost.

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

I'd like to share my experience of using Ant in building projects, *.properties files should be copied explicitly. This is because Ant will not compile *.properties files into the build working directory by default (javac just ignore *.properties). For example:

<target name="compile" depends="init">
    <javac destdir="${dst}" srcdir="${src}" debug="on" encoding="utf-8" includeantruntime="false">
        <include name="com/example/**" />
        <classpath refid="libs" />
    </javac>
    <copy todir="${dst}">
        <fileset dir="${src}" includes="**/*.properties" />
    </copy>
</target>

<target name="jars" depends="compile">
    <jar jarfile="${app_jar}" basedir="${dst}" includes="com/example/**/*.*" />
</target>

Please notice that 'copy' section under the 'compile' target, it will replicate *.properties files into the build working directory. Without the 'copy' section the jar file will not contain the properties files, then you may encounter the java.util.MissingResourceException.

How do I detect if software keyboard is visible on Android Device or not?

There's finally a direct way starting from Android R based on Kotlin now.

 val imeInsets = view.rootWindowInsets.getInsets(Type.ime()) 
    if (imeInsets.isVisible) { 
     //Ime is visible
     //Lets move our view by the height of the IME
     view.translationX = imeInsets.bottom }

Set Session variable using javascript in PHP

I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.

The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.

$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
    $.ajax ({
       data:        {"numElems": len},
       url:        '../../Utiles/GuardarNumElems.php',
       type:        'post'
    }); 
});

And the GuardarNumElems.php is as following:

<?php    
    session_start();

    if(isset ($_POST['numElems'] )){
        $numElems = $_POST['numElems'];        
        $_SESSION['elems_table'] = $numElems;
    }else{
        $_SESSION['elems_table'] = 25;
    } 
?>

Laravel is there a way to add values to a request array

I tried $request->merge($array) function in Laravel 5.2 and it is working perfectly.

Example:

$request->merge(["key"=>"value"]);

File opens instead of downloading in internet explorer in a href link

It should be fixed on server side. Your server should return this headers for this file types:

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"

How to import csv file in PHP?

If you use composer, you can try CsvFileLoader

Angular: Can't find Promise, Map, Set and Iterator

If you came here because you see these errors in Visual Studio 2017 then you have a different problem as above, if you succeed in compiling. This is because the language service doesn't pick your tsconfig.json.

https://developercommunity.visualstudio.com/content/problem/208941/vs-156-ignores-tsconfigjson-and-typescriptcompileb.html

You have to set the Build Action of your tsconfig.json to "Content"(Right click -> Properties), then VS will pick it up.

C# Call a method in a new thread

As far as I understand you need mean terminate as Thread.Abort() right? In this case, you can just exit the Foo(). Or you can use Process to catch the thread.

Thread myThread = new Thread(DoWork);

myThread.Abort();

myThread.Start(); 

Process example:

using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading;
using Microsoft.VisualBasic;

class PrintProcessClass
{

    private Process myProcess = new Process();
    private int elapsedTime;
    private bool eventHandled;

    // Print a file with any known extension.
    public void PrintDoc(string fileName)
    {

        elapsedTime = 0;
        eventHandled = false;

        try
        {
            // Start a process to print a file and raise an event when done.
            myProcess.StartInfo.FileName = fileName;
            myProcess.StartInfo.Verb = "Print";
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.EnableRaisingEvents = true;
            myProcess.Exited += new EventHandler(myProcess_Exited);
            myProcess.Start();

        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred trying to print \"{0}\":" + "\n" + ex.Message, fileName);
            return;
        }

        // Wait for Exited event, but not more than 30 seconds.
        const int SLEEP_AMOUNT = 100;
        while (!eventHandled)
        {
            elapsedTime += SLEEP_AMOUNT;
            if (elapsedTime > 30000)
            {
                break;
            }
            Thread.Sleep(SLEEP_AMOUNT);
        }
    }

    // Handle Exited event and display process information.
    private void myProcess_Exited(object sender, System.EventArgs e)
    {

        eventHandled = true;
        Console.WriteLine("Exit time:    {0}\r\n" +
            "Exit code:    {1}\r\nElapsed time: {2}", myProcess.ExitTime, myProcess.ExitCode, elapsedTime);
    }

    public static void Main(string[] args)
    {

        // Verify that an argument has been entered.
        if (args.Length <= 0)
        {
            Console.WriteLine("Enter a file name.");
            return;
        }

        // Create the process and print the document.
        PrintProcessClass myPrintProcess = new PrintProcessClass();
        myPrintProcess.PrintDoc(args[0]);
    }
}

cleanest way to skip a foreach if array is empty

I wouldn't recommend suppressing the warning output. I would, however, recommend using is_array instead of !empty. If $items happens to be a nonzero scalar, then the foreach will still error out if you use !empty.

C++ vector's insert & push_back difference

The functions have different purposes. vector::insert allows you to insert an object at a specified position in the vector, whereas vector::push_back will just stick the object on the end. See the following example:

using namespace std;
vector<int> v = {1, 3, 4};
v.insert(next(begin(v)), 2);
v.push_back(5);
// v now contains {1, 2, 3, 4, 5}

You can use insert to perform the same job as push_back with v.insert(v.end(), value).

If statement in select (ORACLE)

So simple you can use case statement here.

CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 
         CASE WHEN  ISSUE_DIVISION is null then "Null Value found" //give your option
         Else 1 End
ELSE 0 END As Issue_Division_Result

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

Is it possible to change the package name of an Android app on Google Play?

As far as I can tell what you could do is "retire" your previous app and redirect all users to your new app. This procedure is not supported by Google (tsk... tsk...), but it could be implemented in four steps:

  1. Change the current application to show a message to the users about the upgrade and redirect them to the new app listing. Probably a full screen message would do with some friendly text. This message could be triggered remotely ideally, but a cut-off date can be used too. (But then that will be a hard deadline for you, so be careful... ;))

  2. Release the modified old app as an upgrade, maybe with some feature upgrades/bug fixes too, to "sweeten the deal" to the users. Still there is no guarantee that all users will upgrade, but probably the majority will do.

  3. Prepare your new app with the updated package name and upload it to the store, then trigger the message in the old app (or just wait until it expires, if that was your choice).

  4. Unpublish the old app in Play Store to avoid any new installs. Unpublishing an app doesn't mean the users who already installed it won't have access to it anymore, but at least the potential new users won't find it on the market.

Not ideal and can be annoying to the users, sometimes even impossible to implement due to the status/possibilities of the app. But since Google left us no choice this is the only way to migrate the users of the old apps to a "new" one (even if it is not really new). Not to mention that if you don't have access to the sources and code signing details for the old app then all you could do is hoping that he users will notice the new app...

If anybody figured out a better way by all means: please do tell.

Selecting option by text content with jQuery

If your <option> elements don't have value attributes, then you can just use .val:

$selectElement.val("text_you're_looking_for")

However, if your <option> elements have value attributes, or might do in future, then this won't work, because whenever possible .val will select an option by its value attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value attributes, so we'll have to add one ourselves with a simple plugin:

/*
  Source: https://stackoverflow.com/a/16887276/1709587

  Usage instructions:

  Call

      jQuery('#mySelectElement').selectOptionWithText('target_text');

  to select the <option> element from within #mySelectElement whose text content
  is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
    return this.each(function () {
        var $selectElement, $options, $targetOption;

        $selectElement = jQuery(this);
        $options = $selectElement.find('option');
        $targetOption = $options.filter(
            function () {return jQuery(this).text() == targetText}
        );

        // We use `.prop` if it's available (which it should be for any jQuery
        // versions above and including 1.6), and fall back on `.attr` (which
        // was used for changing DOM properties in pre-1.6) otherwise.
        if ($targetOption.prop) {
            $targetOption.prop('selected', true);
        } 
        else {
            $targetOption.attr('selected', 'true');
        }
    });
}

Just include this plugin somewhere after you add jQuery onto the page, and then do

jQuery('#someSelectElement').selectOptionWithText('Some Target Text');

to select options.

The plugin method uses filter to pick out only the option matching the targetText, and selects it using either .attr or .prop, depending upon jQuery version (see .prop() vs .attr() for explanation).

Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

The best solution for the login problem is to create a login user in sqlServer. Here are the steps to create a SQL Server login that uses Windows Authentication (SQL Server Management Studio):

  1. In SQL Server Management Studio, open Object Explorer and expand the folder of the server instance in which to create the new login.
  2. Right-click the Security folder, point to New, and then click Login.
  3. On the General page, enter the name of a Windows user in the Login name box.
  4. Select Windows Authentication.
  5. Click OK.

For example, if the user name is xyz\ASPNET, then enter this name into Login name Box.

Also you need to change the User mapping to allow access to the Database which you want to access.

Node update a specific package

Most of the time you can just npm update (or yarn upgrade) a module to get the latest non breaking changes (respecting the semver specified in your package.json) (<-- read that last part again).

npm update browser-sync
-------
yarn upgrade browser-sync
  • Use npm|yarn outdated to see which modules have newer versions
  • Use npm update|yarn upgrade (without a package name) to update all modules
  • Include --save-dev|--dev if you want to save the newer version numbers to your package.json. (NOTE: as of npm v5.0 this is only necessary for devDependencies).

Major version upgrades:

In your case, it looks like you want the next major version (v2.x.x), which is likely to have breaking changes and you will need to update your app to accommodate those changes. You can install/save the latest 2.x.x by doing:

npm install browser-sync@2 --save-dev
-------
yarn add browser-sync@2 --dev

...or the latest 2.1.x by doing:

npm install [email protected] --save-dev
-------
yarn add [email protected] --dev

...or the latest and greatest by doing:

npm install browser-sync@latest --save-dev
-------
yarn add browser-sync@latest --dev

Note: the last one is no different than doing this:

npm uninstall browser-sync --save-dev
npm install browser-sync --save-dev
-------
yarn remove browser-sync --dev
yarn add browser-sync --dev

The --save-dev part is important. This will uninstall it, remove the value from your package.json, and then reinstall the latest version and save the new value to your package.json.

batch to copy files with xcopy

Based on xcopy help, I tried and found that following works perfectly for me (tried on Win 7)

xcopy C:\folder1 C:\folder2\folder1 /E /C /I /Q /G /H /R /K /Y /Z /J

SQL server ignore case in a where expression

Usually, string comparisons are case-insensitive. If your database is configured to case sensitive collation, you need to force to use a case insensitive one:

SELECT balance FROM people WHERE email = '[email protected]'
  COLLATE SQL_Latin1_General_CP1_CI_AS 

What is the correct way to write HTML using Javascript?

  1. DOM methods, as outlined by Tom.

  2. innerHTML, as mentioned by iHunger.

DOM methods are highly preferable to strings for setting attributes and content. If you ever find yourself writing innerHTML= '<a href="'+path+'">'+text+'</a>' you're actually creating new cross-site-scripting security holes on the client side, which is a bit sad if you've spent any time securing your server-side.

DOM methods are traditionally described as ‘slow’ compared to innerHTML. But this isn't really the whole story. What is slow is inserting a lot of child nodes:

 for (var i= 0; i<1000; i++)
     div.parentNode.insertBefore(document.createElement('div'), div);

This translates to a load of work for the DOM finding the right place in its nodelist to insert the element, moving the other child nodes up, inserting the new node, updating the pointers, and so on.

Setting an existing attribute's value, or a text node's data, on the other hand, is very fast; you just change a string pointer and that's it. This is going to be much faster than serialising the parent with innerHTML, changing it, and parsing it back in (and won't lose your unserialisable data like event handlers, JS references and form values).

There are techniques to do DOM manipulations without so much slow childNodes walking. In particular, be aware of the possibilities of cloneNode, and using DocumentFragment. But sometimes innerHTML really is quicker. You can still get the best of both worlds by using innerHTML to write your basic structure with placeholders for attribute values and text content, which you then fill in afterwards using DOM. This saves you having to write your own escapehtml() function to get around the escaping/security problems mentioned above.

Get hostname of current request in node.js Express

Here's an alternate

req.hostname

Read about it in the Express Docs.

How to create a CPU spike with a bash command

#!/bin/bash
while [ 1 ]
do
        #Your code goes here
done

vim - How to delete a large block of text without counting the lines?

Deleting a block of text

Assuming your cursor sits at the beginning of the block:

V/^$<CR>d (where <CR> is the enter/return key)

Explanation

  • Enter "linewise-visual" mode: V
  • Highlight until the next empty line: /^$<CR>
  • Delete: d

Key binding

A more robust solution:

:set nowrapscan
:nnoremap D V/^\s*$\\|\%$<CR>d

Explanation

  • Disable search wrap: :set nowrapscan
  • Remap the D key (to the following commands): :nnoremap D
  • Enter "linewise-visual" mode: V
  • Highlight until the next empty/whitespace line or EOF: /^\s*$\\|\%$<CR>
  • Delete: d

How to manage exceptions thrown in filters in Spring?

I come across this issue myself and I performed the steps below to reuse my ExceptionController that is annotated with @ControllerAdvise for Exceptions thrown in a registered Filter.

There are obviously many ways to handle exception but, in my case, I wanted the exception to be handled by my ExceptionController because I am stubborn and also because I don't want to copy/paste the same code (i.e. I have some processing/logging code in ExceptionController). I would like to return the beautiful JSON response just like the rest of the exceptions thrown not from a Filter.

{
  "status": 400,
  "message": "some exception thrown when executing the request"
}

Anyway, I managed to make use of my ExceptionHandler and I had to do a little bit of extra as shown below in steps:

Steps


  1. You have a custom filter that may or may not throw an exception
  2. You have a Spring controller that handles exceptions using @ControllerAdvise i.e. MyExceptionController

Sample code

//sample Filter, to be added in web.xml
public MyFilterThatThrowException implements Filter {
   //Spring Controller annotated with @ControllerAdvise which has handlers
   //for exceptions
   private MyExceptionController myExceptionController; 

   @Override
   public void destroy() {
        // TODO Auto-generated method stub
   }

   @Override
   public void init(FilterConfig arg0) throws ServletException {
       //Manually get an instance of MyExceptionController
       ApplicationContext ctx = WebApplicationContextUtils
                  .getRequiredWebApplicationContext(arg0.getServletContext());

       //MyExceptionHanlder is now accessible because I loaded it manually
       this.myExceptionController = ctx.getBean(MyExceptionController.class); 
   }

   @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        try {
           //code that throws exception
        } catch(Exception ex) {
          //MyObject is whatever the output of the below method
          MyObject errorDTO = myExceptionController.handleMyException(req, ex); 

          //set the response object
          res.setStatus(errorDTO .getStatus());
          res.setContentType("application/json");

          //pass down the actual obj that exception handler normally send
          ObjectMapper mapper = new ObjectMapper();
          PrintWriter out = res.getWriter(); 
          out.print(mapper.writeValueAsString(errorDTO ));
          out.flush();

          return; 
        }

        //proceed normally otherwise
        chain.doFilter(request, response); 
     }
}

And now the sample Spring Controller that handles Exception in normal cases (i.e. exceptions that are not usually thrown in Filter level, the one we want to use for exceptions thrown in a Filter)

//sample SpringController 
@ControllerAdvice
public class ExceptionController extends ResponseEntityExceptionHandler {

    //sample handler
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ExceptionHandler(SQLException.class)
    public @ResponseBody MyObject handleSQLException(HttpServletRequest request,
            Exception ex){
        ErrorDTO response = new ErrorDTO (400, "some exception thrown when "
                + "executing the request."); 
        return response;
    }
    //other handlers
}

Sharing the solution with those who wish to use ExceptionController for Exceptions thrown in a Filter.

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"
 }

What's the difference between size_t and int in C++?

size_t is the type used to represent sizes (as its names implies). Its platform (and even potentially implementation) dependent, and should be used only for this purpose. Obviously, representing a size, size_t is unsigned. Many stdlib functions, including malloc, sizeof and various string operation functions use size_t as a datatype.

An int is signed by default, and even though its size is also platform dependant, it will be a fixed 32bits on most modern machine (and though size_t is 64 bits on 64-bits architecture, int remain 32bits long on those architectures).

To summarize : use size_t to represent the size of an object and int (or long) in other cases.

How to SSH into Docker?

I guess it is possible. You just need to install a SSH server in each container and expose a port on the host. The main annoyance would be maintaining/remembering the mapping of port to container.

However, I have to question why you'd want to do this. SSH'ng into containers should be rare enough that it's not a hassle to ssh to the host then use docker exec to get into the container.

sql server #region

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

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

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

How to get multiple counts with one SQL query?

Building on other posted answers.

Both of these will produce the right values:

select distributor_id,
    count(*) total,
    sum(case when level = 'exec' then 1 else 0 end) ExecCount,
    sum(case when level = 'personal' then 1 else 0 end) PersonalCount
from yourtable
group by distributor_id

SELECT a.distributor_id,
          (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
          (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
          (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
       FROM myTable a ; 

However, the performance is quite different, which will obviously be more relevant as the quantity of data grows.

I found that, assuming no indexes were defined on the table, the query using the SUMs would do a single table scan, while the query with the COUNTs would do multiple table scans.

As an example, run the following script:

IF OBJECT_ID (N't1', N'U') IS NOT NULL 
drop table t1

create table t1 (f1 int)


    insert into t1 values (1) 
    insert into t1 values (1) 
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)


SELECT SUM(CASE WHEN f1 = 1 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 2 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 3 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 4 THEN 1 else 0 end)
from t1

SELECT 
(select COUNT(*) from t1 where f1 = 1),
(select COUNT(*) from t1 where f1 = 2),
(select COUNT(*) from t1 where f1 = 3),
(select COUNT(*) from t1 where f1 = 4)

Highlight the 2 SELECT statements and click on the Display Estimated Execution Plan icon. You will see that the first statement will do one table scan and the second will do 4. Obviously one table scan is better than 4.

Adding a clustered index is also interesting. E.g.

Create clustered index t1f1 on t1(f1);
Update Statistics t1;

The first SELECT above will do a single Clustered Index Scan. The second SELECT will do 4 Clustered Index Seeks, but they are still more expensive than a single Clustered Index Scan. I tried the same thing on a table with 8 million rows and the second SELECT was still a lot more expensive.

How to set up datasource with Spring for HikariCP?

my test java config (for MySql)

@Bean(destroyMethod = "close")
public DataSource dataSource(){
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setDriverClassName("com.mysql.jdbc.Driver");
    hikariConfig.setJdbcUrl("jdbc:mysql://localhost:3306/spring-test"); 
    hikariConfig.setUsername("root");
    hikariConfig.setPassword("admin");

    hikariConfig.setMaximumPoolSize(5);
    hikariConfig.setConnectionTestQuery("SELECT 1");
    hikariConfig.setPoolName("springHikariCP");

    hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
    hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");

    HikariDataSource dataSource = new HikariDataSource(hikariConfig);

    return dataSource;
}

How to do a SOAP Web Service call from Java class?

Or just use Apache CXF's wsdl2java to generate objects you can use.

It is included in the binary package you can download from their website. You can simply run a command like this:

$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl

It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):

DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);

There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html

Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315

How do you do exponentiation in C?

pow only works on floating-point numbers (doubles, actually). If you want to take powers of integers, and the base isn't known to be an exponent of 2, you'll have to roll your own.

Usually the dumb way is good enough.

int power(int base, unsigned int exp) {
    int i, result = 1;
    for (i = 0; i < exp; i++)
        result *= base;
    return result;
 }

Here's a recursive solution which takes O(log n) space and time instead of the easy O(1) space O(n) time:

int power(int base, int exp) {
    if (exp == 0)
        return 1;
    else if (exp % 2)
        return base * power(base, exp - 1);
    else {
        int temp = power(base, exp / 2);
        return temp * temp;
    }
}

Unlink of file Failed. Should I try again?

As stated above, something else is holding the files. Thing is that program doesnt look suspicious for us. I was trying to do a git pull from console, while having GitKraken opened. Closing GitKraken fixed the problem.

How to test if a double is zero?

Yes, it's a valid test although there's an implicit conversion from int to double. For clarity/simplicity you should use (foo.x == 0.0) to test. That will hinder NAN errors/division by zero, but the double value can in some cases be very very very close to 0, but not exactly zero, and then the test will fail (I'm talking about in general now, not your code). Division by that will give huge numbers.

If this has anything to do with money, do not use float or double, instead use BigDecimal.

Insert all data of a datagridview to database at once

You have a syntax error Please try the following syntax as given below:

string StrQuery="INSERT INTO tableName VALUES ('" + dataGridView1.Rows[i].Cells[0].Value + "',' " + dataGridView1.Rows[i].Cells[1].Value + "', '" + dataGridView1.Rows[i].Cells[2].Value + "', '" + dataGridView1.Rows[i].Cells[3].Value + "',' " + dataGridView1.Rows[i].Cells[4].Value + "')";

jQuery: serialize() form and other parameters

serialize() effectively turns the form values into a valid querystring, as such you can simply append to the string:

$.ajax({
    type : 'POST',
    url : 'url',
    data : $('#form').serialize() + "&par1=1&par2=2&par3=232"
}

jQuery UI Dialog OnBeforeUnload

The correct way to display the alert is to simply return a string. Don't call the alert() method yourself.

<script type="text/javascript">
    $(window).on('beforeunload', function() {
        if (iWantTo) {
            return 'you are an idiot!';
        }
    }); 
</script>

See also: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

Extracting the last n characters from a string in R

A simple base R solution using the substring() function (who knew this function even existed?):

RIGHT = function(x,n){
  substring(x,nchar(x)-n+1)
}

This takes advantage of basically being substr() underneath but has a default end value of 1,000,000.

Examples:

> RIGHT('Hello World!',2)
[1] "d!"
> RIGHT('Hello World!',8)
[1] "o World!"

Netbeans how to set command line arguments in Java

For a Maven project using NetBeans 8.x:

  1. Click Run >> Set Project Configuration >> Customise
  2. Select Actions
  3. Select Run file via main()
  4. Set name/value pair to include the arguments.
  5. Click OK

An example name/value pair might resemble:

javax.persistence.jdbc.password=PASSWORD

Then run your project:

  1. Open and focus the Java class that includes main(...).
  2. Press F6 to run the program.

The command line parameters should appear in the Run window.

Note that to obtain the value form with the program, use System.getProperty().

Additional actions for Test file, Run project, and other ways to run the application can have arguments defined. Repeat the steps above for the different actions to accomplish this task.

Rails create or update magic?

The sequel gem adds an update_or_create method which seems to do what you're looking for.

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

I had to modify Lars' answer a bit, as an orphaned \ ended up in the regex, to only compare the actual host (not paying attention to the protocol or port) and I wanted to support localhost domain besides my production domain. Thus I changed the $allowed parameter to be an array.

function getCORSHeaderOrigin($allowed, $input)
{
    if ($allowed == '*') {
        return '*';
    }

    if (!is_array($allowed)) {
        $allowed = array($allowed);
    }

    foreach ($allowed as &$value) {
        $value = preg_quote($value, '/');

        if (($wildcardPos = strpos($value, '\*')) !== false) {
            $value = str_replace('\*', '(.*)', $value);
        }
    }

    $regexp = '/^(' . implode('|', $allowed) . ')$/';

    $inputHost = parse_url($input, PHP_URL_HOST);

    if ($inputHost === null || !preg_match($regexp, $inputHost, $matches)) {
        return 'none';
    }

    return $input;
}

Usage as follows:

if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: " . getCORSHeaderOrigin(array("*.myproduction.com", "localhost"), $_SERVER['HTTP_ORIGIN']));
}

'module' object has no attribute 'DataFrame'

For me he problem was that my script was called pandas.py in the folder pandas which obviously messed up my imports.

How do I create a MongoDB dump of my database?

Use mongodump:

$ ./mongodump --host prod.example.com
connected to: prod.example.com
all dbs
DATABASE: log    to   dump/log
        log.errors to dump/log/errors.bson
                713 objects
        log.analytics to dump/log/analytics.bson
                234810 objects
DATABASE: blog    to    dump/blog
        blog.posts to dump/log/blog.posts.bson
                59 objects
DATABASE: admin    to    dump/admin

Source: http://www.mongodb.org/display/DOCS/Import+Export+Tools

HTML5 Audio Looping

I did it this way,

<audio controls="controls" loop="loop">
<source src="someSound.ogg" type="audio/ogg" />
</audio>

and it looks like this

enter image description here

What do I do when my program crashes with exception 0xc0000005 at address 0?

Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).

So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.

How to upgrade docker container after its image changed

Just for providing a more general (not mysql specific) answer...

  1. In short

Synchronize with service image registry (https://docs.docker.com/compose/compose-file/#image):

docker-compose pull 

Recreate container if docker-compose file or image have changed:

docker-compose up -d
  1. Background

Container image management is one of the reason for using docker-compose (see https://docs.docker.com/compose/reference/up/)

If there are existing containers for a service, and the service’s configuration or image was changed after the container’s creation, docker-compose up picks up the changes by stopping and recreating the containers (preserving mounted volumes). To prevent Compose from picking up changes, use the --no-recreate flag.

Data management aspect being also covered by docker-compose through mounted external "volumes" (See https://docs.docker.com/compose/compose-file/#volumes) or data container.

This leaves potential backward compatibility and data migration issues untouched, but these are "applicative" issues, not Docker specific, which have to be checked against release notes and tests...

CodeIgniter htaccess and URL rewrite issues

I had similar issue on Linux Ubuntu 14.

After constant 403 error messages in the browser and reading all answers here I could not figure out what was wrong.

Then I have reached for apache's error log, and finally got a hint that was a bit unexpected but perfectly logical.

the codeIgniter main folder had no X permission on folder rendering everything else unreadable by web server.

chmod ugo+x yourCodeIgniterFolder

fixed first problem. Killed 403 errors.

But then I started getting error 500.

Culprit was a wrong settings line in .htaccess

Then I started getting php errors.

Culprit was same problem as main folder no X flag for 'others' permission for inner folders in application and system folders.

My two cents for this question: READ Apache Error.log.

But, also be aware of security issues. CodeIgniter suggests moving application and system folder out of web space therefore changing permissions shall be taken with a great care if these folders remain in web space.

Another thing worth mentioning here is that I have unzipped downloaded CodeIgniter archive directly to the web space. Folder permissions are likely created straight from the archive. As given they are secure, but folder access issue (on unix like systems) is not mentioned in CodeIgniter manual https://codeigniter.com/user_guide/installation/index.html and perhaps it shall be mentioned there with guidelines on how to relax security for CodeIgniter to work while keeping security tight for the production system (some security hints are already there in the manual as mentioned beforehand).

Determine what attributes were changed in Rails after_save callback?

Rails 5.1+

Use saved_change_to_published?:

class SomeModel < ActiveRecord::Base
  after_update :send_notification_after_change

  def send_notification_after_change
    Notification.send(…) if (saved_change_to_published? && self.published == true)
  end

end

Or if you prefer, saved_change_to_attribute?(:published).

Rails 3–5.1

Warning

This approach works through Rails 5.1 (but is deprecated in 5.1 and has breaking changes in 5.2). You can read about the change in this pull request.

In your after_update filter on the model you can use _changed? accessor. So for example:

class SomeModel < ActiveRecord::Base
  after_update :send_notification_after_change

  def send_notification_after_change
    Notification.send(...) if (self.published_changed? && self.published == true)
  end

end

It just works.

Append String in Swift

Its very simple:

For ObjC:

     NSString *string1 = @"This is";
     NSString *string2 = @"Swift Language";

ForSwift:

    let string1 = "This is"
    let string2 = "Swift Language"

For ObjC AppendString:

     NSString *appendString=[NSString stringWithFormat:@"%@ %@",string1,string2];

For Swift AppendString:

    var appendString1 = "\(string1) \(string2)"
    var appendString2 = string1+string2

Result:

    print("APPEND STRING 1:\(appendString1)")
    print("APPEND STRING 2:\(appendString2)")

Complete Code In Swift:

    let string1 = "This is"
    let string2 = "Swift Language"
    var appendString = "\(string1) \(string2)"
    var appendString1 = string1+string2
    print("APPEND STRING1:\(appendString1)")
    print("APPEND STRING2:\(appendString2)")

How to create a oracle sql script spool file

This will spool the output from the anonymous block into a file called output_<YYYYMMDD>.txt located in the root of the local PC C: drive where <YYYYMMDD> is the current date:

SET SERVEROUTPUT ON FORMAT WRAPPED
SET VERIFY OFF

SET FEEDBACK OFF
SET TERMOUT OFF

column date_column new_value today_var
select to_char(sysdate, 'yyyymmdd') date_column
  from dual
/
DBMS_OUTPUT.ENABLE(1000000);

SPOOL C:\output_&today_var..txt

DECLARE
   ab varchar2(10) := 'Raj';
   cd varchar2(10);
   a  number := 10;
   c  number;
   d  number; 
BEGIN
   c := a+10;
   --
   SELECT ab, c 
     INTO cd, d 
     FROM dual;
   --
   DBMS_OUTPUT.put_line('cd: '||cd);
   DBMS_OUTPUT.put_line('d: '||d);
END; 

SPOOL OFF

SET TERMOUT ON
SET FEEDBACK ON
SET VERIFY ON

PROMPT
PROMPT Done, please see file C:\output_&today_var..txt
PROMPT

Hope it helps...

EDIT:

After your comment to output a value for every iteration of a cursor (I realise each value will be the same in this example but you should get the gist of what i'm doing):

BEGIN
   c := a+10;
   --
   FOR i IN 1 .. 10
   LOOP
      c := a+10;
      -- Output the value of C
      DBMS_OUTPUT.put_line('c: '||c);
   END LOOP;
   --
END; 

What’s the best way to check if a file exists in C++? (cross platform)

Be careful of race conditions: if the file disappears between the "exists" check and the time you open it, your program will fail unexpectedly.

It's better to go and open the file, check for failure and if all is good then do something with the file. It's even more important with security-critical code.

Details about security and race conditions: http://www.ibm.com/developerworks/library/l-sprace.html

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

If anyone else stuck on same point, following solved my problem.

In web.xml

 <listener>
            <listener-class>
                    org.springframework.web.context.request.RequestContextListener 
            </listener-class>
  </listener>

In Session component

@Component
@Scope(value = "session",  proxyMode = ScopedProxyMode.TARGET_CLASS)

In pom.xml

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.1</version>
    </dependency>

Call Python function from JavaScript code

Communicating through processes

Example:

Python: This python code block should return random temperatures.

# sensor.py

import random, time
while True:
    time.sleep(random.random() * 5)  # wait 0 to 5 seconds
    temperature = (random.random() * 20) - 5  # -5 to 15
    print(temperature, flush=True, end='')

Javascript (Nodejs): Here we will need to spawn a new child process to run our python code and then get the printed output.

// temperature-listener.js

const { spawn } = require('child_process');
const temperatures = []; // Store readings

const sensor = spawn('python', ['sensor.py']);
sensor.stdout.on('data', function(data) {

    // convert Buffer object to Float
    temperatures.push(parseFloat(data));
    console.log(temperatures);
});

The entity type <type> is not part of the model for the current context

if you are trying DB first then be sure that your table has primary key

Omitting all xsi and xsd namespaces when serializing an object in .NET?

After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer and custom XML serialization via IXmlSerialiazble.

To wit, I'll use the same MyTypeWithNamespaces XML sample that's been used in the answers to this question so far.

[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
    // As noted below, per Microsoft's documentation, if the class exposes a public
    // member of type XmlSerializerNamespaces decorated with the 
    // XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
    // namespaces during serialization.
    public MyTypeWithNamespaces( )
    {
        this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
            // Don't do this!! Microsoft's documentation explicitly says it's not supported.
            // It doesn't throw any exceptions, but in my testing, it didn't always work.

            // new XmlQualifiedName(string.Empty, string.Empty),  // And don't do this:
            // new XmlQualifiedName("", "")

            // DO THIS:
            new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
            // Add any other namespaces, with prefixes, here.
        });
    }

    // If you have other constructors, make sure to call the default constructor.
    public MyTypeWithNamespaces(string label, int epoch) : this( )
    {
        this._label = label;
        this._epoch = epoch;
    }

    // An element with a declared namespace different than the namespace
    // of the enclosing type.
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        get { return this._label; }
        set { this._label = value; }
    }
    private string _label;

    // An element whose tag will be the same name as the property name.
    // Also, this element will inherit the namespace of the enclosing type.
    public int Epoch
    {
        get { return this._epoch; }
        set { this._epoch = value; }
    }
    private int _epoch;

    // Per Microsoft's documentation, you can add some public member that
    // returns a XmlSerializerNamespaces object. They use a public field,
    // but that's sloppy. So I'll use a private backed-field with a public
    // getter property. Also, per the documentation, for this to work with
    // the XmlSerializer, decorate it with the XmlNamespaceDeclarations
    // attribute.
    [XmlNamespaceDeclarations]
    public XmlSerializerNamespaces Namespaces
    {
        get { return this._namespaces; }
    }
    private XmlSerializerNamespaces _namespaces;
}

That's all to this class. Now, some objected to having an XmlSerializerNamespaces object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.

Now, when it comes time to serialize the class, you would use the following code:

MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);

/******
   OK, I just figured I could do this to make the code shorter, so I commented out the
   below and replaced it with what follows:

// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
    new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");

******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
    new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });

// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();

// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.

// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;

// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);

Once you have done this, you should get the following output:

<MyTypeWithNamespaces>
    <Label xmlns="urn:Whoohoo">myLabel</Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable.

It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi and xsd namespaces generated by the XmlSerializer.

UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra and Whoohoo. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra is the defalt namespace. I could inside my MyTypeWithNamespaces class add a namespace prefix for the Whoohoo namespace like so:

public MyTypeWithNamespaces
{
    this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
        new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
        new XmlQualifiedName("w", "urn:Whoohoo")
    });
}

Now, in my class definition, I indicated that the <Label/> element is in the namespace "urn:Whoohoo", so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:

<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
    <w:Label>myLabel</w:Label>
    <Epoch>42</Epoch>
</MyTypeWithNamespaces>

Because <Label> is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi and xsd namespaces.

ReferenceError: Invalid left-hand side in assignment

The same happened for me with eslint module. EsLinter throw Parsing error: Invalid left-hand side in assignment expression for await in second if statement.

if (condition_one) {
  let result = await myFunction()
}

if (condition_two) {
  let result = await myFunction() // eslint parsing error
}

As strange as it sounds what fixed this error was to add ; semicolon at the end of line where await occurred.

if (condition_one) {
  let result = await myFunction();
}

if (condition_two) {
  let result = await myFunction();
}

Does Visual Studio have code coverage for unit tests?

As already mentioned you can use Fine Code Coverage that visualize coverlet output. If you create a xunit test project (dotnet new xunit) you'll find coverlet reference already present in csproj file because Coverlet is the default coverage tool for every .NET Core and >= .NET 5 applications.

Microsoft has an example using ReportGenerator that converts coverage reports generated by coverlet, OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.

Example report:

enter image description here

While the article focuses on C# and xUnit as the test framework, both MSTest and NUnit would also work.

Guide:

https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports

If you want code coverage in .xml files you can run any of these commands:

dotnet test --collect:"XPlat Code Coverage"

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

Convert tabs to spaces in Notepad++

Settings -> Preference -> Edit Components (tab) -> Tab Setting (group) -> Replace by space

In version 5.6.8 (and above):

Settings -> Preferences... -> Language Menu/Tab Settings -> Tab Settings (group) -> Replace by space

Adding padding to a tkinter widget only on one side

There are multiple ways of doing that you can use either place or grid or even the packmethod.

Sample code:

from tkinter import *
root = Tk()

l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.

To place a widget to on basis of columns and rows , use the grid method:

but = Button(root, text="hello" )
but.grid(row=0, column=1)

Char array to hex string C++

The simplest:

int main()
{
    const char* str = "hello";
    for (const char* p = str; *p; ++p)
    {
        printf("%02x", *p);
    }
    printf("\n");
    return 0;
}

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

In Kotlin:

recyclerView.viewTreeObserver.addOnGlobalLayoutListener { scrollToEnd() }

private fun scrollToEnd() =
        (adapter.itemCount - 1).takeIf { it > 0 }?.let(recyclerView::smoothScrollToPosition)

How to find Max Date in List<Object>?

A small improvement from the accepted answer is to do the null check and also get full object.

public class DateComparator {

public static void main(String[] args) throws ParseException {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    List<Employee> employees = new ArrayList<>();
    employees.add(new Employee(1, "name1", addDays(new Date(), 1)));
    employees.add(new Employee(2, "name2", addDays(new Date(), 3)));
    employees.add(new Employee(3, "name3", addDays(new Date(), 6)));
    employees.add(new Employee(4, "name4", null));
    employees.add(new Employee(5, "name5", addDays(new Date(), 4)));
    employees.add(new Employee(6, "name6", addDays(new Date(), 5)));
    System.out.println(employees);
    Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).get();
    System.out.println(format.format(maxDate));
    //Comparator<Employee> comparator = (p1, p2) -> p1.getJoiningDate().compareTo(p2.getJoiningDate());
    Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
    Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).get();
    System.out.println(" maxDatedEmploye : " + maxDatedEmploye);

    Employee minDatedEmployee = employees.stream().filter(emp -> emp.getJoiningDate() != null).min(comparator).get();
    System.out.println(" minDatedEmployee : " + minDatedEmployee);

}

public static Date addDays(Date date, int days) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.DATE, days); // minus number would decrement the days
    return cal.getTime();
}
}

You would get below results :

 [Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018],
Employee [empId=2, empName=name2, joiningDate=Fri Mar 23 13:33:09 EDT 2018],
Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018],
Employee [empId=4, empName=name4, joiningDate=null],
Employee [empId=5, empName=name5, joiningDate=Sat Mar 24 13:33:09 EDT 2018],
Employee [empId=6, empName=name6, joiningDate=Sun Mar 25 13:33:09 EDT 2018]
]
2018-03-26
 maxDatedEmploye : Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018]

 minDatedEmployee : Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018]

Update : What if list itself is empty ?

        Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).orElse(new Date());
    System.out.println(format.format(maxDate));
    Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
    Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).orElse(null);
    System.out.println(" maxDatedEmploye : " + maxDatedEmploye);

How can I convert an integer to a hexadecimal string in C?

The following code takes an integer and makes a string out of it in hex format:

int  num = 32424;
char hex[5];

sprintf(hex, "%x", num);
puts(hex);

gives

7ea8

Git says remote ref does not exist when I delete remote branch

Given that the remote branch is remotes/origin/test you can use two ways:

git push origin --delete test

and

git branch -D -r origin/test

Parse RSS with jQuery

The jQuery-rss project is pretty lightweight and doesn't impose any particular styling.

The syntax can be as simple as

$("#rss-feeds").rss("http://www.recruiter.com/feed/career.xml")

See a working example at http://jsfiddle.net/jhfrench/AFHfn/

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

The issue is with this line

 xlo.Worksheets(1).Cells(2, 2) = TextBox1.Text

You have the textbox defined at some other location which you are not using here. Excel is unable to find the textbox object in the current sheet while this textbox was defined in xlw.

Hence replace this with

 xlo.Worksheets(1).Cells(2, 2) = worksheets("xlw").TextBox1.Text 

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

You need an extra reference for this; the most convenient way to do this is via the NuGet package System.IO.Compression.ZipFile

<!-- Version here correct at time of writing, but please check for latest -->
<PackageReference Include="System.IO.Compression.ZipFile" Version="4.3.0" />

If you are working on .NET Framework without NuGet, you need to add a dll reference to the assembly, "System.IO.Compression.FileSystem.dll" - and ensure you are using at least .NET 4.5 (since it doesn't exist in earlier frameworks).

For info, you can find the assembly and .NET version(s) from MSDN

How to load/edit/run/save text files (.py) into an IPython notebook cell?

I have not found a satisfying answer for this question, i.e how to load edit, run and save. Overwriting either using %%writefile or %save -f doesn't work well if you want to show incremental changes in git. It would look like you delete all the lines in filename.py and add all new lines, even though you just edit 1 line.

Using NOT operator in IF conditions

In general, ! is a perfectly good and readable boolean logic operator. No reason not to use it unless you're simplifying by removing double negatives or applying Morgan's law.

!(!A) = A

or

!(!A | !B) = A & B

As a rule of thumb, keep the signature of your boolean return methods mnemonic and in line with convention. The problem with the scenario that @hvgotcodes proposes is that of course a.b and c.d.e are not very friendly examples to begin with. Suppose you have a Flight and a Seat class for a flight booking application. Then the condition for booking a flight could perfectly be something like

if(flight.isActive() && !seat.isTaken())
{
    //book the seat
}

This perfectly readable and understandable code. You could re-define your boolean logic for the Seat class and rephrase the condition to this, though.

if(flight.isActive() && seat.isVacant())
{
    //book the seat
}

Thus removing the ! operator if it really bothers you, but you'll see that it all depends on what your boolean methods mean.

CSS submit button weird rendering on iPad/iPhone

The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)

-webkit-appearance:none;
opacity: 1

After setting the opacity, the button looked the same on all the different devices/emulator/desktop.

Java: How to get input from System.console()

I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.

It introduces an abstraction layer similar to the one proposed by McDowell. If System.console() returns null, the library switches to a Swing-based console.

In addition, Text-IO has a series of useful features:

  • supports reading values with various data types.
  • allows masking the input when reading sensitive data.
  • allows selecting a value from a list.
  • allows specifying constraints on the input values (format patterns, value ranges, length constraints etc.).

Usage example:

TextIO textIO = TextIoFactory.getTextIO();

String user = textIO.newStringInputReader()
        .withDefaultValue("admin")
        .read("Username");

String password = textIO.newStringInputReader()
        .withMinLength(6)
        .withInputMasking(true)
        .read("Password");

int age = textIO.newIntInputReader()
        .withMinVal(13)
        .read("Age");

Month month = textIO.newEnumInputReader(Month.class)
        .read("What month were you born in?");

textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
        "was born in " + month + " and has the password " + password + ".");

In this image you can see the above code running in a Swing-based console.

Add/remove class with jquery based on vertical scroll?

Is this value intended? if (scroll <= 500) { ... This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

use this code solve the problem:

string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + "Uploadfile\\" + fileName;
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, (int)fs.Length);
fs.Close();
Response.ContentType = "application/x-unknown/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName;+ "\"");
try
{
    if (bt != null)
    {
        System.IO.MemoryStream stream1 = new System.IO.MemoryStream(bt, true);
        stream1.Write(bt, 0, bt.Length);
        Response.BinaryWrite(bt);
        //Response.OutputStream.Write(bt, 0, (int)stream1.Length);
        Response.Flush();
        // Response.End();
    }
}
catch (Exception ex)
{
    Response.Write(ex.Message);
    throw ex;
}
finally
{
    Response.End();
}

What is the Ruby <=> (spaceship) operator?

What is <=> ( The 'Spaceship' Operator )

According to the RFC that introduced the operator, $a <=> $b

 -  0 if $a == $b
 - -1 if $a < $b
 -  1 if $a > $b

 - Return 0 if values on either side are equal
 - Return 1 if value on the left is greater
 - Return -1 if the value on the right is greater

Example:

//Comparing Integers

echo 1 <=> 1; //ouputs 0
echo 3 <=> 4; //outputs -1
echo 4 <=> 3; //outputs 1

//String Comparison

echo "x" <=> "x"; // 0
echo "x" <=> "y"; //-1
echo "y" <=> "x"; //1

MORE:

// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1

// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1

// Objects
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 0

reading HttpwebResponse json response, C#

I'd use RestSharp - https://github.com/restsharp/RestSharp

Create class to deserialize to:

public class MyObject {
    public string Id { get; set; }
    public string Text { get; set; }
    ...
}

And the code to get that object:

RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");

// The above code will make a request URL of 
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need

var response = client.Execute<MyObject>(request);

MyObject obj = response.Data;

Check out http://restsharp.org/ to get started.

How to fix a locale setting warning from Perl

We will set locales that are not unset after reboot.

First open the Bash file and edit it:

nano .bashrc

Add these lines to the file:

export LC_ALL="en_US.UTF-8"
export LANG="en_US.UTF-8"
export LANGUAGE="en_US.UTF-8"

Activate the change by reloading Bash:

source ~/.bashrc

Test results:

locale

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

I was upgrading tensorflow to 1.4.0 & was hitting my head on wall as this error was not solving, but finally solved it. Guess what?

One of my python script was running, and it was using tensorflow . Package installed successfully after closing it.

How does one represent the empty char?

It might be useful to assign a null in a string rather than explicitly making some index the null char '\0'. I've used this for testing functions that handle strings ensuring they stay within their appropriate bounds.

With:

char test_src[] = "fuu\0foo";

This creates an array of size 8 with values:

{'f', 'u', 'u', '\0', 'f', 'o', 'o', '\0'}

How to use ClassLoader.getResources() correctly?

There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.

For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.

Transposing a 2D-array in JavaScript

Another approach by iterating the array from outside to inside and reduce the matrix by mapping inner values.

_x000D_
_x000D_
const_x000D_
    transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []),_x000D_
    matrix = [[1, 2, 3], [1, 2, 3], [1, 2, 3]];_x000D_
_x000D_
console.log(transpose(matrix));
_x000D_
_x000D_
_x000D_

How to add elements of a Java8 stream into an existing List

The short answer is no (or should be no). EDIT: yeah, it's possible (see assylias' answer below), but keep reading. EDIT2: but see Stuart Marks' answer for yet another reason why you still shouldn't do it!

The longer answer:

The purpose of these constructs in Java 8 is to introduce some concepts of Functional Programming to the language; in Functional Programming, data structures are not typically modified, instead, new ones are created out of old ones by means of transformations such as map, filter, fold/reduce and many others.

If you must modify the old list, simply collect the mapped items into a fresh list:

final List<Integer> newList = list.stream()
                                  .filter(n -> n % 2 == 0)
                                  .collect(Collectors.toList());

and then do list.addAll(newList) — again: if you really must.

(or construct a new list concatenating the old one and the new one, and assign it back to the list variable—this is a little bit more in the spirit of FP than addAll)

As to the API: even though the API allows it (again, see assylias' answer) you should try to avoid doing that regardless, at least in general. It's best not to fight the paradigm (FP) and try to learn it rather than fight it (even though Java generally isn't a FP language), and only resort to "dirtier" tactics if absolutely needed.

The really long answer: (i.e. if you include the effort of actually finding and reading an FP intro/book as suggested)

To find out why modifying existing lists is in general a bad idea and leads to less maintainable code—unless you're modifying a local variable and your algorithm is short and/or trivial, which is out of the scope of the question of code maintainability—find a good introduction to Functional Programming (there are hundreds) and start reading. A "preview" explanation would be something like: it's more mathematically sound and easier to reason about to not modify data (in most parts of your program) and leads to higher level and less technical (as well as more human friendly, once your brain transitions away from the old-style imperative thinking) definitions of program logic.

How to convert Milliseconds to "X mins, x seconds" in Java?

This answer is similar to some answers above. However, I feel that it would be beneficial because, unlike other answers, this will remove any extra commas or whitespace and handles abbreviation.

/**
 * Converts milliseconds to "x days, x hours, x mins, x secs"
 * 
 * @param millis
 *            The milliseconds
 * @param longFormat
 *            {@code true} to use "seconds" and "minutes" instead of "secs" and "mins"
 * @return A string representing how long in days/hours/minutes/seconds millis is.
 */
public static String millisToString(long millis, boolean longFormat) {
    if (millis < 1000) {
        return String.format("0 %s", longFormat ? "seconds" : "secs");
    }
    String[] units = {
            "day", "hour", longFormat ? "minute" : "min", longFormat ? "second" : "sec"
    };
    long[] times = new long[4];
    times[0] = TimeUnit.DAYS.convert(millis, TimeUnit.MILLISECONDS);
    millis -= TimeUnit.MILLISECONDS.convert(times[0], TimeUnit.DAYS);
    times[1] = TimeUnit.HOURS.convert(millis, TimeUnit.MILLISECONDS);
    millis -= TimeUnit.MILLISECONDS.convert(times[1], TimeUnit.HOURS);
    times[2] = TimeUnit.MINUTES.convert(millis, TimeUnit.MILLISECONDS);
    millis -= TimeUnit.MILLISECONDS.convert(times[2], TimeUnit.MINUTES);
    times[3] = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < 4; i++) {
        if (times[i] > 0) {
            s.append(String.format("%d %s%s, ", times[i], units[i], times[i] == 1 ? "" : "s"));
        }
    }
    return s.toString().substring(0, s.length() - 2);
}

/**
 * Converts milliseconds to "x days, x hours, x mins, x secs"
 * 
 * @param millis
 *            The milliseconds
 * @return A string representing how long in days/hours/mins/secs millis is.
 */
public static String millisToString(long millis) {
    return millisToString(millis, false);
}

What's a clean way to stop mongod on Mac OS X?

If you have installed mongodb community server via homebrew, then you can do:

brew services list

This will list the current services as below:

Name              Status  User          Plist
mongodb-community started thehaystacker /Users/thehaystacker/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist

redis             stopped

Then you can restart mongodb by first stopping and restart:

brew services stop mongodb
brew services start mongodb

Swift how to sort array of custom objects by property value

If you want to sort original array of custom objects. Here is another way to do so in Swift 2.1

var myCustomerArray = [Customer]()
myCustomerArray.sortInPlace {(customer1:Customer, customer2:Customer) -> Bool in
    customer1.id < customer2.id
}

Where id is an Integer. You can use the same < operator for String properties as well.

You can learn more about its use by looking at an example here: Swift2: Nearby Customers

How to get controls in WPF to fill available space?

There are also some properties you can set to force a control to fill its available space when it would otherwise not do so. For example, you can say:

HorizontalContentAlignment="Stretch"

... to force the contents of a control to stretch horizontally. Or you can say:

HorizontalAlignment="Stretch"

... to force the control itself to stretch horizontally to fill its parent.

Should I use SVN or Git?

It comes down to this:

Will your development be linear? If so, you should stick with Subversion.

If on the other hand, your development will not be linear, which means that you will need to create branching for different changes, and then merging such changes back to the main development line (known to Git as the master branch) then Git will do MUCH more for you.

nodejs module.js:340 error: cannot find module

I had the same problem then I found that I wasn´t hitting the node server command in the proper directory where the server.js is located.

Hope this helps.

What is a tracking branch?

The Pro Git book mentions:

Tracking branches are local branches that have a direct relationship to a remote branch

Not exactly. The SO question "Having a hard time understanding git-fetch" includes:

There's no such concept of local tracking branches, only remote tracking branches.
So origin/master is a remote tracking branch for master in the origin repo.

But actually, once you establish an upstream branch relationship between:

  • a local branch like master
  • and a remote tracking branch like origin/master

Then you can consider master as a local tracking branch: It tracks the remote tracking branch origin/master which, in turn, tracks the master branch of the upstream repo origin.

alt text

Regular expression for a hexadecimal number?

If you are looking for an specific hex character in the middle of the string, you can use "\xhh" where hh is the character in hexadecimal. I've tried and it works. I use framework for C++ Qt but it can solve problems in other cases, depends on the flavor you need to use (php, javascript, python , golang, etc.).

This answer was taken from:http://ult-tex.net/info/perl/

Property 'json' does not exist on type 'Object'

For future visitors: In the new HttpClient (Angular 4.3+), the response object is JSON by default, so you don't need to do response.json().data anymore. Just use response directly.

Example (modified from the official documentation):

import { HttpClient } from '@angular/common/http';

@Component(...)
export class YourComponent implements OnInit {

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('https://api.github.com/users')
        .subscribe(response => console.log(response));
  }
}

Don't forget to import it and include the module under imports in your project's app.module.ts:

...
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module after BrowserModule.
    HttpClientModule,
    ...
  ],
  ...

How can I decrease the size of Ratingbar?

If you are using Rating bar in Linearlayout with weightSum. Please make sure that you should not assign the layout_weight for rating bar. Instead, that place rating bar inside relative layout and give weight to the relative layout. Make rating bar width wrap content.

<RelativeLayout
    android:layout_width="0dp"
    android:layout_weight="30"
    android:layout_gravity="center"
    android:layout_height="wrap_content">
        <RatingBar
            android:id="@+id/userRating"
            style="@style/Widget.AppCompat.RatingBar.Small"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:stepSize="1" />
</RelativeLayout>

Git: How to squash all commits on branch

Another simple way to do this: go on the origin branch and do a merge --squash. This command doesn't do the "squashed" commit. when you do it, all commit messages of yourBranch will be gathered.

$ git checkout master
$ git merge --squash yourBranch
$ git commit # all commit messages of yourBranch in one, really useful
 > [status 5007e77] Squashed commit of the following: ...

How to start Spyder IDE on Windows

As stated in the documentation of Spyder, you need to install PyQt5 first.

Open a Command Prompt as Administrator, then run:

pip install pyqt5
pip install spyder

Then you can find the spyder3.exe in the Python3.6/Scripts folder. You can also make a shortcut to it. No need for Anaconda.

How to define a two-dimensional array?

If all you want is a two dimensional container to hold some elements, you could conveniently use a dictionary instead:

Matrix = {}

Then you can do:

Matrix[1,2] = 15
print Matrix[1,2]

This works because 1,2 is a tuple, and you're using it as a key to index the dictionary. The result is similar to a dumb sparse matrix.

As indicated by osa and Josap Valls, you can also use Matrix = collections.defaultdict(lambda:0) so that the missing elements have a default value of 0.

Vatsal further points that this method is probably not very efficient for large matrices and should only be used in non performance-critical parts of the code.

Using multiple .cpp files in c++ program?

You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.

other.h

void MyFunc();

main.cpp

#include "other.h"
int main() {
    MyFunc();
}

other.cpp

#include "other.h"
#include <iostream>
void MyFunc() {
    std::cout << "Ohai from another .cpp file!";
    std::cin.get();
}

JCheckbox - ActionListener and ItemListener?

For reference, here's an sscce that illustrates the difference. Console:

SELECTED
ACTION_PERFORMED
DESELECTED
ACTION_PERFORMED

Code:

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

/** @see http://stackoverflow.com/q/9882845/230513 */
public class Listeners {

    private void display() {
        JFrame f = new JFrame("Listeners");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JCheckBox b = new JCheckBox("JCheckBox");
        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(e.getID() == ActionEvent.ACTION_PERFORMED
                    ? "ACTION_PERFORMED" : e.getID());
            }
        });
        b.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                System.out.println(e.getStateChange() == ItemEvent.SELECTED
                    ? "SELECTED" : "DESELECTED");
            }
        });
        JPanel p = new JPanel();
        p.add(b);
        f.add(p);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Listeners().display();
            }
        });
    }
}

git ignore exception

This is how I do it, with a README.md file in each directory:

/data/*
!/data/README.md

!/data/input/
/data/input/*
!/data/input/README.md

!/data/output/
/data/output/*
!/data/output/README.md

How to fix .pch file missing on build?

I know this topic is very old, but I was dealing with this in VS2015 recently and what helped was to deleted the build folders and re-build it. This may have happen due to trying to close the program or a program halting/freezing VS while building.

In which conda environment is Jupyter executing?

You can also switch environments in Anaconda Navigator, install Jupiter and run it. Anaconda Navigator

Suppress/ print without b' prefix for bytes in Python 3

If the bytes use an appropriate character encoding already; you could print them directly:

sys.stdout.buffer.write(data)

or

nwritten = os.write(sys.stdout.fileno(), data)  # NOTE: it may write less than len(data) bytes

AppCompat v7 r21 returning error in values.xml?

THIS HELPED ME

  • Update the Android SDK to latest version
  • Update app/build.gradle with latest components:

    compileSdkVersion 25  
    buildToolsVersion "25.0.2"  
    minSdkVersion 17  
    targetSdkVersion 25
    

Hope this solves your problem

How to Create a real one-to-one relationship in SQL Server

I'm pretty sure it is technically impossible in SQL Server to have a True 1 to 1 relationship, as that would mean you would have to insert both records at the same time (otherwise you'd get a constraint error on insert), in both tables, with both tables having a foreign key relationship to each other.

That being said, your database design described with a foreign key is a 1 to 0..1 relationship. There is no constrain possible that would require a record in tableB. You can have a pseudo-relationship with a trigger that creates the record in tableB.

So there are a few pseudo-solutions

First, store all the data in a single table. Then you'll have no issues in EF.

Or Secondly, your entity must be smart enough to not allow an insert unless it has an associated record.

Or thirdly, and most likely, you have a problem you are trying to solve, and you are asking us why your solution doesn't work instead of the actual problem you are trying to solve (an XY Problem).

UPDATE

To explain in REALITY how 1 to 1 relationships don't work, I'll use the analogy of the Chicken or the egg dilemma. I don't intend to solve this dilemma, but if you were to have a constraint that says in order to add a an Egg to the Egg table, the relationship of the Chicken must exist, and the chicken must exist in the table, then you couldn't add an Egg to the Egg table. The opposite is also true. You cannot add a Chicken to the Chicken table without both the relationship to the Egg and the Egg existing in the Egg table. Thus no records can be every made, in a database without breaking one of the rules/constraints.

Database nomenclature of a one-to-one relationship is misleading. All relationships I've seen (there-fore my experience) would be more descriptive as one-to-(zero or one) relationships.

What is the optimal way to compare dates in Microsoft SQL server?

Converting to a DATE or using an open-ended date range in any case will yield the best performance. FYI, convert to date using an index are the best performers. More testing a different techniques in article: What is the most efficient way to trim time from datetime? Posted by Aaron Bertrand

From that article:

DECLARE @dateVar datetime = '19700204';

-- Quickest when there is an index on t.[DateColumn], 
-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE, t.[DateColumn]) = CONVERT(DATE, @dateVar);

-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY, 1, @dateVar);
SELECT t.[DateColumn] 
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND 
      t.[DateColumn] < @dateEnd;

Also from that article: using BETWEEN, DATEDIFF or CONVERT(CHAR(8)... are all slower.

Property 'map' does not exist on type 'Observable<Response>'

I tried all the possible answers posted above none of them worked,

I resolved it by simply restarting my IDE i.e., Visual Studio Code

May it helps someone.

Repeat a string in JavaScript a number of times

Right pads with zeros with no arrays or loops. Just uses repeat() using ES6 2015, which has wide support now. Left pads if you switch the concatenation.

function pad(text, maxLength){ 
  var res = text + "0".repeat(maxLength - text.length);
  return res;
}

console.log(pad('hello', 8)); //hello000

Sending commands and strings to Terminal.app with Applescript

Petruza,

Instead of using keystroke use key code.
The following example should work for you.

tell application "System Events"
    tell application process "Terminal"
        set frontmost to true
        key code {2, 0, 17, 14}
        keystroke return
    end tell
end tell

The above example will send the characters {d a t e} to Terminal and then
keystroke return will enter and run the command. Use the above example
with whatever key codes you need and you'll be able to do what you're trying to do.

WCF, Service attribute value in the ServiceHost directive could not be found

If you have renamed anything verify the (Properties/) AssemblyInfo.cs is correct, as well as the header in the service file.

ServiceName.svc

<%@ ServiceHost Language="C#" Debug="true" Service="Company.Namespace.WcfApp" CodeBehind="WcfApp.svc.cs" %>

Aligning with your namespace in your Service.svc.cs

How to trigger a click on a link using jQuery

Sorry, but the event handler is really not needed. What you do need is another element within the tag to click on.

<a id="test1" href="javascript:alert('test1')">TEST1</a>
<a id="test2" href="javascript:alert('test2')"><span>TEST2</span></a>

Jquery:

$('#test1').trigger('click'); // Nothing
$('#test2').find('span').trigger('click'); // Works
$('#test2 span').trigger('click'); // Also Works

This is all about what you are clicking and it is not the tag but the thing within it. Unfortunately, bare text does not seem to be recognised by JQuery, but it is by vanilla javascript:

document.getElementById('test1').click(); // Works!

Or by accessing the jQuery object as an array

$('#test1')[0].click(); // Works too!!!

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

Basically you tried to use a nil value in places where Swift allows only non-nil ones, by telling the compiler to trust you that there will never be nil value there, thus allowing your app to compile.

There are several scenarios that lead to this kind of fatal error:

  1. forced unwraps:

    let user = someVariable!
    

    If someVariable is nil, then you'll get a crash. By doing a force unwrap you moved the nil check responsibility from the compiler to you, basically by doing a forced unwrap you're guaranteeing to the compiler that you'll never have nil values there. And guess what it happens if somehow a nil value ends in in someVariable?

    Solution? Use optional binding (aka if-let), do the variable processing there:

    if user = someVariable {
        // do your stuff
    }
    
  2. forced (down)casts:

    let myRectangle = someShape as! Rectangle
    

    Here by force casting you tell the compiler to no longer worry, as you'll always have a Rectangle instance there. And as long as that holds, you don't have to worry. The problems start when you or your colleagues from the project start circulating non-rectangle values.

    Solution? Use optional binding (aka if-let), do the variable processing there:

    if let myRectangle = someShape as? Rectangle {
        // yay, I have a rectangle
    }
    
  3. Implicitly unwrapped optionals. Let's assume you have the following class definition:

    class User {
        var name: String!
    
        init() {
            name = "(unnamed)"
        }
    
        func nicerName() {
            return "Mr/Ms " + name
        }
    }
    

    Now, if no-one messes up with the name property by setting it to nil, then it works as expected, however if User is initialized from a JSON that lacks the name key, then you get the fatal error when trying to use the property.

    Solution? Don't use them :) Unless you're 102% sure that the property will always have a non-nil value by the time it needs to be used. In most cases converting to an optional or non-optional will work. Making it non-optional will also result in the compiler helping you by telling the code paths you missed giving a value to that property

  4. Unconnected, or not yet connected, outlets. This is a particular case of scenario #3. Basically you have some XIB-loaded class that you want to use.

    class SignInViewController: UIViewController {
    
        @IBOutlet var emailTextField: UITextField!
    }
    

    Now if you missed connecting the outlet from the XIB editor, then the app will crash as soon as you'll want to use the outlet. Solution? Make sure all outlets are connected. Or use the ? operator on them: emailTextField?.text = "[email protected]". Or declare the outlet as optional, though in this case the compiler will force you to unwrap it all over the code.

  5. Values coming from Objective-C, and that don't have nullability annotations. Let's assume we have the following Objective-C class:

    @interface MyUser: NSObject
    @property NSString *name;
    @end
    

    Now if no nullability annotations are specified (either explicitly or via NS_ASSUME_NONNULL_BEGIN/NS_ASSUME_NONNULL_END), then the name property will be imported in Swift as String! (an IUO - implicitly unwrapped optional). As soon as some swift code will want to use the value, it will crash if name is nil.

    Solution? Add nullability annotations to your Objective-C code. Beware though, the Objective-C compiler is a little bit permissive when it comes to nullability, you might end up with nil values, even if you explicitly marked them as nonnull.

How to close TCP and UDP ports via windows command line

wkillcx is a reliable windows command line tool for killing tcp connections from the command line that hasn't been mentioned. It does have issues with servers with large number of connections sometimes though. I sometimes use tcpview for interactive kills but wkillcx can be used in scripts.

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

This error is coming from the staticfile handler -- which by default doesn't filter any verbs, but probably can only deal with HEAD and GET.

And this is because no other handler stepped up to the plate and said they could handle DELETE.

Since you are using the WEBAPI, which because of routing doesn't have files and therefore extensions, the following additions need to be added to your web.config file:

<system.webserver>
    <httpProtocol>
        <handlers>
          ...
            <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
            <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />

            <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="C:\windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
            <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="C:\windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

Obviously what is needed depends on classicmode vs integratedmode, and classicmode depends on bitness. In addition, the OPTIONS header has been added for CORS processing, but if you don't do CORS you don't need that.

FYI, your web.config is the local to the application (or application directory) version whose top level is applicationHost.config.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

Select "all project" and right click

Maven-> Update project

iOS how to set app icon and launch images

I use a tool called Prepo to produce all the right image sizes. You simply feed the app you image file and it will spit out each necessary file with an appropriate name.

Once you do this, you can then drag in the appropriate files or simply point to your Prepo exported folder.

Print PHP Call Stack

Strange that noone posted this way:

debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);

This actually prints backtrace without the garbage - just what method was called and where.

CSS checkbox input styling

Although CSS does provide a way for you to do the style specific to the checkbox type or another type, there are going to be problems with browsers that do not support this.

I think your only option in this case is going to be to apply classes to your checkboxes.

just add the class="checkbox" to your checkboxes.

Then create that style in your css code.

One thing you could do is this:

main.css

input[type="checkbox"] { /* css code here */ }

ie.css

.checkbox{ /* css code here for ie */ }

Then use the IE specific css include:

<!--[if lt IE 7]>
   <link rel="stylesheet" type="text/css" href="ie.css" />
<![endif]-->

You will still need to add the class for it to work in IE, and it will not work in other non-IE browsers that do not support IE. But it will make your website forward-thinking with css code and as IE gets support, you will be able to remove the ie specific css code and also the css classes from the checkboxes.

How to get min, seconds and milliseconds from datetime.now() in python?

Sorry to open an old thread but I'm posting just in case it helps someone. This seems to be the easiest way to do this in Python 3.

from datetime import datetime

Date = str(datetime.now())[:10]
Hour = str(datetime.now())[11:13]
Minute = str(datetime.now())[14:16]
Second = str(datetime.now())[17:19]
Millisecond = str(datetime.now())[20:]

If you need the values as a number just cast them as an int e.g

Hour = int(str(datetime.now())[11:13])

What's the difference between import java.util.*; and import java.util.Date; ?

import java.util.*;

imports everything within java.util including the Date class.

import java.util.Date;

just imports the Date class.

Doing either of these could not make any difference.

How to manually update datatables table with new JSON data

You need to destroy old data-table instance and then re-initialize data-table

First Check if data-table instance exist by using $.fn.dataTable.isDataTable

if exist then destroy it and then create new instance like this

    if ($.fn.dataTable.isDataTable('#dataTableExample')) {
        $('#dataTableExample').DataTable().destroy();
    }

    $('#dataTableExample').DataTable({
        responsive: true,
        destroy: true
    });

LINQ Group By and select collection

you may also like this

var Grp = Model.GroupBy(item => item.Order.Customer)
      .Select(group => new 
        { 
             Customer = Model.First().Customer, 
             CustomerId= group.Key,  
             Orders= group.ToList() 
       })
      .ToList();

Eclipse: Frustration with Java 1.7 (unbound library)

Updated eclipse.ini file with key value property -Dosgi.requiredJavaVersion=1.7 (or) 1.8 whichever applicable. - it works for me.

plot with custom text for x axis points

This worked for me. Each month on X axis

str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)

How can I get the error message for the mail() function?

Try this. If I got any error on any file then I got error mail on my email id. Create two files index.php and checkErrorEmail.php and uploaded them to your server. Then load index.php with your browser.

Index.php

<?php
    include('checkErrorEmail.php');
    include('dereporting.php');
    $temp;
    echo 'hi '.$temp;
?>

checkErrorEmail.php

<?php
  // Destinations
  define("ADMIN_EMAIL", "[email protected]");
  //define("LOG_FILE", "/my/home/errors.log");

  // Destination types
  define("DEST_EMAIL", "1");
  //define("DEST_LOGFILE", "3");

  /* Examples */

  // Send an e-mail to the administrator
  //error_log("Fix me!", DEST_EMAIL, ADMIN_EMAIL);

  // Write the error to our log file
  //error_log("Error", DEST_LOGFILE, LOG_FILE);

  /**
    * my_error_handler($errno, $errstr, $errfile, $errline)
    *
    * Author(s): thanosb, ddonahue
    * Date: May 11, 2008
    * 
    * custom error handler
    *
    * Parameters:
    *  $errno:   Error level
    *  $errstr:  Error message
    *  $errfile: File in which the error was raised
    *  $errline: Line at which the error occurred
    */

  function my_error_handler($errno, $errstr, $errfile, $errline)
  {  
  echo "<br><br><br><br>errno ".$errno.",<br>errstr ".$errstr.",<br>errfile ".$errfile.",<br>errline ".$errline;
      if($errno)
      {
              error_log("Error: $errstr \n error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);
      }
    /*switch ($errno) {
      case E_USER_ERROR:
        // Send an e-mail to the administrator
        error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_EMAIL, ADMIN_EMAIL);

        // Write the error to our log file
        //error_log("Error: $errstr \n Fatal error on line $errline in file $errfile \n", DEST_LOGFILE, LOG_FILE);
        break;

      case E_USER_WARNING:
        // Write the error to our log file
        //error_log("Warning: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
        break;

      case E_USER_NOTICE:
        // Write the error to our log file
       // error_log("Notice: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
        break;

      default:
        // Write the error to our log file
        //error_log("Unknown error [#$errno]: $errstr \n in $errfile on line $errline \n", DEST_LOGFILE, LOG_FILE);
        break;
    }*/

    // Don't execute PHP's internal error handler
    return TRUE;
  }


  // Use set_error_handler() to tell PHP to use our method
  $old_error_handler = set_error_handler("my_error_handler");


?>

Sending email with gmail smtp with codeigniter email library

$config = Array(
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.googlemail.com',
    'smtp_port' => 465,
    'smtp_user' => 'xxx',
    'smtp_pass' => 'xxx',
    'mailtype'  => 'html', 
    'charset'   => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");

// Set to, from, message, etc.

$result = $this->email->send();

From the CodeIgniter Forums

How do I enable TODO/FIXME/XXX task tags in Eclipse?

I'm using Eclipse Classic 3.7.1.

The solution is: Window > Preferences > General > Editors > Sctructured Text Editors > Task Tags and checking "Enable searching for Task Tags" checkbox.

How to decode a QR-code image in (preferably pure) Python?

For Windows using ZBar

Pre-requisites:

To decode:

from PIL import Image
from pyzbar import pyzbar

img = Image.open('My-Image.jpg')
output = pyzbar.decode(img)
print(output)

Alternatively, you can also try using ZBarLight by setting it up as mentioned here:
https://pypi.org/project/zbarlight/

What is the 'realtime' process priority setting for?

It would be the highest available priority setting, and would usually only be used on box that was dedicated to running that specific program. It's actually high enough that it could cause starvation of the keyboard and mouse threads to the extent that they become unresponsive.

So basicly, if you have to ask, don't use it :)

Is it possible to install another version of Python to Virtualenv?

You may use pyenv.

There are a lot of different versions anaconda, jython, pypy and so on...

https://github.com/yyuu/pyenv

Installation as simple as pyenv install 3.2.6

pyenv install --list
Available versions:
  2.1.3
  2.2.3
  2.3.7
  2.4
  2.4.1
  2.4.2
  2.4.3
  2.4.4
  2.4.5
  2.4.6
  2.5
  2.5.1
  2.5.2
  2.5.3
  2.5.4
  2.5.5
  2.5.6
  2.6.6

...

How to create jobs in SQL Server Express edition

The functionality of creating SQL Agent Jobs is not available in SQL Server Express Edition. An alternative is to execute a batch file that executes a SQL script using Windows Task Scheduler.

In order to do this first create a batch file named sqljob.bat

sqlcmd -S servername -U username -P password -i <path of sqljob.sql>

Replace the servername, username, password and path with yours.

Then create the SQL Script file named sqljob.sql

USE [databasename]
--T-SQL commands go here
GO

Replace the [databasename] with your database name. The USE and GO is necessary when you write the SQL script.

sqlcmd is a command-line utility to execute SQL scripts. After creating these two files execute the batch file using Windows Task Scheduler.

NB: An almost same answer was posted for this question before. But I felt it was incomplete as it didn't specify about login information using sqlcmd.

Present and dismiss modal view controller

presentModalViewController:

MainViewController *mainViewController=[[MainViewController alloc]init];
[self.navigationController presentModalViewController:mainViewController animated:YES];

dismissModalViewController:

[self dismissModalViewControllerAnimated:YES];

Handling ExecuteScalar() when no results are returned

This is the easiest way to do this...

sql = "select username from usermst where userid=2"
object getusername = command.ExecuteScalar();
if (getusername!=null)
{
    //do whatever with the value here
    //use getusername.toString() to get the value from the query
}

Running multiple commands with xargs

You can use

cat file.txt | xargs -i  sh -c 'command {} | command2 {} && command3 {}'

{} = variable for each line on the text file

Calling UserForm_Initialize() in a Module

IMHO the method UserForm_Initialize should remain private bacause it is event handler for Initialize event of the UserForm.

This event handler is called when new instance of the UserForm is created. In this even handler u can initialize the private members of UserForm1 class.

Example:

Standard module code:

Option Explicit

Public Sub Main()
  Dim myUserForm As UserForm1

  Set myUserForm = New UserForm1
  myUserForm.Show

End Sub

User form code:

Option Explicit

Private m_initializationDate As Date

Private Sub UserForm_Initialize()
  m_initializationDate = VBA.DateTime.Date
  MsgBox "Hi from UserForm_Initialize event handler.", vbInformation
End Sub

How to use android emulator for testing bluetooth application?

Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux instead of Other.

After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.

Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.

Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.

Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.

In VirtualBox screen, go to Devices>USB devices. Select your dongle.

Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.

Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.

Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .

Source

How to install a previous exact version of a NPM package?

On Ubuntu you can try this command.

sudo npm cache clean -f
sudo npm install -g n
sudo n stable 

Specific version : sudo n 8.11.3 instead of sudo n stable

How to throw std::exceptions with variable messages?

The standard exceptions can be constructed from a std::string:

#include <stdexcept>

char const * configfile = "hardcode.cfg";
std::string const anotherfile = get_file();

throw std::runtime_error(std::string("Failed: ") + configfile);
throw std::runtime_error("Error: " + anotherfile);

Note that the base class std::exception can not be constructed thus; you have to use one of the concrete, derived classes.

jQuery - Dynamically Create Button and Attach Event Handler

Your problem is that you're converting the button into an HTML snippet when you add it to the table, but that snippet is not the same object as the one that has the click handler on it.

$("#myButton").click(function () {
    var test = $('<button>Test</button>').click(function () {
        alert('hi');
    });

    $("#nodeAttributeHeader").css('display', 'table-row'); // NB: changed

    var tr = $('<tr>').insertBefore('#addNodeTable tr:last');
    var td = $('<td>').append(test).appendTo(tr);
});

Set width to match constraints in ConstraintLayout

I found one more answer when there is a constraint layout inside the scroll view then we need to put

android:fillViewport="true"

to the scroll view

and

android:layout_height="0dp"

in the constraint layout

Example:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

    <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="0dp">

// Rest of the views

</androidx.constraintlayout.widget.ConstraintLayout>

</ScrollView>