Programs & Examples On #Httpserverutility

Count number of matches of a regex in Javascript

(('a a a').match(/b/g) || []).length; // 0
(('a a a').match(/a/g) || []).length; // 3

Based on https://stackoverflow.com/a/48195124/16777 but fixed to actually work in zero-results case.

Pass variables between two PHP pages without using a form or the URL of page

Have you tried adding both to $_SESSION?

Then at the top of your page2.php just add:

<?php
session_start();

Permission denied (publickey) when SSH Access to Amazon EC2 instance

for the ubuntu 12.04 lts micro instance i had to set the user name as option

ssh -i pemfile.pem -l ubuntu dns

How do I disable right click on my web page?

Use this function to disable right click.You can disable left click and tap also by checking 1 and 0 corresponding

document.onmousedown = rightclickD;
            function rightclickD(e) 
            { 
                e = e||event;
                console.log(e);
                if (e.button == 2) {
                //alert('Right click disabled!!!'); 
                 return false; }
            }

Split comma-separated values

Split a Textbox value separated by comma and count the total number of values in text and splitted values are shown in ritchTextBox.

    private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = "";
        richTextBox1.Text = "";

        string strText = textBox1.Text.Trim();
        string[] strArr = strText.Split(',');
        int count = 0;
        for (int i = 0; i < strArr.Length; i++)
        {
            count++;
        }
        label1.Text = Convert.ToString(count);
        for (int i = 0; i < strArr.Length; i++)
        {
            richTextBox1.Text += strArr[i].Trim() + "\n";
        }
    }

Extract first item of each sublist

You could use zip:

>>> lst=[[1,2,3],[11,12,13],[21,22,23]]
>>> zip(*lst)[0]
(1, 11, 21)

Or, Python 3 where zip does not produce a list:

>>> list(zip(*lst))[0]
(1, 11, 21)

Or,

>>> next(zip(*lst))
(1, 11, 21)

Or, (my favorite) use numpy:

>>> import numpy as np
>>> a=np.array([[1,2,3],[11,12,13],[21,22,23]])
>>> a
array([[ 1,  2,  3],
       [11, 12, 13],
       [21, 22, 23]])
>>> a[:,0]
array([ 1, 11, 21])

Calling jQuery method from onClick attribute in HTML

this works....

<script language="javascript">
    (function($) {
     $.fn.MessageBox = function(msg) {
       return this.each(function(){
         alert(msg);
       })
     };
    })(jQuery);? 
</script>

.

   <body>
      <div class="Title">Welcome!</div>
     <input type="button" value="ahaha"  onclick="$(this).MessageBox('msg');" />
    </body>

edit

you are using a failsafe jQuery code using the $ alias... it should be written like:

(function($) {
  // plugin code here, use $ as much as you like
})(jQuery); 

or

jQuery(function($) {
   // your code using $ alias here
 });

note that it has a 'jQuery' word in each of it....

Sorted collection in Java

Using LambdaJ

You can try solving these tasks with LambdaJ if you are using prior versions to java 8. You can find it here: http://code.google.com/p/lambdaj/

Here you have an example:

Sort Iterative

List<Person> sortedByAgePersons = new ArrayList<Person>(persons);
Collections.sort(sortedByAgePersons, new Comparator<Person>() {
        public int compare(Person p1, Person p2) {
           return Integer.valueOf(p1.getAge()).compareTo(p2.getAge());
        }
}); 

Sort with LambdaJ

List<Person> sortedByAgePersons = sort(persons, on(Person.class).getAge()); 

Of course, having this kind of beauty impacts in the performance (an average of 2 times), but can you find a more readable code?

Sort with java 8 using lambda expression

Collections.sort(persons, (p1, p2) -> p1.getAge().compareTo(p2.getAge()));
//or
persons.sort((p1, p2) -> p1.getAge().compareTo(p2.getAge()));

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

You define var scatterSeries = [];, and then try to parse it as a json string at console.info(JSON.parse(scatterSeries)); which obviously fails. The variable is converted to an empty string, which causes an "unexpected end of input" error when trying to parse it.

set the iframe height automatically

If you a framework like Bootstrap you can make any iframe video responsive by using this snippet:

<div class="embed-responsive embed-responsive-16by9">
    <iframe class="embed-responsive-item" src="vid.mp4" allowfullscreen></iframe>
</div>

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No, it is not possible to use the curl_setopt call with CURLOPT_HTTPHEADER. The second call will overwrite the headers of the first call.

Instead the function needs to be called once with all headers:

$headers = array(
    'Content-type: application/xml',
    'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

MySQL Trigger - Storing a SELECT in a variable

Or you can just include the SELECT statement in the SQL that's invoking the trigger, so its passed in as one of the columns in the trigger row(s). As long as you're certain it will infallibly return only one row (hence one value). (And, of course, it must not return a value that interacts with the logic in the trigger, but that's true in any case.)

changing the language of error message in required field in html5 contact form

<input type="text" id="inputName"  placeholder="Enter name"  required  oninvalid="this.setCustomValidity('Please Enter your first name')" >

this can help you even more better, Fast, Convenient & Easiest.

PHP: Get the key from an array in a foreach loop

you need nested foreach loops

foreach($samplearr as $key => $item){
   echo $key;
    foreach($item as $detail){
       echo $detail['value1'] . " " . $detail['value2']
     }
 }

Inserting multiple rows in a single SQL query?

If you are inserting into a single table, you can write your query like this (maybe only in MySQL):

INSERT INTO table1 (First, Last)
VALUES
    ('Fred', 'Smith'),
    ('John', 'Smith'),
    ('Michael', 'Smith'),
    ('Robert', 'Smith');

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

First of all its not the Notepad++ problem for sure. Its your "String Matching problem"

The common string throughout all IE version is MSIE Check out the various userAgent strings at http://www.useragentstring.com/pages/Internet%20Explorer/

if(navigator.userAgent.indexOf("MSIE") != -1){
   alert('I am Internet Explorer!!');
}

-didSelectRowAtIndexPath: not being called

you must check this selection must be single selection and editing must be no seleciton during edition and you change setting in uttableviewcell properties also you edit in table view cell style must be custom and identifier must be Rid and section is none

Xcopy Command excluding files and folders

Like Andrew said /exclude parameter of xcopy should be existing file that has list of excludes.

Documentation of xcopy says:

Using /exclude

List each string in a separate line in each file. If any of the listed strings match any part of the absolute path of the file to be copied, that file is then excluded from the copying process. For example, if you specify the string "\Obj\", you exclude all files underneath the Obj directory. If you specify the string ".obj", you exclude all files with the .obj extension.

Example:

xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

and list-of-excluded-files.txt should exist in current folder (otherwise pass full path), with listing of files/folders to exclude - one file/folder per line. In your case that would be:

exclusion.txt

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

Enums in Javascript with ES6

As mentioned above, you could also write a makeEnum() helper function:

function makeEnum(arr){
    let obj = {};
    for (let val of arr){
        obj[val] = Symbol(val);
    }
    return Object.freeze(obj);
}

Use it like this:

const Colors = makeEnum(["red","green","blue"]);
let startColor = Colors.red; 
console.log(startColor); // Symbol(red)

if(startColor == Colors.red){
    console.log("Do red things");
}else{
    console.log("Do non-red things");
}

Offline Speech Recognition In Android (JellyBean)

In short, I don't have the implementation, but the explanation.

Google did not make offline speech recognition available to third party apps. Offline recognition is only accessable via the keyboard. Ben Randall (the developer of utter!) explains his workaround in an article at Android Police:

I had implemented my own keyboard and was switching between Google Voice Typing and the users default keyboard with an invisible edit text field and transparent Activity to get the input. Dirty hack!

This was the only way to do it, as offline Voice Typing could only be triggered by an IME or a system application (that was my root hack) . The other type of recognition API … didn't trigger it and just failed with a server error. … A lot of work wasted for me on the workaround! But at least I was ready for the implementation...

From Utter! Claims To Be The First Non-IME App To Utilize Offline Voice Recognition In Jelly Bean

Direct download from Google Drive using Google Drive API

This seems to be updated again as of May 19, 2015:

How I got it to work:

As in jmbertucci's recently updated answer, make your folder public to everyone. This is a bit more complicated than before, you have to click Advanced to change the folder to "On - Public on the web."

Find your folder UUID as before--just go into the folder and find your UUID in the address bar:

https://drive.google.com/drive/folders/<folder UUID>

Then head to

https://googledrive.com/host/<folder UUID>

It will redirect you to an index type page with a giant subdomain, but you should be able to see the files in your folder. Then you can right click to save the link to the file you want (I noticed that this direct link also has this big subdomain for googledrive.com). Worked great for me with wget.

This also seems to work with others' shared folders.

e.g.,

https://drive.google.com/folderview?id=0B7l10Bj_LprhQnpSRkpGMGV2eE0&usp=sharing

maps to

https://googledrive.com/host/0B7l10Bj_LprhQnpSRkpGMGV2eE0

And a right click can save a direct link to any of those files.

Changing EditText bottom line color with appcompat v7

I felt like this needed an answer in case somebody wanted to change just a single edittext. I do it like this:

editText.getBackground().mutate().setColorFilter(ContextCompat.getColor(context, R.color.your_color), PorterDuff.Mode.SRC_ATOP);

How to configure XAMPP to send mail from localhost?

You can send mail from localhost with sendmail package , sendmail package is inbuild in XAMPP. So if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

PS: don't forgot to replace my-gmail-id and my-gmail-password in above code. Also, don't forget to remove duplicate keys if you copied settings from above. For example comment following line if there is another sendmail_path : sendmail_path="C:\xampp\mailtodisk\mailtodisk.exe" in the php.ini file

Also remember to restart the server using the XAMMP control panel so the changes take effect.

For gmail please check https://support.google.com/accounts/answer/6010255 to allow access from less secure apps.

To send email on Linux (with sendmail package) through Gmail from localhost please check PHP+Ubuntu Send email using gmail form localhost.

Triggering change detection manually in Angular

I used accepted answer reference and would like to put an example, since Angular 2 documentation is very very hard to read, I hope this is easier:

  1. Import NgZone:

    import { Component, NgZone } from '@angular/core';
    
  2. Add it to your class constructor

    constructor(public zone: NgZone, ...args){}
    
  3. Run code with zone.run:

    this.zone.run(() => this.donations = donations)
    

Set TextView text from html-formatted string resource in XML

Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). You CAN include raw HTML in strings.xml, as long as you wrap it in

<![CDATA[ ...raw html... ]]>

Example:

<string name="nice_html">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>

Then, in your code:

TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(R.string.nice_html)));

IMHO, this is several orders of magnitude nicer to work with :-)

Converting an int to std::string

If you cannot use std::to_string from C++11, you can write it as it is defined on cppreference.com:

std::string to_string( int value ) Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%d", value) would produce for sufficiently large buf.

Implementation

#include <cstdio>
#include <string>
#include <cassert>

std::string to_string( int x ) {
  int length = snprintf( NULL, 0, "%d", x );
  assert( length >= 0 );
  char* buf = new char[length + 1];
  snprintf( buf, length + 1, "%d", x );
  std::string str( buf );
  delete[] buf;
  return str;
}

You can do more with it. Just use "%g" to convert float or double to string, use "%x" to convert int to hex representation, and so on.

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

document.getElementsByClassName returns a NodeList, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()

or if you want plain JS try :

function toggle_by_class(cls, on) {
    var lst = document.getElementsByClassName(cls);
    for(var i = 0; i < lst.length; ++i) {
        lst[i].style.display = on ? '' : 'none';
    }
}

jQuery UI Slider (setting programmatically)

In my case with jquery slider with 2 handles only following way worked.

$('#Slider').slider('option',{values: [0.15, 0.6]});

Python - Passing a function into another function

For passing both a function, and any arguments to the function:

from typing import Callable    

def looper(fn: Callable, n:int, *args, **kwargs):
    """
    Call a function `n` times

    Parameters
    ----------
    fn: Callable
        Function to be called.
    n: int
        Number of times to call `func`.
    *args
        Positional arguments to be passed to `func`.
    **kwargs
        Keyword arguments to be passed to `func`.

    Example
    -------
    >>> def foo(a:Union[float, int], b:Union[float, int]):
    ...    '''The function to pass'''
    ...    print(a+b)
    >>> looper(foo, 3, 2, b=4)
    6
    6
    6       
    """
    for i in range(n):
        fn(*args, **kwargs)

Depending on what you are doing, it could make sense to define a decorator, or perhaps use functools.partial.

How to run a hello.js file in Node.js on windows?

type node js command prompt in start screen. and use it. OR set PATH of node in environment variable.

SQL Query Where Field DOES NOT Contain $x

What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:

-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);

If you are searching a string, go for the LIKE operator (but this will be slow):

-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';

If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:

-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';

How can I insert values into a table, using a subquery with more than one result?

the sub query looks like

 insert into table_name (col1,col2,....) values (select col1,col2,... FROM table_2 ...)

hope this help

When do you use the "this" keyword?

When you are many developers working on the same code base, you need some code guidelines/rules. Where I work we've desided to use 'this' on fields, properties and events.

To me it makes good sense to do it like this, it makes the code easier to read when you differentiate between class-variables and method-variables.

Do I need to compile the header files in a C program?

You don't need to compile header files. It doesn't actually do anything, so there's no point in trying to run it. However, it is a great way to check for typos and mistakes and bugs, so it'll be easier later.

Multiple Indexes vs Multi-Column Indexes

If you have queries that will be frequently using a relatively static set of columns, creating a single covering index that includes them all will improve performance dramatically.

By putting multiple columns in your index, the optimizer will only have to access the table directly if a column is not in the index. I use these a lot in data warehousing. The downside is that doing this can cost a lot of overhead, especially if the data is very volatile.

Creating indexes on single columns is useful for lookup operations frequently found in OLTP systems.

You should ask yourself why you're indexing the columns and how they'll be used. Run some query plans and see when they are being accessed. Index tuning is as much instinct as science.

How to delete a file from SD card?

Change for Android 4.4+

Apps are not allowed to write (delete, modify ...) to external storage except to their package-specific directories.

As Android documentation states:

"Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions."

However nasty workaround exists (see code below). Tested on Samsung Galaxy S4, but this fix does't work on all devices. Also I wouldn’t count on this workaround being available in future versions of Android.

There is a great article explaining (4.4+) external storage permissions change.

You can read more about workaround here. Workaround source code is from this site.

public class MediaFileFunctions 
{
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static boolean deleteViaContentProvider(Context context, String fullname) 
    { 
      Uri uri=getFileUri(context,fullname); 

      if (uri==null) 
      {
         return false;
      }

      try 
      { 
         ContentResolver resolver=context.getContentResolver(); 

         // change type to image, otherwise nothing will be deleted 
         ContentValues contentValues = new ContentValues(); 
         int media_type = 1; 
         contentValues.put("media_type", media_type); 
         resolver.update(uri, contentValues, null, null); 

         return resolver.delete(uri, null, null) > 0; 
      } 
      catch (Throwable e) 
      { 
         return false; 
      } 
   }

   @TargetApi(Build.VERSION_CODES.HONEYCOMB)
   private static Uri getFileUri(Context context, String fullname) 
   {
      // Note: check outside this class whether the OS version is >= 11 
      Uri uri = null; 
      Cursor cursor = null; 
      ContentResolver contentResolver = null;

      try
      { 
         contentResolver=context.getContentResolver(); 
         if (contentResolver == null)
            return null;

         uri=MediaStore.Files.getContentUri("external"); 
         String[] projection = new String[2]; 
         projection[0] = "_id"; 
         projection[1] = "_data"; 
         String selection = "_data = ? ";    // this avoids SQL injection 
         String[] selectionParams = new String[1]; 
         selectionParams[0] = fullname; 
         String sortOrder = "_id"; 
         cursor=contentResolver.query(uri, projection, selection, selectionParams, sortOrder); 

         if (cursor!=null) 
         { 
            try 
            { 
               if (cursor.getCount() > 0) // file present! 
               {   
                  cursor.moveToFirst(); 
                  int dataColumn=cursor.getColumnIndex("_data"); 
                  String s = cursor.getString(dataColumn); 
                  if (!s.equals(fullname)) 
                     return null; 
                  int idColumn = cursor.getColumnIndex("_id"); 
                  long id = cursor.getLong(idColumn); 
                  uri= MediaStore.Files.getContentUri("external",id); 
               } 
               else // file isn't in the media database! 
               {   
                  ContentValues contentValues=new ContentValues(); 
                  contentValues.put("_data",fullname); 
                  uri = MediaStore.Files.getContentUri("external"); 
                  uri = contentResolver.insert(uri,contentValues); 
               } 
            } 
            catch (Throwable e) 
            { 
               uri = null; 
            }
            finally
            {
                cursor.close();
            }
         } 
      } 
      catch (Throwable e) 
      { 
         uri=null; 
      } 
      return uri; 
   } 
}

How to find the size of integer array

If array is static allocated:

size_t size = sizeof(arr) / sizeof(int);

if array is dynamic allocated(heap):

int *arr = malloc(sizeof(int) * size);

where variable size is a dimension of the arr.

Codeigniter: does $this->db->last_query(); execute a query?

For me save_queries option was turned off so,

$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;

Ref: Can't get result from $this->db->last_query(); codeigniter

Getting Checkbox Value in ASP.NET MVC 4

If you really want to use plain HTML (for whatever reason) and not the built-in HtmlHelper extensions, you can do it this way.

Instead of

<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />

try using

<input id="Remember" name="Remember" type="checkbox" value="true" @(Model.Remember ? "checked" : "") />

Checkbox inputs in HTML work so that when they're checked, they send the value, and when they're not checked, they don't send anything at all (which will cause ASP.NET MVC to fallback to the default value of the field, false). Also, the value of the checkbox in HTML can be anything not just true/false, so if you really wanted, you can even use a checkbox for a string field in your model.

If you use the built-in Html.RenderCheckbox, it actually outputs two inputs: checkbox and a hidden field so that a false value is sent when the checkbox is unchecked (not just nothing). That may cause some unexpected situations, like this:

Refresh page after form submitting

If you want the form to be submitted on the same page then remove the action from the form attributes.

<form method="POST" name="myform">
 <!-- Your HTML code Here -->
</form>

However, If you want to reload the page or redirect the page after submitting the form from another file then you call this function in php and it will redirect the page in 0 seconds. Also, You can use the header if you want to, just make sure you don't have any content before using the header

 function page_redirect($location)
 {
   echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$location.'">';
   exit; 
 }

 // I want the page to go to google.
 // page_redirect("http://www.google.com")

How to round down to nearest integer in MySQL?

Use FLOOR:

SELECT FLOOR(your_field) FROM your_table

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

Jupyter has its own PATH variable, JUPYTER_PATH.

Adding this line to the .bashrc file worked for me:

export JUPYTER_PATH=<directory_for_your_module>:$JUPYTER_PATH

MySQL select query with multiple conditions

I would use this query:

SELECT
  user_id
FROM
  wp_usermeta 
WHERE 
  (meta_key = 'first_name' AND meta_value = '$us_name') OR 
  (meta_key = 'yearofpassing' AND meta_value = '$us_yearselect') OR 
  (meta_key = 'u_city' AND meta_value = '$us_reg') OR
  (meta_key = 'us_course' AND meta_value = '$us_course')
GROUP BY
  user_id
HAVING
  COUNT(DISTINCT meta_key)=4

this will select all user_id that meets all four conditions.

How to find the mime type of a file in python?

This may be old already, but why not use UploadedFile.content_type directly from Django? Is not the same?(https://docs.djangoproject.com/en/1.11/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile.content_type)

Key Presses in Python

AutoHotKey is perfect for this kind of tasks (keyboard automation / remapping)

Script to send "A" 100 times:

Send {A 100}

That's all

EDIT: to send the keys to an specific application:

WinActivate Word
Send {A 100}

An efficient way to transpose a file in Bash

A Python solution:

python -c "import sys; print('\n'.join(' '.join(c) for c in zip(*(l.split() for l in sys.stdin.readlines() if l.strip()))))" < input > output

The above is based on the following:

import sys

for c in zip(*(l.split() for l in sys.stdin.readlines() if l.strip())):
    print(' '.join(c))

This code does assume that every line has the same number of columns (no padding is performed).

Using Bootstrap Modal window as PartialView

I use AJAX to do this. You have your partial with your typical twitter modal template html:

<div class="container">
  <!-- Modal -->
  <div class="modal fade" id="LocationNumberModal" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">
            &times;
          </button>
          <h4 class="modal-title">
            Serial Numbers
          </h4>
        </div>
        <div class="modal-body">
          <span id="test"></span>
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">
            Close
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

Then you have your controller method, I use JSON and have a custom class that rendors the view to a string. I do this so I can perform multiple ajax updates on the screen with one ajax call. Reference here: Example but you can use an PartialViewResult/ActionResult on return if you are just doing the one call. I will show it using JSON..

And the JSON Method in Controller:

public JsonResult LocationNumberModal(string partNumber = "")
{
  //Business Layer/DAL to get information
  return Json(new {
      LocationModal = ViewUtility.RenderRazorViewToString(this.ControllerContext, "LocationNumberModal.cshtml", new SomeModelObject())
    },
    JsonRequestBehavior.AllowGet
  );
}

And then, in the view using your modal: You can package the AJAX in your partial and call @{Html.RenderPartial... Or you can have a placeholder with a div:

<div id="LocationNumberModalContainer"></div>

then your ajax:

function LocationNumberModal() {
  var partNumber = "1234";

  var src = '@Url.Action("LocationNumberModal", "Home", new { area = "Part" })'
    + '?partNumber='' + partNumber; 

  $.ajax({
    type: "GET",
    url: src,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
      $("#LocationNumberModalContainer").html(data.LocationModal);
      $('#LocationNumberModal').modal('show');
    }
  });
};

Then the button to your modal:

<button type="button" id="GetLocBtn" class="btn btn-default" onclick="LocationNumberModal()">Get</button>

Partly cherry-picking a commit with Git

Actually, the best solution for this question is to use checkout commend

git checkout <branch> <path1>,<path2> ..

For example, assume you are in master, you want to the changes from dev1 on project1/Controller/WebController1.java and project1/Service/WebService1.java, you can use this:

git checkout dev1 project1/Controller/WebController1.java project1/Service/WebService1.java

That means the master branch only updates from dev1 on those two paths.

What is the difference between onBlur and onChange attribute in HTML?

onBlur is when your focus is no longer on the field in question.

The onblur property returns the onBlur event handler code, if any, that exists on the current element.

onChange is when the value of the field changes.

SQL Server after update trigger

It is very simple to do that, First create a copy of your table that your want keep the log for For example you have Table dbo.SalesOrder with columns SalesOrderId, FirstName,LastName, LastModified

Your Version archieve table should be dbo.SalesOrderVersionArchieve with columns SalesOrderVersionArhieveId, SalesOrderId, FirstName,LastName, LastModified

Here is the how you will set up a trigger on SalesOrder table

USE [YOURDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Karan Dhanu
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE TRIGGER dbo.[CreateVersionArchiveRow]
   ON  dbo.[SalesOrder]
  AFTER Update
AS 
BEGIN

    SET NOCOUNT ON;
INSERT INTO dbo.SalesOrderVersionArchive

   SELECT *
   FROM deleted;

END

Now if you make any changes in saleOrder table it will show you the change in VersionArchieve table

How to pass a value from one jsp to another jsp page?

Using Query parameter

<a href="edit.jsp?userId=${user.id}" />  

Using Hidden variable .

<form method="post" action="update.jsp">  
...  
   <input type="hidden" name="userId" value="${user.id}">  

you can send Using Session object.

   session.setAttribute("userId", userid);

These values will now be available from any jsp as long as your session is still active.

   int userid = session.getAttribute("userId"); 

How to get the seconds since epoch from the time + date output of gmtime()?

There are two ways, depending on your original timestamp:

mktime() and timegm()

http://docs.python.org/library/time.html

How to change Bootstrap's global default font size?

I just solved this type of problem. I was trying to increase

font-size to h4 size. I do not want to use h4 tag. I added my css after bootstrap.css it didn't work. The easiest way is this: On the HTML doc, type

<p class="h4">

You do not need to add anything to your css sheet. It works fine Question is suppose I want a size between h4 and h5? Answer why? Is this the only way to please your viewers? I will prefer this method to tampering with standard docs like bootstrap.

How to get the integer value of day of week

Use

day1 = (int)ClockInfoFromSystem.DayOfWeek;

Write to custom log file from a Bash script

I did it by using a filter. Most linux systems use rsyslog these days. The config files are located at /etc/rsyslog.conf and /etc/rsyslog.d.

Whenever I run the command logger -t SRI some message, I want "some message" to only show up in /var/log/sri.log.

To do this I added the file /etc/rsyslog.d/00-sri.conf with the following content.

# Filter all messages whose tag starts with SRI
# Note that 'isequal, "SRI:"' or 'isequal "SRI"' will not work.
#
:syslogtag, startswith, "SRI" /var/log/sri.log

# The stop command prevents this message from getting processed any further.
# Thus the message will not show up in /var/log/messages.
#
& stop

Then restart the rsyslogd service:

systemctl restart rsyslog.service

Here is a shell session showing the results:

[root@rpm-server html]# logger -t SRI Hello World!
[root@rpm-server html]# cat /var/log/sri.log
Jun  5 10:33:01 rpm-server SRI[11785]: Hello World!
[root@rpm-server html]#
[root@rpm-server html]# # see that nothing shows up in /var/log/messages
[root@rpm-server html]# tail -10 /var/log/messages | grep SRI
[root@rpm-server html]#

Replace substring with another substring C++

If you are sure that the required substring is present in the string, then this will replace the first occurence of "abc" to "hij"

test.replace( test.find("abc"), 3, "hij");

It will crash if you dont have "abc" in test, so use it with care.

callback to handle completion of pipe

Code snippet for piping content from web via http(s) to filesystem. As @starbeamrainbowlabs noticed event finish does job

var tmpFile = "/tmp/somefilename.doc";

var ws = fs.createWriteStream(tmpFile);
ws.on('finish', function() {
  // pipe done here, do something with file
});

var client = url.slice(0, 5) === 'https' ? https : http;
client.get(url, function(response) {
  return response.pipe(ws);
});

jQuery events .load(), .ready(), .unload()

If both "document.ready" variants are used they will both fire, in the order of appearance

$(function(){
    alert('shorthand document.ready');
});

//try changing places
$(document).ready(function(){
    alert('document.ready');
});

Executing multiple SQL queries in one statement with PHP

With mysqli you're able to use multiple statements for real using mysqli_multi_query().

Read more on multiple statements in the PHP Docs.

A SQL Query to select a string between two known strings

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

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

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

Here's the code:

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

For the above question, the usage is as follows:

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

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

We could do without any xxxFactory, xxxManager or xxxRepository classes if we modeled the real world correctly:

Universe.Instance.Galaxies["Milky Way"].SolarSystems["Sol"]
        .Planets["Earth"].Inhabitants.OfType<Human>().WorkingFor["Initech, USA"]
        .OfType<User>().CreateNew("John Doe");

;-)

How to print variables without spaces between values

It's the comma which is providing that extra white space.

One way is to use the string % method:

print 'Value is "%d"' % (value)

which is like printf in C, allowing you to incorporate and format the items after % by using format specifiers in the string itself. Another example, showing the use of multiple values:

print '%s is %3d.%d' % ('pi', 3, 14159)

For what it's worth, Python 3 greatly improves the situation by allowing you to specify the separator and terminator for a single print call:

>>> print(1,2,3,4,5)
1 2 3 4 5

>>> print(1,2,3,4,5,end='<<\n')
1 2 3 4 5<<

>>> print(1,2,3,4,5,sep=':',end='<<\n')
1:2:3:4:5<<

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

Understanding Matlab FFT example

The reason why your X-axis plots frequencies only till 500 Hz is your command statement 'f = Fs/2*linspace(0,1,NFFT/2+1);'. Your Fs is 1000. So when you divide it by 2 & then multiply by values ranging from 0 to 1, it returns a vector of length NFFT/2+1. This vector consists of equally spaced frequency values, ranging from 0 to Fs/2 (i.e. 500 Hz). Since you plot using 'plot(f,2*abs(Y(1:NFFT/2+1)))' command, your X-axis limit is 500 Hz.

Are there dictionaries in php?

No, there are no dictionaries in php. The closest thing you have is an array. However, an array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index. What do I mean by that?

$array = array(
    "foo" => "bar",
    "bar" => "foo"
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

The following line is allowed with the above array but would give an error if it was a dictionary.

print $array[0]

Python has both arrays and dictionaries.

Bootstrap: How do I identify the Bootstrap version?

An easy way to do this, without searching files or folders would be:

  • Open your web page on browser
  • press ctrl+U
  • search boostrap.min.js or boostrap.min.css, then click it (it would open source file)
  • at first line(commented) you should see boostrap version

Is it possible to implement a Python for range loop without an iterator variable?

May be answer would depend on what problem you have with using iterator? may be use

i = 100
while i:
    print i
    i-=1

or

def loop(N, doSomething):
    if not N:
        return
    print doSomething(N)
    loop(N-1, doSomething)

loop(100, lambda a:a)

but frankly i see no point in using such approaches

Array.Add vs +=

When using the $array.Add()-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.

$array += $element creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the $array-variable

You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. For example, to add an element with a value of 200 to the array in the $a variable, type:

    $a += 200

Source: about_Arrays

+= is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:

$arr = 1..3    #Array
$arr += (4..5) #Combine with another array in a single write-operation

$arr.Count
5

If that's not possible, consider using a more efficient collection like List or ArrayList (see the other answer).

Change background color of edittext in android

The simplest solution I have found is to change the background color programmatically. This does not require dealing with any 9-patch images:

((EditText) findViewById(R.id.id_nick_name)).getBackground()
    .setColorFilter(Color.<your-desi??red-color>, PorterDuff.Mode.MULTIPLY);

Source: another answer

Cannot refer to a non-final variable inside an inner class defined in a different method

use ClassName.this.variableName to reference the non-final variable

What is PHPSESSID?

PHPSESSID reveals you are using PHP. If you don't want this you can easily change the name using the session.name in your php.ini file or using the session_name() function.

Spring REST Service: how to configure to remove null objects in json response

If you are using Jackson 2, the message-converters tag is:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="prefixJson" value="true"/>
            <property name="supportedMediaTypes" value="application/json"/>
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <property name="serializationInclusion" value="NON_NULL"/>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

Android changing Floating Action Button color

The document suggests that it takes the @color/accent by default. But we can override it on code by using

fab.setBackgroundTintList(ColorStateList)

Also remember,

The minimum API version to use this library is 15 so you need to update it! if you dont want to do it then you need to define a custom drawable and decorate it!

How do I find the maximum of 2 numbers?

Use the builtin function max.

Example: max(2, 4) returns 4.

Just for giggles, there's a min as well...should you need it. :P

Height of an HTML select box (dropdown)

The Chi Row answer is a good option for the problem, but I've found an error i the onclick arguments. Instead, would be:

<select size="1" position="absolute" onclick="size=(size!=1)?1:n;" ...>

(And mention you must replace the "n" with the number of lines you need)

Android java.lang.NoClassDefFoundError

Imaage

Go to Order and export from project properties and make sure you're including the required jars in the export, this did it for me

How to diff one file to an arbitrary version in Git?

git diff master~20 -- pom.xml

Works if you are not in master branch too.

urllib2.HTTPError: HTTP Error 403: Forbidden

import urllib.request

bank_pdf_list = ["https://www.hdfcbank.com/content/bbp/repositories/723fb80a-2dde-42a3-9793-7ae1be57c87f/?path=/Personal/Home/content/rates.pdf",
"https://www.yesbank.in/pdf/forexcardratesenglish_pdf",
"https://www.sbi.co.in/documents/16012/1400784/FOREX_CARD_RATES.pdf"]


def get_pdf(url):
    user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
    
    #url = "https://www.yesbank.in/pdf/forexcardratesenglish_pdf"
    headers={'User-Agent':user_agent,} 
    
    request=urllib.request.Request(url,None,headers) #The assembled request
    response = urllib.request.urlopen(request)
    #print(response.text)
    data = response.read()
#    print(type(data))
    
    name = url.split("www.")[-1].split("//")[-1].split(".")[0]+"_FOREX_CARD_RATES.pdf"
    f = open(name, 'wb')
    f.write(data)
    f.close()
    

for bank_url in bank_pdf_list:
    try: 
        get_pdf(bank_url)
    except:
        pass

Golang read request body

Inspecting and mocking request body

When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.

One option is to read the whole body using ioutil.ReadAll(), which gives you the body as a byte slice.

You may use bytes.NewBuffer() to obtain an io.Reader from a byte slice.

The last missing piece is to make the io.Reader an io.ReadCloser, because bytes.Buffer does not have a Close() method. For this you may use ioutil.NopCloser() which wraps an io.Reader, and returns an io.ReadCloser, whose added Close() method will be a no-op (does nothing).

Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.

Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!

Inspecting / modifying response body

If you also want to read the response body, then you have to wrap the http.ResponseWriter you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).

Here's a simple ResponseWriter wrapper, which just caches the data, so it'll be available after the subsequent handler returns:

type MyResponseWriter struct {
    http.ResponseWriter
    buf *bytes.Buffer
}

func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
    return mrw.buf.Write(p)
}

Note that MyResponseWriter.Write() just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write() method) and write the data immediately to the wrapped / embedded ResponseWriter. You may even modify the data. You have full control.

Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.

Full example

Putting the pieces together, here's a full working example:

func loginmw(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            log.Printf("Error reading body: %v", err)
            http.Error(w, "can't read body", http.StatusBadRequest)
            return
        }

        // Work / inspect body. You may even modify it!

        // And now set a new body, which will simulate the same data we read:
        r.Body = ioutil.NopCloser(bytes.NewBuffer(body))

        // Create a response wrapper:
        mrw := &MyResponseWriter{
            ResponseWriter: w,
            buf:            &bytes.Buffer{},
        }

        // Call next handler, passing the response wrapper:
        handler.ServeHTTP(mrw, r)

        // Now inspect response, and finally send it out:
        // (You can also modify it before sending it out!)
        if _, err := io.Copy(w, mrw.buf); err != nil {
            log.Printf("Failed to send out response: %v", err)
        }
    })
}

SQL MERGE statement to update data

Update energydata set energydata.kWh = temp.kWh 
where energydata.webmeterID = (select webmeterID from temp_energydata as temp) 

How to exclude a directory in find . command

#find command in linux
def : find command used to locate /search files in unix /linux system ,
      find  search for files in a directory hierarchy
1)exec   Show diagnostic information relating to -exec, -execdir, -ok and -okdir
2)-options
  -H =do not follow symoblic links while except while procesing .
  -L = follow symbolic links
  -P =never follow symbolic links

  -type c
             File is of type c:

             b      block (buffered) special

             c      character (unbuffered) special

             d      directory

             p      named pipe (FIFO)

             f      regular file

             l      symbolic  link;  this  is  never true if the -L option or the -follow option is in effect, unless the
                    symbolic link is broken.  If you want to search for symbolic links when -L is in effect, use -xtype.

             s      socket

             D      door (Solaris)

    -Delete
    Delete files; true if removal succeeded.  If the removal failed, an error message  is  issued.
    If  -delete
    #fails, find's exit status will be nonzero (when it eventually exits).


find /home/mohan/a -mindepth 3 -maxdepth 3 -type f -name "*.txt" |xargs rm -rf
find -type d -name
find -type f -Name
find /path/ -type f -iname (i is case insenstive)

#find directores a/b/c and only delete c directory inside have "*.txt "
find /home/mohan/a -mindepth 3 -maxdepth 3 -type f -name "*.txt" |xargs rm -rf
find /home/mohan/a -mindepth 3 -maxdepath 3 -type f -name "*.txt" -delete


#delete particular directory have empty file and only  we can delete empty files
find /home/mohan -type f -name "*.txt" -empty -DELETE


#find multiple files and also find empty files
find /home/mohan -type f \( -name "*.sh" -o  -name "*.txt" \) -empty

#delete empty files two or more Files
find /home/mohan -type f \( -nmae "*.sh" -o -name "*.txt" \) -empty -delete


#How to append contents of multiple files into one file
find . -type f -name '*.txt' -exec cat {} + >> output.file

#last modified files finding using less than 1 min (-n)
ls -lrth|find . -type f -mmin -1

#last modified files more than 1 min (+n)
ls -lrth|find . -type f -mmin +1


#last modified files exactly one mins
find . -type f -mmin 1

last modifiedfiles exactly in one day by using command (-mtime)
find . -type f -mtime 10

#last modified more than 10 days
find . -type  f -mtime +10

#last modified less than 10 days
find . -type f -mtime -10

#How to Find Modified Files and Folders Starting from a Given Date to the Latest Date
find . -type f  -newermt "17-11-2020"

#How to Find a List of “sh” Extension Files Accessed in the Last 30 Days--- -matdimtype
ls -lrt|find . -type f -iname ".sh" -atime -30

#How to Find a List of Files Created Today, -1 means less than min,
ls -lrt | find . -type f -ctime -1 -ls

Searching a list of objects in Python

Consider using a dictionary:

myDict = {}

for i in range(20):
    myDict[i] = i * i

print(5 in myDict)

Webpack - webpack-dev-server: command not found

I found the accepted answer does not work in all scenarios. To ensure it 100% works one must ALSO clear the npm cache. Either directly Goto the cache and clear locks, caches, anonymous-cli-metrics.json; or one can try npm cache clean.

Since the author had cleared the cache before trying the recommended solution its possible that failed to make it part of the pre-requisites.

Init array of structs in Go

It looks like you are trying to use (almost) straight up C code here. Go has a few differences.

  • First off, you can't initialize arrays and slices as const. The term const has a different meaning in Go, as it does in C. The list should be defined as var instead.
  • Secondly, as a style rule, Go prefers basenameOpts as opposed to basename_opts.
  • There is no char type in Go. You probably want byte (or rune if you intend to allow unicode codepoints).
  • The declaration of the list must have the assignment operator in this case. E.g.: var x = foo.
  • Go's parser requires that each element in a list declaration ends with a comma. This includes the last element. The reason for this is because Go automatically inserts semi-colons where needed. And this requires somewhat stricter syntax in order to work.

For example:

type opt struct {
    shortnm      byte
    longnm, help string
    needArg      bool
}

var basenameOpts = []opt { 
    opt {
        shortnm: 'a', 
        longnm: "multiple", 
        needArg: false, 
        help: "Usage for a",
    },
    opt {
        shortnm: 'b', 
        longnm: "b-option", 
        needArg: false, 
        help: "Usage for b",
    },
}

An alternative is to declare the list with its type and then use an init function to fill it up. This is mostly useful if you intend to use values returned by functions in the data structure. init functions are run when the program is being initialized and are guaranteed to finish before main is executed. You can have multiple init functions in a package, or even in the same source file.

    type opt struct {
        shortnm      byte
        longnm, help string
        needArg      bool
    }

    var basenameOpts []opt

    func init() { 
        basenameOpts = []opt{
            opt {
                shortnm: 'a', 
                longnm: "multiple", 
                needArg: false, 
                help: "Usage for a",
            },
            opt {
                shortnm: 'b', 
                longnm: "b-option", 
                needArg: false, 
               help: "Usage for b",
            },
        }
    }

Since you are new to Go, I strongly recommend reading through the language specification. It is pretty short and very clearly written. It will clear a lot of these little idiosyncrasies up for you.

How do I see if Wi-Fi is connected on Android?

Try out this method.

public boolean isInternetConnected() {
    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    boolean ret = true;
    if (conMgr != null) {
        NetworkInfo i = conMgr.getActiveNetworkInfo();

        if (i != null) {
            if (!i.isConnected()) {
                ret = false;
            }

            if (!i.isAvailable()) {
                ret = false;
            }
        }

        if (i == null)
            ret = false;
    } else
        ret = false;
    return ret;
}

This method will help to find internet connection available or not.

Stopping an Android app from console

I tried all answers here on Linux nothing worked for debugging on unrooted device API Level 23, so i found an Alternative for debugging From Developer Options -> Apps section -> check Do Not keep activities that way when ever you put the app in background it gets killed

P.S remember to uncheck it after you finished debugging

What does set -e mean in a bash script?

set -e stops the execution of a script if a command or pipeline has an error - which is the opposite of the default shell behaviour, which is to ignore errors in scripts. Type help set in a terminal to see the documentation for this built-in command.

Yarn install command error No such file or directory: 'install'

I had the same issue on Ubuntu 18.04. This was what worked for me:

I removed cmdtest and yarn

sudo apt remove cmdtest

sudo apt remove yarn

Install yarn globally using npm

sudo npm install -g yarn

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

Preferred way to create a Scala list

And for simple cases:

val list = List(1,2,3) 

:)

jquery fill dropdown with json data

In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)

    <script>

        $(document).ready(function(){

            GetData('DLState',data,'stateid','statename');
        });

        var data = [{"stateid" : "1","statename" : "Mumbai"},
                    {"stateid" : "2","statename" : "Panjab"},
                    {"stateid" : "3","statename" : "Pune"},
                     {"stateid" : "4","statename" : "Nagpur"},
                     {"stateid" : "5","statename" : "kanpur"}];

        var Did=document.getElementById("DLState");

        function GetData(Did,data,valkey,textkey){
          var str= "";
          for (var i = 0; i <data.length ; i++){

            console.log(data);


            str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";

          }
          $("#"+Did).append(str);
        };    </script>

</head>
<body>
  <select id="DLState">
  </select>
</body>
</html>

Regex for Mobile Number Validation

Satisfies all your requirements if you use the trick told below

Regex: /^(\+\d{1,3}[- ]?)?\d{10}$/

  1. ^ start of line
  2. A + followed by \d+ followed by a or - which are optional.
  3. Whole point two is optional.
  4. Negative lookahead to make sure 0s do not follow.
  5. Match \d+ 10 times.
  6. Line end.

DEMO Added multiline flag in demo to check for all cases

P.S. You really need to specify which language you use so as to use an if condition something like below:

// true if above regex is satisfied and (&&) it does not (`!`) match `0`s `5` or more times

if(number.match(/^(\+\d{1,3}[- ]?)?\d{10}$/) && ! (number.match(/0{5,}/)) )

What is the Java equivalent for LINQ?

I tried guava-libraries from google. It has a FluentIterable which I think is close to LINQ. Also see FunctionalExplained.

List<String> parts = new ArrayList<String>();  // add parts to the collection.    
FluentIterable<Integer> partsStartingA = 
    FluentIterable.from(parts).filter(new Predicate<String>() {
        @Override
        public boolean apply(final String input) {
            return input.startsWith("a");
        }
    }).transform(new Function<String, Integer>() {
        @Override
        public Integer apply(final String input) {
            return input.length();
        }
    });

Seems to be an extensive library for Java. Certainly not as succinct as LINQ but looks interesting.

How to list all Git tags?

Listing the available tags in Git is straightforward. Just type git tag (with optional -l or --list).

$ git tag
v5.5
v6.5

You can also search for tags that match a particular pattern.

$ git tag -l "v1.8.5*"
v1.8.5
v1.8.5-rc0
v1.8.5-rc1
v1.8.5-rc2

Getting latest tag on git repository

The command finds the most recent tag that is reachable from a commit. If the tag points to the commit, then only the tag is shown. Otherwise, it suffixes the tag name with the number of additional commits on top of the tagged object and the abbreviated object name of the most recent commit.

git describe

With --abbrev set to 0, the command can be used to find the closest tagname without any suffix:

git describe --abbrev=0

Other examples:

git describe --abbrev=0 --tags # gets tag from current branch
git describe --tags `git rev-list --tags --max-count=1` // gets tags across all branches, not just the current branch

How to prune local git tags that don't exist on remote

To put it simple, if you are trying to do something like git fetch -p -t, it will not work starting with git version 1.9.4.

However, there is a simple workaround that still works in latest versions:

git tag -l | xargs git tag -d  // remove all local tags
git fetch -t                   // fetch remote tags

dyld: Library not loaded: @rpath/libswiftCore.dylib

There are lot's of answers there but might be my answer will help some one.

I am having same issue, My app works fine on Simulator but on Device got crashed as I Lunches app and gives error as above. I have tried all answers and solutions . In My Case , My Project I am having multiple targets .I have created duplicate target B from target A. Target B works fine while target A got crashed. I am using different Image assets for each target. After searching and doing google I have found something which might help to someone.

App stop crashing when I change name of Launch images assets for both apps . e.g Target A Launch Image asset name LaunchImage A . Target B Lunch Image asset name LaunchImage B and assigned properly in General Tab of each target . My Apps works fine.

Converting int to string in C

char string[something];
sprintf(string, "%d", 42);

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

This worked for me. Might want to try editing virtual machine settings:

Click on Edit virtual machine settings

Switch to Always Enabled in Options, Shared Folders

MySQL foreign key constraints, cascade delete

I think (I'm not certain) that foreign key constraints won't do precisely what you want given your table design. Perhaps the best thing to do is to define a stored procedure that will delete a category the way you want, and then call that procedure whenever you want to delete a category.

CREATE PROCEDURE `DeleteCategory` (IN category_ID INT)
LANGUAGE SQL
NOT DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY DEFINER
BEGIN

DELETE FROM
    `products`
WHERE
    `id` IN (
        SELECT `products_id`
        FROM `categories_products`
        WHERE `categories_id` = category_ID
    )
;

DELETE FROM `categories`
WHERE `id` = category_ID;

END

You also need to add the following foreign key constraints to the linking table:

ALTER TABLE `categories_products` ADD
    CONSTRAINT `Constr_categoriesproducts_categories_fk`
    FOREIGN KEY `categories_fk` (`categories_id`) REFERENCES `categories` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT `Constr_categoriesproducts_products_fk`
    FOREIGN KEY `products_fk` (`products_id`) REFERENCES `products` (`id`)
    ON DELETE CASCADE ON UPDATE CASCADE

The CONSTRAINT clause can, of course, also appear in the CREATE TABLE statement.

Having created these schema objects, you can delete a category and get the behaviour you want by issuing CALL DeleteCategory(category_ID) (where category_ID is the category to be deleted), and it will behave how you want. But don't issue a normal DELETE FROM query, unless you want more standard behaviour (i.e. delete from the linking table only, and leave the products table alone).

Android "elevation" not showing a shadow

If you have a view with no background this line will help you

android:outlineProvider="bounds"

If you have a view with background this line will help you

android:outlineProvider="paddedBounds"

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

To refine the answer from Zed, and to answer your comment:

INSERT INTO dues_storage
SELECT d.*, CURRENT_DATE()
FROM dues d
WHERE id = 5;

See T.J. Crowder's comment

How to get std::vector pointer to the raw data?

Take a pointer to the first element instead:

process_data (&something [0]);

.trim() in JavaScript not working in IE

This issue can be caused by IE using compatibility mode on intranet sites. There are two ways to resolve this, you can either update IE to not use compatibility mode on your local machine (in IE11: Tools-> Compatibility View Settings -> Uncheck Display intranet sites in Compatibility View)

Better yet you can update the meta tags in your webpage. Add in:

...
<head>
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
...

What does this mean? It is telling IE to use the latest compatibility mode. More information is available in MSDN: Specifying legacy document modes

What is the difference between IQueryable<T> and IEnumerable<T>?

IQueryable is faster than IEnumerable if we are dealing with huge amounts of data from database because,IQueryable gets only required data from database where as IEnumerable gets all the data regardless of the necessity from the database

Entity Framework : How do you refresh the model when the db changes?

Are you looking at the designer or code view? You can force the designer to open by right clicking on your EDMX file and selecting Open With -> ADO.NET Entity Data Model Designer

Right click on the designer surface of the EDMX designer and click Update Model From Database...

All entities are refreshed by default, new entities are only added if you select them.


EDIT: If it is not refreshing well.

  • Select all the tables and view-s in the EDMX designer.
  • Delete them.
  • Then, update model from database

Access HTTP response as string in Go

The method you're using to read the http body response returns a byte slice:

func ReadAll(r io.Reader) ([]byte, error)

official documentation

You can convert []byte to a string by using

body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

According to the HTML standard, the content model of the HTML element is:

A head element followed by a body element.

You can either define the BODY element in the source code:

<html>
    <body>
        ... web-page ...
    </body>
</html>

or you can omit the BODY element:

<html>
    ... web-page ...
</html>

However, it is invalid to place the BODY element inside the web-page content (in-between other elements or text content), like so:

<html>
    ... content ...
    <body>
        ... content ...
    </body>
    ... content ...
</html>

how to hide keyboard after typing in EditText in android?

editText.setInputType(InputType.TYPE_NULL);

What is the difference between Jupyter Notebook and JupyterLab?

This answer shows the python perspective. Jupyter supports various languages besides python.

Both Jupyter Notebook and Jupyterlab are browser compatible interactive python (i.e. python ".ipynb" files) environments, where you can divide the various portions of the code into various individually executable cells for the sake of better readability. Both of these are popular in Data Science/Scientific Computing domain.

I'd suggest you to go with Jupyterlab for the advantages over Jupyter notebooks:

  1. In Jupyterlab, you can create ".py" files, ".ipynb" files, open terminal etc. Jupyter Notebook allows ".ipynb" files while providing you the choice to choose "python 2" or "python 3".
  2. Jupyterlab can open multiple ".ipynb" files inside a single browser tab. Whereas, Jupyter Notebook will create new tab to open new ".ipynb" files every time. Hovering between various tabs of browser is tedious, thus Jupyterlab is more helpful here.

I'd recommend using PIP to install Jupyterlab.

If you can't open a ".ipynb" file using Jupyterlab on Windows system, here are the steps:

  1. Go to the file --> Right click --> Open With --> Choose another app --> More Apps --> Look for another apps on this PC --> Click.
  2. This will open a file explorer window. Now go inside your Python installation folder. You should see Scripts folder. Go inside it.
  3. Once you find jupyter-lab.exe, select that and now it will open the .ipynb files by default on your PC.

How to write a confusion matrix in Python?

This function creates confusion matrices for any number of classes.

def create_conf_matrix(expected, predicted, n_classes):
    m = [[0] * n_classes for i in range(n_classes)]
    for pred, exp in zip(predicted, expected):
        m[pred][exp] += 1
    return m

def calc_accuracy(conf_matrix):
    t = sum(sum(l) for l in conf_matrix)
    return sum(conf_matrix[i][i] for i in range(len(conf_matrix))) / t

In contrast to your function above, you have to extract the predicted classes before calling the function, based on your classification results, i.e. sth. like

[1 if p < .5 else 2 for p in classifications]

CSS: On hover show and hide different div's at the same time?

http://jsfiddle.net/MBLZx/

Here is the code

_x000D_
_x000D_
 .showme{ _x000D_
   display: none;_x000D_
 }_x000D_
 .showhim:hover .showme{_x000D_
   display : block;_x000D_
 }_x000D_
 .showhim:hover .ok{_x000D_
   display : none;_x000D_
 }
_x000D_
 <div class="showhim">_x000D_
     HOVER ME_x000D_
     <div class="showme">hai</div>_x000D_
     <div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

How to check if a string contains only numbers?

You may just remove all spaces and leverage LINQ All:

Determines whether all elements of a sequence satisfy a condition.

Use it as shown below:

Dim number As String = "077 234 211"
If number.Replace(" ", "").All(AddressOf Char.IsDigit) Then
    Console.WriteLine("The string is all numeric (spaces ignored)!")
Else
    Console.WriteLine("The string contains a char that is not numeric and space!")
End If

To only check if a string consists of only digits use:

If number.All(AddressOf Char.IsDigit) Then

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

For angular-cli and webpack users I suspected that there is some issue while importing the fonts in css file , so please also provide url location encoded with single quotes as following -

@font-face {
font-family: 'some_family';
src: url('./assets/fonts/folder/some_family-regular-webfont.woff2') format('woff2'),
     url('./assets/fonts/folder/some_family-regular-webfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}

This post might be old , but this is the solution which worked for me .

How to convert an Image to base64 string in java?

The problem is that you are returning the toString() of the call to Base64.encodeBase64(bytes) which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.

Instead, you should do:

encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");

Run bash command on jenkins pipeline

According to this document, you should be able to do it like so:

node {
    sh "#!/bin/bash \n" + 
       "echo \"Hello from \$SHELL\""
}

How can I create a simple message box in Python?

In Windows, you can use ctypes with user32 library:

from ctypes import c_int, WINFUNCTYPE, windll
from ctypes.wintypes import HWND, LPCSTR, UINT
prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)

MessageBox()
MessageBox(text="Spam, spam, spam")
MessageBox(flags=2, text="foo bar")

jQuery .each() index?

$('#list option').each(function(index){
  //do stuff
  console.log(index);
});

logs the index :)

a more detailed example is below.

_x000D_
_x000D_
function run_each() {_x000D_
_x000D_
  var $results = $(".results");_x000D_
_x000D_
  $results.empty();_x000D_
_x000D_
  $results.append("==================== START 1st each ====================");_x000D_
  console.log("==================== START 1st each ====================");_x000D_
_x000D_
  $('#my_select option').each(function(index, value) {_x000D_
    $results.append("<br>");_x000D_
    // log the index_x000D_
    $results.append("index: " + index);_x000D_
    $results.append("<br>");_x000D_
    console.log("index: " + index);_x000D_
    // logs the element_x000D_
    // $results.append(value);  this would actually remove the element_x000D_
    $results.append("<br>");_x000D_
    console.log(value);_x000D_
    // logs element property_x000D_
    $results.append(value.innerHTML);_x000D_
    $results.append("<br>");_x000D_
    console.log(value.innerHTML);_x000D_
    // logs element property_x000D_
    $results.append(this.text);_x000D_
    $results.append("<br>");_x000D_
    console.log(this.text);_x000D_
    // jquery_x000D_
    $results.append($(this).text());_x000D_
    $results.append("<br>");_x000D_
    console.log($(this).text());_x000D_
_x000D_
    // BEGIN just to see what would happen if nesting an .each within an .each_x000D_
    $('p').each(function(index) {_x000D_
      $results.append("==================== nested each");_x000D_
      $results.append("<br>");_x000D_
      $results.append("nested each index: " + index);_x000D_
      $results.append("<br>");_x000D_
      console.log(index);_x000D_
    });_x000D_
    // END just to see what would happen if nesting an .each within an .each_x000D_
_x000D_
  });_x000D_
_x000D_
  $results.append("<br>");_x000D_
  $results.append("==================== START 2nd each ====================");_x000D_
  console.log("");_x000D_
  console.log("==================== START 2nd each ====================");_x000D_
_x000D_
_x000D_
  $('ul li').each(function(index, value) {_x000D_
    $results.append("<br>");_x000D_
    // log the index_x000D_
    $results.append("index: " + index);_x000D_
    $results.append("<br>");_x000D_
    console.log(index);_x000D_
    // logs the element_x000D_
    // $results.append(value); this would actually remove the element_x000D_
    $results.append("<br>");_x000D_
    console.log(value);_x000D_
    // logs element property_x000D_
    $results.append(value.innerHTML);_x000D_
    $results.append("<br>");_x000D_
    console.log(value.innerHTML);_x000D_
    // logs element property_x000D_
    $results.append(this.innerHTML);_x000D_
    $results.append("<br>");_x000D_
    console.log(this.innerHTML);_x000D_
    // jquery_x000D_
    $results.append($(this).text());_x000D_
    $results.append("<br>");_x000D_
    console.log($(this).text());_x000D_
  });_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
$(document).on("click", ".clicker", function() {_x000D_
_x000D_
  run_each();_x000D_
_x000D_
});
_x000D_
.results {_x000D_
  background: #000;_x000D_
  height: 150px;_x000D_
  overflow: auto;_x000D_
  color: lime;_x000D_
  font-family: arial;_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.one,_x000D_
.two,_x000D_
.three {_x000D_
  width: 33.3%;_x000D_
}_x000D_
_x000D_
.one {_x000D_
  background: yellow;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.two {_x000D_
  background: pink;_x000D_
}_x000D_
_x000D_
.three {_x000D_
  background: darkgray;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
  <div class="one">_x000D_
    <select id="my_select">_x000D_
      <option>apple</option>_x000D_
      <option>orange</option>_x000D_
      <option>pear</option>_x000D_
    </select>_x000D_
  </div>_x000D_
_x000D_
  <div class="two">_x000D_
    <ul id="my_list">_x000D_
      <li>canada</li>_x000D_
      <li>america</li>_x000D_
      <li>france</li>_x000D_
    </ul>_x000D_
  </div>_x000D_
_x000D_
  <div class="three">_x000D_
    <p>do</p>_x000D_
    <p>re</p>_x000D_
    <p>me</p>_x000D_
  </div>_x000D_
_x000D_
</div>_x000D_
_x000D_
<button class="clicker">run_each()</button>_x000D_
_x000D_
_x000D_
<div class="results">_x000D_
_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Use of Greater Than Symbol in XML

CDATA is a better general solution.

Load HTML file into WebView

In this case, using WebView#loadDataWithBaseUrl() is better than WebView#loadUrl()!

webView.loadDataWithBaseURL(url, 
        data,
        "text/html",
        "utf-8",
        null);

url: url/path String pointing to the directory all your JavaScript files and html links have their origin. If null, it's about:blank. data: String containing your hmtl file, read with BufferedReader for example

More info: WebView.loadDataWithBaseURL(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)

NumPy first and last element from array

How about this?

>>> import numpy
>>> test1 = numpy.array([1,23,4,6,7,8])
>>> forward = iter(test1)
>>> backward = reversed(test1)
>>> for a in range((len(test1)+1)//2):
...     print forward.next(), backward.next()
... 
1 8
23 7
4 6

The (len(test1)+1)//2 ensures that the middle element of odd length arrays is also returned:

>>> test1 = numpy.array([1,23,4,9,6,7,8]) # additional element '9' in the middle
>>> forward = iter(test1)                                                      
>>> backward = reversed(test1)
>>> for a in range((len(test1)+1)//2):
...     print forward.next(), backward.next()
1 8
23 7
4 6
9 9

Using just len(test1)//2 will drop the middle elemen of odd length arrays.

Fatal error: Cannot use object of type stdClass as array in

if you really want an array instead you can use:

$getvidids->result_array()

which would return the same information as an associative array.

Syntax error on print with Python 3

It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.

print('Hello world!')

Show hide div using codebehind

Hiding on the Client Side with javascript

Using plain old javascript, you can easily hide the same element in this manner:

var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";

Then to show again:

myDivElem.style.display = "";

jQuery makes hiding elements a little simpler if you prefer to use jQuery:

var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();

... and to show:

myDiv.show();

How to return a string from a C++ function?

You never give any value to your strings in main so they are empty, and thus obviously the function returns an empty string.

Replace:

string str1, str2, str3;

with:

string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";

Also, you have several problems in your replaceSubstring function:

int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
  • std::string::find returns a std::string::size_type (aka. size_t) not an int. Two differences: size_t is unsigned, and it's not necessarily the same size as an int depending on your platform (eg. on 64 bits Linux or Windows size_t is unsigned 64 bits while int is signed 32 bits).
  • What happens if s2 is not part of s1? I'll leave it up to you to find how to fix that. Hint: std::string::npos ;)

__init__() missing 1 required positional argument

Your constructor is expecting one parameter (data). You're not passing it in the call. I guess you wanted to initialise a field in the object. That would look like this:

class DHT:
    def __init__(self):
        self.data = {}
        self.data['one'] = '1'
        self.data['two'] = '2'
        self.data['three'] = '3'
    def showData(self):
        print(self.data)

if __name__ == '__main__':
    DHT().showData()

Or even just:

class DHT:
    def __init__(self):
        self.data = {'one': '1', 'two': '2', 'three': '3'}
    def showData(self):
        print(self.data)

Return JSON for ResponseEntity<String>

public ResponseEntity<?> ApiCall(@PathVariable(name = "id") long id) {
    JSONObject resp = new JSONObject();
    resp.put("status", 0);
    resp.put("id", id);

    return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use the below code on your string and you will get the complete string without html part.

string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;",string.Empty);            
        string s = Regex.Replace(title, "<.*?>", String.Empty);

Why do you use typedef when declaring an enum in C++?

The actual answer to the "why" question (which is surprisingly ignored by the existing answers top this old question) is that this enum declaration is probably located in a header file that is intended to be cross-compilable as both C and C++ code (i.e. included into both C and C++ implementation fiules). The art of writing such header files relies on the author's ability to select language features that have the proper compatible meaning in both languages.

When do I use the PHP constant "PHP_EOL"?

No, PHP_EOL does not handle endline issues, because the system where you use that constant is not the same system where you send the output to.

I would not recommend using PHP_EOL at all. Unix/Linux use \n, MacOS / OS X changed from \r to \n too and on Windows many applications (especially browsers) can display it correctly too. On Windows, it is also easy change existing client-side code to use \n only and still maintain backward-compatibility: Just change the delimiter for line trimming from \r\n to \n and wrap it in a trim() like function.

Java Reflection: How to get the name of a variable?

You can do like this:

Field[] fields = YourClass.class.getDeclaredFields();
//gives no of fields
System.out.println(fields.length);         
for (Field field : fields) {
    //gives the names of the fields
    System.out.println(field.getName());   
}

How, in general, does Node.js handle 10,000 concurrent requests?

I understand that Node.js uses a single-thread and an event loop to process requests only processing one at a time (which is non-blocking).

I could be misunderstanding what you've said here, but "one at a time" sounds like you may not be fully understanding the event-based architecture.

In a "conventional" (non event-driven) application architecture, the process spends a lot of time sitting around waiting for something to happen. In an event-based architecture such as Node.js the process doesn't just wait, it can get on with other work.

For example: you get a connection from a client, you accept it, you read the request headers (in the case of http), then you start to act on the request. You might read the request body, you will generally end up sending some data back to the client (this is a deliberate simplification of the procedure, just to demonstrate the point).

At each of these stages, most of the time is spent waiting for some data to arrive from the other end - the actual time spent processing in the main JS thread is usually fairly minimal.

When the state of an I/O object (such as a network connection) changes such that it needs processing (e.g. data is received on a socket, a socket becomes writable, etc) the main Node.js JS thread is woken with a list of items needing to be processed.

It finds the relevant data structure and emits some event on that structure which causes callbacks to be run, which process the incoming data, or write more data to a socket, etc. Once all of the I/O objects in need of processing have been processed, the main Node.js JS thread will wait again until it's told that more data is available (or some other operation has completed or timed out).

The next time that it is woken, it could well be due to a different I/O object needing to be processed - for example a different network connection. Each time, the relevant callbacks are run and then it goes back to sleep waiting for something else to happen.

The important point is that the processing of different requests is interleaved, it doesn't process one request from start to end and then move onto the next.

To my mind, the main advantage of this is that a slow request (e.g. you're trying to send 1MB of response data to a mobile phone device over a 2G data connection, or you're doing a really slow database query) won't block faster ones.

In a conventional multi-threaded web server, you will typically have a thread for each request being handled, and it will process ONLY that request until it's finished. What happens if you have a lot of slow requests? You end up with a lot of your threads hanging around processing these requests, and other requests (which might be very simple requests that could be handled very quickly) get queued behind them.

There are plenty of others event-based systems apart from Node.js, and they tend to have similar advantages and disadvantages compared with the conventional model.

I wouldn't claim that event-based systems are faster in every situation or with every workload - they tend to work well for I/O-bound workloads, not so well for CPU-bound ones.

Add item to Listview control

  • Very Simple

    private void button1_Click(object sender, EventArgs e)
    {
        ListViewItem item = new ListViewItem();
        item.SubItems.Add(textBox2.Text);
        item.SubItems.Add(textBox3.Text);
        item.SubItems.Add(textBox4.Text);
        listView1.Items.Add(item);
        textBox2.Clear();
        textBox3.Clear();
        textBox4.Clear();
    }
    
  • You can also Do this stuff...

        ListViewItem item = new ListViewItem();
        item.SubItems.Add("Santosh");
        item.SubItems.Add("26");
        item.SubItems.Add("India");
    

java Compare two dates

Try using this Function.It Will help You:-

public class Main {   
public static void main(String args[]) 
 {        
  Date today=new Date();                     
  Date myDate=new Date(today.getYear(),today.getMonth()-1,today.getDay());
  System.out.println("My Date is"+myDate);    
  System.out.println("Today Date is"+today);
  if(today.compareTo(myDate)<0)
     System.out.println("Today Date is Lesser than my Date");
  else if(today.compareTo(myDate)>0)
     System.out.println("Today Date is Greater than my date"); 
  else
     System.out.println("Both Dates are equal");      
  }
}

How to normalize an array in NumPy to a unit vector?

If you don't need utmost precision, your function can be reduced to:

v_norm = v / (np.linalg.norm(v) + 1e-16)

Python OpenCV2 (cv2) wrapper to get image size?

I'm afraid there is no "better" way to get this size, however it's not that much pain.

Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size:

import numpy as np
import cv2

# ...

def cv_size(img):
    return tuple(img.shape[1::-1])

If you're on a terminal / ipython, you can also express it with a lambda:

>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)

Writing functions with def is not fun while working interactively.

Edit

Originally I thought that using [:2] was OK, but the numpy shape is (height, width[, depth]), and we need (width, height), as e.g. cv2.resize expects, so - we must use [1::-1]. Even less memorable than [:2]. And who remembers reverse slicing anyway?

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

Good ways to sort a queryset? - Django

I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by method accepts multiple arguments, you could easily chain them:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):

>>> auths = Author.objects.order_by('-score')[:5]
>>> for x in auths: print x
... 
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name:

>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
... 
Benjamin Harrison (467)
James Monroe (487)
Gerald Rudolph (464)
Ulysses Simpson (474)
Harry Truman (471)

And now the combined order_by call:

>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
>>> for x in myauths: print x
... 
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

As you can see it is the same result as the first one, meaning it doesn't work as you would expect.

Chart.js v2 hide dataset labels

It's just as simple as adding this: legend: { display: false, }

// Or if you want you could use this other option which should also work:

Chart.defaults.global.legend.display = false;

Where should I put the CSS and Javascript code in an HTML webpage?

You should put it in the <head>. I typically put style references above JS and I order my JS from top to bottom if some of them are dependent on others, but I beleive all of the references are loaded before the page is rendered.

Get time of specific timezone

This is Correct way to get ##

function getTime(offset)
        {
            var d = new Date();
            localTime = d.getTime();
            localOffset = d.getTimezoneOffset() * 60000;

            // obtain UTC time in msec
            utc = localTime + localOffset;
            // create new Date object for different city
            // using supplied offset
            var nd = new Date(utc + (3600000*offset));
            //nd = 3600000 + nd;
            utc = new Date(utc);
            // return time as a string
            $("#local").html(nd.toLocaleString());
            $("#utc").html(utc.toLocaleString());
        }

Subtract two variables in Bash

Alternatively to the suggested 3 methods you can try let which carries out arithmetic operations on variables as follows:

let COUNT=$FIRSTV-$SECONDV

or

let COUNT=FIRSTV-SECONDV

ASP.NET - How to write some html in the page? With Response.Write?

If you really don't want to use any server controls, you should put the Response.Write in the place you want the string to be written:

<body>
<% Response.Write(stringVariable); %>
</body>

A shorthand for this syntax is:

<body>
<%= stringVariable %>
</body>

Unit testing void methods?

If a method doesn't return anything, it's either one of the following

  • imperative - You're either asking the object to do something to itself.. e.g change state (without expecting any confirmation.. its assumed that it will be done)
  • informational - just notifying someone that something happened (without expecting action or response) respectively.

Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g.

void DeductFromBalance( dAmount ) 

can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount

Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g.

void OnAccountDebit( dAmount )  // emails account holder with info

can be tested by verifying if the email is being sent

Post more details about your actual method and people will be able to answer better.
Update: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested.

string[] ExamineLogFileForX( string sFileName );
void InsertStringsIntoDatabase( string[] );

String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check this thread for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch.
In the code it would be used like

InsertStringsIntoDatabase( ExamineLogFileForX( "c:\OMG.log" ) );

On select change, get data attribute value

By using this you can get the text, value and data attribute.

<select name="your_name" id="your_id" onchange="getSelectedDataAttribute(this)">
    <option value="1" data-id="123">One</option>
    <option value="2" data-id="234">Two</option>
</select>

function getSelectedDataAttribute(event) {
    var selected_text = event.options[event.selectedIndex].innerHTML;
    var selected_value = event.value;
    var data-id = event.options[event.selectedIndex].dataset.id);    
}

Efficient way to remove keys with empty strings from a dict

Some of Methods mentioned above ignores if there are any integers and float with values 0 & 0.0

If someone wants to avoid the above can use below code(removes empty strings and None values from nested dictionary and nested list):

def remove_empty_from_dict(d):
    if type(d) is dict:
        _temp = {}
        for k,v in d.items():
            if v == None or v == "":
                pass
            elif type(v) is int or type(v) is float:
                _temp[k] = remove_empty_from_dict(v)
            elif (v or remove_empty_from_dict(v)):
                _temp[k] = remove_empty_from_dict(v)
        return _temp
    elif type(d) is list:
        return [remove_empty_from_dict(v) for v in d if( (str(v).strip() or str(remove_empty_from_dict(v)).strip()) and (v != None or remove_empty_from_dict(v) != None))]
    else:
        return d

What is the difference between localStorage, sessionStorage, session and cookies?

  1. LocalStorage

    Pros:

    1. Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. If you look at the Mozilla source code we can see that 5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.
    2. The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
    3. The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

    Cons:

    1. It works on same-origin policy. So, data stored will only be available on the same origin.
  2. Cookies

    Pros:

    1. Compared to others, there's nothing AFAIK.

    Cons:

    1. The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
    2. The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

      Typically, the following are allowed:

      • 300 cookies in total
      • 4096 bytes per cookie
      • 20 cookies per domain
      • 81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)
  3. sessionStorage

    Pros:

    1. It is similar to localStorage.
    2. The data is not persistent i.e. data is only available per window (or tab in browsers like Chrome and Firefox). Data is only available during the page session. Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted.

    Cons:

    1. The data is available only inside the window/tab in which it was set.
    2. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

Checkout across-tabs - how to facilitate easy communication between cross-origin browser tabs.

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

Cannot send a content-body with this verb-type

Because you didn't specify the Header.

I've added an extended example:

var request = (HttpWebRequest)WebRequest.Create(strServer + strURL.Split('&')[1].ToString());

Header(ref request, p_Method);

And the method Header:

private void Header(ref HttpWebRequest p_request, string p_Method)
{
    p_request.ContentType = "application/x-www-form-urlencoded";
    p_request.Method = p_Method;
    p_request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows CE)";
    p_request.Host = strServer.Split('/')[2].ToString();
    p_request.Accept = "*/*";
    if (String.IsNullOrEmpty(strURLReferer))
    {
        p_request.Referer = strServer;
    }
    else
    {
        p_request.Referer = strURLReferer;
    }
    p_request.Headers.Add("Accept-Language", "en-us\r\n");
    p_request.Headers.Add("UA-CPU", "x86 \r\n");
    p_request.Headers.Add("Cache-Control", "no-cache\r\n");
    p_request.KeepAlive = true;
}

What is the difference between private and protected members of C++ classes?

Private members are only accessible within the class defining them.

Protected members are accessible in the class that defines them and in classes that inherit from that class.

Edit: Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes.

Edit 2: Use whatever makes sense in the context of your problem. You should try to make members private whenever you can to reduce coupling and protect the implementation of the base class, but if that's not possible then use protected members. Check C++ FAQ for a better understanding of the issue. This question about protected variables might also help.

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

The easy solution is to create a payload class that has the str1 and the str2 as attributes:

@Getter
@Setter
public class ObjHolder{

String str1;
String str2;

}

And after you can pass

@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody ObjHolder Str) {}

and the body of your request is:

{
    "str1": "test one",
    "str2": "two test"
}

How to filter by string in JSONPath?

''Alastair, you can use this lib and tool; DefiantJS. It enables XPath queries on JSON structures and you can test and validate this XPath:

//data[category="Politician"]

DefiantJS extends the global object with the method "search", which in turn returns an array with the matches. In Javascript, it'll look like this:

var person = JSON.search(json_data, "//people[category='Politician']");
console.log( person[0].name );
// Barack Obama

`React/RCTBridgeModule.h` file not found

Go to iOS folder in your project and install pod -

$ pod install

If you are getting any error in installation of pod type command-

$ xcode-select -p

Result should be - /Applications/Xcode.app/Contents/Developer

If the path is incorrect then open your iOS project in Xcode and go to: Xcode->preferences->command line tools-> select Xcode

And again install the pod your issue will be fixed.

Date Conversion from String to sql Date in Java giving different output?

You need to use MM as mm stands for minutes.

There are two ways of producing month pattern.

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); //outputs month in numeric way, 2013-02-01

SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy"); // Outputs months as follows, 2013-Feb-01

Full coding snippet:

        String startDate="01-Feb-2013"; // Input String
        SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); // New Pattern
        java.util.Date date = sdf1.parse(startDate); // Returns a Date format object with the pattern
        java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
        System.out.println(sqlStartDate); // Outputs : 2013-02-01

How can I make the Android emulator show the soft keyboard?

Settings > Language & input > Current keyboard > Hardware Switch ON.

This option worked.

Common CSS Media Queries Break Points

If you go to your google analytics you can see which screen resolutions your visitors to the website use:

Audience > Technology > Browser & OS > Screen Resolution ( in the menu above the stats)

My site gets about 5,000 visitors a month and the dimensions used for the free version of responsinator.com are pretty accurate summary of my visitors' screen resolutions.

This could save you from needing to be too perfectionistic.

Base64 String throwing invalid character error

One gotcha to do with converting Base64 from a string is that some conversion functions use the preceding "data:image/jpg;base64," and others only accept the actual data.

How can I make the cursor turn to the wait cursor?

It is easier to use UseWaitCursor at the Form or Window level. A typical use case can look like below:

    private void button1_Click(object sender, EventArgs e)
    {

        try
        {
            this.Enabled = false;//optional, better target a panel or specific controls
            this.UseWaitCursor = true;//from the Form/Window instance
            Application.DoEvents();//messages pumped to update controls
            //execute a lengthy blocking operation here, 
            //bla bla ....
        }
        finally
        {
            this.Enabled = true;//optional
            this.UseWaitCursor = false;
        }
    }

For a better UI experience you should use Asynchrony from a different thread.

Where are Magento's log files located?

You can find them in /var/log within your root Magento installation

There will usually be two files by default, exception.log and system.log.

If the directories or files don't exist, create them and give them the correct permissions, then enable logging within Magento by going to System > Configuration > Developer > Log Settings > Enabled = Yes

How to backup a local Git repository?

[Just leaving this here for my own reference.]

My bundle script called git-backup looks like this

#!/usr/bin/env ruby
if __FILE__ == $0
        bundle_name = ARGV[0] if (ARGV[0])
        bundle_name = `pwd`.split('/').last.chomp if bundle_name.nil? 
        bundle_name += ".git.bundle"
        puts "Backing up to bundle #{bundle_name}"
        `git bundle create /data/Dropbox/backup/git-repos/#{bundle_name} --all`
end

Sometimes I use git backup and sometimes I use git backup different-name which gives me most of the possibilities I need.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

Note that I ran into this trouble after I upgraded my Ubuntu 14.04 distribution using apt-get upgrade. I had to completely purge mysql-server and mysql-client and reinstall it to fix this issue.

sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get purge mysql-server mysql-client
sudo apt-get install mysql-server mysql-client

Hope this helps.

Git: Recover deleted (remote) branch

If the delete is recent enough (Like an Oh-NO! moment) you should still have a message:

Deleted branch <branch name> (was abcdefghi).

you can still run:

git checkout abcdefghi

git checkout -b <some new branch name or the old one>

unable to remove file that really exists - fatal: pathspec ... did not match any files

If your file idea/workspace.xml is added to .gitignore (or its parent folder) just add it manually to git version control. Also you can add it using TortoiseGit. After the next push you will see, that your problem is solved.

Add to git versioning using TortoiseGit

How do I check if I'm running on Windows in Python?

import platform
is_windows = any(platform.win32_ver())

or

import sys
is_windows = hasattr(sys, 'getwindowsversion')

How to programmatically open the Permission Screen for a specific app on Android Marshmallow?

Try This

  Intent intent = new Intent(Intent.ACTION_MAIN);
  intent.setComponent(new ComponentName(appDetails.packageName,"com.android.packageinstaller.permission.ui.ManagePermissionsActivity"));
  startActivity(intent);

How can I print out C++ map values?

If your compiler supports (at least part of) C++11 you could do something like:

for (auto& t : myMap)
    std::cout << t.first << " " 
              << t.second.first << " " 
              << t.second.second << "\n";

For C++03 I'd use std::copy with an insertion operator instead:

typedef std::pair<string, std::pair<string, string> > T;

std::ostream &operator<<(std::ostream &os, T const &t) { 
    return os << t.first << " " << t.second.first << " " << t.second.second;
}

// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));

Insert line at middle of file with Python?

This is a way of doing the trick.

f = open("path_to_file", "r")
contents = f.readlines()
f.close()

contents.insert(index, value)

f = open("path_to_file", "w")
contents = "".join(contents)
f.write(contents)
f.close()

"index" and "value" are the line and value of your choice, lines starting from 0.

How can I combine two HashMap objects containing the same types?

you can use - addAll method

http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html

But there is always this issue that - if your two hash maps have any key same - then it will override the value of the key from first hash map with the value of the key from second hash map.

For being on safer side - change the key values - you can use prefix or suffix on the keys - ( different prefix/suffix for first hash map and different prefix/suffix for second hash map )

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

Tank´s Yogihosting

I have in my database one goups of tables from Open Streep Maps and I tested successful.

Distance work fine in meters.

SET @orig_lat=-8.116137;
SET @orig_lon=-34.897488;
SET @dist=1000;

SELECT *,(((acos(sin((@orig_lat*pi()/180)) * sin((dest.latitude*pi()/180))+cos((@orig_lat*pi()/180))*cos((dest.latitude*pi()/180))*cos(((@orig_lon-dest.longitude)*pi()/180))))*180/pi())*60*1.1515*1609.344) as distance FROM nodes AS dest HAVING distance < @dist ORDER BY distance ASC LIMIT 100;

Easy way to get a test file into JUnit

If you need to actually get a File object, you could do the following:

URL url = this.getClass().getResource("/test.wsdl");
File testWsdl = new File(url.getFile());

Which has the benefit of working cross platform, as described in this blog post.

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

Have encountered the same issue in my asp.net project, in the end i found the issue is with the target function not static, the issue fixed after I put the keyword static.

[WebMethod]
public static List<string> getRawData()

How can I check if a string represents an int, without using try/except?

I do this all the time b/c I have a mild but admittedly irrational aversion to using the try/except pattern. I use this:

all([xi in '1234567890' for xi in x])

It doesn't accommodate negative numbers, so you could strip out all minus signs on the left side, and then check if the result comprises digits from 0-9:

all([xi in '1234567890' for xi in x.lstrip('-')])

You could also pass x to str() if you're not sure the input is a string:

all([xi in '1234567890' for xi in str(x).lstrip('-')])

There are some (edge?) cases where this falls apart:

  1. It doesn't work for various scientific and/or exponential notations (e.g. 1.2E3, 10^3, etc.) - both will return False. I don't think other answers accommodated this either, and even Python 3.8 has inconsistent opinions, since type(1E2) gives <class 'float'> whereas type(10^2) gives <class 'int'>.
  2. An empty string input gives True.
  3. A leading plus sign (e.g. "+7") gives False.
  4. Multiple minus signs are ignored so long as they're leading characters. This behavior is similar to the python interpreter* in that type(---1) returns <class int>. However, it isn't completely consistent with the interpreter in that int('---1') gives an error, but my solution returns True with the same input.

So it won't work for every possible input, but if you can exclude those, it's an OK one-line check that returns False if x is not an integer and True if x is an integer. But if you really want behavior that exactly models the int() built-in, you're better off using try/except.

I don't know if it's pythonic, but it's one line, and it's relatively clear what the code does.

*I don't mean to say that the interpreter ignores leading minus signs, just that any number of leading minus signs does not change that the result is an integer. int(--1) is actually interpreted as -(-1), or 1. int(---1) is interpreted as -(-(-1)), or -1. So an even number of leading minus signs gives a positive integer, and an odd number of minus signs gives a negative integer, but the result is always an integer.

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

The Angular way

The correct Angular way to do this is to write a single page app, AJAX in the form template, then populate it dynamically from the model. The model is not populated from the form by default because the model is the single source of truth. Instead Angular will go the other way and try to populate the form from the model.

If however, you don't have time to start over from scratch

If you have an app written, this might involve some fairly hefty architectural changes. If you're trying to use Angular to enhance an existing form, rather than constructing an entire single page app from scratch, you can pull the value from the form and store it in the scope at link time using a directive. Angular will then bind the value in the scope back to the form and keep it in sync.

Using a directive

You can use a relatively simple directive to pull the value from the form and load it in to the current scope. Here I've defined an initFromForm directive.

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

angular.module('initFromForm', [])
  .directive("initFromForm", function ($parse) {
    return {
      link: function (scope, element, attrs) {
        var attr = attrs.initFromForm || attrs.ngModel || element.attrs('name'),
        val = attrs.value;
        if (attrs.type === "number") {val = parseInt(val)}
        $parse(attr).assign(scope, val);
      }
    };
  });

You can see I've defined a couple of fallbacks to get a model name. You can use this directive in conjunction with the ngModel directive, or bind to something other than $scope if you prefer.

Use it like this:

<input name="test" ng-model="toaster.test" value="hello" init-from-form />
{{toaster.test}}

Note this will also work with textareas, and select dropdowns.

<textarea name="test" ng-model="toaster.test" init-from-form>hello</textarea>
{{toaster.test}}

Convert tuple to list and back

List to Tuple and back can be done as below

import ast, sys
input_str = sys.stdin.read()
input_tuple = ast.literal_eval(input_str)

l = list(input_tuple)
l.append('Python')
#print(l)
tuple_2 = tuple(l)

# Make sure to name the final tuple 'tuple_2'
print(tuple_2)

"On Exit" for a Console Application

This code works to catch the user closing the console window:

using System;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        handler = new ConsoleEventDelegate(ConsoleEventCallback);
        SetConsoleCtrlHandler(handler, true);
        Console.ReadLine();
    }

    static bool ConsoleEventCallback(int eventType) {
        if (eventType == 2) {
            Console.WriteLine("Console window closing, death imminent");
        }
        return false;
    }
    static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected
    // Pinvoke
    private delegate bool ConsoleEventDelegate(int eventType);
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

}

Beware of the restrictions. You have to respond quickly to this notification, you've got 5 seconds to complete the task. Take longer and Windows will kill your code unceremoniously. And your method is called asynchronously on a worker thread, the state of the program is entirely unpredictable so locking is likely to be required. Do make absolutely sure that an abort cannot cause trouble. For example, when saving state into a file, do make sure you save to a temporary file first and use File.Replace().

Anaconda export Environment file

The easiest way to save the packages from an environment to be installed in another computer is:

$ conda list -e > req.txt

then you can install the environment using

$ conda create -n <environment-name> --file req.txt

if you use pip, please use the following commands: reference https://pip.pypa.io/en/stable/reference/pip_freeze/

$ env1/bin/pip freeze > requirements.txt
$ env2/bin/pip install -r requirements.txt

Ubuntu apt-get unable to fetch packages

After trying all the suggestions given here and other threads like this one I still couldn't get apt_get to work on my Vagrant Ubuntu 16.04. In the end removing the file apt.conf from /etc/apt resolved the issue for me. My remaining files in that directory are:

vagrant@default:~$ ls -l /etc/apt/
total 68
drwxr-xr-x 2 root root  4096 Apr 15 12:20 apt.conf.d
drwxr-xr-x 2 root root  4096 May 21  2019 auth.conf.d
-rw-r--r-- 1 root root    53 Mar 19 19:50 preferences
drwxr-xr-x 2 root root  4096 Apr 14  2016 preferences.d
-rw-r--r-- 1 root root  3166 Sep 10 15:55 sources.list
drwxr-xr-x 2 root root  4096 Sep 10 16:04 sources.list.d
-rw-r--r-- 1 root root 17640 Mar 19 20:04 trusted.gpg
-rw-r--r-- 1 root root 17281 Mar 19 20:01 trusted.gpg~
drwxr-xr-x 2 root root  4096 Sep 10 13:45 trusted.gpg.d

How to change href attribute using JavaScript after opening the link in a new window?

You can delay your code using setTimeout to execute after click

function changeLink(){
    setTimeout(function() {
        var link = document.getElementById("mylink");
        link.setAttribute('href', "http://facebook.com");
        document.getElementById("mylink").innerHTML = "facebook";
    }, 100);
}

Find kth smallest element in a binary search tree in Optimum way

Best approach is already there.But I'd like to add a simple Code for that

int kthsmallest(treenode *q,int k){
int n = size(q->left) + 1;
if(n==k){
    return q->val;
}
if(n > k){
    return kthsmallest(q->left,k);
}
if(n < k){
    return kthsmallest(q->right,k - n);
}

}

int size(treenode *q){
if(q==NULL){
    return 0;
}
else{
    return ( size(q->left) + size(q->right) + 1 );
}}

Alter and Assign Object Without Side Effects

Try this instead:

var myArray = [];

myArray.push({ id: 0, value: 1 });
myArray.push({ id: 2, value: 3 });

or will this not work for your situation?

Is SQL syntax case sensitive?

The SQL Keywords are case-insensitive (SELECT, FROM, WHERE, etc), but are often written in all caps. However in some setups table and column names are case-sensitive. MySQL has a configuration option to enable/disable it. Usually case-sensitive table and column names are the default on Linux MySQL and case-insensitive used to be the default on Windows, but now the installer asked about this during setup. For MSSQL it is a function of the database's collation setting.

Here is the MySQL page about name case-sensitivity

Here is the article in MSDN about collations for MSSQL

How to install Hibernate Tools in Eclipse?

Since it is for Ganymede (eclipse 3.4), I would advise to uncompress the zip in the dropins in the HibernateTools-3.2.4.Beta1-R20081031133 directory created after the name of the archive.

Once it is done, create in the [eclipse\dropins\HibernateTools-3.2.4.Beta1-R20081031133] an 'eclipse' directory, in which you will move the plugins and features directories creating at the extraction of the files of the archive.

Add a .exclipseextension in [eclipse\dropins\HibernateTools-3.2.4.Beta1-R20081031133\eclipse]:

name=QuickRex
id=org.hibernate.eclipse
version=3.2.4b1

So:

eclipse
    dropins
         HibernateTools-3.2.4.Beta1-R20081031133
             eclipse
                 .eclipseextension
                 features
                 plugins

Relaunch eclipse and the plugin Hibernate should be detected.

If you install another eclipse, just copy the content of your dropins directory to the new eclipse\dropins and your set of plugins will be detected again.

In Java, how do I call a base class's method from the overriding method in a derived class?

Just call it using super.

public void myMethod()
{
    // B stuff
    super.myMethod();
    // B stuff
}

how to fetch array keys with jQuery?

you can use the each function:

var a = {};
a['alfa'] = 0;
a['beta'] = 1;
$.each(a, function(key, value) {
      alert(key)
});

it has several nice shortcuts/tricks: check the gory details here

Can I simultaneously declare and assign a variable in VBA?

You can define and assign value as shown below in one line. I have given an example of two variables declared and assigned in single line. if the data type of multiple variables are same

 Dim recordStart, recordEnd As Integer: recordStart = 935: recordEnd = 946

Android Paint: .measureText() vs .getTextBounds()

The mice answer is great... And here is the description of the real problem:

The short simple answer is that Paint.getTextBounds(String text, int start, int end, Rect bounds) returns Rect which doesn't starts at (0,0). That is, to get actual width of text that will be set by calling Canvas.drawText(String text, float x, float y, Paint paint) with the same Paint object from getTextBounds() you should add the left position of Rect. Something like that:

public int getTextWidth(String text, Paint paint) {
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, end, bounds);
    int width = bounds.left + bounds.width();
    return width;
}

Notice this bounds.left - this the key of the problem.

In this way you will receive the same width of text, that you would receive using Canvas.drawText().

And the same function should be for getting height of the text:

public int getTextHeight(String text, Paint paint) {
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, end, bounds);
    int height = bounds.bottom + bounds.height();
    return height;
}

P.s.: I didn't test this exact code, but tested the conception.


Much more detailed explanation is given in this answer.

matching query does not exist Error in Django

As mentioned in Django docs, when get method finds no entry or finds multiple entries, it raises an exception, this is the expected behavior:

get() raises MultipleObjectsReturned if more than one object was found. The MultipleObjectsReturned exception is an attribute of the model class.

get() raises a DoesNotExist exception if an object wasn’t found for the given parameters. This exception is an attribute of the model class.

Using exceptions is a way to handle this problem, but I actually don't like the ugly try-except block. An alternative solution, and cleaner to me, is to use the combination of filter + first.

user = UniversityDetails.objects.filter(email=email).first()

When you do .first() to an empty queryset it returns None. This way you can have the same effect in a single line.

The only difference between catching the exception and using this method occurs when you have multiple entries, the former will raise an exception while the latter will set the first element, but as you are using get I may assume we won't fall on this situation.

Note that first method was added on Django 1.6.

create array from mysql query php

You may want to go look at the SQL Injection article on Wikipedia. Look under the "Hexadecimal Conversion" part to find a small function to do your SQL commands and return an array with the information in it.

https://en.wikipedia.org/wiki/SQL_injection

I wrote the dosql() function because I got tired of having my SQL commands executing all over the place, forgetting to check for errors, and being able to log all of my commands to a log file for later viewing if need be. The routine is free for whoever wants to use it for whatever purpose. I actually have expanded on the function a bit because I wanted it to do more but this basic function is a good starting point for getting the output back from an SQL call.

How to read large text file on windows?

I just used less on top of Cygwin to read a 3GB file, though I ended up using grep to find what I needed in it.

(less is more, but better.)

See this answer for more details on less: https://stackoverflow.com/a/1343576/1005039

Automatic HTTPS connection/redirect with node.js/express

If you follow conventional ports since HTTP tries port 80 by default and HTTPS tries port 443 by default you can simply have two server's on the same machine: Here's the code:

var https = require('https');

var fs = require('fs');
var options = {
    key: fs.readFileSync('./key.pem'),
    cert: fs.readFileSync('./cert.pem')
};

https.createServer(options, function (req, res) {
    res.end('secure!');
}).listen(443);

// Redirect from http port 80 to https
var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(301, { "Location": "https://" + req.headers['host'] + req.url });
    res.end();
}).listen(80);

Test with https:

$ curl https://127.0.0.1 -k
secure!

With http:

$ curl http://127.0.0.1 -i
HTTP/1.1 301 Moved Permanently
Location: https://127.0.0.1/
Date: Sun, 01 Jun 2014 06:15:16 GMT
Connection: keep-alive
Transfer-Encoding: chunked

More details : Nodejs HTTP and HTTPS over same port

How to force keyboard with numbers in mobile website in Android

This should work. But I have same problems on an Android phone.

<input type="number" /> <input type="tel" />

I found out, that if I didn't include the jquerymobile-framework, the keypad showed correctly on the two types of fields.

But I havn't found a solution to solve that problem, if you really need to use jquerymobile.

UPDATE: I found out, that if the form-tag is stored out of the

<div data-role="page"> 

The number keypad isn't shown. This must be a bug...

How can I find the first occurrence of a sub-string in a python string?

verse = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n And yet don’t look too good, nor talk too wise:"

enter code here

print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))

Deserialize JSON into C# dynamic object?

.NET 4.0 has a built-in library to do this:

using System.Web.Script.Serialization;
JavaScriptSerializer jss = new JavaScriptSerializer();
var d = jss.Deserialize<dynamic>(str);

This is the simplest way.

Hide Text with CSS, Best Practice?

Can't you use simply display: none; like this

HTML

<div id="web-title">
   <a href="http://website.com" title="Website" rel="home">
       <span class="webname">Website Name</span>
   </a>
</div>

CSS

.webname {
   display: none;
}

Or how about playing with visibility if you are concerned to reserve the space

.webname {
   visibility: hidden;
}

How to reset postgres' primary key sequence when it falls out of sync?

-- Login to psql and run the following

-- What is the result?
SELECT MAX(id) FROM your_table;

-- Then run...
-- This should be higher than the last result.
SELECT nextval('your_table_id_seq');

-- If it's not higher... run this set the sequence last to your highest id. 
-- (wise to run a quick pg_dump first...)

BEGIN;
-- protect against concurrent inserts while you update the counter
LOCK TABLE your_table IN EXCLUSIVE MODE;
-- Update the sequence
SELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false);
COMMIT;

Source - Ruby Forum

how to specify new environment location for conda create

You can create it like this

conda create --prefix C:/tensorflow2 python=3.7

and you don't have to move to that folder to activate it.

# To activate this environment, use:
# > activate C:\tensorflow2

As you see I do it like this.

D:\Development_Avector\PycharmProjects\TensorFlow>activate C:\tensorflow2

(C:\tensorflow2) D:\Development_Avector\PycharmProjects\TensorFlow>

(C:\tensorflow2) D:\Development_Avector\PycharmProjects\TensorFlow>conda --version
conda 4.5.13