Programs & Examples On #Browser width

ipython notebook clear cell output in code

You can use IPython.display.clear_output to clear the output of a cell.

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print("Hello World!")

At the end of this loop you will only see one Hello World!.

Without a code example it's not easy to give you working code. Probably buffering the latest n events is a good strategy. Whenever the buffer changes you can clear the cell's output and print the buffer again.

To show only file name without the entire directory path

The selected answer did not work for me, as I had spaces, quotes and other strange characters in my filenames. To quote the input for basename, you should use:

ls /path/to/my/directory | xargs -n1 -I{} basename "{}"

This is guaranteed to work, regardless of what the files are called.

What is the default maximum heap size for Sun's JVM from Java SE 6?

One can ask with some Java code:

long maxBytes = Runtime.getRuntime().maxMemory();
System.out.println("Max memory: " + maxBytes / 1024 / 1024 + "M");

See javadoc.

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

I encountered the same error when added http-builder to dependencies.
In my case, I could solve by simply excluding asm like this:

compile('org.codehaus.groovy.modules.http-builder:http-builder:0.7'){
    excludes 'xml-apis'
    exclude(group:'xerces', module: 'xercesImpl')
    excludes 'asm'
}

How to align this span to the right of the div?

The solution using flexbox without justify-content: space-between.

<div class="title">
  <span>Cumulative performance</span>
  <span>20/02/2011</span>
</div>

.title {
  display: flex;
}

span:first-of-type {
  flex: 1;
}

When we use flex:1 on the first <span>, it takes up the entire remaining space and moves the second <span> to the right. The Fiddle with this solution: https://jsfiddle.net/2k1vryn7/

Here https://jsfiddle.net/7wvx2uLp/3/ you can see the difference between two flexbox approaches: flexbox with justify-content: space-between and flexbox with flex:1 on the first <span>.

isset() and empty() - what to use

In your particular case: if ($var).

You need to use isset if you don't know whether the variable exists or not. Since you declared it on the very first line though, you know it exists, hence you don't need to, nay, should not use isset.

The same goes for empty, only that empty also combines a check for the truthiness of the value. empty is equivalent to !isset($var) || !$var and !empty is equivalent to isset($var) && $var, or isset($var) && $var == true.

If you only want to test a variable that should exist for truthiness, if ($var) is perfectly adequate and to the point.

PHP check whether property exists in object or class

Just putting my 2 cents here.

Given the following class:

class Foo
{
  private $data;

  public function __construct(array $data)
  {
    $this->data = $data;
  }

  public function __get($name)
  {
    return $data[$name];
  }

  public function __isset($name)
  {
    return array_key_exists($name, $this->data);
  }
}

the following will happen:

$foo = new Foo(['key' => 'value', 'bar' => null]);

var_dump(property_exists($foo, 'key'));  // false
var_dump(isset($foo->key));  // true
var_dump(property_exists($foo, 'bar'));  // false
var_dump(isset($foo->bar));  // true, although $data['bar'] == null

Hope this will help anyone

How can I check for an empty/undefined/null string in JavaScript?

I usually use something like this,

if (!str.length) {
    // Do something
}

Questions every good Java/Java EE Developer should be able to answer?

How about what is a session bean and describe some differences between stateless and stateful session beans.

Uri content://media/external/file doesn't exist for some devices

Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.

How to supply value to an annotation from a Constant java

You're not supplying it with an array in your example. The following compiles fine:

public @interface SampleAnnotation {
    String[] sampleValues();
}

public class Values {
    public static final String val0 = "A";
    public static final String val1 = "B";

    @SampleAnnotation(sampleValues={ val0, val1 })
    public void foo() {
    }
}

Returning data from Axios API

IMO extremely important rule of thumb for your client side js code is to keep separated the data handling and ui building logic into different funcs, which is also valid for axios data fetching ... in this way your control flow and error handlings will be much more simple and easier to manage, as it could be seen from this ok fetch

and this NOK fetch

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>

       function getUrlParams (){
          var url_params = new URLSearchParams();
          if( window.location.toString().indexOf("?") != -1) {
             var href_part = window.location.search.split('?')[1]
             href_part.replace(/([^=&]+)=([^&]*)/g,
                function(m, key, value) {
                   var attr = decodeURIComponent(key)
                   var val = decodeURIComponent(value)
                   url_params.append(attr,val);
             });
          }
          // for(var pair of url_params.entries()) { consolas.log(pair[0]+ '->'+ pair[1]); }
          return url_params ;
       }


      function getServerData (url, urlParams ){
          if ( typeof url_params == "undefined" ) { urlParams = getUrlParams()  }
          return axios.get(url , { params: urlParams } )
          .then(response => {
             return response ;
          })
          .catch(function(error) {
             console.error ( error )
             return error.response;
          })
       }

    // Action !!!
    getServerData(url , url_params)
        .then( response => {
           if ( response.status === 204 ) {
              var warningMsg = response.statusText
              console.warn ( warningMsg )
              return
           } else if ( response.status === 404 || response.status === 400) {
              var errorMsg = response.statusText // + ": "  + response.data.msg // this is my api
              console.error( errorMsg )
              return ;
           } else {
              var data = response.data
              var dataType = (typeof data)
              if ( dataType === 'undefined' ) {
                 var msg = 'unexpected error occurred while fetching data !!!'
                 // pass here to the ui change method the msg aka
                 // showMyMsg ( msg , "error")
              } else {
                 var items = data.dat // obs this is my api aka "dat" attribute - that is whatever happens to be your json key to get the data from
                 // call here the ui building method
                 // BuildList ( items )
              }
              return
           }

        })




    </script>

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

Here is a modification for the prev. answer. The main difference is when the user is not authenticated, it uses the original "HandleUnauthorizedRequest" method to redirect to login page:

   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {

        if (filterContext.HttpContext.User.Identity.IsAuthenticated) {

            filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Account",
                                action = "Unauthorised"
                            })
                        );
        }
        else
        {
             base.HandleUnauthorizedRequest(filterContext);
        }
    }

Chrome refuses to execute an AJAX script due to wrong MIME type

By adding a callback argument, you are telling jQuery that you want to make a request for JSONP using a script element instead of a request for JSON using XMLHttpRequest.

JSONP is not JSON. It is a JavaScript program.

Change your server so it outputs the right MIME type for JSONP which is application/javascript.

(While you are at it, stop telling jQuery that you are expecting JSON as that is contradictory: dataType: 'jsonp').

Adding a y-axis label to secondary y-axis in matplotlib

There is a straightforward solution without messing with matplotlib: just pandas.

Tweaking the original example:

table = sql.read_frame(query,connection)

ax = table[0].plot(color=colors[0],ylim=(0,100))
ax2 = table[1].plot(secondary_y=True,color=colors[1], ax=ax)

ax.set_ylabel('Left axes label')
ax2.set_ylabel('Right axes label')

Basically, when the secondary_y=True option is given (eventhough ax=ax is passed too) pandas.plot returns a different axes which we use to set the labels.

I know this was answered long ago, but I think this approach worths it.

How to set the environmental variable LD_LIBRARY_PATH in linux

For some reason no one has mentioned the fact that the bashrc needs to be re-sourced after editing. You can either log out and log back in (like mentioned above) but you can also use the commands: source ~/.bashrc or . ~/.bashrc.

How to find out what character key is pressed?

**check this out** 
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(document).keypress(function(e)
        {

            var keynum;
            if(window.event)
            { // IE                 
                keynum = e.keyCode;
            }
                else if(e.which)
                    { 
                    // Netscape/Firefox/Opera                   
                    keynum = e.which;
                    }
                    alert(String.fromCharCode(keynum));
                    var unicode=e.keyCode? e.keyCode : e.charCode;
                    alert(unicode);
        });
});  

</script>
</head>
<body>

<input type="text"></input>
</body>
</html>

Copy Data from a table in one Database to another separate database

We can three part naming like database_name..object_name

The below query will create the table into our database(with out constraints)

SELECT * 
INTO DestinationDB..MyDestinationTable 
FROM SourceDB..MySourceTable 

Alternatively you could:

INSERT INTO DestinationDB..MyDestinationTable 
SELECT * FROM SourceDB..MySourceTable

If your destination table exists and is empty.

How to check is Apache2 is stopped in Ubuntu?

In the command line type service apache2 status then hit enter. The result should say:

Apache2 is running (pid xxxx)

How to count how many values per level in a given factor?

Using plyr package:

library(plyr)

count(mydf$V1)

It will return you a frequency of each value.

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

I just had the same error with Visual Studio 2013 and EF6. I had to use a NewGet packed Entity Framework and done the job perfectly

Run PostgreSQL queries from the command line

psql -U username -d mydatabase -c 'SELECT * FROM mytable'

If you're new to postgresql and unfamiliar with using the command line tool psql then there is some confusing behaviour you should be aware of when you've entered an interactive session.

For example, initiate an interactive session:

psql -U username mydatabase 
mydatabase=#

At this point you can enter a query directly but you must remember to terminate the query with a semicolon ;

For example:

mydatabase=# SELECT * FROM mytable;

If you forget the semicolon then when you hit enter you will get nothing on your return line because psql will be assuming that you have not finished entering your query. This can lead to all kinds of confusion. For example, if you re-enter the same query you will have most likely create a syntax error.

As an experiment, try typing any garble you want at the psql prompt then hit enter. psql will silently provide you with a new line. If you enter a semicolon on that new line and then hit enter, then you will receive the ERROR:

mydatabase=# asdfs 
mydatabase=# ;  
ERROR:  syntax error at or near "asdfs"
LINE 1: asdfs
    ^

The rule of thumb is: If you received no response from psql but you were expecting at least SOMETHING, then you forgot the semicolon ;

Why do I have ORA-00904 even when the column is present?

Oracle will throw ORA-00904 if executing user does not have proper permissions on objects involved in the query.

jQuery: Get selected element tag name

You can use the DOM's nodeName property:

$(...)[0].nodeName

Project with path ':mypath' could not be found in root project 'myproject'

I got similar error after deleting a subproject, removed

"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"

in build.gradle (dependencies) under Gradle Scripts

Remove leading comma from a string

One-liner

str = str.replace(/^,/, '');

I'll be back.

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

Yet another solution to get timezone offset:

TimeZone tz = TimeZone.getDefault();
String current_Time_Zone = getGmtOffsetString(tz.getRawOffset());

public static String getGmtOffsetString(int offsetMillis) {
    int offsetMinutes = offsetMillis / 60000;
    char sign = '+';
    if (offsetMinutes < 0) {
        sign = '-';
        offsetMinutes = -offsetMinutes;
    }
    return String.format("GMT%c%02d:%02d", sign, offsetMinutes/60, offsetMinutes % 60);
}

Efficient iteration with index in Scala

I have the following approaches

object HelloV2 {

   def main(args: Array[String]) {

     //Efficient iteration with index in Scala

     //Approach #1
     var msg = "";

     for (i <- args.indices)
     {
       msg+=(args(i));
     }
     var msg1="";

     //Approach #2
     for (i <- 0 until args.length) 
     {
       msg1 += (args(i));
     }

     //Approach #3
     var msg3=""
     args.foreach{
       arg =>
        msg3 += (arg)
     }


      println("msg= " + msg);

      println("msg1= " + msg1);

      println("msg3= " + msg3);

   }
}

How can I get Eclipse to show .* files?

For Project Explorer View:
1. Click on arrow(View Menu) in right corner
2. Select Customize View... item from menu
3. Uncheck *.resources checkbox under Filters tab
4. Click OK

--
Eclipse Juno

Load image from url

The accepted answer above is great if you are loading the image based on a button click, however if you are doing it in a new activity it freezes up the UI for a second or two. Looking around I found that a simple asynctask eliminated this problem.

To use an asynctask to add this class at the end of your activity:

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
  ImageView bmImage;

  public DownloadImageTask(ImageView bmImage) {
      this.bmImage = bmImage;
  }

  protected Bitmap doInBackground(String... urls) {
      String urldisplay = urls[0];
      Bitmap mIcon11 = null;
      try {
        InputStream in = new java.net.URL(urldisplay).openStream();
        mIcon11 = BitmapFactory.decodeStream(in);
      } catch (Exception e) {
          Log.e("Error", e.getMessage());
          e.printStackTrace();
      }
      return mIcon11;
  }

  protected void onPostExecute(Bitmap result) {
      bmImage.setImageBitmap(result);
  }
}

And call from your onCreate() method using:

new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
        .execute(MY_URL_STRING);

Dont forget to add below permission in your manifest file

<uses-permission android:name="android.permission.INTERNET"/>

Works great for me. :)

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

This happens if you forgot to change your build settings to Simulator. Unless you want to build to a device, in which case you should see the other answers.

Angular - res.json() is not a function

Had a similar problem where we wanted to update from deprecated Http module to HttpClient in Angular 7. But the application is large and need to change res.json() in a lot of places. So I did this to have the new module with back support.

return this.http.get(this.BASE_URL + url)
      .toPromise()
      .then(data=>{
        let res = {'results': JSON.stringify(data),
        'json': ()=>{return data;}
      };
       return res; 
      })
      .catch(error => {
        return Promise.reject(error);
      });

Adding a dummy "json" named function from the central place so that all other services can still execute successfully before updating them to accommodate a new way of response handling i.e. without "json" function.

How to run Nginx within a Docker container without halting?

It is also good idea to use supervisord or runit[1] for service management.

[1] https://github.com/phusion/baseimage-docker

Binding Combobox Using Dictionary as the Datasource

Just Try to do like this....

SortedDictionary<string, int> userCache = UserCache.getSortedUserValueCache();

    // Add this code
    if(userCache != null)
    {
        userListComboBox.DataSource = new BindingSource(userCache, null); // Key => null
        userListComboBox.DisplayMember = "Key";
        userListComboBox.ValueMember = "Value";
    }

How to only find files in a given directory, and ignore subdirectories using bash

Is there any particular reason that you need to use find? You can just use ls to find files that match a pattern in a directory.

ls /dev/abc-*

If you do need to use find, you can use the -maxdepth 1 switch to only apply to the specified directory.

How to specify new GCC path for CMake

Export should be specific about which version of GCC/G++ to use, because if user had multiple compiler version, it would not compile successfully.

 export CC=path_of_gcc/gcc-version
 export CXX=path_of_g++/g++-version
 cmake  path_of_project_contain_CMakeList.txt
 make 

In case project use C++11 this can be handled by using -std=C++-11 flag in CMakeList.txt

How to edit incorrect commit message in Mercurial?

In TortoiseHg, right-click on the revision you want to modify. Choose Modify History->Import MQ. That will convert all the revisions up to and including the selected revision from Mercurial changesets into Mercurial Queue patches. Select the Patch you want to modify the message for, and it should automatically change the screen to the MQ editor. Edit the message which is in the middle of the screen, then click QRefresh. Finally, right click on the patch and choose Modify History->Finish Patch, which will convert it from a patch back into a change set.

Oh, this assumes that MQ is an active extension for TortoiseHG on this repository. If not, you should be able to click File->Settings, click Extensions, and click the mq checkbox. It should warn you that you have to close TortoiseHg before the extension is active, so close and reopen.

How does PHP 'foreach' actually work?

In example 3 you don't modify the array. In all other examples you modify either the contents or the internal array pointer. This is important when it comes to PHP arrays because of the semantics of the assignment operator.

The assignment operator for the arrays in PHP works more like a lazy clone. Assigning one variable to another that contains an array will clone the array, unlike most languages. However, the actual cloning will not be done unless it is needed. This means that the clone will take place only when either of the variables is modified (copy-on-write).

Here is an example:

$a = array(1,2,3);
$b = $a;  // This is lazy cloning of $a. For the time
          // being $a and $b point to the same internal
          // data structure.

$a[] = 3; // Here $a changes, which triggers the actual
          // cloning. From now on, $a and $b are two
          // different data structures. The same would
          // happen if there were a change in $b.

Coming back to your test cases, you can easily imagine that foreach creates some kind of iterator with a reference to the array. This reference works exactly like the variable $b in my example. However, the iterator along with the reference live only during the loop and then, they are both discarded. Now you can see that, in all cases but 3, the array is modified during the loop, while this extra reference is alive. This triggers a clone, and that explains what's going on here!

Here is an excellent article for another side effect of this copy-on-write behaviour: The PHP Ternary Operator: Fast or not?

Detect home button press in android

Since API 14 you can use the function onTrimMemory() and check for the flag TRIM_MEMORY_UI_HIDDEN. This will tell you that your Application is going to the background.

So in your custom Application class you can write something like:

override fun onTrimMemory(level: Int) {
    if (level == TRIM_MEMORY_UI_HIDDEN) {
        // Application going to background, do something
    }
}

For an in-depth study of this, I invite you to read this article: http://www.developerphil.com/no-you-can-not-override-the-home-button-but-you-dont-have-to/

Check string for nil & empty

If you want to access the string as a non-optional, you should use Ryan's Answer, but if you only care about the non-emptiness of the string, my preferred shorthand for this is

if stringA?.isEmpty == false {
    ...blah blah
}

Since == works fine with optional booleans, I think this leaves the code readable without obscuring the original intention.

If you want to check the opposite: if the string is nil or "", I prefer to check both cases explicitly to show the correct intention:

if stringA == nil || stringA?.isEmpty == true {
    ...blah blah
}

Error when trying to access XAMPP from a network

In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:

# Close XAMPP sites here
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
</LocationMatch>

and add

"Allow from all"

after Allow from ::1 127.0.0.0/8 {line}

Restart xampp, and you are done.

In later versions of Xampp

...you can simply remove this part

#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
        Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

from the same file and it should work over the local network.

Best way to check if a URL is valid

You can use this function, but its will return false if website offline.

  function isValidUrl($url) {
    $url = parse_url($url);
    if (!isset($url["host"])) return false;
    return !(gethostbyname($url["host"]) == $url["host"]);
}

Convert char array to a int number in C

Why not just use atoi? For example:

char myarray[4] = {'-','1','2','3'};

int i = atoi(myarray);

printf("%d\n", i);

Gives me, as expected:

-123

Update: why not - the character array is not null terminated. Doh!

How to pass parameter to a promise function

Wrap your Promise inside a function or it will start to do its job right away. Plus, you can pass parameters to the function:

var some_function = function(username, password)
{
 return new Promise(function(resolve, reject)
 {
  /*stuff using username, password*/
  if ( /* everything turned out fine */ )
  {
   resolve("Stuff worked!");
  }
  else
  {
   reject(Error("It broke"));
  }
 });
}

Then, use it:

some_module.some_function(username, password).then(function(uid)
{
 // stuff
})

 

ES6:

const some_function = (username, password) =>
{
 return new Promise((resolve, reject) =>
 {
  /*stuff using username, password*/

  if ( /* everything turned out fine */ )
  {
   resolve("Stuff worked!");
  }
  else
  {
   reject(Error("It broke"));
  }
 });
};

Use:

some_module.some_function(username, password).then(uid =>
{
 // stuff
});

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Login to remote site with PHP cURL

Panama Jack Example not work for me - Give Fatal error: Call to undefined function build_unique_path(). I used this code - (more simple - my opinion) :


// options
$login_email = '[email protected]';
$login_pass = 'alabala4807';
$cookie_file_path = "/tmp/cookies.txt";
$LOGINURL = "http://alabala.com/index.php?route=account/login";
$agent = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)";

// begin script
$ch = curl_init();

// extra headers
$headers[] = "Accept: */*";
$headers[] = "Connection: Keep-Alive";

// basic curl options for all requests
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);

// set first URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// execute session to get cookies and required form inputs
$content = curl_exec($ch);

// grab the hidden inputs from the form required to login
$fields = getFormFields($content);
$fields['email'] = $login_email;
$fields['password'] = $login_pass;

// set postfields using what we extracted from the form
$POSTFIELDS = http_build_query($fields);
// change URL to login URL
curl_setopt($ch, CURLOPT_URL, $LOGINURL);

// set post options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);

// perform login
$result = curl_exec($ch);

print $result;

function getFormFields($data)
{
if (preg_match('/()/is', $data, $matches)) {
$inputs = getInputs($matches[1]);

return $inputs;
} else {
die('didnt find login form');
}
}

function getInputs($form)
{
$inputs = array();
$elements = preg_match_all("/(]+>)/is", $form, $matches);
if ($elements > 0) {
for($i = 0;$i $el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);
if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
$name = $name[1];

$value = '';
if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
$value = $value[1];
}

$inputs[$name] = $value;
}
}
}

return $inputs;
}

$grab_url='http://grab.url/alabala';

//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, $grab_url);
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);

var_dump($html);
die;

How to change webservice url endpoint?

IMO, the provider is telling you to change the service endpoint (i.e. where to reach the web service), not the client endpoint (I don't understand what this could be). To change the service endpoint, you basically have two options.

Use the Binding Provider to set the endpoint URL

The first option is to change the BindingProvider.ENDPOINT_ADDRESS_PROPERTY property value of the BindingProvider (every proxy implements javax.xml.ws.BindingProvider interface):

...
EchoService service = new EchoService();
Echo port = service.getEchoPort();

/* Set NEW Endpoint Location */
String endpointURL = "http://NEW_ENDPOINT_URL";
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);

System.out.println("Server said: " + echo.echo(args[0]));
...

The drawback is that this only works when the original WSDL is still accessible. Not recommended.

Use the WSDL to get the endpoint URL

The second option is to get the endpoint URL from the WSDL.

...
URL newEndpoint = new URL("NEW_ENDPOINT_URL");
QName qname = new QName("http://ws.mycompany.tld","EchoService"); 

EchoService service = new EchoService(newEndpoint, qname);
Echo port = service.getEchoPort();

System.out.println("Server said: " + echo.echo(args[0]));
...

generate random string for div id

I would suggest that you start with some sort of placeholder, you may have this already, but its somewhere to append the div.

<div id="placeholder"></div>

Now, the idea is to dynamically create a new div, with your random id:

var rndId = randomString(8); 
var div = document.createElement('div');
div.id = rndId
div.innerHTML = "Whatever you want the content of your div to be";

this can be apended to your placeholder as follows:

document.getElementById('placeholder').appendChild(div);

You can then use that in your jwplayer code:

jwplayer(rndId).setup(...);

Live example: http://jsfiddle.net/pNYZp/

Sidenote: Im pretty sure id's must start with an alpha character (ie, no numbers) - you might want to change your implementation of randomstring to enforce this rule. (ref)

JavaScript Array to Set

What levi said about passing it into the constructor is correct, but you could also use an object.

I think what Veverke is trying to say is that you could easily use the delete keyword on an object to achieve the same effect.

I think you're confused by the terminology; properties are components of the object that you can use as named indices (if you want to think of it that way).

Try something like this:

var obj = {
    "bob": "dole",
    "mr.": "peabody",
    "darkwing": "duck"
};

Then, you could just do this:

delete obj["bob"];

The structure of the object would then be this:

{
    "mr.": "peabody",
    "darkwing": "duck"
}

Which has the same effect.

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Your application has an AppCompat theme

<application
    android:theme="@style/AppTheme">

But, you overwrote the Activity (which extends AppCompatActivity) with a theme that isn't descendant of an AppCompat theme

<activity android:name=".MainActivity"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >

You could define your own fullscreen theme like so (notice AppCompat in the parent=)

<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

Then set that on the Activity.

<activity android:name=".MainActivity"
    android:theme="@style/AppFullScreenTheme" >

Note: There might be an AppCompat theme that's already full screen, but don't know immediately

How to get cookie expiration date / creation date from javascript?

One possibility is to delete to cookie you are looking for the expiration date from and rewrite it. Then you'll know the expiration date.

Nginx: stat() failed (13: permission denied)

You may have Security-Enhanced Linux running, so add rule for that. I had permission 13 errors, even though permissions were set and user existed..

chcon -Rt httpd_sys_content_t /username/test/static

How to filter multiple values (OR operation) in angularJS

you can use searchField filter of angular.filter

JS:

$scope.users = [
 { first_name: 'Sharon', last_name: 'Melendez' },
 { first_name: 'Edmundo', last_name: 'Hepler' },
 { first_name: 'Marsha', last_name: 'Letourneau' }
];

HTML:

<input ng-model="search" placeholder="search by full name"/> 
<th ng-repeat="user in users | searchField: 'first_name': 'last_name' | filter: search">
  {{ user.first_name }} {{ user.last_name }}
</th>
<!-- so now you can search by full name -->

Generating random numbers with Swift

===== Swift 4.2 / Xcode 10 =====

let randomIntFrom0To10 = Int.random(in: 1..<10)
let randomFloat = Float.random(in: 0..<1)

// if you want to get a random element in an array
let greetings = ["hey", "hi", "hello", "hola"]
greetings.randomElement()

Under the hood Swift uses arc4random_buf to get job done.

===== Swift 4.1 / Xcode 9 =====

arc4random() returns a random number in the range of 0 to 4 294 967 295

drand48() returns a random number in the range of 0.0 to 1.0

arc4random_uniform(N) returns a random number in the range of 0 to N - 1

Examples:

arc4random() // => UInt32 = 2739058784
arc4random() // => UInt32 = 2672503239
arc4random() // => UInt32 = 3990537167
arc4random() // => UInt32 = 2516511476
arc4random() // => UInt32 = 3959558840

drand48() // => Double = 0.88642843322303122
drand48() // => Double = 0.015582849408328769
drand48() // => Double = 0.58409022031727176
drand48() // => Double = 0.15936862653180484
drand48() // => Double = 0.38371587480719427

arc4random_uniform(3) // => UInt32 = 0
arc4random_uniform(3) // => UInt32 = 1
arc4random_uniform(3) // => UInt32 = 0
arc4random_uniform(3) // => UInt32 = 1
arc4random_uniform(3) // => UInt32 = 2

arc4random_uniform() is recommended over constructions like arc4random() % upper_bound as it avoids "modulo bias" when the upper bound is not a power of two.

Best way to format if statement with multiple conditions

The first one is easier, because, if you read it left to right you get: "If something AND somethingelse AND somethingelse THEN" , which is an easy to understand sentence. The second example reads "If something THEN if somethingelse THEN if something else THEN", which is clumsy.

Also, consider if you wanted to use some ORs in your clause - how would you do that in the second style?

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Here is another, very manual solution. You can define the size of the axis and paddings are considered accordingly (including legend and tickmarks). Hope it is of use to somebody.

Example (axes size are the same!):

enter image description here

Code:

#==================================================
# Plot table

colmap = [(0,0,1) #blue
         ,(1,0,0) #red
         ,(0,1,0) #green
         ,(1,1,0) #yellow
         ,(1,0,1) #magenta
         ,(1,0.5,0.5) #pink
         ,(0.5,0.5,0.5) #gray
         ,(0.5,0,0) #brown
         ,(1,0.5,0) #orange
         ]


import matplotlib.pyplot as plt
import numpy as np

import collections
df = collections.OrderedDict()
df['labels']        = ['GWP100a\n[kgCO2eq]\n\nasedf\nasdf\nadfs','human\n[pts]','ressource\n[pts]'] 
df['all-petroleum long name'] = [3,5,2]
df['all-electric']  = [5.5, 1, 3]
df['HEV']           = [3.5, 2, 1]
df['PHEV']          = [3.5, 2, 1]

numLabels = len(df.values()[0])
numItems = len(df)-1
posX = np.arange(numLabels)+1
width = 1.0/(numItems+1)

fig = plt.figure(figsize=(2,2))
ax = fig.add_subplot(111)
for iiItem in range(1,numItems+1):
  ax.bar(posX+(iiItem-1)*width, df.values()[iiItem], width, color=colmap[iiItem-1], label=df.keys()[iiItem])
ax.set(xticks=posX+width*(0.5*numItems), xticklabels=df['labels'])

#--------------------------------------------------
# Change padding and margins, insert legend

fig.tight_layout() #tight margins
leg = ax.legend(loc='upper left', bbox_to_anchor=(1.02, 1), borderaxespad=0)
plt.draw() #to know size of legend

padLeft   = ax.get_position().x0 * fig.get_size_inches()[0]
padBottom = ax.get_position().y0 * fig.get_size_inches()[1]
padTop    = ( 1 - ax.get_position().y0 - ax.get_position().height ) * fig.get_size_inches()[1]
padRight  = ( 1 - ax.get_position().x0 - ax.get_position().width ) * fig.get_size_inches()[0]
dpi       = fig.get_dpi()
padLegend = ax.get_legend().get_frame().get_width() / dpi 

widthAx = 3 #inches
heightAx = 3 #inches
widthTot = widthAx+padLeft+padRight+padLegend
heightTot = heightAx+padTop+padBottom

# resize ipython window (optional)
posScreenX = 1366/2-10 #pixel
posScreenY = 0 #pixel
canvasPadding = 6 #pixel
canvasBottom = 40 #pixel
ipythonWindowSize = '{0}x{1}+{2}+{3}'.format(int(round(widthTot*dpi))+2*canvasPadding
                                            ,int(round(heightTot*dpi))+2*canvasPadding+canvasBottom
                                            ,posScreenX,posScreenY)
fig.canvas._tkcanvas.master.geometry(ipythonWindowSize) 
plt.draw() #to resize ipython window. Has to be done BEFORE figure resizing!

# set figure size and ax position
fig.set_size_inches(widthTot,heightTot)
ax.set_position([padLeft/widthTot, padBottom/heightTot, widthAx/widthTot, heightAx/heightTot])
plt.draw()
plt.show()
#--------------------------------------------------
#==================================================

clear table jquery

This will remove all of the rows belonging to the body, thus keeping the headers and body intact:

$("#tableLoanInfos tbody tr").remove();

Detect Scroll Up & Scroll down in ListView

I've used this much simpler solution:

setOnScrollListener( new OnScrollListener() 
{

    private int mInitialScroll = 0;

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) 
    {
        int scrolledOffset = computeVerticalScrollOffset();

        boolean scrollUp = scrolledOffset > mInitialScroll;
        mInitialScroll = scrolledOffset;
    }


    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {


    }

}

How do I pass a command line argument while starting up GDB in Linux?

Once gdb starts, you can run the program using "r args".

So if you are running your code by:

$ executablefile arg1 arg2 arg3 

Debug it on gdb by:

$ gdb executablefile  
(gdb) r arg1 arg2 arg3

JavaScript - document.getElementByID with onClick

In JavaScript functions are objects.

document.getElementById('foo').onclick = function(){
    prompt('Hello world');
}

Passing parameter to controller from route in laravel

You don't need anything special for adding paramaters. Just like you had it.

Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups@show'));


class Groups_Controller extends Base_Controller {

    public $restful = true;    

    public function get_show($groupID) {
        return 'I am group id ' . $groupID;
    }  


}

Display a jpg image on a JPanel

I would use a Canvas that I add to the JPanel, and draw the image on the Canvas. But Canvas is a quite heavy object, sine it is from awt.

Recyclerview inside ScrollView not scrolling smoothly

Using Nested Scroll View instead of Scroll View solved my problem

<LinearLayout> <!--Main Layout -->
   <android.support.v4.widget.NestedScrollView>
     <LinearLayout > <!--Nested Scoll View enclosing Layout -->`

       <View > <!-- upper content --> 
       <RecyclerView >


     </LinearLayout > 
   </android.support.v4.widget.NestedScrollView>
</LinearLayout>

Load local images in React.js

In order to load local images to your React.js application, you need to add require parameter in media sections like or Image tags, as below:

image={require('./../uploads/temp.jpg')}

How to split a delimited string into an array in awk?

Actually awk has a feature called 'Input Field Separator Variable' link. This is how to use it. It's not really an array, but it uses the internal $ variables. For splitting a simple string it is easier.

echo "12|23|11" | awk 'BEGIN {FS="|";} { print $1, $2, $3 }'

How to refresh a page with jQuery by passing a parameter to URL

Concision counts: I prefer window.location = "?single"; or window.location += "?single";

Calculate number of hours between 2 dates in PHP

$t1 = strtotime( '2006-04-14 11:30:00' );
$t2 = strtotime( '2006-04-12 12:30:00' );
$diff = $t1 - $t2;
$hours = $diff / ( 60 * 60 );

Converting a datetime string to timestamp in Javascript

For those of us using non-ISO standard date formats, like civilian vernacular 01/01/2001 (mm/dd/YYYY), including time in a 12hour date format with am/pm marks, the following function will return a valid Date object:

function convertDate(date) {

    // # valid js Date and time object format (YYYY-MM-DDTHH:MM:SS)
    var dateTimeParts = date.split(' ');

    // # this assumes time format has NO SPACE between time and am/pm marks.
    if (dateTimeParts[1].indexOf(' ') == -1 && dateTimeParts[2] === undefined) {

        var theTime = dateTimeParts[1];

        // # strip out all except numbers and colon
        var ampm = theTime.replace(/[0-9:]/g, '');

        // # strip out all except letters (for AM/PM)
        var time = theTime.replace(/[[^a-zA-Z]/g, '');

        if (ampm == 'pm') {

            time = time.split(':');

            // # if time is 12:00, don't add 12
            if (time[0] == 12) {
                time = parseInt(time[0]) + ':' + time[1] + ':00';
            } else {
                time = parseInt(time[0]) + 12 + ':' + time[1] + ':00';
            }

        } else { // if AM

            time = time.split(':');

            // # if AM is less than 10 o'clock, add leading zero
            if (time[0] < 10) {
                time = '0' + time[0] + ':' + time[1] + ':00';
            } else {
                time = time[0] + ':' + time[1] + ':00';
            }
        }
    }
    // # create a new date object from only the date part
    var dateObj = new Date(dateTimeParts[0]);

    // # add leading zero to date of the month if less than 10
    var dayOfMonth = (dateObj.getDate() < 10 ? ("0" + dateObj.getDate()) : dateObj.getDate());

    // # parse each date object part and put all parts together
    var yearMoDay = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dayOfMonth;

    // # finally combine re-formatted date and re-formatted time!
    var date = new Date(yearMoDay + 'T' + time);

    return date;
}

Usage:

date = convertDate('11/15/2016 2:00pm');

What is move semantics?

To illustrate the need for move semantics, let's consider this example without move semantics:

Here's a function that takes an object of type T and returns an object of the same type T:

T f(T o) { return o; }
  //^^^ new object constructed

The above function uses call by value which means that when this function is called an object must be constructed to be used by the function.
Because the function also returns by value, another new object is constructed for the return value:

T b = f(a);
  //^ new object constructed

Two new objects have been constructed, one of which is a temporary object that's only used for the duration of the function.

When the new object is created from the return value, the copy constructor is called to copy the contents of the temporary object to the new object b. After the function completes, the temporary object used in the function goes out of scope and is destroyed.


Now, let's consider what a copy constructor does.

It must first initialize the object, then copy all the relevant data from the old object to the new one.
Depending on the class, maybe its a container with very much data, then that could represent much time and memory usage

// Copy constructor
T::T(T &old) {
    copy_data(m_a, old.m_a);
    copy_data(m_b, old.m_b);
    copy_data(m_c, old.m_c);
}

With move semantics it's now possible to make most of this work less unpleasant by simply moving the data rather than copying.

// Move constructor
T::T(T &&old) noexcept {
    m_a = std::move(old.m_a);
    m_b = std::move(old.m_b);
    m_c = std::move(old.m_c);
}

Moving the data involves re-associating the data with the new object. And no copy takes place at all.

This is accomplished with an rvalue reference.
An rvalue reference works pretty much like an lvalue reference with one important difference:
an rvalue reference can be moved and an lvalue cannot.

From cppreference.com:

To make strong exception guarantee possible, user-defined move constructors should not throw exceptions. In fact, standard containers typically rely on std::move_if_noexcept to choose between move and copy when container elements need to be relocated. If both copy and move constructors are provided, overload resolution selects the move constructor if the argument is an rvalue (either a prvalue such as a nameless temporary or an xvalue such as the result of std::move), and selects the copy constructor if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy constructor is provided, all argument categories select it (as long as it takes a reference to const, since rvalues can bind to const references), which makes copying the fallback for moving, when moving is unavailable. In many situations, move constructors are optimized out even if they would produce observable side-effects, see copy elision. A constructor is called a 'move constructor' when it takes an rvalue reference as a parameter. It is not obligated to move anything, the class is not required to have a resource to be moved and a 'move constructor' may not be able to move a resource as in the allowable (but maybe not sensible) case where the parameter is a const rvalue reference (const T&&).

How to round a numpy array?

If you want the output to be

array([1.6e-01, 9.9e-01, 3.6e-04])

the problem is not really a missing feature of NumPy, but rather that this sort of rounding is not a standard thing to do. You can make your own rounding function which achieves this like so:

def my_round(value, N):
    exponent = np.ceil(np.log10(value))
    return 10**exponent*np.round(value*10**(-exponent), N)

For a general solution handling 0 and negative values as well, you can do something like this:

def my_round(value, N):
    value = np.asarray(value).copy()
    zero_mask = (value == 0)
    value[zero_mask] = 1.0
    sign_mask = (value < 0)
    value[sign_mask] *= -1
    exponent = np.ceil(np.log10(value))
    result = 10**exponent*np.round(value*10**(-exponent), N)
    result[sign_mask] *= -1
    result[zero_mask] = 0.0
    return result

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

How to pass props to {this.props.children}

Render props is most accurate approach to this problem. Instead of passing the child component to parent component as children props, let parent render child component manually. Render is built-in props in react, which takes function parameter. In this function you can let parent component render whatever you want with custom parameters. Basically it does the same thing as child props but it is more customizable.

class Child extends React.Component {
  render() {
    return <div className="Child">
      Child
      <p onClick={this.props.doSomething}>Click me</p>
           {this.props.a}
    </div>;
  }
}

class Parent extends React.Component {
  doSomething(){
   alert("Parent talks"); 
  }

  render() {
    return <div className="Parent">
      Parent
      {this.props.render({
        anythingToPassChildren:1, 
        doSomething: this.doSomething})}
    </div>;
  }
}

class Application extends React.Component {
  render() {
    return <div>
      <Parent render={
          props => <Child {...props} />
        }/>
    </div>;
  }
}

Example at codepen

How to get the EXIF data from a file using C#

As suggested, you can use some 3rd party library, or do it manually (which is not that much work), but the simplest and the most flexible is to perhaps use the built-in functionality in .NET. For more see:

I say "it’s the most flexible" because .NET does not try to interpret or coalesce the data in any way. For each EXIF you basically get an array of bytes. This may be good or bad depending on how much control you actually want.

Also, I should point out that the property list does not in fact directly correspond to the EXIF values. EXIF itself is stored in multiple tables with overlapping ID’s, but .NET puts everything in one list and redefines ID’s of some items. But as long as you don’t care about the precise EXIF ID’s, you should be fine with the .NET mapping.


Edit: It's possible to do it without loading the full image following this answer: https://stackoverflow.com/a/552642/2097240

PNG transparency issue in IE8

Dan Tello fix worked well for me.

One additional issue I found with IE8 was that if the PNG was held in a DIV with smaller CSS width or height dimensions than the PNG then the black edge prob was re-triggered.

Correcting the width and height CSS or removing them altogether fixed.

How do I auto-submit an upload form when a file is selected?

For those who are using .NET WebForms a full page submit may not be desired. Instead, use the same onchange idea to have javascript click a hidden button (e.g. <asp:Button...) and the hidden button can take of the rest. Make sure you are doing a display: none; on the button and not Visible="false".

tkinter: Open a new window with a button prompt

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

Calling a JavaScript function named in a variable

Definitely avoid using eval to do something like this, or you will open yourself to XSS (Cross-Site Scripting) vulnerabilities.

For example, if you were to use the eval solutions proposed here, a nefarious user could send a link to their victim that looked like this:

http://yoursite.com/foo.html?func=function(){alert('Im%20In%20Teh%20Codez');}

And their javascript, not yours, would get executed. This code could do something far worse than just pop up an alert of course; it could steal cookies, send requests to your application, etc.

So, make sure you never eval untrusted code that comes in from user input (and anything on the query string id considered user input). You could take user input as a key that will point to your function, but make sure that you don't execute anything if the string given doesn't match a key in your object. For example:

// set up the possible functions:
var myFuncs = {
  func1: function () { alert('Function 1'); },
  func2: function () { alert('Function 2'); },
  func3: function () { alert('Function 3'); },
  func4: function () { alert('Function 4'); },
  func5: function () { alert('Function 5'); }
};
// execute the one specified in the 'funcToRun' variable:
myFuncs[funcToRun]();

This will fail if the funcToRun variable doesn't point to anything in the myFuncs object, but it won't execute any code.

simple way to display data in a .txt file on a webpage?

I find that if I try things that others say do not work, it's how I learn the most.

<p>&nbsp;</p>
<p>README.txt</p>
<p>&nbsp;</p>
<div id="list">
  <p><iframe src="README.txt" frameborder="0" height="400"
      width="95%"></iframe></p>
</div>

This worked for me. I used the yellow background-color that I set in the stylesheet.

#list  p {
    font: arial;
    font-size: 14px;
    background-color: yellow ;
}

How can I create an observable with a delay

Using the following imports:

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/delay';

Try this:

let fakeResponse = [1,2,3];
let delayedObservable = Observable.of(fakeResponse).delay(5000);
delayedObservable.subscribe(data => console.log(data));

UPDATE: RXJS 6

The above solution doesn't really work anymore in newer versions of RXJS (and of angular for example).

So the scenario is that I have an array of items to check with an API with. The API only accepts a single item, and I do not want to kill the API by sending all requests at once. So I need a timed release of items on the Observable stream with a small delay in between.

Use the following imports:

import { from, of } from 'rxjs';
import { delay } from 'rxjs/internal/operators';
import { concatMap } from 'rxjs/internal/operators';

Then use the following code:

const myArray = [1,2,3,4];

from(myArray).pipe(
        concatMap( item => of(item).pipe ( delay( 1000 ) ))
    ).subscribe ( timedItem => {
        console.log(timedItem)
    });

It basically creates a new 'delayed' Observable for every item in your array. There are probably many other ways of doing it, but this worked fine for me, and complies with the 'new' RXJS format.

Unsafe JavaScript attempt to access frame with URL

Crossframe-Scripting is not possible when the two frames have different domains -> Security.

See this: http://javascript.about.com/od/reference/a/frame3.htm

Now to answer your question: there is no solution or work around, you simply should check your website-design why there must be two frames from different domains that changes the url of the other one.

How to pass an array into a SQL Server stored procedure

As others have noted above, one way to do this is to convert your array to a string and then split the string inside SQL Server.

As of SQL Server 2016, there's a built-in way to split strings called

STRING_SPLIT()

It returns a set of rows that you can insert into your temp table (or real table).

DECLARE @str varchar(200)
SET @str = "123;456;789;246;22;33;44;55;66"
SELECT value FROM STRING_SPLIT(@str, ';')

would yield:

value
-----
  123
  456
  789
  246
   22
   33
   44
   55
   66

If you want to get fancier:

DECLARE @tt TABLE (
    thenumber int
)
DECLARE @str varchar(200)
SET @str = "123;456;789;246;22;33;44;55;66"

INSERT INTO @tt
SELECT value FROM STRING_SPLIT(@str, ';')

SELECT * FROM @tt
ORDER BY thenumber

would give you the same results as above (except the column name is "thenumber"), but sorted. You can use the table variable like any other table, so you can easily join it with other tables in the DB if you want.

Note that your SQL Server install has to be at compatibility level 130 or higher in order for the STRING_SPLIT() function to be recognized. You can check your compatibility level with the following query:

SELECT compatibility_level
FROM sys.databases WHERE name = 'yourdatabasename';

Most languages (including C#) have a "join" function you can use to create a string from an array.

int[] myarray = {22, 33, 44};
string sqlparam = string.Join(";", myarray);

Then you pass sqlparam as your parameter to the stored procedure above.

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN
IF THEN ELSE
IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

So your code should appear like this.

    declare
        var_number number;
    begin
        var_number := 10;
        if var_number > 100 then
           dbms_output.put_line(var_number ||' is greater than 100');
--elseif should be replaced with elsif
        elsif var_number < 100 then
           dbms_output.put_line(var_number ||' is less than 100');
        else
           dbms_output.put_line(var_number ||' is equal to 100');
        end if;
    end; 

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

This can also happen when the log file is restricted in size.

Right click database in Object Explorer

Select Properties

Select Files

On the log line, click the ellipsis in the Autogrowth / Maxsize column

Change/verify Maximum File Size is Unlimited.

enter image description here

After chaning to unlimited, database came back to life.

Pandas conditional creation of a series/dataframe column

The following is slower than the approaches timed here, but we can compute the extra column based on the contents of more than one column, and more than two values can be computed for the extra column.

Simple example using just the "Set" column:

def set_color(row):
    if row["Set"] == "Z":
        return "red"
    else:
        return "green"

df = df.assign(color=df.apply(set_color, axis=1))

print(df)
  Set Type  color
0   Z    A    red
1   Z    B    red
2   X    B  green
3   Y    C  green

Example with more colours and more columns taken into account:

def set_color(row):
    if row["Set"] == "Z":
        return "red"
    elif row["Type"] == "C":
        return "blue"
    else:
        return "green"

df = df.assign(color=df.apply(set_color, axis=1))

print(df)
  Set Type  color
0   Z    A    red
1   Z    B    red
2   X    B  green
3   Y    C   blue

Edit (21/06/2019): Using plydata

It is also possible to use plydata to do this kind of things (this seems even slower than using assign and apply, though).

from plydata import define, if_else

Simple if_else:

df = define(df, color=if_else('Set=="Z"', '"red"', '"green"'))

print(df)
  Set Type  color
0   Z    A    red
1   Z    B    red
2   X    B  green
3   Y    C  green

Nested if_else:

df = define(df, color=if_else(
    'Set=="Z"',
    '"red"',
    if_else('Type=="C"', '"green"', '"blue"')))

print(df)                            
  Set Type  color
0   Z    A    red
1   Z    B    red
2   X    B   blue
3   Y    C  green

Using :before CSS pseudo element to add image to modal

1.this is my answer for your problem.

.ModalCarrot::before {
content:'';
background: url('blackCarrot.png'); /*url of image*/
height: 16px; /*height of image*/
width: 33px;  /*width of image*/
position: absolute;
}

Does reading an entire file leave the file handle open?

Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:

with open('Path/to/file', 'r') as content_file:
    content_list = content_file.read().strip().split("\n")

As can be seen, one needs to add the concatenated methods .strip().split("\n") to the main answer in this thread.

Here, .strip() just removes whitespace and newline characters at the endings of the entire file string, and .split("\n") produces the actual list via splitting the entire file string at every newline character \n.

Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.

how to evenly distribute elements in a div next to each other?

_x000D_
_x000D_
.container {_x000D_
  padding: 10px;_x000D_
}_x000D_
.parent {_x000D_
  width: 100%;_x000D_
  background: #7b7b7b;_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  height: 4px;_x000D_
}_x000D_
.child {_x000D_
  color: #fff;_x000D_
  background: green;_x000D_
  padding: 10px 10px;_x000D_
  border-radius: 50%;_x000D_
  position: relative;_x000D_
  top: -8px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="parent">_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
    <span class="child"></span>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery select change event get selected option

$('select').on('change', function (e) {
    var optionSelected = $("option:selected", this);
    var valueSelected = this.value;
    ....
});

How to import set of icons into Android Studio project

Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.

HashMap - getting First Key value

Also a nice way of doing this :)

Map<Integer,JsonObject> requestOutput = getRequestOutput(client,post);
int statusCode = requestOutput.keySet().stream().findFirst().orElseThrow(() -> new RuntimeException("Empty"));

ActiveModel::ForbiddenAttributesError when creating new user

I guess you are using Rails 4. If so, the needed parameters must be marked as required.

You might want to do it like this:

class UsersController < ApplicationController

  def create
    @user = User.new(user_params)
    # ...
  end

  private

  def user_params
    params.require(:user).permit(:username, :email, :password, :salt, :encrypted_password)
  end
end

Show spinner GIF during an $http request in AngularJS?

https://github.com/wongatech/angular-http-loader is a good project for this.

Example here http://wongatech.github.io/angular-http-loader/

The code below shows a template example/loader.tpl.html when a request is happening.

<div ng-http-loader template="example/loader.tpl.html"></div>

Fully change package name including company domain

Hi I found the easiest way to do this.

  1. Create a new project with the desired package name
  2. copy all files from old project to new project (all file in old.bad.oldpackage=>new.fine.newpackage, res=>res)
  3. copy old build.graddle inside new build.graddle
  4. copy old Manifest inside new Manifest
  5. Backup or simply delete old project

Done!

What are the obj and bin folders (created by Visual Studio) used for?

I would encourage you to see this youtube video which demonstrates the difference between C# bin and obj folders and also explains how we get the benefit of incremental/conditional compilation.

C# compilation is a two-step process, see the below diagram for more details:

  1. Compiling: In compiling phase individual C# code files are compiled into individual compiled units. These individual compiled code files go in the OBJ directory.
  2. Linking: In the linking phase these individual compiled code files are linked to create single unit DLL and EXE. This goes in the BIN directory.

C# bin vs obj folders

If you compare both bin and obj directory you will find greater number of files in the "obj" directory as it has individual compiled code files while "bin" has a single unit.

bin vs obj

Manually map column names with class properties

Before you open the connection to your database, execute this piece of code for each of your poco classes:

// Section
SqlMapper.SetTypeMap(typeof(Section), new CustomPropertyTypeMap(
    typeof(Section), (type, columnName) => type.GetProperties().FirstOrDefault(prop =>
    prop.GetCustomAttributes(false).OfType<ColumnAttribute>().Any(attr => attr.Name == columnName))));

Then add the data annotations to your poco classes like this:

public class Section
{
    [Column("db_column_name1")] // Side note: if you create aliases, then they would match this.
    public int Id { get; set; }
    [Column("db_column_name2")]
    public string Title { get; set; }
}

After that, you are all set. Just make a query call, something like:

using (var sqlConnection = new SqlConnection("your_connection_string"))
{
    var sqlStatement = "SELECT " +
                "db_column_name1, " +
                "db_column_name2 " +
                "FROM your_table";

    return sqlConnection.Query<Section>(sqlStatement).AsList();
}

For each row in an R dataframe

You can use the by() function:

by(dataFrame, seq_len(nrow(dataFrame)), function(row) dostuff)

But iterating over the rows directly like this is rarely what you want to; you should try to vectorize instead. Can I ask what the actual work in the loop is doing?

JAX-RS — How to return JSON and HTTP status code together?

In case you want to change the status code because of an exception, with JAX-RS 2.0 you can implement an ExceptionMapper like this. This handles this kind of exception for the whole app.

@Provider
public class UnauthorizedExceptionMapper implements ExceptionMapper<EJBAccessException> {

    @Override
    public Response toResponse(EJBAccessException exception) {
        return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
    }

}

Can I convert long to int?

Just do (int)myLongValue. It'll do exactly what you want (discarding MSBs and taking LSBs) in unchecked context (which is the compiler default). It'll throw OverflowException in checked context if the value doesn't fit in an int:

int myIntValue = unchecked((int)myLongValue);

How can I use grep to show just filenames on Linux?

The standard option grep -l (that is a lowercase L) could do this.

From the Unix standard:

-l
    (The letter ell.) Write only the names of files containing selected
    lines to standard output. Pathnames are written once per file searched.
    If the standard input is searched, a pathname of (standard input) will
    be written, in the POSIX locale. In other locales, standard input may be
    replaced by something more appropriate in those locales.

You also do not need -H in this case.

Xcode 6.1 Missing required architecture X86_64 in file

Following changes you have to make that's it(change architecture into armv7 and remove others) :-

Change you have to make

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

The correct answer is the following:

import numpy 
numpy.shape(a)

You have not accepted the license agreements of the following SDK components

You can accept the license agreement by launching Android Studio, then going to:

Help > Check for Updates...

When you are installing updates, it'll ask you to accept the license agreement. Accept the license agreement and install the updates, and you are all set.

What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

FragmentPagerAdapter: the fragment of each page the user visits will be stored in memory, although the view will be destroyed. So when the page is visible again, the view will be recreated but the fragment instance is not recreated. This can result in a significant amount of memory being used. FragmentPagerAdapter should be used when we need to store the whole fragment in memory. FragmentPagerAdapter calls detach(Fragment) on the transaction instead of remove(Fragment).

FragmentStatePagerAdapter: the fragment instance is destroyed when it is not visible to the User, except the saved state of the fragment. This results in using only a small amount of Memory and can be useful for handling larger data sets. Should be used when we have to use dynamic fragments, like fragments with widgets, as their data could be stored in the savedInstanceState.Also it won’t affect the performance even if there are large number of fragments.

jQuery Mobile Page refresh mechanism

I solved this problem by using the the data-cache="false" attribute in the page div on the pages I wanted refreshed.

<div data-role="page" data-cache="false">
/*content goes here*/

</div>

In my case it was my shopping cart. If a customer added an item to their cart and then continued shopping and then added another item to their cart the cart page would not show the new item. Unless they refreshed the page. Setting data-cache to false instructs JQM not to cache that page as far as I understand.

Hope this helps others in the future.

Search for all files in project containing the text 'querystring' in Eclipse

press Ctrl + H . Then choose "File Search" tab.

additional search options

search for resources: Ctrl + Shift + R

search for Java types: Ctrl + Shift + T

Cannot install Aptana Studio 3.6 on Windows

Right click the installer and choose "Run as administrator". I suspect it needs administrator account to download and install Node JS during installation.

How to unapply a migration in ASP.NET Core with EF Core

In general if you are using the Package Manager Console the right way to remove a specific Migration is by referencing the name of the migration

Update-Database -Migration {Name of Migration} -Context {context}

Another way to remove the last migration you have applied according to the docs is by using the command:

dotnet ef migrations remove

This command should be executed from the developer command prompt (how to open command prompt) inside your solution directory.

For example if your application is inside name "Application" and is in the folder c:\Projects. Then your path should be:

C:\Projects\Application

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

When you use recv in connection with select if the socket is ready to be read from but there is no data to read that means the client has closed the connection.

Here is some code that handles this, also note the exception that is thrown when recv is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :

def listenToSockets(self):

    while True:

        changed_sockets = self.currentSockets

        ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)

        for s in ready_to_read:

            if s == self.serverSocket:
                self.acceptNewConnection(s)
            else:
                self.readDataFromSocket(s)

And the function that receives the data :

def readDataFromSocket(self, socket):

    data = ''
    buffer = ''
    try:

        while True:
            data = socket.recv(4096)

            if not data: 
                break

            buffer += data

    except error, (errorCode,message): 
        # error 10035 is no data available, it is non-fatal
        if errorCode != 10035:
            print 'socket.error - ('+str(errorCode)+') ' + message


    if data:
        print 'received '+ buffer
    else:
        print 'disconnected'

Setting HTTP headers

All of the above answers are wrong because they fail to handle the OPTIONS preflight request, the solution is to override the mux router's interface. See AngularJS $http get request failed with custom header (alllowed in CORS)

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/save", saveHandler)
    http.Handle("/", &MyServer{r})
    http.ListenAndServe(":8080", nil);

}

type MyServer struct {
    r *mux.Router
}

func (s *MyServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    if origin := req.Header.Get("Origin"); origin != "" {
        rw.Header().Set("Access-Control-Allow-Origin", origin)
        rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        rw.Header().Set("Access-Control-Allow-Headers",
            "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
    }
    // Stop here if its Preflighted OPTIONS request
    if req.Method == "OPTIONS" {
        return
    }
    // Lets Gorilla work
    s.r.ServeHTTP(rw, req)
}

Convert and format a Date in JSP

You can do that using the SimpleDateFormat class.

SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String dates=formatter.format(mydate);
//mydate is your date object

R: Print list to a text file

Format won't be completely the same, but it does write the data to a text file, and R will be able to reread it using dget when you want to retrieve it again as a list.

dput(mylist, "mylist.txt")

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

Got a similar error, fixed with removing all records (in my case directory journals, and file mongo.lock...), after that check port with sudo lsof -i:27017, if smth running on it kill <PID of the process>, and try to run ./mongod again

In JavaScript can I make a "click" event fire programmatically for a file input element?

There are ways to redirect events to the control but don't expect to be able to easily fire events to the fire control yourself as the browsers will try to block that for (good) security reasons.

If you only need the file dialog to show up when a user clicks something, let's say because you want better looking file upload buttons, then you might want to take a look at what Shaun Inman came up with.

I've been able to achieve keyboard triggering with creative shifting of focus in and out of the control between keydown, keypress & keyup events. YMMV.

My sincere advice is to leave this the alone, because this is a world of browser-incompatibility-pain. Minor browser updates may also block tricks without warning and you may have to keep reinventing hacks to keep it working.

JavaScript null check

In JavaScript, null is a special singleton object which is helpful for signaling "no value". You can test for it by comparison and, as usual in JavaScript, it's a good practice to use the === operator to avoid confusing type coercion:

var a = null;
alert(a === null); // true

As @rynah mentions, "undefined" is a bit confusing in JavaScript. However, it's always safe to test if the typeof(x) is the string "undefined", even if "x" is not a declared variable:

alert(typeof(x) === 'undefined'); // true

Also, variables can have the "undefined value" if they are not initialized:

var y;
alert(typeof(y) === 'undefined'); // true

Putting it all together, your check should look like this:

if ((typeof(data) !== 'undefined') && (data !== null)) {
  // ...

However, since the variable "data" is always defined since it is a formal function parameter, using the "typeof" operator is unnecessary and you can safely compare directly with the "undefined value".

function(data) {
  if ((data !== undefined) && (data !== null)) {
    // ...

This snippet amounts to saying "if the function was called with an argument which is defined and is not null..."

How to call Base Class's __init__ method from the child class?

You could use super(ChildClass, self).__init__()

class BaseClass(object):
    def __init__(self, *args, **kwargs):
        pass

class ChildClass(BaseClass):
    def __init__(self, *args, **kwargs):
        super(ChildClass, self).__init__(*args, **kwargs)

Your indentation is incorrect, here's the modified code:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super(ElectricCar, self).__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Here's the output:

{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}

Difference between mkdir() and mkdirs() in java for java.io.File

mkdirs() will create the specified directory path in its entirety where mkdir() will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.

In other words mkdir() is like mkdir and mkdirs() is like mkdir -p.

For example, imagine we have an empty /tmp directory. The following code

new File("/tmp/one/two/three").mkdirs();

would create the following directories:

  • /tmp/one
  • /tmp/one/two
  • /tmp/one/two/three

Where this code:

new File("/tmp/one/two/three").mkdir();

would not create any directories - as it wouldn't find /tmp/one/two - and would return false.

How to convert CSV to JSON in Node.js

I have used csvtojson library for converting csv string to json array. It has variety of function which can help you to convert to JSON.
It also supports reading from file and file streaming.

Be careful while parsing the csv which can contain the comma(,) or any other delimiter . For removing the delimiter please see my answer here.

Jackson and generic type reference

'JavaType' works !! I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution. Code:

JsonMarshallerUnmarshaller<T> {
    T targetClass;

    public ArrayList<T> unmarshal(String jsonString) {
        ObjectMapper mapper = new ObjectMapper();

        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
        mapper.getDeserializationConfig()
            .withAnnotationIntrospector(introspector);

        mapper.getSerializationConfig()
            .withAnnotationIntrospector(introspector);
        JavaType type = mapper.getTypeFactory().
            constructCollectionType(
                ArrayList.class, 
                targetclass.getClass());

        try {
            Class c1 = this.targetclass.getClass();
            Class c2 = this.targetclass1.getClass();
            ArrayList<T> temp = (ArrayList<T>) 
                mapper.readValue(jsonString,  type);
            return temp ;
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null ;
    }  
}

ASP.Net 2012 Unobtrusive Validation with jQuery

This is the official Microsoft answer from the MS Connect forums. I am copying the relevant text below :-

When targeting .NET 4.5 Unobtrusive Validation is enabled by default. You need to have jQuery in your project and have something like this in Global.asax to register jQuery properly:

ScriptManager.ScriptResourceMapping.AddDefinition("jquery", 
    new ScriptResourceDefinition {
        Path = "~/scripts/jquery-1.4.1.min.js",
        DebugPath = "~/scripts/jquery-1.4.1.js",
        CdnPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.min.js",
        CdnDebugPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.js"
    });

Replacing the version of jQuery with the version you are using.

You can also disable this new feature in web.config by removing the following line:

<add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />

Sum columns with null values in oracle

The other answers regarding the use of nvl() are correct however none seem to address a more salient point:

Should you even have NULLs in this column?

Do they have a meaning other than 0?

This seems like a case where you should have a NOT NULL DEFAULT 0 on th ecolumn

Jquery button click() function is not working

You need to use a delegated event handler, as the #add elements dynamically appended won't have the click event bound to them. Try this:

$("#buildyourform").on('click', "#add", function() {
    // your code...
});

Also, you can make your HTML strings easier to read by mixing line quotes:

var fieldWrapper = $('<div class="fieldwrapper" name="field' + intId + '" id="field' + intId + '"/>');

Or even supplying the attributes as an object:

var fieldWrapper = $('<div></div>', { 
    'class': 'fieldwrapper',
    'name': 'field' + intId,
    'id': 'field' + intId
});

how to remove json object key and value.?

There are several ways to do this, lets see them one by one:

  1. delete method: The most common way

_x000D_
_x000D_
const myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
};_x000D_
_x000D_
delete myObject['currentIndustry'];_x000D_
// OR delete myObject.currentIndustry;_x000D_
  _x000D_
console.log(myObject);
_x000D_
_x000D_
_x000D_

  1. By making key value undefined: Alternate & a faster way:

_x000D_
_x000D_
let myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
  };_x000D_
_x000D_
myObject.currentIndustry = undefined;_x000D_
myObject = JSON.parse(JSON.stringify(myObject));_x000D_
_x000D_
console.log(myObject);
_x000D_
_x000D_
_x000D_

  1. With es6 spread Operator:

_x000D_
_x000D_
const myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
};_x000D_
_x000D_
_x000D_
const {currentIndustry, ...filteredObject} = myObject;_x000D_
console.log(filteredObject);
_x000D_
_x000D_
_x000D_

Or if you can use omit() of underscore js library:

const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);

When to use what??

If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.

hope this helps :)

How to convert int to float in C?

I routinely multiply by 1.0 if I want floating point, it's easier than remembering the rules.

JavaScript: set dropdown selected item based on option text

var textToFind = 'Google';

var dd = document.getElementById('MyDropDown');
for (var i = 0; i < dd.options.length; i++) {
    if (dd.options[i].text === textToFind) {
        dd.selectedIndex = i;
        break;
    }
}

Using Composer's Autoload

The autoload config does start below the vendor dir. So you might want change the vendor dir, e.g.

{
    "config": {
        "vendor-dir": "../vendor/"
    },
    "autoload": {
        "psr-0": {"AppName": "src/"}
    }
}

Or isn't this possible in your project?

Disable click outside of bootstrap modal area to close modal

none of these solutions worked for me.

I have a terms and conditions modal that i wanted to force people to review before continuing...the defaults "static" and "keyboard" as per the options made it impossible to scroll down the page as the terms and conditions are a few pages log, static was not the answer for me.

So instead i went to unbind the the click method on the modal, with the following i was able to get the desired effect.

$('.modal').off('click');

Why does my Eclipse keep not responding?

If there is a project you earlier imported externally (outside of Workspace), that may cause this problem. If you can access Eclipse try to remove it. If you are getting the 'No responding at startup', then go delete the file at source.

This will solve the problem.

HttpClient - A task was cancelled?

in my .net core 3.1 applications I am getting two problem where inner cause was timeout exception. 1, one is i am getting aggregate exception and in it's inner exception was timeout exception 2, other case was Task canceled exception

My solution is

catch (Exception ex)
            {
                if (ex.InnerException is TimeoutException)
                {
                    ex = ex.InnerException;
                }
                else if (ex is TaskCanceledException)
                {
                    if ((ex as TaskCanceledException).CancellationToken == null || (ex as TaskCanceledException).CancellationToken.IsCancellationRequested == false)
                    {
                        ex = new TimeoutException("Timeout occurred");
                    }
                }                
                Logger.Fatal(string.Format("Exception at calling {0} :{1}", url, ex.Message), ex);
            }

How to filter files when using scp to copy dir recursively?

There is no feature in scp to filter files. For "advanced" stuff like this, I recommend using rsync:

rsync -av --exclude '*.svn' user@server:/my/dir .

(this line copy rsync from distant folder to current one)

Recent versions of rsync tunnel over an ssh connection automatically by default.

Case insensitive regular expression without re.compile?

To perform case-insensitive operations, supply re.IGNORECASE

>>> import re
>>> test = 'UPPER TEXT, lower text, Mixed Text'
>>> re.findall('text', test, flags=re.IGNORECASE)
['TEXT', 'text', 'Text']

and if we want to replace text matching the case...

>>> def matchcase(word):
        def replace(m):
            text = m.group()
            if text.isupper():
                return word.upper()
            elif text.islower():
                return word.lower()
            elif text[0].isupper():
                return word.capitalize()
            else:
                return word
        return replace

>>> re.sub('text', matchcase('word'), test, flags=re.IGNORECASE)
'UPPER WORD, lower word, Mixed Word'

How do I escape double and single quotes in sed?

You can use %

sed -i "s%http://www.fubar.com%URL_FUBAR%g"

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

You can use ExtendedXmlSerializer. If you have a class:

public class TestClass
{
    public Dictionary<int, string> Dictionary { get; set; }
}

and create instance of this class:

var obj = new TestClass
{
    Dictionary = new Dictionary<int, string>
    {
        {1, "First"},
        {2, "Second"},
        {3, "Other"},
    }
};

You can serialize this object using ExtendedXmlSerializer:

var serializer = new ConfigurationContainer()
    .UseOptimizedNamespaces() //If you want to have all namespaces in root element
    .Create();

var xml = serializer.Serialize(
    new XmlWriterSettings { Indent = true }, //If you want to formated xml
    obj);

Output xml will look like:

<?xml version="1.0" encoding="utf-8"?>
<TestClass xmlns:sys="https://extendedxmlserializer.github.io/system" xmlns:exs="https://extendedxmlserializer.github.io/v2" xmlns="clr-namespace:ExtendedXmlSerializer.Samples;assembly=ExtendedXmlSerializer.Samples">
  <Dictionary>
    <sys:Item>
      <Key>1</Key>
      <Value>First</Value>
    </sys:Item>
    <sys:Item>
      <Key>2</Key>
      <Value>Second</Value>
    </sys:Item>
    <sys:Item>
      <Key>3</Key>
      <Value>Other</Value>
    </sys:Item>
  </Dictionary>
</TestClass>

You can install ExtendedXmlSerializer from nuget or run the following command:

Install-Package ExtendedXmlSerializer

Click event on select option element in chrome

Since $(this) isn't correct anymore with ES6 arrow function which don't have have the same this than function() {}, you shouldn't use $( this ) if you use ES6 syntax.
Besides according to the official jQuery's anwser, there's a simpler way to do that what the top answer says.
The best way to get the html of a selected option is to use

$('#yourSelect option:selected').html();

You can replace html() by text() or anything else you want (but html() was in the original question).
Just add the event listener change, with the jQuery's shorthand method change(), to trigger your code when the selected option change.

 $ ('#yourSelect' ).change(() => {
    process($('#yourSelect option:selected').html());
  });

If you just want to know the value of the option:selected (the option that the user has chosen) you can just use $('#yourSelect').val()

Getting mouse position in c#

You must also have the following imports in order to import the DLL

using System.Runtime.InteropServices;
using System.Diagnostics;

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

In PHP 7 you can write it even shorter:

$age = $_GET['age'] ?? 27;

This means that the $age variable will be set to the age parameter if it is provided in the URL, or it will default to 27.

See all new features of PHP 7.

How to calculate mean, median, mode and range from a set of numbers

public class Mode {
    public static void main(String[] args) {
        int[] unsortedArr = new int[] { 3, 1, 5, 2, 4, 1, 3, 4, 3, 2, 1, 3, 4, 1 ,-1,-1,-1,-1,-1};
        Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();

        for (int i = 0; i < unsortedArr.length; i++) {
            Integer value = countMap.get(unsortedArr[i]);

            if (value == null) {
                countMap.put(unsortedArr[i], 0);
            } else {
                int intval = value.intValue();
                intval++;
                countMap.put(unsortedArr[i], intval);
            }
        }

        System.out.println(countMap.toString());

        int max = getMaxFreq(countMap.values());
        List<Integer> modes = new ArrayList<Integer>();

        for (Entry<Integer, Integer> entry : countMap.entrySet()) {
            int value = entry.getValue();
            if (value == max)
                modes.add(entry.getKey());
        }
        System.out.println(modes);
    }

    public static int getMaxFreq(Collection<Integer> valueSet) {
        int max = 0;
        boolean setFirstTime = false;

        for (Iterator iterator = valueSet.iterator(); iterator.hasNext();) {
            Integer integer = (Integer) iterator.next();

            if (!setFirstTime) {
                max = integer;
                setFirstTime = true;
            }
            if (max < integer) {
                max = integer;
            }
        }
        return max;
    }
}

Test data

Modes {1,3} for { 3, 1, 5, 2, 4, 1, 3, 4, 3, 2, 1, 3, 4, 1 };
Modes {-1} for { 3, 1, 5, 2, 4, 1, 3, 4, 3, 2, 1, 3, 4, 1 ,-1,-1,-1,-1,-1};

How do I control how Emacs makes backup files?

You can disable them altogether by

(setq make-backup-files nil)

Install a .NET windows service without InstallUtil.exe

Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...

Here's an example:

[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
    public MyServiceInstallerProcess()
    {
        this.Account = ServiceAccount.NetworkService;
    }
}

[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
    public MyServiceInstaller()
    {
        this.Description = "Service Description";
        this.DisplayName = "Service Name";
        this.ServiceName = "ServiceName";
        this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
    }
}

static void Install(bool undo, string[] args)
{
    try
    {
        Console.WriteLine(undo ? "uninstalling" : "installing");
        using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
        {
            IDictionary state = new Hashtable();
            inst.UseNewContext = true;
            try
            {
                if (undo)
                {
                    inst.Uninstall(state);
                }
                else
                {
                    inst.Install(state);
                    inst.Commit(state);
                }
            }
            catch
            {
                try
                {
                    inst.Rollback(state);
                }
                catch { }
                throw;
            }
        }
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
    }
}

Two Decimal places using c#

Probably a variant of the other examples, but I use this method to also make sure a dot is shown before the decimal places and not a comma:

someValue.ToString("0.00", CultureInfo.InvariantCulture)

laravel Unable to prepare route ... for serialization. Uses Closure

If someone is still looking for an answer, for me the problem was in routes/web.php file. Example:

Route::get('/', function () {
    return view('welcome');
});

It is also Route, so yeah...Just remove it if not needed and you are good to go! You should also follow answers provided from above.

How SQL query result insert in temp table?

You can use select ... into ... to create and populate a temp table and then query the temp table to return the result.

select *
into #TempTable
from YourTable

select *
from #TempTable

How to calculate percentage with a SQL statement

This one is working well in MS SQL. It transforms varchar to the result of two-decimal-places-limited float.

Select field1, cast(Try_convert(float,(Count(field2)* 100) / 
Try_convert(float, (Select Count(*) From table1))) as decimal(10,2)) as new_field_name 
From table1 
Group By field1, field2;

Eclipse internal error while initializing Java tooling

Close all open projects and exit Eclipse. Now you can open Eclipse without getting the error. Start opening your projects one by one to find which one causes the problem. This is most likely because you deleted a Device profile inside the AVD manager.

Or you can start working on a new workspace, (i.e. change your workspace), then try to import your project from the old workspace

How to get json key and value in javascript?

you have parse that Json string using JSON.parse()

..
}).done(function(data){
    obj = JSON.parse(data);
    alert(obj.jobtitel);
});

NSRange to Range<String.Index>

As of Swift 4 (Xcode 9), the Swift standard library provides methods to convert between Swift string ranges (Range<String.Index>) and NSString ranges (NSRange). Example:

let str = "abc"
let r1 = str.range(of: "")!

// String range to NSRange:
let n1 = NSRange(r1, in: str)
print((str as NSString).substring(with: n1)) // 

// NSRange back to String range:
let r2 = Range(n1, in: str)!
print(str[r2]) // 

Therefore the text replacement in the text field delegate method can now be done as

func textField(_ textField: UITextField,
               shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {

    if let oldString = textField.text {
        let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!,
                                                      with: string)
        // ...
    }
    // ...
}

(Older answers for Swift 3 and earlier:)

As of Swift 1.2, String.Index has an initializer

init?(_ utf16Index: UTF16Index, within characters: String)

which can be used to convert NSRange to Range<String.Index> correctly (including all cases of Emojis, Regional Indicators or other extended grapheme clusters) without intermediate conversion to an NSString:

extension String {
    func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
        let from16 = advance(utf16.startIndex, nsRange.location, utf16.endIndex)
        let to16 = advance(from16, nsRange.length, utf16.endIndex)
        if let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self) {
                return from ..< to
        }
        return nil
    }
}

This method returns an optional string range because not all NSRanges are valid for a given Swift string.

The UITextFieldDelegate delegate method can then be written as

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if let swRange = textField.text.rangeFromNSRange(range) {
        let newString = textField.text.stringByReplacingCharactersInRange(swRange, withString: string)
        // ...
    }
    return true
}

The inverse conversion is

extension String {
    func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
        let utf16view = self.utf16
        let from = String.UTF16View.Index(range.startIndex, within: utf16view) 
        let to = String.UTF16View.Index(range.endIndex, within: utf16view)
        return NSMakeRange(from - utf16view.startIndex, to - from)
    }
}

A simple test:

let str = "abc"
let r1 = str.rangeOfString("")!

// String range to NSRange:
let n1 = str.NSRangeFromRange(r1)
println((str as NSString).substringWithRange(n1)) // 

// NSRange back to String range:
let r2 = str.rangeFromNSRange(n1)!
println(str.substringWithRange(r2)) // 

Update for Swift 2:

The Swift 2 version of rangeFromNSRange() was already given by Serhii Yakovenko in this answer, I am including it here for completeness:

extension String {
    func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
        let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
        let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
        if let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self) {
                return from ..< to
        }
        return nil
    }
}

The Swift 2 version of NSRangeFromRange() is

extension String {
    func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
        let utf16view = self.utf16
        let from = String.UTF16View.Index(range.startIndex, within: utf16view)
        let to = String.UTF16View.Index(range.endIndex, within: utf16view)
        return NSMakeRange(utf16view.startIndex.distanceTo(from), from.distanceTo(to))
    }
}

Update for Swift 3 (Xcode 8):

extension String {
    func nsRange(from range: Range<String.Index>) -> NSRange {
        let from = range.lowerBound.samePosition(in: utf16)
        let to = range.upperBound.samePosition(in: utf16)
        return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
                       length: utf16.distance(from: from, to: to))
    }
}

extension String {
    func range(from nsRange: NSRange) -> Range<String.Index>? {
        guard
            let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
            let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location + nsRange.length, limitedBy: utf16.endIndex),
            let from = from16.samePosition(in: self),
            let to = to16.samePosition(in: self)
            else { return nil }
        return from ..< to
    }
}

Example:

let str = "abc"
let r1 = str.range(of: "")!

// String range to NSRange:
let n1 = str.nsRange(from: r1)
print((str as NSString).substring(with: n1)) // 

// NSRange back to String range:
let r2 = str.range(from: n1)!
print(str.substring(with: r2)) // 

push() a two-dimensional array

var r = 3; //start from rows 3
var c = 5; //start from col 5

var rows = 8;

var cols = 7;


for (var i = 0; i < rows; i++)

{

 for (var j = 0; j < cols; j++)

 {
    if(j <= c && i <= r) {
      myArray[i][j] = 1;
    } else {
      myArray[i][j] = 0;
    }
}

}

Import Android volley to Android Studio

add volly to your studio gradle app by compile 'com.android.volley:volley:1.0.0'

Returning binary file from controller in ASP.NET Web API

Try using a simple HttpResponseMessage with its Content property set to a StreamContent:

// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;

public HttpResponseMessage Post(string version, string environment,
    string filetype)
{
    var path = @"C:\Temp\test.exe";
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

A few things to note about the stream used:

  • You must not call stream.Dispose(), since Web API still needs to be able to access it when it processes the controller method's result to send data back to the client. Therefore, do not use a using (var stream = …) block. Web API will dispose the stream for you.

  • Make sure that the stream has its current position set to 0 (i.e. the beginning of the stream's data). In the above example, this is a given since you've only just opened the file. However, in other scenarios (such as when you first write some binary data to a MemoryStream), make sure to stream.Seek(0, SeekOrigin.Begin); or set stream.Position = 0;

  • With file streams, explicitly specifying FileAccess.Read permission can help prevent access rights issues on web servers; IIS application pool accounts are often given only read / list / execute access rights to the wwwroot.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

The strategy from Wikipedia for playing a perfect game (win or tie every time) seems like straightforward pseudo-code:

Quote from Wikipedia (Tic Tac Toe#Strategy)

A player can play a perfect game of Tic-tac-toe (to win or, at least, draw) if they choose the first available move from the following list, each turn, as used in Newell and Simon's 1972 tic-tac-toe program.[6]

  1. Win: If you have two in a row, play the third to get three in a row.

  2. Block: If the opponent has two in a row, play the third to block them.

  3. Fork: Create an opportunity where you can win in two ways.

  4. Block Opponent's Fork:

    Option 1: Create two in a row to force the opponent into defending, as long as it doesn't result in them creating a fork or winning. For example, if "X" has a corner, "O" has the center, and "X" has the opposite corner as well, "O" must not play a corner in order to win. (Playing a corner in this scenario creates a fork for "X" to win.)

    Option 2: If there is a configuration where the opponent can fork, block that fork.

  5. Center: Play the center.

  6. Opposite Corner: If the opponent is in the corner, play the opposite corner.

  7. Empty Corner: Play an empty corner.

  8. Empty Side: Play an empty side.

Recognizing what a "fork" situation looks like could be done in a brute-force manner as suggested.

Note: A "perfect" opponent is a nice exercise but ultimately not worth 'playing' against. You could, however, alter the priorities above to give characteristic weaknesses to opponent personalities.

Recursively looping through an object to build a property list

Here is a simple solution. This is a late answer but may be simple one-

_x000D_
_x000D_
const data = {
  city: 'foo',
  year: 2020,
  person: {
    name: {
      firstName: 'john',
      lastName: 'doe'
    },
    age: 20,
    type: {
      a: 2,
      b: 3,
      c: {
        d: 4,
        e: 5
      }
    }
  },
}

function getKey(obj, res = [], parent = '') {
  const keys = Object.keys(obj);
  
  /** Loop throw the object keys and check if there is any object there */
  keys.forEach(key => {
    if (typeof obj[key] !== 'object') {
      // Generate the heirarchy
      parent ? res.push(`${parent}.${key}`) : res.push(key);
    } else {
      // If object found then recursively call the function with updpated parent
      let newParent = parent ? `${parent}.${key}` : key;
      getKey(obj[key], res, newParent);
    }
    
  });
}

const result = [];

getKey(data, result, '');

console.log(result);
_x000D_
.as-console-wrapper{min-height: 100%!important; top: 0}
_x000D_
_x000D_
_x000D_

How to write std::string to file?

Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:

std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;

What is the most compatible way to install python modules on a Mac?

If you use Python from MacPorts, it has it's own easy_install located at: /opt/local/bin/easy_install-2.6 (for py26, that is). It's not the same one as simply calling easy_install directly, even if you used python_select to change your default python command.

How to scroll to bottom in react?

The easiest and best way I would recommend is.

My ReactJS version: 16.12.0


For Class Components

HTML structure inside render() function

    render()
        return(
            <body>
                <div ref="messageList">
                    <div>Message 1</div>
                    <div>Message 2</div>
                    <div>Message 3</div>
                </div>
            </body>
        )
    )

scrollToBottom() function which will get reference of the element. and scroll according to scrollIntoView() function.

  scrollToBottom = () => {
    const { messageList } = this.refs;
    messageList.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
  }

and call the above function inside componentDidMount() and componentDidUpdate()


For Functional Components (Hooks)

Import useRef() and useEffect()

import { useEffect, useRef } from 'react'

Inside your export function, (same as calling a useState())

const messageRef = useRef();

And let's assume you have to scroll when page load,

useEffect(() => {
    if (messageRef.current) {
      messageRef.current.scrollIntoView(
        {
          behavior: 'smooth',
          block: 'end',
          inline: 'nearest'
        })
    }
  })

OR if you want it to trigger once an action performed,

useEffect(() => {
  if (messageRef.current) {
    messageRef.current.scrollIntoView(
      {
        behavior: 'smooth',
        block: 'end',
        inline: 'nearest'
      })
  }
},
[stateVariable])

And Finally, to your HTML structure

return(
    <body>
        <div ref={messageRef}> // <= The only different is we are calling a variable here
            <div>Message 1</div>
            <div>Message 2</div>
            <div>Message 3</div>
        </div>
    </body>
)

for more explanation about Element.scrollIntoView() visit developer.mozilla.org

More detailed explanation in Callback refs visit reactjs.org

PHP: How to get referrer URL?

Underscore. Not space.

$_SERVER['HTTP_REFERER']

How to upsert (update or insert) in SQL Server 2005

You could do this with an INSTEAD OF INSERT trigger on the table, that checks for the existance of the row and then updates/inserts depending on whether it exists already. There is an example of how to do this for SQL Server 2000+ on MSDN here:

CREATE TRIGGER IO_Trig_INS_Employee ON Employee
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
-- Check for duplicate Person. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT P.SSN
      FROM Person P, inserted I
      WHERE P.SSN = I.SSN))
   INSERT INTO Person
      SELECT SSN,Name,Address,Birthdate
      FROM inserted
ELSE
-- Log attempt to insert duplicate Person row in PersonDuplicates table.
   INSERT INTO PersonDuplicates
      SELECT SSN,Name,Address,Birthdate,SUSER_SNAME(),GETDATE()
      FROM inserted
-- Check for duplicate Employee. If no duplicate, do an insert.
IF (NOT EXISTS (SELECT E.SSN
      FROM EmployeeTable E, inserted
      WHERE E.SSN = inserted.SSN))
   INSERT INTO EmployeeTable
      SELECT EmployeeID,SSN, Department, Salary
      FROM inserted
ELSE
--If duplicate, change to UPDATE so that there will not
--be a duplicate key violation error.
   UPDATE EmployeeTable
      SET EmployeeID = I.EmployeeID,
          Department = I.Department,
          Salary = I.Salary
   FROM EmployeeTable E, inserted I
   WHERE E.SSN = I.SSN
END

How to check if directory exist using C++ and winAPI

This code might work:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 

CSS text-decoration underline color

You can do it if you wrap your text into a span like:

_x000D_
_x000D_
a {_x000D_
  color: red;_x000D_
  text-decoration: underline;_x000D_
}_x000D_
span {_x000D_
  color: blue;_x000D_
  text-decoration: none;_x000D_
}
_x000D_
<a href="#">_x000D_
  <span>Text</span>_x000D_
</a>
_x000D_
_x000D_
_x000D_

Converting a year from 4 digit to 2 digit and back again in C#

If you're creating a DateTime object using the expiration dates (month/year), you can use ToString() on your DateTime variable like so:

DateTime expirationDate = new DateTime(2008, 1, 31); // random date
string lastTwoDigitsOfYear = expirationDate.ToString("yy");

Edit: Be careful with your dates though if you use the DateTime object during validation. If somebody selects 05/2008 as their card's expiration date, it expires at the end of May, not on the first.

How do I search for files in Visual Studio Code?

Other answers don't mention this command is named workbench.action.quickOpen.

You can use this to search the Keyboard Shortcuts menu located in Preferences.

On MacOS the default keybinding is cmd ? + P.

(Coming from Sublime Text, I always change this to cmd ? + T)

@Autowired and static method

You have to workaround this via static application context accessor approach:

@Component
public class StaticContextAccessor {

    private static StaticContextAccessor instance;

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void registerInstance() {
        instance = this;
    }

    public static <T> T getBean(Class<T> clazz) {
        return instance.applicationContext.getBean(clazz);
    }

}

Then you can access bean instances in a static manner.

public class Boo {

    public static void randomMethod() {
         StaticContextAccessor.getBean(Foo.class).doStuff();
    }

}

How to solve privileges issues when restore PostgreSQL Database

For people using Google Cloud Platform, any error will stop the import process. Personally I encountered two different errors depending on the pg_dump command I issued :

1- The input is a PostgreSQL custom-format dump. Use the pg_restore command-line client to restore this dump to a database.

Occurs when you've tried to dump your DB in a non plain text format. I.e when the command lacks the -Fp or --format=plain parameter. However, if you add it to your command, you may then encounter the following error :

2- SET SET SET SET SET SET CREATE EXTENSION ERROR: must be owner of extension plpgsql

This is a permission issue I have been unable to fix using the command provided in the GCP docs, the tips from this current thread, or following advice from Google Postgres team here. Which recommended to issue the following command :

pg_dump -Fp --no-acl --no-owner -U myusername myDBName > mydump.sql

The only thing that did the trick in my case was manually editing the dump file and commenting out all commands relating to plpgsql.

I hope this helps GCP-reliant souls.

Update :

It's easier to dump the file commenting out extensions, especially since some dumps can be huge : pg_dump ... | grep -v -E '(CREATE\ EXTENSION|COMMENT\ ON)' > mydump.sql

Which can be narrowed down to plpgsql : pg_dump ... | grep -v -E '(CREATE\ EXTENSION\ IF\ NOT\ EXISTS\ plpgsql|COMMENT\ ON\ EXTENSION\ plpgsql)' > mydump.sql

Update elements in a JSONObject

Remove key and then add again the modified key, value pair as shown below :

    JSONObject js = new JSONObject();
    js.put("name", "rai");

    js.remove("name");
    js.put("name", "abc");

I haven't used your example; but conceptually its same.

Refresh or force redraw the fragment

In my case, detach and attach worked:

 getSupportFragmentManager()
   .beginTransaction()
   .detach(contentFragment)
   .attach(contentFragment)
   .commit();

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

Instead of casting the model in the RenderPartial call, and since you're using razor, you can modify the first line in your view from

@model dynamic

to

@model YourNamespace.YourModelType

This has the advantage of working on every @Html.Partial call you have in the view, and also gives you intellisense for the properties.

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

System.Linq has ToList() on IQueryable<> and IEnumerable<>. It will cause a full pass through the data to put it into a list, though. You loose your deferred invoke when you do this. Not a big deal if it is the consumer of the data.

Android read text raw resource file

You can use this:

    try {
        Resources res = getResources();
        InputStream in_s = res.openRawResource(R.raw.help);

        byte[] b = new byte[in_s.available()];
        in_s.read(b);
        txtHelp.setText(new String(b));
    } catch (Exception e) {
        // e.printStackTrace();
        txtHelp.setText("Error: can't show help.");
    }

Saving timestamp in mysql table using php

Check field type in table just save time stamp value in datatype like bigint etc.

Not datetime type

Automatically start a Windows Service on install

Automatic startup means that the service is automatically started when Windows starts. As others have mentioned, to start it from the console you should use the ServiceController.

python tuple to dict

A slightly simpler method:

>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}

Parse JSON with R

Try below code using RJSONIO in console

library(RJSONIO)
library(RCurl)


json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")

json_file2 = RJSONIO::fromJSON(json_file)

head(json_file2)

How do I get a background location update every n minutes in my iOS application?

if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
}

This is needed for background location tracking since iOS 9.

What do I use for a max-heap implementation in Python?

To elaborate on https://stackoverflow.com/a/59311063/1328979, here is a fully documented, annotated and tested Python 3 implementation for the general case.

from __future__ import annotations  # To allow "MinHeap.push -> MinHeap:"
from typing import Generic, List, Optional, TypeVar
from heapq import heapify, heappop, heappush, heapreplace


T = TypeVar('T')


class MinHeap(Generic[T]):
    '''
    MinHeap provides a nicer API around heapq's functionality.
    As it is a minimum heap, the first element of the heap is always the
    smallest.
    >>> h = MinHeap([3, 1, 4, 2])
    >>> h[0]
    1
    >>> h.peek()
    1
    >>> h.push(5)  # N.B.: the array isn't always fully sorted.
    [1, 2, 4, 3, 5]
    >>> h.pop()
    1
    >>> h.pop()
    2
    >>> h.pop()
    3
    >>> h.push(3).push(2)
    [2, 3, 4, 5]
    >>> h.replace(1)
    2
    >>> h
    [1, 3, 4, 5]
    '''
    def __init__(self, array: Optional[List[T]] = None):
        if array is None:
            array = []
        heapify(array)
        self.h = array
    def push(self, x: T) -> MinHeap:
        heappush(self.h, x)
        return self  # To allow chaining operations.
    def peek(self) -> T:
        return self.h[0]
    def pop(self) -> T:
        return heappop(self.h)
    def replace(self, x: T) -> T:
        return heapreplace(self.h, x)
    def __getitem__(self, i) -> T:
        return self.h[i]
    def __len__(self) -> int:
        return len(self.h)
    def __str__(self) -> str:
        return str(self.h)
    def __repr__(self) -> str:
        return str(self.h)


class Reverse(Generic[T]):
    '''
    Wrap around the provided object, reversing the comparison operators.
    >>> 1 < 2
    True
    >>> Reverse(1) < Reverse(2)
    False
    >>> Reverse(2) < Reverse(1)
    True
    >>> Reverse(1) <= Reverse(2)
    False
    >>> Reverse(2) <= Reverse(1)
    True
    >>> Reverse(2) <= Reverse(2)
    True
    >>> Reverse(1) == Reverse(1)
    True
    >>> Reverse(2) > Reverse(1)
    False
    >>> Reverse(1) > Reverse(2)
    True
    >>> Reverse(2) >= Reverse(1)
    False
    >>> Reverse(1) >= Reverse(2)
    True
    >>> Reverse(1)
    1
    '''
    def __init__(self, x: T) -> None:
        self.x = x
    def __lt__(self, other: Reverse) -> bool:
        return other.x.__lt__(self.x)
    def __le__(self, other: Reverse) -> bool:
        return other.x.__le__(self.x)
    def __eq__(self, other) -> bool:
        return self.x == other.x
    def __ne__(self, other: Reverse) -> bool:
        return other.x.__ne__(self.x)
    def __ge__(self, other: Reverse) -> bool:
        return other.x.__ge__(self.x)
    def __gt__(self, other: Reverse) -> bool:
        return other.x.__gt__(self.x)
    def __str__(self):
        return str(self.x)
    def __repr__(self):
        return str(self.x)


class MaxHeap(MinHeap):
    '''
    MaxHeap provides an implement of a maximum-heap, as heapq does not provide
    it. As it is a maximum heap, the first element of the heap is always the
    largest. It achieves this by wrapping around elements with Reverse,
    which reverses the comparison operations used by heapq.
    >>> h = MaxHeap([3, 1, 4, 2])
    >>> h[0]
    4
    >>> h.peek()
    4
    >>> h.push(5)  # N.B.: the array isn't always fully sorted.
    [5, 4, 3, 1, 2]
    >>> h.pop()
    5
    >>> h.pop()
    4
    >>> h.pop()
    3
    >>> h.pop()
    2
    >>> h.push(3).push(2).push(4)
    [4, 3, 2, 1]
    >>> h.replace(1)
    4
    >>> h
    [3, 1, 2, 1]
    '''
    def __init__(self, array: Optional[List[T]] = None):
        if array is not None:
            array = [Reverse(x) for x in array]  # Wrap with Reverse.
        super().__init__(array)
    def push(self, x: T) -> MaxHeap:
        super().push(Reverse(x))
        return self
    def peek(self) -> T:
        return super().peek().x
    def pop(self) -> T:
        return super().pop().x
    def replace(self, x: T) -> T:
        return super().replace(Reverse(x)).x


if __name__ == '__main__':
    import doctest
    doctest.testmod()

https://gist.github.com/marccarre/577a55850998da02af3d4b7b98152cf4

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

Consider following code

<ul id="myTask">
  <li>Coding</li>
  <li>Answering</li>
  <li>Getting Paid</li>
</ul>

Now, here goes the difference

// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
  $(this).remove()
});

Now, what if we add a myTask again?

$('#myTask').append('<li>Answer this question on SO</li>');

Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on, the new item would work without any extra effort on our part. Here's how the .on version would look:

$('#myTask').on('click', 'li', function (event) {
  $(event.target).remove()
});

Summary:

The difference between .on() and .click() would be that .click() may not work when the DOM elements associated with the .click() event are added dynamically at a later point while .on() can be used in situations where the DOM elements associated with the .on() call may be generated dynamically at a later point.

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

you could use "AUTHID CURRENT_USER" in body of your procedure definition for your requirements.

How to show "Done" button on iPhone number pad

I found @user1258240's answer to be pretty concise given this is not as simple as setting a returnKeyType property.

Just wanted to contribute my own "re-usable" approach to this:

func SetDoneToolbar(field:UITextField) {
    let doneToolbar:UIToolbar = UIToolbar()

    doneToolbar.items=[
        UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil),
        UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.plain, target: self, action: #selector(ViewController.dismissKeyboard))
    ]

    doneToolbar.sizeToFit()
    field.inputAccessoryView = doneToolbar
}

override func viewDidLoad() {
    super.viewDidLoad()

    SetDoneToolbar(field: UITextField_1)
    SetDoneToolbar(field: UITextField_2)
    SetDoneToolbar(field: UITextField_3)
    SetDoneToolbar(field: UITextField_N)
}

What are FTL files

FTL stands for FreeMarker Template.

It is very useful when you want to follow the MVC (Model View Controller) pattern.

The idea behind using the MVC pattern for dynamic Web pages is that you separate the designers (HTML authors) from the programmers.

How to add items to a combobox in a form in excel VBA?

The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.

Sub UserForm_Initialize()
  ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub

Which websocket library to use with Node.js?

Getting the ball rolling with this community wiki answer. Feel free to edit me with your improvements.

  • ws WebSocket server and client for node.js. One of the fastest libraries if not the fastest one.

  • websocket-node WebSocket server and client for node.js

  • websocket-driver-node WebSocket server and client protocol parser node.js - used in faye-websocket-node

  • faye-websocket-node WebSocket server and client for node.js - used in faye and sockjs

  • socket.io WebSocket server and client for node.js + client for browsers + (v0 has newest to oldest fallbacks, v1 of Socket.io uses engine.io) + channels - used in stack.io. Client library tries to reconnect upon disconnection.

  • sockjs WebSocket server and client for node.js and others + client for browsers + newest to oldest fallbacks

  • faye WebSocket server and client for node.js and others + client for browsers + fallbacks + support for other server-side languages

  • deepstream.io clusterable realtime server that handles WebSockets & TCP connections and provides data-sync, pub/sub and request/response

  • socketcluster WebSocket server cluster which makes use of all CPU cores on your machine. For example, if you were to use an xlarge Amazon EC2 instance with 32 cores, you would be able to handle almost 32 times the traffic on a single instance.

  • primus Provides a common API for most of the libraries above for easy switching + stability improvements for all of them.

When to use:

  • use the basic WebSocket servers when you want to use the native WebSocket implementations on the clientside, beware of the browser incompatabilities

  • use the fallback libraries when you care about browser fallbacks

  • use the full featured libraries when you care about channels

  • use primus when you have no idea about what to use, are not in the mood for rewriting your application when you need to switch frameworks because of changing project requirements or need additional connection stability.

Where to test:

Firecamp is a GUI testing environment for SocketIO, WS and all major real-time technology. Debug the real-time events while you're developing it.

How to ping ubuntu guest on VirtualBox

Using NAT (the default) this is not possible. Bridged Networking should allow it. If bridged does not work for you (this may be the case when your network adminstration does not allow multiple IP addresses on one physical interface), you could try 'Host-only networking' instead.

For configuration of Host-only here is a quote from the vbox manual(which is pretty good). http://www.virtualbox.org/manual/ch06.html:

For host-only networking, like with internal networking, you may find the DHCP server useful that is built into VirtualBox. This can be enabled to then manage the IP addresses in the host-only network since otherwise you would need to configure all IP addresses statically.

In the VirtualBox graphical user interface, you can configure all these items in the global settings via "File" -> "Settings" -> "Network", which lists all host-only networks which are presently in use. Click on the network name and then on the "Edit" button to the right, and you can modify the adapter and DHCP settings.

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

This is how I fix it

  1. Check and Update the path variable (See below on how to update the path variable)
  2. Delete node_modules and package-lock.json
  3. run npm install
  4. run npm run start

if this didn't work, try to install the nodejs and run repair

or clean npm cache npm cache clean --force

To update the path variable

  1. press windows key
  2. Search for Edit the system environmental variable
  3. Click on Environment Variables...
  4. on System variable bottom section ( there will be two section )
  5. Select Path variable name
  6. Click Edit..
  7. Check if there is C:\Program Files\nodejs on the list, if not add this

Get width in pixels from element with style set with %?

Try jQuery:

$("#banner-contenedor").width();

Start and stop a timer PHP

class Timer
{
    private $startTime = null;

    public function __construct($showSeconds = true)
    {
        $this->startTime = microtime(true);
        echo 'Working - please wait...' . PHP_EOL;
    }

    public function __destruct()
    {
        $endTime = microtime(true);
        $time = $endTime - $this->startTime;

        $hours = (int)($time / 60 / 60);
        $minutes = (int)($time / 60) - $hours * 60;
        $seconds = (int)$time - $hours * 60 * 60 - $minutes * 60;
        $timeShow = ($hours == 0 ? "00" : $hours) . ":" . ($minutes == 0 ? "00" : ($minutes < 10 ? "0" . $minutes : $minutes)) . ":" . ($seconds == 0 ? "00" : ($seconds < 10 ? "0" . $seconds : $seconds));

        echo 'Job finished in ' . $timeShow . PHP_EOL;
    }
}

$t = new Timer(); // echoes "Working, please wait.."

[some operations]

unset($t);  // echoes "Job finished in h:m:s"

Does Java have an exponential operator?

In case if anyone wants to create there own exponential function using recursion, below is for your reference.

public static double power(double value, double p) {
        if (p <= 0)
            return 1;

        return value * power(value, p - 1);
    }

Notepad++ add to every line

To append different text to the end of each line, you can use the plugin ConyEdit to do this.
With ConyEdit running in the background, follow these steps.

  1. use the command line cc.gl a to get lines and store in an array named a.
  2. use the command line cc.aal //$a to append after each line, using the contents of array a.

Example
enter image description here

What does 'const static' mean in C and C++?

It has uses in both C and C++.

As you guessed, the static part limits its scope to that compilation unit. It also provides for static initialization. const just tells the compiler to not let anybody modify it. This variable is either put in the data or bss segment depending on the architecture, and might be in memory marked read-only.

All that is how C treats these variables (or how C++ treats namespace variables). In C++, a member marked static is shared by all instances of a given class. Whether it's private or not doesn't affect the fact that one variable is shared by multiple instances. Having const on there will warn you if any code would try to modify that.

If it was strictly private, then each instance of the class would get its own version (optimizer notwithstanding).

Return a 2d array from a function

A better alternative to using pointers to pointers is to use std::vector. That takes care of the details of memory allocation and deallocation.

std::vector<std::vector<int>> create2DArray(unsigned height, unsigned width)
{
   return std::vector<std::vector<int>>(height, std::vector<int>(width, 0));
}

Routing with Multiple Parameters using ASP.NET MVC

Starting with MVC 5, you can also use Attribute Routing to move the URL parameter configuration to your controllers.

A detailed discussion is available here: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

Summary:

First you enable attribute routing

 public class RouteConfig 
 {
     public static void RegisterRoutes(RouteCollection routes)
     {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

         routes.MapMvcAttributeRoutes();
     } 
 }

Then you can use attributes to define parameters and optionally data types

public class BooksController : Controller
{
    // eg: /books
    // eg: /books/1430210079
    [Route("books/{isbn?}")]
    public ActionResult View(string isbn)

Pass variables to AngularJS controller, best practice?

You could create a basket service. And generally in JS you use objects instead of lots of parameters.

Here's an example: http://jsfiddle.net/2MbZY/

var app = angular.module('myApp', []);

app.factory('basket', function() {
    var items = [];
    var myBasketService = {};

    myBasketService.addItem = function(item) {
        items.push(item);
    };
    myBasketService.removeItem = function(item) {
        var index = items.indexOf(item);
        items.splice(index, 1);
    };
    myBasketService.items = function() {
        return items;
    };

    return myBasketService;
});

function MyCtrl($scope, basket) {
    $scope.newItem = {};
    $scope.basket = basket;    
}

Why does make think the target is up to date?

Maybe you have a file/directory named test in the directory. If this directory exists, and has no dependencies that are more recent, then this target is not rebuild.

To force rebuild on these kind of not-file-related targets, you should make them phony as follows:

.PHONY: all test clean

Note that you can declare all of your phony targets there.

A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request.

using jQuery .animate to animate a div from right to left?

If you know the width of the child element you are animating, you can use and animate a margin offset as well. For example, this will animate from left:0 to right:0

CSS:

.parent{
width:100%;
position:relative;
}

#itemToMove{
position:absolute;
width:150px;
right:100%;
margin-right:-150px;
}

Javascript:

$( "#itemToMove" ).animate({
"margin-right": "0",
"right": "0"
}, 1000 );

How to get height of Keyboard?

// Step 1 :- Register NotificationCenter

ViewDidLoad() {

   self.yourtextfield.becomefirstresponder()

   // Register your Notification, To know When Key Board Appears.
    NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

   // Register your Notification, To know When Key Board Hides.
    NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

// Step 2 :- These Methods will be called Automatically when Keyboard appears Or Hides

    func keyboardWillShow(notification:NSNotification) {
        let userInfo:NSDictionary = notification.userInfo! as NSDictionary
        let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
        tblViewListData.frame.size.height = fltTblHeight-keyboardHeight
    }

    func keyboardWillHide(notification:NSNotification) {
        tblViewListData.frame.size.height = fltTblHeight
    }

Setting up a JavaScript variable from Spring model by using Thymeleaf

var message =/*[[${message}]]*/ 'defaultanyvalue';

Change status bar color with AppCompat ActionBarActivity

I'm not sure I understand the problem.

I you want to change the status bar color programmatically (and provided the device has Android 5.0) then you can use Window.setStatusBarColor(). It shouldn't make a difference whether the activity is derived from Activity or ActionBarActivity.

Just try doing:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.setStatusBarColor(Color.BLUE);
}

Just tested this with ActionBarActivity and it works alright.


Note: Setting the FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag programmatically is not necessary if your values-v21 styles file has it set already, via:

    <item name="android:windowDrawsSystemBarBackgrounds">true</item>

Check if XML Element exists

Not sure what you're wanting to do but using a DTD or schema might be all you need to validate the xml.

Otherwise, if you want to find an element you could use an xpath query to search for a particular element.

How do I rename the android package name?

Deselect Hide Empty Middle Packages in Project Explorer Windows settings menu than you will be able to refactor each directory

Simple way to sort strings in the (case sensitive) alphabetical order

If you don't want to add a dependency on Guava (per Michael's answer) then this comparator is equivalent:

private static Comparator<String> ALPHABETICAL_ORDER = new Comparator<String>() {
    public int compare(String str1, String str2) {
        int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2);
        if (res == 0) {
            res = str1.compareTo(str2);
        }
        return res;
    }
};

Collections.sort(list, ALPHABETICAL_ORDER);

And I think it is just as easy to understand and code ...

The last 4 lines of the method can written more concisely as follows:

        return (res != 0) ? res : str1.compareTo(str2);

ASP.NET Bundles how to disable minification

If you set the following property to false then it will disable both bundling and minification.

In Global.asax.cs file, add the line as mentioned below

protected void Application_Start()
{
    System.Web.Optimization.BundleTable.EnableOptimizations = false;
}