Programs & Examples On #Source insight

Source Insight is an advanced code editor and browser with built-in analysis for C/C++, C#, and Java programs.

How to import data from one sheet to another

Saw this thread while looking for something else and I know it is super old, but I wanted to add my 2 cents.

NEVER USE VLOOKUP. It's one of the worst performing formulas in excel. Use index match instead. It even works without sorting data, unless you have a -1 or 1 in the end of the match formula (explained more below)

Here is a link with the appropriate formulas.

The Sheet 2 formula would be this: =IF(A2="","",INDEX(Sheet1!B:B,MATCH($A2,Sheet1!$A:$A,0)))

  • IF(A2="","", means if A2 is blank, return a blank value
  • INDEX(Sheet1!B:B, is saying INDEX B:B where B:B is the data you want to return. IE the name column.
  • Match(A2, is saying to Match A2 which is the ID you want to return the Name for.
  • Sheet1!A:A, is saying you want to match A2 to the ID column in the previous sheet
  • ,0)) is specifying you want an exact value. 0 means return an exact match to A2, -1 means return smallest value greater than or equal to A2, 1 means return the largest value that is less than or equal to A2. Keep in mind -1 and 1 have to be sorted.

More information on the Index/Match formula

Other fun facts: $ means absolute in a formula. So if you specify $B$1 when filling a formula down or over keeps that same value. If you over $B1, the B remains the same across the formula, but if you fill down, the 1 increases with the row count. Likewise, if you used B$1, filling to the right will increment the B, but keep the reference of row 1.

I also included the use of indirect in the second section. What indirect does is allow you to use the text of another cell in a formula. Since I created a named range sheet1!A:A = ID, sheet1!B:B = Name, and sheet1!C:C=Price, I can use the column name to have the exact same formula, but it uses the column heading to change the search criteria.

Good luck! Hope this helps.

Trim whitespace from a String

#include <vector>
#include <numeric>
#include <sstream>
#include <iterator>

void Trim(std::string& inputString)
{
    std::istringstream stringStream(inputString);
    std::vector<std::string> tokens((std::istream_iterator<std::string>(stringStream)), std::istream_iterator<std::string>());

    inputString = std::accumulate(std::next(tokens.begin()), tokens.end(),
                                 tokens[0], // start with first element
                                 [](std::string a, std::string b) { return a + " " + b; });
}

In Python, how do I split a string and keep the separators?

Another no-regex solution that works well on Python 3

# Split strings and keep separator
test_strings = ['<Hello>', 'Hi', '<Hi> <Planet>', '<', '']

def split_and_keep(s, sep):
   if not s: return [''] # consistent with string.split()

   # Find replacement character that is not used in string
   # i.e. just use the highest available character plus one
   # Note: This fails if ord(max(s)) = 0x10FFFF (ValueError)
   p=chr(ord(max(s))+1) 

   return s.replace(sep, sep+p).split(p)

for s in test_strings:
   print(split_and_keep(s, '<'))


# If the unicode limit is reached it will fail explicitly
unicode_max_char = chr(1114111)
ridiculous_string = '<Hello>'+unicode_max_char+'<World>'
print(split_and_keep(ridiculous_string, '<'))

How do you upload a file to a document library in sharepoint?

try
{
    //Variablen für die Verarbeitung
    string source_file = @"C:\temp\offer.pdf";
    string web_url = "https://stackoverflow.sharepoint.com";
    string library_name = "Documents";
    string admin_name = "[email protected]";
    string admin_password = "Password";

    //Verbindung mit den Login-Daten herstellen
    var sercured_password = new SecureString();
    foreach (var c in admin_password) sercured_password.AppendChar(c);
    SharePointOnlineCredentials credent = new 
    SharePointOnlineCredentials(admin_name, sercured_password);

    //Context mit Credentials erstellen
    ClientContext context = new ClientContext(web_url);
    context.Credentials = credent;

    //Bibliothek festlegen
    var library = context.Web.Lists.GetByTitle(library_name);

    //Ausgewählte Datei laden
    FileStream fs = System.IO.File.OpenRead(source_file);

    //Dateinamen aus Pfad ermitteln
    string source_filename = Path.GetFileName(source_file);

    //Datei ins SharePoint-Verzeichnis hochladen
    FileCreationInformation fci = new FileCreationInformation();
    fci.Overwrite = true;
    fci.ContentStream = fs;
    fci.Url = source_filename;
    var file_upload = library.RootFolder.Files.Add(fci);

    //Ausführen
    context.Load(file_upload);
    context.ExecuteQuery();
    
    //Datenübertragen schließen
    fs.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Fehler");
    throw;
}

What is python's site-packages directory?

When you use --user option with pip, the package gets installed in user's folder instead of global folder and you won't need to run pip command with admin privileges.

The location of user's packages folder can be found using:

python -m site --user-site

This will print something like:

C:\Users\%USERNAME%\AppData\Roaming\Python\Python35\site-packages

When you don't use --user option with pip, the package gets installed in global folder given by:

python -c "import site; print(site.getsitepackages())"

This will print something like:

['C:\\Program Files\\Anaconda3', 'C:\\Program Files\\Anaconda3\\lib\\site-packages'

Note: Above printed values are for On Windows 10 with Anaconda 4.x installed with defaults.

How to install pip for Python 3 on Mac OS X?

Install Python3 on mac

1. brew install python3
2. curl https://bootstrap.pypa.io/get-pip.py | python3
3. python3

Use pip3 to install modules

1. pip3 install ipython
2. python3 -m IPython

:)

Passing Variable through JavaScript from one html page to another page

Without reading your code but just your scenario, I would solve by using localStorage. Here's an example, I'll use prompt() for short.

On page1:

window.onload = function() {
   var getInput = prompt("Hey type something here: ");
   localStorage.setItem("storageName",getInput);
}

On page2:

window.onload = alert(localStorage.getItem("storageName"));

You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.

Android: how to handle button click

There are also options available in the form of various libraries that can make this process very familiar to people that have used other MVVM frameworks.

https://developer.android.com/topic/libraries/data-binding/

Shows an example of an official library, that allows you to bind buttons like this:

<Button
    android:text="Start second activity"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="@{() -> presenter.showList()}"
/>

How can I express that two values are not equal to eachother?

"Not equals" can be expressed with the "not" operator ! and the standard .equals.

if (a.equals(b)) // a equals b
if (!a.equals(b)) // a not equal to b

SQL Server: Null VS Empty String

if it's not a foreign key field, not using empty strings could save you some trouble. only allow nulls if you'll take null to mean something different than an empty string. for example if you have a password field, a null value could indicate that a new user has not created his password yet while an empty varchar could indicate a blank password. for a field like "address2" allowing nulls can only make life difficult. things to watch out for include null references and unexpected results of = and <> operators mentioned by Vagif Verdi, and watching out for these things is often unnecessary programmer overhead.

edit: if performance is an issue see this related question: Nullable vs. non-null varchar data types - which is faster for queries?

How to drop a database with Mongoose?

This works for me as of Mongoose v4.7.0:

mongoose.connection.dropDatabase();

Force DOM redraw/refresh on Chrome/Mac

Not sure exactly what you're trying to achieve but this is a method I have used in the past with success to force the browser to redraw, maybe it will work for you.

// in jquery
$('#parentOfElementToBeRedrawn').hide().show(0);

// in plain js
document.getElementById('parentOfElementToBeRedrawn').style.display = 'none';
document.getElementById('parentOfElementToBeRedrawn').style.display = 'block';

If this simple redraw doesn't work you can try this one. It inserts an empty text node into the element which guarantees a redraw.

var forceRedraw = function(element){

    if (!element) { return; }

    var n = document.createTextNode(' ');
    var disp = element.style.display;  // don't worry about previous display style

    element.appendChild(n);
    element.style.display = 'none';

    setTimeout(function(){
        element.style.display = disp;
        n.parentNode.removeChild(n);
    },20); // you can play with this timeout to make it as short as possible
}

EDIT: In response to Šime Vidas what we are achieving here would be a forced reflow. You can find out more from the master himself http://paulirish.com/2011/dom-html5-css3-performance/

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

Display calendar to pick a date in java

  1. Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.

  2. Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:

    TableModel datePicker = new DatePickerTable("01011999","12302000");
    
  3. Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:

    datePicker.interval = 15;
    
  4. Attach your table model into your JTable:

    JTable newtable = new JTable (datePicker);
    

    Your Java application now has a drop-down date selection dialog.

Trusting all certificates using HttpClient over HTTPS

Any body still struggling with StartCom SSL Certificates on Android 2.1 visit https://www.startssl.com/certs/ and download the ca.pem, now in the answer provided by @emmby replace

`export CLASSPATH=bcprov-jdk16-145.jar
 CERTSTORE=res/raw/mystore.bks
      if [ -a $CERTSTORE ]; then
          rm $CERTSTORE || exit 1
      fi
 keytool \
  -import \
  -v \
  -trustcacerts \
  -alias 0 \
  -file <(openssl x509 -in mycert.pem) \
  -keystore $CERTSTORE \
  -storetype BKS \
  -provider org.bouncycastle.jce.provider.BouncyCastleProvider \
  -providerpath /usr/share/java/bcprov.jar \
  -storepass some-password`

with

 `export CLASSPATH=bcprov-jdk16-145.jar
 CERTSTORE=res/raw/mystore.bks
      if [ -a $CERTSTORE ]; then
          rm $CERTSTORE || exit 1
      fi
 keytool \
  -import \
  -v \
  -trustcacerts \
  -alias 0 \
  -file <(openssl x509 -in ca.pem) \
  -keystore $CERTSTORE \
  -storetype BKS \
  -provider org.bouncycastle.jce.provider.BouncyCastleProvider \
  -providerpath /usr/share/java/bcprov.jar \
  -storepass some-password`

Should work out of the box. I was struggling it for over a day even after a perfect answer by @emmby.. Hope this helps someone...

Difference between <context:annotation-config> and <context:component-scan>

<context:annotation-config> is used to activate annotations in beans already registered in the application context (no matter if they were defined with XML or by package scanning).

<context:component-scan> can also do what <context:annotation-config> does but <context:component-scan> also scans packages to find and register beans within the application context.

I'll use some examples to show the differences/similarities.

Lets start with a basic setup of three beans of type A, B and C, with B and C being injected into A.

package com.xxx;
public class B {
  public B() {
    System.out.println("creating bean B: " + this);
  }
}

package com.xxx;
public class C {
  public C() {
    System.out.println("creating bean C: " + this);
  }
}

package com.yyy;
import com.xxx.B;
import com.xxx.C;
public class A { 
  private B bbb;
  private C ccc;
  public A() {
    System.out.println("creating bean A: " + this);
  }
  public void setBbb(B bbb) {
    System.out.println("setting A.bbb with " + bbb);
    this.bbb = bbb;
  }
  public void setCcc(C ccc) {
    System.out.println("setting A.ccc with " + ccc);
    this.ccc = ccc; 
  }
}

With the following XML configuration :

<bean id="bBean" class="com.xxx.B" />
<bean id="cBean" class="com.xxx.C" />
<bean id="aBean" class="com.yyy.A">
  <property name="bbb" ref="bBean" />
  <property name="ccc" ref="cBean" />
</bean>

Loading the context produces the following output:

creating bean B: com.xxx.B@c2ff5
creating bean C: com.xxx.C@1e8a1f6
creating bean A: com.yyy.A@1e152c5
setting A.bbb with com.xxx.B@c2ff5
setting A.ccc with com.xxx.C@1e8a1f6

OK, this is the expected output. But this is "old style" Spring. Now we have annotations so lets use those to simplify the XML.

First, lets autowire the bbb and ccc properties on bean A like so:

package com.yyy;
import org.springframework.beans.factory.annotation.Autowired;
import com.xxx.B;
import com.xxx.C;
public class A { 
  private B bbb;
  private C ccc;
  public A() {
    System.out.println("creating bean A: " + this);
  }
  @Autowired
  public void setBbb(B bbb) {
    System.out.println("setting A.bbb with " + bbb);
    this.bbb = bbb;
  }
  @Autowired
  public void setCcc(C ccc) {
    System.out.println("setting A.ccc with " + ccc);
    this.ccc = ccc;
  }
}

This allows me to remove the following rows from the XML:

<property name="bbb" ref="bBean" />
<property name="ccc" ref="cBean" />

My XML is now simplified to this:

<bean id="bBean" class="com.xxx.B" />
<bean id="cBean" class="com.xxx.C" />
<bean id="aBean" class="com.yyy.A" />

When I load the context I get the following output:

creating bean B: com.xxx.B@5e5a50
creating bean C: com.xxx.C@54a328
creating bean A: com.yyy.A@a3d4cf

OK, this is wrong! What happened? Why aren't my properties autowired?

Well, annotations are a nice feature but by themselves they do nothing whatsoever. They just annotate stuff. You need a processing tool to find the annotations and do something with them.

<context:annotation-config> to the rescue. This activates the actions for the annotations that it finds on the beans defined in the same application context where itself is defined.

If I change my XML to this:

<context:annotation-config />
<bean id="bBean" class="com.xxx.B" />
<bean id="cBean" class="com.xxx.C" />
<bean id="aBean" class="com.yyy.A" />

when I load the application context I get the proper result:

creating bean B: com.xxx.B@15663a2
creating bean C: com.xxx.C@cd5f8b
creating bean A: com.yyy.A@157aa53
setting A.bbb with com.xxx.B@15663a2
setting A.ccc with com.xxx.C@cd5f8b

OK, this is nice, but I've removed two rows from the XML and added one. That's not a very big difference. The idea with annotations is that it's supposed to remove the XML.

So let's remove the XML definitions and replace them all with annotations:

package com.xxx;
import org.springframework.stereotype.Component;
@Component
public class B {
  public B() {
    System.out.println("creating bean B: " + this);
  }
}

package com.xxx;
import org.springframework.stereotype.Component;
@Component
public class C {
  public C() {
    System.out.println("creating bean C: " + this);
  }
}

package com.yyy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.xxx.B;
import com.xxx.C;
@Component
public class A { 
  private B bbb;
  private C ccc;
  public A() {
    System.out.println("creating bean A: " + this);
  }
  @Autowired
  public void setBbb(B bbb) {
    System.out.println("setting A.bbb with " + bbb);
    this.bbb = bbb;
  }
  @Autowired
  public void setCcc(C ccc) {
    System.out.println("setting A.ccc with " + ccc);
    this.ccc = ccc;
  }
}

While in the XML we only keep this:

<context:annotation-config />

We load the context and the result is... Nothing. No beans are created, no beans are autowired. Nothing!

That's because, as I said in the first paragraph, the <context:annotation-config /> only works on beans registered within the application context. Because I removed the XML configuration for the three beans there is no bean created and <context:annotation-config /> has no "targets" to work on.

But that won't be a problem for <context:component-scan> which can scan a package for "targets" to work on. Let's change the content of the XML config into the following entry:

<context:component-scan base-package="com.xxx" />

When I load the context I get the following output:

creating bean B: com.xxx.B@1be0f0a
creating bean C: com.xxx.C@80d1ff

Hmmmm... something is missing. Why?

If you look closelly at the classes, class A has package com.yyy but I've specified in the <context:component-scan> to use package com.xxx so this completely missed my A class and only picked up B and C which are on the com.xxx package.

To fix this, I add this other package also:

<context:component-scan base-package="com.xxx,com.yyy" />

and now we get the expected result:

creating bean B: com.xxx.B@cd5f8b
creating bean C: com.xxx.C@15ac3c9
creating bean A: com.yyy.A@ec4a87
setting A.bbb with com.xxx.B@cd5f8b
setting A.ccc with com.xxx.C@15ac3c9

And that's it! Now you don't have XML definitions anymore, you have annotations.

As a final example, keeping the annotated classes A, B and C and adding the following to the XML, what will we get after loading the context?

<context:component-scan base-package="com.xxx" />
<bean id="aBean" class="com.yyy.A" />

We still get the correct result:

creating bean B: com.xxx.B@157aa53
creating bean C: com.xxx.C@ec4a87
creating bean A: com.yyy.A@1d64c37
setting A.bbb with com.xxx.B@157aa53
setting A.ccc with com.xxx.C@ec4a87

Even if the bean for class A isn't obtained by scanning, the processing tools are still applied by <context:component-scan> on all beans registered in the application context, even for A which was manually registered in the XML.

But what if we have the following XML, will we get duplicated beans because we've specified both <context:annotation-config /> and <context:component-scan>?

<context:annotation-config />
<context:component-scan base-package="com.xxx" />
<bean id="aBean" class="com.yyy.A" />

No, no duplications, We again get the expected result:

creating bean B: com.xxx.B@157aa53
creating bean C: com.xxx.C@ec4a87
creating bean A: com.yyy.A@1d64c37
setting A.bbb with com.xxx.B@157aa53
setting A.ccc with com.xxx.C@ec4a87

That's because both tags register the same processing tools (<context:annotation-config /> can be omitted if <context:component-scan> is specified) but Spring takes care of running them only once.

Even if you register the processing tools yourself multiple times, Spring will still make sure they do their magic only once; this XML:

<context:annotation-config />
<context:component-scan base-package="com.xxx" />
<bean id="aBean" class="com.yyy.A" />
<bean id="bla" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="bla1" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="bla2" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean id="bla3" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

will still generate the following result:

creating bean B: com.xxx.B@157aa53
creating bean C: com.xxx.C@ec4a87
creating bean A: com.yyy.A@25d2b2
setting A.bbb with com.xxx.B@157aa53
setting A.ccc with com.xxx.C@ec4a87

OK, that about raps it up.

I hope this information along with the responses from @Tomasz Nurkiewicz and @Sean Patrick Floyd are all you need to understand how <context:annotation-config> and <context:component-scan> work.

How to force DNS refresh for a website?

It might be possible to delete the Zone Record entirely, then recreate it exactly as you want it. Perhaps this will force a full propagation. If I'm wrong, somebody tell me and I'll delete this suggestion. Also, I don't know how to save a Zone Record and recreate it using WHM or any other tool.

I do know that when I deleted a hosting account today and recreated it, the original Zone Record seemed to be propagated instantly to a DNS resolver up the line from my computer. That is good evidence it works.

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

I had the same problem with eclipse, the WA solution was to copy the libs to WEB-INF/lib

jquery - return value using ajax result on success

// Common ajax caller
function AjaxCall(url,successfunction){
  var targetUrl=url;
  $.ajax({
    'url': targetUrl,
    'type': 'GET',
    'dataType': 'json',
    'success': successfunction,
    'error': function() {
      alert("error");
    }
  });
}

// Calling Ajax
$(document).ready(function() {
  AjaxCall("productData.txt",ajaxSuccessFunction);
});

// Function details of success function
function ajaxSuccessFunction(d){
  alert(d.Pioneer.Product[0].category);
}

it may help, create a common ajax call function and attach a function which invoke when success the ajax call, see the example

SOAP request to WebService with java

I have come across other similar question here. Both of above answers are perfect, but here trying to add additional information for someone looking for SOAP1.1, and not SOAP1.2.

Just change one line code provided by @acdcjunior, use SOAPMessageFactory1_1Impl implementation, it will change namespace to xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", which is SOAP1.1 implementation.

Change callSoapWebService method first line to following.

SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();

I hope it will be helpful to others.

How to get the current date without the time?

I think you need separately date parts like (day, Month, Year)

DateTime today = DateTime.Today;

Will not work for your case. You can get date separately so you don't need variable today to be as a DateTimeType, so lets just give today variable int Type because the day is only int. So today is 10 March 2020 then the result of

int today = DateTime.Today.Day;

int month = DateTime.Today.Month;

int year = DateTime.Today.Year;

MessageBox.Show(today.ToString()+ " - this is day. "+month.ToString()+ " - this is month. " + year.ToString() + " - this is year");

would be "10 - this is day. 3 - this is month. 2020 - this is year"

How to edit data in result grid in SQL Server Management Studio

The way you can do this is by:

  • turning your select query into a view
  • right click on the view and choose Edit All Rows (you will get a grid of values you can edit - even if the values are from different tables).

You can also add Insert/Update triggers to your view that will allow you to grab the values from your view fields and then use T-SQL to manage updates to multiple tables.

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

Show values from a MySQL database table inside a HTML table on a webpage

OOP Style : At first connection with database.

<?php
class database
{

 public $host = "localhost";
 public $user = "root";
 public $pass = "";
 public $db   = "db";
 public $link;

 public function __construct()
 {
    $this->connect();
 }

 private function connect()
 {
   $this->link = new mysqli($this->host, $this->user, $this->pass, $this->db);
    return $this->link;
 }

 public function select($query)
 {
    $result = $this->link->query($query) or die($this->link->error.__LINE__);

    if($result->num_rows>0)
    {
      return $result;
    } 
    else 
    {
      return false;
    }
}
?>

Then :

    <?php
        $db = new database();

        $query = "select * from data";
        $result = $db->select($query);

        echo "<table>";
         echo "<tr>";
            echo "<th>Name </th>";
            echo "<th>Roll </th>";
         echo "</tr>";
         while($row = mysqli_fetch_array($result)) 
         {
            echo "<tr>";
            echo "<td> $row[name]</td>";
            echo "<td> $row[roll]</td>";
            echo "</tr>";
         }
       echo "</table>";
 ?>

PHP removing a character in a string

I think that it's better to use simply str_replace, like the manual says:

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace().

<?
$badUrl = "http://www.site.com/backend.php?/c=crud&m=index&t=care";
$goodUrl = str_replace('?/', '?', $badUrl);

React - uncaught TypeError: Cannot read property 'setState' of undefined

Just change your bind statement from what you have to => this.delta = this.delta.bind(this);

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

The first parameter of Html.RadioButtonFor() should be the property name you're using, and the second parameter should be the value of that specific radio button. Then they'll have the same name attribute value and the helper will select the given radio button when/if it matches the property value.

Example:

<div class="editor-field">
    <%= Html.RadioButtonFor(m => m.Gender, "M" ) %> Male
    <%= Html.RadioButtonFor(m => m.Gender, "F" ) %> Female
</div>

Here's a more specific example:

I made a quick MVC project named "DeleteMeQuestion" (DeleteMe prefix so I know that I can remove it later after I forget about it).

I made the following model:

namespace DeleteMeQuestion.Models
{
    public class QuizModel
    {
        public int ParentQuestionId { get; set; }
        public int QuestionId { get; set; }
        public string QuestionDisplayText { get; set; }
        public List<Response> Responses { get; set; }

        [Range(1,999, ErrorMessage = "Please choose a response.")]
        public int SelectedResponse { get; set; }
    }

    public class Response
    {
        public int ResponseId { get; set; }
        public int ChildQuestionId { get; set; }
        public string ResponseDisplayText { get; set; }
    }
}

There's a simple range validator in the model, just for fun. Next up, I made the following controller:

namespace DeleteMeQuestion.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(int? id)
        {
            // TODO: get question to show based on method parameter 
            var model = GetModel(id);
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(int? id, QuizModel model)
        {
            if (!ModelState.IsValid)
            {
                var freshModel = GetModel(id);
                return View(freshModel);
            }

            // TODO: save selected answer in database
            // TODO: get next question based on selected answer (hard coded to 999 for now)

            var nextQuestionId = 999;
            return RedirectToAction("Index", "Home", new {id = nextQuestionId});
        }

        private QuizModel GetModel(int? questionId)
        {
            // just a stub, in lieu of a database

            var model = new QuizModel
            {
                QuestionDisplayText = questionId.HasValue ? "And so on..." : "What is your favorite color?",
                QuestionId = 1,
                Responses = new List<Response>
                                                {
                                                    new Response
                                                        {
                                                            ChildQuestionId = 2,
                                                            ResponseId = 1,
                                                            ResponseDisplayText = "Red"
                                                        },
                                                    new Response
                                                        {
                                                            ChildQuestionId = 3,
                                                            ResponseId = 2,
                                                            ResponseDisplayText = "Blue"
                                                        },
                                                    new Response
                                                        {
                                                            ChildQuestionId = 4,
                                                            ResponseId = 3,
                                                            ResponseDisplayText = "Green"
                                                        },
                                                }
            };

            return model;
        }
    }
}

Finally, I made the following view that makes use of the model:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DeleteMeQuestion.Models.QuizModel>" %>

<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">

    <% using (Html.BeginForm()) { %>

        <div>

            <h1><%: Model.QuestionDisplayText %></h1>

            <div>
            <ul>
            <% foreach (var item in Model.Responses) { %>
                <li>
                    <%= Html.RadioButtonFor(m => m.SelectedResponse, item.ResponseId, new {id="Response" + item.ResponseId}) %>
                    <label for="Response<%: item.ResponseId %>"><%: item.ResponseDisplayText %></label>
                </li>
            <% } %>
            </ul>

            <%= Html.ValidationMessageFor(m => m.SelectedResponse) %>

        </div>

        <input type="submit" value="Submit" />

    <% } %>

</asp:Content>

As I understand your context, you have questions with a list of available answers. Each answer will dictate the next question. Hopefully that makes sense from my model and TODO comments.

This gives you the radio buttons with the same name attribute, but different ID attributes.

What does "./" (dot slash) refer to in terms of an HTML file path location?

./ is the the folder that the working file is in:

So in /index.htm ./ is the root directory
but in /css/style.css ./ is the css folder.

This is important to remember because if you move CSS from /index.htm to /css/style.css the path will change.

Laravel 5.1 API Enable Cors

For me i put this codes in public\index.php file. and it worked just fine for all CRUD operations.

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");

Notepad++: Multiple words search in a file (may be in different lines)?

You need a new version of notepad++. Looks like old versions don't support |.

Note: egrep "CAT|TOWN" will search for lines containing CATOWN. (CAT)|(TOWN) is the proper or extension (matching 1,3,4). Strangely you wrote and which is btw (CAT.*TOWN)|(TOWN.*CAT)

Can Mockito capture arguments of a method called multiple times?

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive) - the code samples below require it to work:

import static org.mockito.Mockito.*;

In the verify() method you can pass the ArgumentCaptor to assure execution in the test and the ArgumentCaptor to evaluate the arguments:

ArgumentCaptor<MyExampleClass> argument = ArgumentCaptor.forClass(MyExampleClass.class);
verify(yourmock, atleast(2)).myMethod(argument.capture());

List<MyExampleClass> passedArguments = argument.getAllValues();

for (MyExampleClass data : passedArguments){
    //assertSometing ...
    System.out.println(data.getFoo());
}

The list of all passed arguments during your test is accessible via the argument.getAllValues() method.

The single (last called) argument's value is accessible via the argument.getValue() for further manipulation / checking or whatever you wish to do.

PivotTable's Report Filter using "greater than"

One way to do this is to pull your field into the rows section of the pivot table from the Filter section. Then group the values that you want to keep into a group, using the group option on the menu. After that is completed, drag your field back into the Filters section. The grouping will remain and you can check or uncheck one box to remove lots of values.

HttpClient 4.0.1 - how to release connection?

I'm chiming in with a detailed answer that specifically addresses Apache HttpClient 4.0.1. I'm using this HttpClient version, since it's provided by WAS v8.0, and I need to use that provided HttpClient within Apache Wink v1.1.1, also provided by WAS v8.0, to make some NTLM-authenticated REST calls to Sharepoint.

To quote Oleg Kalnichevski on the Apache HttpClient mailing list:

Pretty much all this code is not necessary. (1) HttpClient will automatically release the underlying connection as long as the entity content is consumed to the end of stream; (2) HttpClient will automatically release the underlying connection on any I/O exception thrown while reading the response content. No special processing is required in such as case.

In fact, this is perfectly sufficient to ensure proper release of resources:

HttpResponse rsp = httpclient.execute(target, req); 
HttpEntity entity = rsp.getEntity(); 
if (entity != null) {
     InputStream instream = entity.getContent();
     try {
         // process content
     } finally {
         instream.close();
         // entity.consumeContent() would also do
     } 
}

That is it.

Source

Meaning of "referencing" and "dereferencing" in C

The context that * is in, confuses the meaning sometimes.

  // when declaring a function
int function(int*); // This function is being declared as a function that takes in an 'address' that holds a number (so int*), it's asking for a 'reference', interchangeably called 'address'. When I 'call'(use) this function later, I better give it a variable-address! So instead of var, or q, or w, or p, I give it the address of var so &var, or &q, or &w, or &p.   

//even though the symbol ' * ' is typically used to mean 'dereferenced variable'(meaning: to use the value at the address of a variable)--despite it's common use, in this case, the symbol means a 'reference', again, in THIS context. (context here being the declaration of a 'prototype'.) 


    //when calling a function
int main(){ 
    function(&var);  // we are giving the function a 'reference', we are giving it an 'address'
  }

So, in the context of declaring a type such as int or char, we would use the dereferencer ' * ' to actually mean the reference (the address), which makes it confusing if you see an error message from the compiler saying: 'expecting char*' which is asking for an address.

In that case, when the * is after a type (int, char, etc.) the compiler is expecting a variable's address. We give it this by using a reference operator, alos called the address-of operator ' & ' before a variable. Even further, in the case I just made up above, the compiler is expecting the address to hold a character value, not a number. (type char * == address of a value that has a character)

int* p;
int *a;   // both are 'pointer' declarations. We are telling the compiler that we will soon give these variables an address (with &).

int c = 10;  //declare and initialize a random variable
//assign the variable to a pointer, we do this so that we can modify the value of c from a different function regardless of the scope of that function (elaboration in a second)

p = c; //ERROR, we assigned a 'value' to this 'pointer'. We need to assign an 'address', a 'reference'.
p = &c; // instead of a value such as: 'q',5,'t', or 2.1 we gave the pointer an 'address', which we could actually print with printf(), and would be something like
//so
p = 0xab33d111; //the address of c, (not specifically this value for the address, it'll look like this though, with the 0x in the beggining, the computer treats these different from regular numbers)
*p = 10; // the value of c

a = &c; // I can still give c another pointer, even though it already has the pointer variable "p"

*a = 10;
 a = 0xab33d111;

Think of each variable as having a position (or an index value if you are familiar with arrays) and a value. It might take some getting used-to to think of each variable having two values to it, one value being it's position, physically stored with electricity in your computer, and a value representing whatever quantity or letter(s) the programmer wants to store.

//Why it's used
int function(b){
    b = b + 1; // we just want to add one to any variable that this function operates on.
} 

int main(){

    int c = 1;  // I want this variable to be 3.

    function(c); 
    function(c);// I call the function I made above twice, because I want c to be 3.

     // this will return c as 1. Even though I called it twice.
     // when you call a function it makes a copy of the variable.
     // so the function that I call "function", made a copy of c, and that function is only changing the "copy" of c, so it doesn't affect the original
}
  //let's redo this whole thing, and use pointers

int function(int* b){ // this time, the function is 'asking' (won't run without) for a variable that 'points' to a number-value (int). So it wants an integer pointer--an address that holds a number.
*b = *b + 1; //grab the value of the address, and add one to the value stored at that address
}

int main(){
    int c = 1; //again, I want this to be three at the end of the program
    int *p = &c; // on the left, I'm declaring a pointer, I'm telling the compiler that I'm about to have this letter point to an certain spot in my computer. Immediately after I used the assignment operator (the ' = ') to assign the address of c to this variable (pointer in this case) p. I do this using the address-of operator (referencer)' & '.
    function(p); // not *p, because that will dereference. which would give an integer, not an integer pointer ( function wants a reference to an int called int*, we aren't going to use *p because that will give the function an int instead of an address that stores an int.

    function(&c); // this is giving the same thing as above, p = the address of c, so we can pass the 'pointer' or we can pass the 'address' that the pointer(variable) is 'pointing','referencing' to. Which is &c. 0xaabbcc1122...


      //now, the function is making a copy of c's address, but it doesn't matter if it's a copy or not, because it's going to point the computer to the exact same spot (hence, The Address), and it will be changed for main's version of c as well.

}

Inside each and every block, it copies the variables (if any) that are passed into (via parameters within "()"s). Within those blocks, the changes to a variable are made to a copy of that variable, the variable uses the same letters but is at a different address (from the original). By using the address "reference" of the original, we can change a variable using a block outside of main, or inside a child of main.

Return first N key:value pairs from dict

This depends on what is 'most efficient' in your case.

If you just want a semi-random sample of a huge dictionary foo, use foo.iteritems() and take as many values from it as you need, it's a lazy operation that avoids creation of an explicit list of keys or items.

If you need to sort keys first, there's no way around using something like keys = foo.keys(); keys.sort() or sorted(foo.iterkeys()), you'll have to build an explicit list of keys. Then slice or iterate through first N keys.

BTW why do you care about the 'efficient' way? Did you profile your program? If you did not, use the obvious and easy to understand way first. Chances are it will do pretty well without becoming a bottleneck.

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

JAVA_HOME should be like this C:\PROGRA~1\Java\jdk

Hope this will work!

Simulator or Emulator? What is the difference?

If a flight-simulator could transport you from A to B then it would be a flight-emulator.

An emulator can replace the original for real use.
A Virtual PC emulates a PC.

A simulator is a model for study and analysis.

An emulator will always have to operate close to real-time. For a simulator that is not always the case. A geological simulation could do 1000 years/second or more.

How do I concatenate strings?

2020 Update: Concatenation by String Interpolation

RFC 2795 issued 2019-10-27: Suggests support for implicit arguments to do what many people would know as "string interpolation" -- a way of embedding arguments within a string to concatenate them.

RFC: https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html

Latest issue status can be found here: https://github.com/rust-lang/rust/issues/67984

At the time of this writing (2020-9-24), I believe this feature should be available in the Rust Nightly build.

This will allow you to concatenate via the following shorthand:

format_args!("hello {person}")

It is equivalent to this:

format_args!("hello {person}", person=person)

There is also the "ifmt" crate, which provides its own kind of string interpolation:

https://crates.io/crates/ifmt

How to get values from selected row in DataGrid for Windows Form Application?

Description

Assuming i understand your question.

You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.

Sample

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Information

What's a good hex editor/viewer for the Mac?

The one that I like is HexEdit Quick and easy to use

Delete all duplicate rows Excel vba

There's a RemoveDuplicates method that you could use:

Sub DeleteRows()

    With ActiveSheet
        Set Rng = Range("A1", Range("B1").End(xlDown))
        Rng.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes
    End With

End Sub

How to compare datetime with only date in SQL Server

DON'T be tempted to do things like this:

Select * from [User] U where convert(varchar(10),U.DateCreated, 120) = '2014-02-07'

This is a better way:

Select * from [User] U 
where U.DateCreated >= '2014-02-07' and U.DateCreated < dateadd(day,1,'2014-02-07')

see: What does the word “SARGable” really mean?

EDIT + There are 2 fundamental reasons for avoiding use of functions on data in the where clause (or in join conditions).

  1. In most cases using a function on data to filter or join removes the ability of the optimizer to access an index on that field, hence making the query slower (or more "costly")
  2. The other is, for every row of data involved there is at least one calculation being performed. That could be adding hundreds, thousands or many millions of calculations to the query so that we can compare to a single criteria like 2014-02-07. It is far more efficient to alter the criteria to suit the data instead.

"Amending the criteria to suit the data" is my way of describing "use SARGABLE predicates"


And do not use between either.

the best practice with date and time ranges is to avoid BETWEEN and to always use the form:

WHERE col >= '20120101' AND col < '20120201' This form works with all types and all precisions, regardless of whether the time part is applicable.

http://sqlmag.com/t-sql/t-sql-best-practices-part-2 (Itzik Ben-Gan)

private final static attribute vs private final attribute

If you mark this variable static then as you know, you would be requiring static methods to again access these values,this will be useful if you already think of using these variables only in static methods. If this is so then this would be the best one.

You can however make the variable now as public since no one can modify it just like "System.out", it again depends upon your intentions and what you want to achieve.

Creating a LINQ select from multiple tables

change

select op) 

to

select new { op, pg })

Unable to auto-detect email address

With SmartGit, you can also edit them by going to Project > Repository settings and hitting the "Commit" tab (make sure to have "Remember as default" selected).

python how to "negate" value : if true return false, if false return true

In python, not is a boolean operator which gets the opposite of a value:

>>> myval = 0
>>> nyvalue = not myval
>>> nyvalue
True
>>> myval = 1
>>> nyvalue = not myval
>>> nyvalue
False

And True == 1 and False == 0 (if you need to convert it to an integer, you can use int())

How to include external Python code to use in other files?

Just write the "include" command :

import os

def include(filename):
    if os.path.exists(filename): 
        execfile(filename)


include('myfile.py')

@Deleet :

@bfieck remark is correct, for python 2 and 3 compatibility, you need either :

Python 2 and 3: alternative 1

from past.builtins import execfile

execfile('myfile.py')

Python 2 and 3: alternative 2

exec(compile(open('myfile.py').read()))

Pandas split column of lists into multiple columns

The above solutions didn't work for me since I have nan observations in my dataframe. In my case df2[['team1','team2']] = pd.DataFrame(df2.teams.values.tolist(), index= df2.index) yields:

object of type 'float' has no len()

I solve this using list comprehension. Here the replicable example:

import pandas as pd
import numpy as np
d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
            ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
df2.loc[2,'teams'] = np.nan
df2.loc[4,'teams'] = np.nan
df2

output:

        teams
0   [SF, NYG]
1   [SF, NYG]
2   NaN
3   [SF, NYG]
4   NaN
5   [SF, NYG]
6   [SF, NYG]

df2['team1']=np.nan
df2['team2']=np.nan

solving with list comprehension:

for i in [0,1]:
    df2['team{}'.format(str(i+1))]=[k[i] if isinstance(k,list) else k for k in df2['teams']]

df2

yields:

    teams   team1   team2
0   [SF, NYG]   SF  NYG
1   [SF, NYG]   SF  NYG
2   NaN        NaN  NaN
3   [SF, NYG]   SF  NYG
4   NaN        NaN  NaN
5   [SF, NYG]   SF  NYG
6   [SF, NYG]   SF  NYG

Generating PDF files with JavaScript

Even if you could generate the PDF in-memory in JavaScript, you would still have the issue of how to transfer that data to the user. It's hard for JavaScript to just push a file at the user.

To get the file to the user, you would want to do a server submit in order to get the browser to bring up the save dialog.

With that said, it really isn't too hard to generate PDFs. Just read the spec.

Stack, Static, and Heap in C++

A similar question was asked, but it didn't ask about statics.

Summary of what static, heap, and stack memory are:

  • A static variable is basically a global variable, even if you cannot access it globally. Usually there is an address for it that is in the executable itself. There is only one copy for the entire program. No matter how many times you go into a function call (or class) (and in how many threads!) the variable is referring to the same memory location.

  • The heap is a bunch of memory that can be used dynamically. If you want 4kb for an object then the dynamic allocator will look through its list of free space in the heap, pick out a 4kb chunk, and give it to you. Generally, the dynamic memory allocator (malloc, new, et c.) starts at the end of memory and works backwards.

  • Explaining how a stack grows and shrinks is a bit outside the scope of this answer, but suffice to say you always add and remove from the end only. Stacks usually start high and grow down to lower addresses. You run out of memory when the stack meets the dynamic allocator somewhere in the middle (but refer to physical versus virtual memory and fragmentation). Multiple threads will require multiple stacks (the process generally reserves a minimum size for the stack).

When you would want to use each one:

  • Statics/globals are useful for memory that you know you will always need and you know that you don't ever want to deallocate. (By the way, embedded environments may be thought of as having only static memory... the stack and heap are part of a known address space shared by a third memory type: the program code. Programs will often do dynamic allocation out of their static memory when they need things like linked lists. But regardless, the static memory itself (the buffer) is not itself "allocated", but rather other objects are allocated out of the memory held by the buffer for this purpose. You can do this in non-embedded as well, and console games will frequently eschew the built in dynamic memory mechanisms in favor of tightly controlling the allocation process by using buffers of preset sizes for all allocations.)

  • Stack variables are useful for when you know that as long as the function is in scope (on the stack somewhere), you will want the variables to remain. Stacks are nice for variables that you need for the code where they are located, but which isn't needed outside that code. They are also really nice for when you are accessing a resource, like a file, and want the resource to automatically go away when you leave that code.

  • Heap allocations (dynamically allocated memory) is useful when you want to be more flexible than the above. Frequently, a function gets called to respond to an event (the user clicks the "create box" button). The proper response may require allocating a new object (a new Box object) that should stick around long after the function is exited, so it can't be on the stack. But you don't know how many boxes you would want at the start of the program, so it can't be a static.

Garbage Collection

I've heard a lot lately about how great Garbage Collectors are, so maybe a bit of a dissenting voice would be helpful.

Garbage Collection is a wonderful mechanism for when performance is not a huge issue. I hear GCs are getting better and more sophisticated, but the fact is, you may be forced to accept a performance penalty (depending upon use case). And if you're lazy, it still may not work properly. At the best of times, Garbage Collectors realize that your memory goes away when it realizes that there are no more references to it (see reference counting). But, if you have an object that refers to itself (possibly by referring to another object which refers back), then reference counting alone will not indicate that the memory can be deleted. In this case, the GC needs to look at the entire reference soup and figure out if there are any islands that are only referred to by themselves. Offhand, I'd guess that to be an O(n^2) operation, but whatever it is, it can get bad if you are at all concerned with performance. (Edit: Martin B points out that it is O(n) for reasonably efficient algorithms. That is still O(n) too much if you are concerned with performance and can deallocate in constant time without garbage collection.)

Personally, when I hear people say that C++ doesn't have garbage collection, my mind tags that as a feature of C++, but I'm probably in the minority. Probably the hardest thing for people to learn about programming in C and C++ are pointers and how to correctly handle their dynamic memory allocations. Some other languages, like Python, would be horrible without GC, so I think it comes down to what you want out of a language. If you want dependable performance, then C++ without garbage collection is the only thing this side of Fortran that I can think of. If you want ease of use and training wheels (to save you from crashing without requiring that you learn "proper" memory management), pick something with a GC. Even if you know how to manage memory well, it will save you time which you can spend optimizing other code. There really isn't much of a performance penalty anymore, but if you really need dependable performance (and the ability to know exactly what is going on, when, under the covers) then I'd stick with C++. There is a reason that every major game engine that I've ever heard of is in C++ (if not C or assembly). Python, et al are fine for scripting, but not the main game engine.

Replacing instances of a character in a string

This should cover a slightly more general case, but you should be able to customize it for your purpose

def selectiveReplace(myStr):
    answer = []
    for index,char in enumerate(myStr):
        if char == ';':
            if index%2 == 1: # replace ';' in even indices with ":"
                answer.append(":")
            else:
                answer.append("!") # replace ';' in odd indices with "!"
        else:
            answer.append(char)
    return ''.join(answer)

Hope this helps

Free easy way to draw graphs and charts in C++?

Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.

Redirect from a view to another view

That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:

public ActionResult SomeAction()
{
    ...
    return RedirectToAction("SomeAction", "SomeController");
}

Now since I see that in your example you are attempting to redirect to the LogOn action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize] attribute:

[Authorize]
public ActionResult SomeProtectedAction()
{
    ...
}

Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl).

PHP Create and Save a txt file to root directory

If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT. This means that the path is dynamic, and can be moved between servers without messing about with the code.

<?php
  $fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
  $file = fopen($fileLocation,"w");
  $content = "Your text here";
  fwrite($file,$content);
  fclose($file);
?>

Using FileUtils in eclipse

FileUtils is class from apache org.apache.commons.io package, you need to download org.apache.commons.io.jar and then configure that jar file in your class path.

How to get domain URL and application name?

The web application name (actually the context path) is available by calling HttpServletrequest#getContextPath() (and thus NOT getServletPath() as one suggested before). You can retrieve this in JSP by ${pageContext.request.contextPath}.

<p>The context path is: ${pageContext.request.contextPath}.</p>

If you intend to use this for all relative paths in your JSP page (which would make this question more sense), then you can make use of the HTML <base> tag:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<c:set var="req" value="${pageContext.request}" />
<c:set var="url">${req.requestURL}</c:set>
<c:set var="uri" value="${req.requestURI}" />

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2204870</title>
        <base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/">
        <script src="js/global.js"></script>
        <link rel="stylesheet" href="css/global.css">
    </head>
    <body>
        <ul>
            <li><a href="home.jsp">Home</a></li>
            <li><a href="faq.jsp">FAQ</a></li>
            <li><a href="contact.jsp">Contact</a></li>
        </ul>
    </body>
</html>

All links in the page will then automagically be relative to the <base> so that you don't need to copypaste the context path everywhere. Note that when relative links start with a /, then they will not be relative to the <base> anymore, but to the domain root instead.

MySQL: Convert INT to DATETIME

The function STR_TO_DATE(COLUMN, '%input_format') can do it, you only have to specify the input format. Example : to convert p052011

SELECT STR_TO_DATE('p052011','p%m%Y') FROM your_table;

The result : 2011-05-00

How to check if object has any properties in JavaScript?

ES6 function

/**
 * Returns true if an object is empty.
 * @param  {*} obj the object to test
 * @return {boolean} returns true if object is empty, otherwise returns false
 */
const pureObjectIsEmpty = obj => obj && obj.constructor === Object && Object.keys(obj).length === 0

Examples:


let obj = "this is an object with String constructor"
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = {}
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = []
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = [{prop:"value"}]
console.log(pureObjectIsEmpty(obj)) // empty? true

obj = {prop:"value"}
console.log(pureObjectIsEmpty(obj)) // empty? false

Tools: replace not replacing in Android manifest

You can replace those in your Manifest application tag:

<application
    tools:replace="android:icon, android:label, android:theme, android:name,android:allowBackup"
android:allowBackup="false"...>

and will work for you.

How to resolve ORA 00936 Missing Expression Error?

Remove the coma at the end of your SELECT statement (VALUE,), and also remove the one at the end of your FROM statement (rrf b,)

ImportError: cannot import name NUMPY_MKL

The reason for the error is you upgraded your numpy library of which there are some functionalities from scipy that are required by the current version for it to run which may not be found in scipy. Just upgrade your scipy library using python -m pip install scipy --upgrade. I was facing the same error and this solution worked on my python 3.5.

Add/remove HTML inside div using JavaScript

Add HTML inside div using JavaScript

Syntax:

element.innerHTML += "additional HTML code"

or

element.innerHTML = element.innerHTML + "additional HTML code"

Remove HTML inside div using JavaScript

elementChild.remove();

Can I write into the console in a unit test? If yes, why doesn't the console window open?

NOTE: The original answer below should work for any version of Visual Studio up through Visual Studio 2012. Visual Studio 2013 does not appear to have a Test Results window any more. Instead, if you need test-specific output you can use @Stretch's suggestion of Trace.Write() to write output to the Output window.


The Console.Write method does not write to the "console" -- it writes to whatever is hooked up to the standard output handle for the running process. Similarly, Console.Read reads input from whatever is hooked up to the standard input.

When you run a unit test through Visual Studio 2010, standard output is redirected by the test harness and stored as part of the test output. You can see this by right-clicking the Test Results window and adding the column named "Output (StdOut)" to the display. This will show anything that was written to standard output.

You could manually open a console window, using P/Invoke as sinni800 says. From reading the AllocConsole documentation, it appears that the function will reset stdin and stdout handles to point to the new console window. (I'm not 100% sure about that; it seems kind of wrong to me if I've already redirected stdout for Windows to steal it from me, but I haven't tried.)

In general, though, I think it's a bad idea; if all you want to use the console for is to dump more information about your unit test, the output is there for you. Keep using Console.WriteLine the way you are, and check the output results in the Test Results window when it's done.

Efficient way to Handle ResultSet in Java

this is my alternative solution, instead of a List of Map, i'm using a Map of List. Tested on tables of 5000 elements, on a remote db, times are around 350ms for eiter method.

private Map<String, List<Object>> resultSetToArrayList(ResultSet rs) throws SQLException {
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    Map<String, List<Object>> map = new HashMap<>(columns);
    for (int i = 1; i <= columns; ++i) {
        map.put(md.getColumnName(i), new ArrayList<>());
    }
    while (rs.next()) {
        for (int i = 1; i <= columns; ++i) {
            map.get(md.getColumnName(i)).add(rs.getObject(i));
        }
    }

    return map;
}

Installing lxml module in python

Just do:

sudo apt-get install python-lxml

For Python 2 (e.g., required by Inkscape):

sudo apt-get install python2-lxml

If you are planning to install from source, then albertov's answer will help. But unless there is a reason, don't, just install it from the repository.

How can I convert an Integer to localized month name in Java?

tl;dr

Month                             // Enum class, predefining and naming a dozen objects, one for each month of the year. 
.of( 12 )                         // Retrieving one of the enum objects by number, 1-12. 
.getDisplayName(
    TextStyle.FULL_STANDALONE , 
    Locale.CANADA_FRENCH          // Locale determines the human language and cultural norms used in localizing. 
)

java.time

Since Java 1.8 (or 1.7 & 1.6 with the ThreeTen-Backport) you can use this:

Month.of(integerMonth).getDisplayName(TextStyle.FULL_STANDALONE, locale);

Note that integerMonth is 1-based, i.e. 1 is for January. Range is always from 1 to 12 for January-December (i.e. Gregorian calendar only).

Remove all classes that begin with a certain string

Prestaul's answer was helpful, but it didn't quite work for me. The jQuery way to select an object by id didn't work. I had to use

document.getElementById("a").className

instead of

$("#a").className

Python def function: How do you specify the end of the function?

Interestingly, if you're just typing at the python interactive interpreter, you have to follow a function with a blank line. This does not work:

def foo(x):
  return x+1
print "last"

although it is perfectly legal python syntax in a file. There are other syntactic differences when typing to the interpreter too, so beware.

How to set enum to null

Color? color = null;

or you can use

Color? color = new Color?();

example where assigning null wont work

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

so you can use :

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 

Java code for getting current time

I understand this is quite an old question. But would like to clarify that:

Date d = new Date() 

is depriciated in the current versions of Java. The recommended way is using a calendar object. For eg:

Calendar cal = Calendar.getInstance();
Date currentTime = cal.getTime();

I hope this will help people who may refer this question in future. Thank you all.

Ignore <br> with CSS?

While this question appears to already have been solved, the accepted answer didn't solve the problem for me on Firefox. Firefox (and possibly IE, though I haven't tried it) skip whitespaces while reading the contents of the "content" tag. While I completely understand why Mozilla would do that, it does bring its share of problems. The easiest workaround I found was to use non-breakable spaces instead of regular ones as shown below.

.noLineBreaks br:before{
content: '\a0'
}

Have a look.

How to write DataFrame to postgres table?

Pandas 0.24.0+ solution

In Pandas 0.24.0 a new feature was introduced specifically designed for fast writes to Postgres. You can learn more about it here: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method

import csv
from io import StringIO

from sqlalchemy import create_engine

def psql_insert_copy(table, conn, keys, data_iter):
    # gets a DBAPI connection that can provide a cursor
    dbapi_conn = conn.connection
    with dbapi_conn.cursor() as cur:
        s_buf = StringIO()
        writer = csv.writer(s_buf)
        writer.writerows(data_iter)
        s_buf.seek(0)

        columns = ', '.join('"{}"'.format(k) for k in keys)
        if table.schema:
            table_name = '{}.{}'.format(table.schema, table.name)
        else:
            table_name = table.name

        sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(
            table_name, columns)
        cur.copy_expert(sql=sql, file=s_buf)

engine = create_engine('postgresql://myusername:mypassword@myhost:5432/mydatabase')
df.to_sql('table_name', engine, method=psql_insert_copy)

How to detect input type=file "change" for the same file?

If you have tried .attr("value", "") and didn't work, don't panic (like I did)

just do .val("") instead, and will work fine

CodeIgniter -> Get current URL relative to base url

If url helper is loaded, use

current_url();

will be better

Find Locked Table in SQL Server

sp_lock

When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:

SELECT object_name(16003073)

EDIT :

There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/

C# Return Different Types?

You could use external class, set the properties types as you wish, then use it in your function.

public class MultipleOpjects
{
    private List<string> _ObjectOne;
    public List<string> ObjectOne {
        get { return _ObjectOne; }
        set { _ObjectOne = value; }
    }
    private List<object> _ObjectTwo;
    public List<object> ObjectTwo {
        get { return _ObjectTwo; }
        set { _ObjectTwo = value; }
    }
    private object _ObjectThree;
    public object ObjectThree {
        get { return _ObjectThree; }
        set { _ObjectThree = value; }
    }
}
public MultipleOpjects GetAnything()
{
    MultipleOpjects Vrble = new MultipleOpjects();
    Vrble.ObjectOne  = SomeThing1;
    Vrble.ObjectTwo = SomeThing2;
    Vrble.ObjectThree = SomeThing3;

    return Vrble;      
}

How to negate specific word in regex?

Unless performance is of utmost concern, it's often easier just to run your results through a second pass, skipping those that match the words you want to negate.

Regular expressions usually mean you're doing scripting or some sort of low-performance task anyway, so find a solution that is easy to read, easy to understand and easy to maintain.

Create html documentation for C# code

The above method for Visual Studio didn't seem to apply to Visual Studio 2013, but I was able to find the described checkbox using the Project Menu and selecting my project (probably the last item on the submenu) to get to the dialog with the checkbox (on the Build tab).

How to get full width in body element

You should set body and html to position:fixed;, and then set right:, left:, top:, and bottom: to 0;. That way, even if content overflows it will not extend past the limits of the viewport.

For example:

<html>
<body>
    <div id="wrapper"></div>
</body>
</html>

CSS:

html, body, {
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
}

JS Fiddle Example

Caveat: Using this method, if the user makes their window smaller, content will be cut off.

how to remove the bold from a headline?

style is accordingly vis css. An example

<h1 class="mynotsoboldtitle">Im not bold</h1>
<style>
.mynotsoboldtitle { font-weight:normal; }
</style>

The difference between Classes, Objects, and Instances

A class is a blueprint that is needed to make an object(= instance).

The difference between an object and an instance is, an object is a thing and an instance is a relation.

In other words, instance describes the relation of an object to the class that the object was made from.

Parse (split) a string in C++ using string delimiter (standard C++)

strtok allows you to pass in multiple chars as delimiters. I bet if you passed in ">=" your example string would be split correctly (even though the > and = are counted as individual delimiters).

EDIT if you don't want to use c_str() to convert from string to char*, you can use substr and find_first_of to tokenize.

string token, mystring("scott>=tiger");
while(token != mystring){
  token = mystring.substr(0,mystring.find_first_of(">="));
  mystring = mystring.substr(mystring.find_first_of(">=") + 1);
  printf("%s ",token.c_str());
}

How to go to a specific element on page?

If the element is currently not visible on the page, you can use the native scrollIntoView() method.

$('#div_' + element_id)[0].scrollIntoView( true );

Where true means align to the top of the page, and false is align to bottom.

Otherwise, there's a scrollTo() plugin for jQuery you can use.

Or maybe just get the top position()(docs) of the element, and set the scrollTop()(docs) to that position:

var top = $('#div_' + element_id).position().top;
$(window).scrollTop( top );

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

POST data to a URL in PHP

If you're looking to post data to a URL from PHP code itself (without using an html form) it can be done with curl. It will look like this:

$url = 'http://www.someurl.com';
$myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2;

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

This will send the post variables to the specified url, and what the page returns will be in $response.

How to make program go back to the top of the code instead of closing

def start():

Offset = 5

def getMode():
    while True:
        print('Do you wish to encrypt or decrypt a message?')
        mode = input().lower()
        if mode in 'encrypt e decrypt d'.split():
            return mode
        else:
            print('Please be sensible try just the lower case')

def getMessage():
    print('Enter your message wanted to :')
    return input()

def getKey():
    key = 0
    while True:
        print('Enter the key number (1-%s)' % (Offset))
        key = int(input())
        if (key >= 1 and key <= Offset):
            return key

def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            translated += chr(num)
        else:
            translated += symbol
    return translated

mode = getMode()
message = getMessage()
key = getKey()

print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
if op.lower() in {'q', 'quit', 'e', 'exit'}:
    print("Goodbye!")
    return

Float a DIV on top of another DIV

Use this css

.close-image {
    cursor: pointer;
    z-index: 3;
    right: 5px;
    top: 5px;
    position: absolute;
}

Convert double to float in Java

I suggest you to retrieve the value stored into the Database as BigDecimal type:

BigDecimal number = new BigDecimal("2.3423424666767E13");

int myInt = number.intValue();
double myDouble = number.doubleValue();

// your purpose
float myFloat = number.floatValue();

BigDecimal provide you a lot of functionalities.

What's the best way to loop through a set of elements in JavaScript?

I prefer the for loop as it's more readable. Looping from length to 0 would be more efficient than looping from 0 to length. And using a reversed while loop is more efficient than a foor loop as you said. I don't have the link to the page with comparison results anymore but I remember that the difference varied on different browsers. For some browser the reversed while loop was twice as fast. However it makes no difference if you're looping "small" arrays. In your example case the length of elements will be "small"

Center div on the middle of screen

2018: CSS3

div{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%);
}

This is even shorter. For more information see this: CSS: Centering Things

PHP - Get bool to echo false when false

No, since the other option is modifying the Zend engine, and one would be hard-pressed to call that a "better way".

Edit:

If you really wanted to, you could use an array:

$boolarray = Array(false => 'false', true => 'true');
echo $boolarray[false];

How to show PIL images on the screen?

If you find that PIL has problems on some platforms, using a native image viewer may help.

img.save("tmp.png") #Save the image to a PNG file called tmp.png.

For MacOS:

import os
os.system("open tmp.png") #Will open in Preview.

For most GNU/Linux systems with X.Org and a desktop environment:

import os
os.system("xdg-open tmp.png")

For Windows:

import os
os.system("powershell -c tmp.png")

Get list of passed arguments in Windows batch script (.bat)

%* seems to hold all of the arguments passed to the script.

How do I get the last four characters from a string in C#?

Compared to some previous answers, the main difference is that this piece of code takes into consideration when the input string is:

  1. Null
  2. Longer than or matching the requested length
  3. Shorter than the requested length.

Here it is:

public static class StringExtensions
{
    public static string Right(this string str, int length)
    {
        return str.Substring(str.Length - length, length);
    }

    public static string MyLast(this string str, int length)
    {
        if (str == null)
            return null;
        else if (str.Length >= length)
            return str.Substring(str.Length - length, length);
        else
            return str;
    }
}

Centering a background image, using CSS

background-repeat:no-repeat;
background-position:center center;

Does not vertically center the background image when using a html 4.01 'STRICT' doctype.

Adding:

background-attachment: fixed;

Should fix the problem

(So Alexander is right)

How do I measure execution time of a command on the Windows command line?

If you want

  1. To measure execution time down to the hundredth of a second in (hh:mm:ss.ff format)
  2. To not have to download and install a resource pack
  3. To look like a huge DOS nerd (who doesn't)

Try copying the following script into a new batch file (e.g. timecmd.bat):

@echo off
@setlocal

set start=%time%

:: Runs your command
cmd /c %*

set end=%time%
set options="tokens=1-4 delims=:.,"
for /f %options% %%a in ("%start%") do set start_h=%%a&set /a start_m=100%%b %% 100&set /a start_s=100%%c %% 100&set /a start_ms=100%%d %% 100
for /f %options% %%a in ("%end%") do set end_h=%%a&set /a end_m=100%%b %% 100&set /a end_s=100%%c %% 100&set /a end_ms=100%%d %% 100

set /a hours=%end_h%-%start_h%
set /a mins=%end_m%-%start_m%
set /a secs=%end_s%-%start_s%
set /a ms=%end_ms%-%start_ms%
if %ms% lss 0 set /a secs = %secs% - 1 & set /a ms = 100%ms%
if %secs% lss 0 set /a mins = %mins% - 1 & set /a secs = 60%secs%
if %mins% lss 0 set /a hours = %hours% - 1 & set /a mins = 60%mins%
if %hours% lss 0 set /a hours = 24%hours%
if 1%ms% lss 100 set ms=0%ms%

:: Mission accomplished
set /a totalsecs = %hours%*3600 + %mins%*60 + %secs%
echo command took %hours%:%mins%:%secs%.%ms% (%totalsecs%.%ms%s total)

Usage

If you put timecmd.bat in a directory in your path, you can call it from anywhere like this:

timecmd [your command]

E.g.

C:\>timecmd pause
Press any key to continue . . .
command took 0:0:1.18

If you want to do output redirection, you can quote the command like this:

timecmd "dir c:\windows /s > nul"

This should handle commands that run from before- to after-midnight, but the output will be wrong if your command runs for 24 hours or more.

Accessing localhost (xampp) from another computer over LAN network - how to?

If you are using XAMPP 1.8.3 Navigate to file httpd-xampp.conf and search for " # # New XAMPP security concept # server-status | server-info))">

     Require local
     ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
     </LocationMatch>

"

Cut this code and save it somewhere for later use i.e restoring this feature( remember removing this code makes your computer vulnerable). Save changes on httpd-xampp.conf, restart services on XAMPP and that's it.

What is the difference between java and core java?

"Core Java" is Sun's term, used to refer to Java SE, the standard edition and a set of related technologies, like the Java VM, CORBA, et cetera. This is mostly to differentiate from, say, Java ME or Java EE.

Also note that they're talking about a set of libraries rather than the programming language. That is, the underlying way you write Java doesn't change, regardless of the libraries you're using.

MySQL convert date string to Unix timestamp

For current date just use UNIX_TIMESTAMP() in your MySQL query.

Make a dictionary in Python from input values

n=int(input())
pair = dict()

for i in range(0,n):
        word = input().split()
        key = word[0]
        value = word[1]
        pair[key]=value

print(pair)

How do I prompt for Yes/No/Cancel input in a Linux shell script?

It is possible to handle a locale-aware "Yes / No choice" in a POSIX shell; by using the entries of the LC_MESSAGES locale category, witch provides ready-made RegEx patterns to match an input, and strings for localized Yes No.

#!/usr/bin/env sh

# Getting LC_MESSAGES values into variables
# shellcheck disable=SC2046 # Intended IFS splitting
IFS='
' set -- $(locale LC_MESSAGES)

yesexpr="$1"
noexpr="$2"
yesstr="$3"
nostr="$4"
messages_codeset="$5" # unused here, but kept as documentation

# Display Yes / No ? prompt into locale
echo "$yesstr / $nostr ?"

# Read answer
read -r yn

# Test answer
case "$yn" in
# match only work with the character class from the expression
  ${yesexpr##^}) echo "answer $yesstr" ;;
  ${noexpr##^}) echo "answer $nostr" ;;
esac

EDIT: As @Urhixidur mentioned in his comment:

Unfortunately, POSIX only specifies the first two (yesexpr and noexpr). On Ubuntu 16, yesstr and nostr are empty.

See: https://www.ee.ryerson.ca/~courses/ele709/susv4/xrat/V4_xbd_chap07.html#tag_21_07_03_06

LC_MESSAGES

The yesstr and nostr locale keywords and the YESSTR and NOSTR langinfo items were formerly used to match user affirmative and negative responses. In POSIX.1-2008, the yesexpr, noexpr, YESEXPR, and NOEXPR extended regular expressions have replaced them. Applications should use the general locale-based messaging facilities to issue prompting messages which include sample desired responses.

Alternatively using locales the Bash way:

#!/usr/bin/env bash

IFS=$'\n' read -r -d '' yesexpr noexpr _ < <(locale LC_MESSAGES)

printf -v yes_or_no_regex "(%s)|(%s)" "$yesexpr" "$noexpr"

printf -v prompt $"Please answer Yes (%s) or No (%s): " "$yesexpr" "$noexpr"

declare -- answer=;

until [[ "$answer" =~ $yes_or_no_regex ]]; do
  read -rp "$prompt" answer
done

if [[ -n "${BASH_REMATCH[1]}" ]]; then
  echo $"You answered: Yes"
else
  echo $"No, was your answer."
fi

The answer is matched using locale environment's provided regexps.

To translate the remaining messages, use bash --dump-po-strings scriptname to output the po strings for localization:

#: scriptname:8
msgid "Please answer Yes (%s) or No (%s): "
msgstr ""
#: scriptname:17
msgid "You answered: Yes"
msgstr ""
#: scriptname:19
msgid "No, was your answer."
msgstr ""

How to Inspect Element using Safari Browser

in menu bar click on Edit->preference->advance at bottom click the check box true that is for Show develop menu in menu bar now a develop menu is display at menu bar where you can see all develop option and inspect.

How to detect incoming calls, in an Android device?

this may helps you and also add require permision

public class PhoneListener extends PhoneStateListener
{
    private Context context;
    public static String getincomno;

    public PhoneListener(Context c) {
        Log.i("CallRecorder", "PhoneListener constructor");
        context = c;
    }

    public void onCallStateChanged (int state, String incomingNumber)
    {

        if(!TextUtils.isEmpty(incomingNumber)){
        // here for Outgoing number make null to get incoming number
        CallBroadcastReceiver.numberToCall = null;
        getincomno = incomingNumber;
        }

        switch (state) {
        case TelephonyManager.CALL_STATE_IDLE:

            break;
        case TelephonyManager.CALL_STATE_RINGING:
            Log.d("CallRecorder", "CALL_STATE_RINGING");
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:

            break;
        }
    }
}

Remove all whitespaces from NSString

This for me is the best way SWIFT

        let myString = "  ciao   \n              ciao     "
        var finalString = myString as NSString

        for character in myString{
        if character == " "{

            finalString = finalString.stringByReplacingOccurrencesOfString(" ", withString: "")

        }else{
            finalString = finalString.stringByReplacingOccurrencesOfString("\n", withString: "")

        }

    }
     println(finalString)

and the result is : ciaociao

But the trick is this!

 extension String {

    var NoWhiteSpace : String {

    var miaStringa = self as NSString

    if miaStringa.containsString(" "){

      miaStringa =  miaStringa.stringByReplacingOccurrencesOfString(" ", withString: "")
    }
        return miaStringa as String

    }
}

let myString = "Ciao   Ciao       Ciao".NoWhiteSpace  //CiaoCiaoCiao

Easiest way to copy a table from one database to another?

Use MySql Workbench's Export and Import functionality. Steps:
1. Select the values you want

E.g. select * from table1; 
  1. Click on the Export button and save it as CSV.
  2. create a new table using similar columns as the first one

    E.g. create table table2 like table1; 
    
  3. select all from the new table

    E.g. select * from table2;  
    
  4. Click on Import and select the CSV file you exported in step 2

Sample of the Export and Import buttons in MySql Workbench

How to check if click event is already bound - JQuery

The best way I see is to use live() or delegate() to capture the event in a parent and not in each child element.

If your button is inside a #parent element, you can replace:

$('#myButton').bind('click', onButtonClicked);

by

$('#parent').delegate('#myButton', 'click', onButtonClicked);

even if #myButton doesn't exist yet when this code is executed.

Array copy values to keys in PHP

Be careful, the solution proposed with $a = array_combine($a, $a); will not work for numeric values.

I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384) to be the keys as well as the values however PHP manual states:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

So I solved it like this:

foreach($array as $key => $val) {
    $new_array[$val]=$val;
}

What does "#pragma comment" mean?

I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.

Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.

Pragma Directives It includes "#pragma comment" in the table you'll see.

HTH

I suspect GCC, for example, has their own set of #pragma's.

Show week number with Javascript?

By adding the snippet you extend the Date object.

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(),0,1);
    return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}

If you want to use this in multiple pages you can add this to a seperate js file which must be loaded first before your other scripts executes. With other scripts I mean the scripts which uses the getWeek() method.

Does Python have a ternary conditional operator?

You can index into a tuple:

(falseValue, trueValue)[test]

test needs to return True or False.
It might be safer to always implement it as:

(falseValue, trueValue)[test == True]

or you can use the built-in bool() to assure a Boolean value:

(falseValue, trueValue)[bool(<expression>)]

CSS background-image - What is the correct usage?

You don't need to use quotes and you can use any path you like!

Get JSON Data from URL Using Android?

My fairly short code to read JSON from an URL. (requires Guava due to usage of CharStreams).

    private static class VersionTask extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... strings) {
            String result = null;
            URL url;
            HttpURLConnection connection = null;
            try {
                url = new URL("https://api.github.com/repos/user_name/repo_name/releases/latest");
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                result = CharStreams.toString(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8));
            } catch (IOException e) {
                Log.d("VersionTask", Log.getStackTraceString(e));
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result != null) {
                String version = "";
                try {
                    version = new JSONObject(result).optString("tag_name").trim();
                } catch (JSONException e) {
                    Log.e("VersionTask", Log.getStackTraceString(e));
                }
                if (version.startsWith("v")) {
                    //process version
                }
            }
        }
    }

PS: This code gets the latest release version (based on tag name) for a given GitHub repo.

Assert a function/method was not called using Mock

Though an old question, I would like to add that currently mock library (backport of unittest.mock) supports assert_not_called method.

Just upgrade yours;

pip install mock --upgrade

Could not create SSL/TLS secure channel, despite setting ServerCertificateValidationCallback

TLS 1.0 and 1.1 are now End of Life. A package on our Amazon web server updated, and we started getting this error.

The answer is above, but you shouldn't use tls or tls11 anymore.

Specifically for ASP.Net, add this to one of your startup methods.

        public Startup()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;

but I'm sure that something like this will work in many other cases.

Instantly detect client disconnection from server socket

Since there are no events available to signal when the socket is disconnected, you will have to poll it at a frequency that is acceptable to you.

Using this extension method, you can have a reliable method to detect if a socket is disconnected.

static class SocketExtensions
{
  public static bool IsConnected(this Socket socket)
  {
    try
    {
      return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
    }
    catch (SocketException) { return false; }
  }
}

How to convert CLOB to VARCHAR2 inside oracle pl/sql

Converting VARCHAR2 to CLOB

In PL/SQL a CLOB can be converted to a VARCHAR2 with a simple assignment, SUBSTR, and other methods. A simple assignment will only work if the CLOB is less then or equal to the size of the VARCHAR2. The limit is 32767 in PL/SQL and 4000 in SQL (although 12c allows 32767 in SQL).

For example, this code converts a small CLOB through a simple assignment and then coverts the beginning of a larger CLOB.

declare
    v_small_clob clob := lpad('0', 1000, '0');
    v_large_clob clob := lpad('0', 32767, '0') || lpad('0', 32767, '0');
    v_varchar2   varchar2(32767);
begin
    v_varchar2 := v_small_clob;
    v_varchar2 := substr(v_large_clob, 1, 32767);
end;

LONG?

The above code does not convert the value to a LONG. It merely looks that way because of limitations with PL/SQL debuggers and strings over 999 characters long.

For example, in PL/SQL Developer, open a Test window and add and debug the above code. Right-click on v_varchar2 and select "Add variable to Watches". Step through the code and the value will be set to "(Long Value)". There is a ... next to the text but it does not display the contents. PLSQL Developer Long Value

C#?

I suspect the real problem here is with C# but I don't know how enough about C# to debug the problem.

What is the difference between mocking and spying when using Mockito?

If there is an object with 8 methods and you have a test where you want to call 7 real methods and stub one method you have two options:

  1. Using a mock you would have to set it up by invoking 7 callRealMethod and stub one method
  2. Using a spy you have to set it up by stubbing one method

The official documentation on doCallRealMethod recommends using a spy for partial mocks.

See also javadoc spy(Object) to find out more about partial mocks. Mockito.spy() is a recommended way of creating partial mocks. The reason is it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.

MongoDB and "joins"

It's no join since the relationship will only be evaluated when needed. A join (in a SQL database) on the other hand will resolve relationships and return them as if they were a single table (you "join two tables into one").

You can read more about DBRef here: http://docs.mongodb.org/manual/applications/database-references/

There are two possible solutions for resolving references. One is to do it manually, as you have almost described. Just save a document's _id in another document's other_id, then write your own function to resolve the relationship. The other solution is to use DBRefs as described on the manual page above, which will make MongoDB resolve the relationship client-side on demand. Which solution you choose does not matter so much because both methods will resolve the relationship client-side (note that a SQL database resolves joins on the server-side).

Android ListView Selector Color

TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)

Here is the FIX for 2.3 and below when using colours:

As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape drawable containing the colour you want, and to use that instead of the colour.

I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).

How do I clear a search box with an 'x' in bootstrap 3?

Thanks unwired your solution was very clean. I was using horizontal bootstrap forms and made a couple modifications to allow for a single handler and form css.

html: - UPDATED to use Bootstrap's has-feedback and form-control-feedback

 <div class="container">
  <form class="form-horizontal">
   <div class="form-group has-feedback">
    <label for="txt1" class="col-sm-2 control-label">Label 1</label>
    <div class="col-sm-10">
     <input id="txt1" type="text" class="form-control hasclear" placeholder="Textbox 1">
     <span class="clearer glyphicon glyphicon-remove-circle form-control-feedback"></span>
    </div>
   </div>
   <div class="form-group has-feedback">
    <label for="txt2" class="col-sm-2 control-label">Label 2</label>
    <div class="col-sm-10">
      <input id="txt2" type="text" class="form-control hasclear" placeholder="Textbox 2">
      <span class="clearer glyphicon glyphicon-remove-circle form-control-feedback"></span>
    </div>
   </div>
   <div class="form-group has-feedback">
    <label for="txt3" class="col-sm-2 control-label">Label 3</label>
    <div class="col-sm-10">
     <input id="txt3" type="text" class="form-control hasclear" placeholder="Textbox 3">
     <span class="clearer glyphicon glyphicon-remove-circle form-control-feedback"></span>
    </div>   
   </div>
  </form>
 </div>

javascript:

$(".hasclear").keyup(function () {
    var t = $(this);
    t.next('span').toggle(Boolean(t.val()));
});
$(".clearer").hide($(this).prev('input').val());
$(".clearer").click(function () {
    $(this).prev('input').val('').focus();
    $(this).hide();
});

example: http://www.bootply.com/130682

How to fully delete a git repository created with init?

To fully delete the .git repository in your computer (in Windows 8 and above):

  1. The .git repository is normally hidden in windows
  2. So you need to mark the "hidden items" to show the hidden folders
  3. At the top site of you directory you find "view" option
  4. Inside "view" option you find "hidden items" and mark it
  5. Then you see the .git repository then you can delete it

How do I get a substring of a string in Python?

A common way to achieve this is by string slicing.

MyString[a:b] gives you a substring from index a to (b - 1).

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

You should simply create your own folder in htdocs and save your .html and .php files in it. An example is create a folder called myNewFolder directly in htdocs. Don't put it in index.html. Then save all your.html and .php files in it like this-> "localhost/myNewFolder/myFilename.html" or "localhost/myNewFolder/myFilename.php" I hope this helps.

Using relative URL in CSS file, what location is it relative to?

One issue that can occur, and seemingly break this is when using auto minimization of css. The request path for the minified bundle can have a different path than the original css. This may happen automatically so it can cause confusion.

The mapped request path for the minified bundle should be "/originalcssfolder/minifiedbundlename" not just "minifiedbundlename".

In other words, name your bundles to have same path (with the /) as the original folder structure, this way any external resources like fonts, images will map to correct URIs by the browser. The alternative is to use absolute url( refs in your css but that isn't usually desirable.

Convert Mongoose docs to json

Try this options:

  UserModel.find({}, function (err, users) {
    //i got into errors using so i changed to res.send()
    return res.send( JSON.parse(JSON.stringify(users)) );
    //Or
    //return JSON.parse(JSON.stringify(users));
  }

How to access random item in list?

ArrayList ar = new ArrayList();
        ar.Add(1);
        ar.Add(5);
        ar.Add(25);
        ar.Add(37);
        ar.Add(6);
        ar.Add(11);
        ar.Add(35);
        Random r = new Random();
        int index = r.Next(0,ar.Count-1);
        MessageBox.Show(ar[index].ToString());

Java: recommended solution for deep cloning/copying an instance

Joshua Bloch's book has a whole chapter entitled "Item 10: Override Clone Judiciously" in which he goes into why overriding clone for the most part is a bad idea because the Java spec for it creates many problems.

He provides a few alternatives:

  • Use a factory pattern in place of a constructor:

         public static Yum newInstance(Yum yum);
    
  • Use a copy constructor:

         public Yum(Yum yum);
    

All of the collection classes in Java support the copy constructor (e.g. new ArrayList(l);)

Encrypt Password in Configuration Files?

Check out jasypt, which is a library offering basic encryption capabilities with minimum effort.

Delete all documents from index/type without deleting type

The Delete-By-Query plugin has been removed in favor of a new Delete By Query API implementation in core. Read here

curl -XPOST 'localhost:9200/twitter/tweet/_delete_by_query?conflicts=proceed&pretty' -H 'Content-Type: application/json' -d'
{
    "query": {
        "match_all": {}
    }
}'

Gradient of n colors ranging from color 1 and color 2

Just to expand on the previous answer colorRampPalettecan handle more than two colors.

So for a more expanded "heat map" type look you can....

colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)

The resulting image:

enter image description here

How to make/get a multi size .ico file?

I found an app for Mac OSX called ICOBundle that allows you to easily drop a selection of ico files in different sizes onto the ICOBundle.app, prompts you for a folder destination and file name, and it creates the multi-icon .ico file.

Now if it were only possible to mix-in an animated gif version into that one file it'd be a complete icon set, sadly not possible and requires a separate file and code snippet.

Get all table names of a particular database by SQL query?

In our Oracle DB (PL/SQL) below code working to get the list of all exists tables in our DB.

select * from tab;

and

select table_name from tabs;

both are working. let's try and find yours.

Spacing between elements

In general we use margins on one of the elements, not spacer elements.

Linux Process States

Yes, the task gets blocked in the read() system call. Another task which is ready runs, or if no other tasks are ready, the idle task (for that CPU) runs.

A normal, blocking disc read causes the task to enter the "D" state (as others have noted). Such tasks contribute to the load average, even though they're not consuming the CPU.

Some other types of IO, especially ttys and network, do not behave quite the same - the process ends up in "S" state and can be interrupted and doesn't count against the load average.

Sending JSON to PHP using ajax

That's because $_POST is pre-populated with form data.

To get JSON data (or any raw input), use php://input.

$json = json_decode(file_get_contents("php://input"));

Create component to specific module with Angular-CLI

For Angular v4 and Above, simply use:

ng g c componentName -m ModuleName

Pretty-Print JSON in Java

Update: new JsonParser().parse(...) is @deprecated


Based on the javadoc for Gson 2.8.6:

No need to instantiate this class, use the static methods instead.

JsonParser static methods:

JsonParser.parseString?(jsonString);
JsonParser.parseReader?(reader);

Packages:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;

Example:

private Gson GSON = new GsonBuilder().setPrettyPrinting().create();
public static String getPerfectJSON(String unformattedJSON) {
    String perfectJSON = GSON.toJson(JsonParser.parseString(unformattedJSON));
    return perfectJSON;
}

Google Gson dependency using Maven:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>

Reference:

How to wait for all threads to finish, using ExecutorService?

you should use executorService.shutdown() and executorService.awaitTermination method.

An example as follows :

public class ScheduledThreadPoolExample {

    public static void main(String[] args) throws InterruptedException {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5);
        executorService.scheduleAtFixedRate(() -> System.out.println("process task."),
                0, 1, TimeUnit.SECONDS);

        TimeUnit.SECONDS.sleep(10);
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.DAYS);
    }

}

Suppress output of a function

invisible(cat("Dataset: ", dataset, fill = TRUE))
invisible(cat(" Width: " ,width, fill = TRUE))
invisible(cat(" Bin1:  " ,bin1interval, fill = TRUE))
invisible(cat(" Bin2:  " ,bin2interval, fill = TRUE))
invisible(cat(" Bin3:  " ,bin3interval, fill = TRUE))

produces output without NULL at the end of the line or on the next line

Dataset:  17 19 26 29 31 32 34 45 47 51 52 59 60 62 63
Width:  15.33333

Bin1:   17 32.33333
Bin2:   32.33333 47.66667
Bin3:   47.66667 63

Fetching data from MySQL database using PHP, Displaying it in a form for editing

<form action="Delegate_update.php" method="post">
Name
<input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
Username
<input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
Password
<input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
<input type="submit" name= "submit" value="Update">
</form>

You didnt closed your opening Form in the first place, plus your code is very very messy. I wont go into the "use pdo or mysqli statements, instead of mysql" thats for you to find out on yourself. Also you have a php tag open and close below it, not sure what is needed there. Something else is that your code refers to an external page, which you didnt post, so if something isnt working there, might be handy to post it too.

Please also note that you had spaces between your $row array variables in the form. You have to link those up together by removing the space (see edited section from me). PHP isn't forgiving when it comes to those mistakes.

Then your HTML. I took the liberty to correct that too

<html>
    <head>
        <title> Delegate edit form</title>
    </head>

    <body>
          <p>Delegate update form</p>
<?php
$usernm="root";
$passwd="";
$host="localhost";
$database="swift";

mysql_connect($host,$usernm,$passwd); 
mysql_select_db($database);

$sql = "SELECT * FROM usermaster WHERE User_name='".$Username."'"; // Please look at this too.
$result = mysql_query($sql) or die (mysql_error()); // dont put spaces in between it, else your code wont recognize it the query that needs to be executed
while ($row = mysql_fetch_array($result)){     // here too, you put a space between it
    $Name=$row['Name'];
    $Username=$row['User_name'];
    $Password=$row['User_password'];
    }
?>

Also, try to be specific. "It doesnt work" doesnt help us much, a specific error type is commonly helpful, plus any indication what the code should do (well, it was kinda obvious here, since its a login/register edit here, but for larger chunks of code it should always be explained)

Anyway, welcome to Stack Overflow

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

Actually your Windows firewall is blocking the connection. You need to enter these commands into cmd.exe from Administrator.

netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=tcp
netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=udp

In case something goes wrong then you can revert by this:

netsh advfirewall firewall delete rule name="FTP" program=%SystemRoot%\System32\ftp.exe

What is the syntax of the enhanced for loop in Java?

Enhanced for loop:

for (String element : array) {

    // rest of code handling current element
}

Traditional for loop equivalent:

for (int i=0; i < array.length; i++) {
    String element = array[i]; 

    // rest of code handling current element
}

Take a look at these forums: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html

How to get Javascript Select box's selected text

Just use

$('#SelectBoxId option:selected').text(); For Getting text as listed

$('#SelectBoxId').val(); For Getting selected Index value

How to make a simple rounded button in Storyboard?

The extension is the best option for this problem. Create an extension of View or Button

public extension UIView {
  //Round the corners
  func roundCorners(){
    let radius = bounds.maxX / 16
    layer.cornerRadius = radius
  }
}

Call it from the code

button.roundCorners()

Remove first 4 characters of a string with PHP

If you’re using a multi-byte character encoding and do not just want to remove the first four bytes like substr does, use the multi-byte counterpart mb_substr. This does of course will also work with single-byte strings.

Regular Expression to get a string between parentheses in Javascript

Try string manipulation:

var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var newTxt = txt.split('(');
for (var i = 1; i < newTxt.length; i++) {
    console.log(newTxt[i].split(')')[0]);
}

or regex (which is somewhat slow compare to the above)

var txt = "I expect five hundred dollars ($500). and new brackets ($600)";
var regExp = /\(([^)]+)\)/g;
var matches = txt.match(regExp);
for (var i = 0; i < matches.length; i++) {
    var str = matches[i];
    console.log(str.substring(1, str.length - 1));
}

Download/Stream file from URL - asp.net

2 years later, I used Dallas' answer, but I had to change the HttpWebRequest to FileWebRequest since I was linking to direct files. Not sure if this is the case everywhere, but I figured I'd add it. Also, I removed

var resp = Http.Current.Resonse

and just used Http.Current.Response in place wherever resp was referenced.

How to style the menu items on an Android action bar

I know its an old post, but just in case anyone is looking here. I added this to my style.xml and it worked for me.

<!-- This is the main theme parent -->
<style name="MyTabStyle">
    <item name="android:actionBarTabTextStyle">@style/MyTabTextStyle</item>
</style>

<style name="MyTabTextStyle" parent="@android:style/Widget.ActionBar.TabText">
    <item name="android:textAppearance">@android:style/TextAppearance.Medium</item>
    <item name="android:textSize">14sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">@color/pressed_skylogtheme</item>
</style>

How to correctly get image from 'Resources' folder in NetBeans

I have a slightly different approach that might be useful/more beneficial to some.

Under your main project folder, create a resource folder. Your folder structure should look something like this.

  • Project Folder
    • build
    • dist
    • lib
    • nbproject
    • resources
    • src

Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.

Under categories on the left side, select Sources.

In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.

enter image description here

You should now be able to pull resources using this line or similar approach:

MyClass.class.getResource("/main.jpg");

If you were to create a package called Images under the resources folder, you can retrieve the resource like this:

MyClass.class.getResource("/Images/main.jpg");

Combine :after with :hover

Just append :after to your #alertlist li:hover selector the same way you do with your #alertlist li.selected selector:

#alertlist li.selected:after, #alertlist li:hover:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}

How to determine total number of open/active connections in ms sql server 2005

SELECT
[DATABASE] = DB_NAME(DBID), 
OPNEDCONNECTIONS =COUNT(DBID),
[USER] =LOGINAME
FROM SYS.SYSPROCESSES
GROUP BY DBID, LOGINAME
ORDER BY DB_NAME(DBID), LOGINAME

"This project is incompatible with the current version of Visual Studio"

I had this issue and after hours of uninstalling and reinstalling I found out the issue in my instance.

The reason why I got this was down to the fact that I didn't have the correct extension.

In my case the ASP.net project (my startup) was the incompatible project and this was because I didn't have the following:

  • Microsoft ASP.NET and Web Tools
  • Micrsoft ASP.NET Web Frameworks and Tools

It was a simple case of going into extensions and updates under the Tools menu

TypeError: tuple indices must be integers, not str

Like the error says, row is a tuple, so you can't do row["pool_number"]. You need to use the index: row[0].

What is w3wp.exe?

Chris pretty much sums up what w3wp is. In order to disable the warning, go to this registry key:

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Debugger

And set the value DisableAttachSecurityWarning to 1.

How to use git merge --squash?

Your feature branch is done and ready to commit to master, develop or other target branch with only one commit

  • Go to merge branch : git checkout master && git pull
  • Create a work branch from your clean local master : git checkout -b work
  • Merge squash your feature branch on work : git merge --squash your_feature_branch.
  • Commit with default or a new message : git commit (with a specific or default message)
  • Go back to your feature branch : git checkout your_feature_branch
  • Point your feature branch to work dir : git reset --hard work
  • Verify but you are ready to push : git push -f
  • Then clean up work branch if needed

Replace master with your target branch : develop and so on

  • No need to specify how many commit from your master to your feature branch. Git takes care*

How to convert Django Model object to dict with its fields and values?

Update

The newer aggregated answer posted by @zags is more complete and elegant than my own. Please refer to that answer instead.

Original

If you are willing to define your own to_dict method like @karthiker suggested, then that just boils this problem down to a sets problem.

>>># Returns a set of all keys excluding editable = False keys
>>>dict = model_to_dict(instance)
>>>dict

{u'id': 1L, 'reference1': 1L, 'reference2': [1L], 'value': 1}


>>># Returns a set of editable = False keys, misnamed foreign keys, and normal keys
>>>otherDict = SomeModel.objects.filter(id=instance.id).values()[0]
>>>otherDict

{'created': datetime.datetime(2014, 2, 21, 4, 38, 51, tzinfo=<UTC>),
 u'id': 1L,
 'reference1_id': 1L,
 'value': 1L,
 'value2': 2L}

We need to remove the mislabeled foreign keys from otherDict.

To do this, we can use a loop that makes a new dictionary that has every item except those with underscores in them. Or, to save time, we can just add those to the original dict since dictionaries are just sets under the hood.

>>>for item in otherDict.items():
...    if "_" not in item[0]:
...            dict.update({item[0]:item[1]})
...
>>>

Thus we are left with the following dict:

>>>dict
{'created': datetime.datetime(2014, 2, 21, 4, 38, 51, tzinfo=<UTC>),
 u'id': 1L,
 'reference1': 1L,
 'reference2': [1L],
 'value': 1,
 'value2': 2L}

And you just return that.

On the downside, you can't use underscores in your editable=false field names. On the upside, this will work for any set of fields where the user-made fields do not contain underscores.

This is not the best way of doing this, but it could work as a temporary solution until a more direct method is found.

For the example below, dict would be formed based on model_to_dict and otherDict would be formed by filter's values method. I would have done this with the models themselves, but I can't get my machine to accept otherModel.

>>> import datetime
>>> dict = {u'id': 1, 'reference1': 1, 'reference2': [1], 'value': 1}
>>> otherDict = {'created': datetime.datetime(2014, 2, 21, 4, 38, 51), u'id': 1, 'reference1_id': 1, 'value': 1, 'value2': 2}
>>> for item in otherDict.items():
...     if "_" not in item[0]:
...             dict.update({item[0]:item[1]})
...
>>> dict
{'reference1': 1, 'created': datetime.datetime(2014, 2, 21, 4, 38, 51), 'value2': 2, 'value': 1, 'id': 1, 'reference2': [1]}
>>>

That should put you in a rough ballpark of the answer to your question, I hope.

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

I'm using DotNet Core MVC and after fighting for a few hours with nuget packages, Startup.cs, attributes, and this place, I simply added this to the MVC action:

Response.Headers.Add("Access-Control-Allow-Origin", "*");

I realise this is pretty clunky, but it's all I needed, and nothing else wanted to add those headers. I hope this helps someone else!

How to ignore certain files in Git

You should write something like

*.class

into your .gitignore file.

Remove values from select list based on condition

Give an id for the select object like this:

<select id="mySelect" name="val" size="1" >
    <option value="A">Apple</option>
    <option value="C">Cars</option>
    <option value="H">Honda</option>
    <option value="F">Fiat</option>
    <option value="I">Indigo</option>                    
</select> 

You can do it in pure JavaScript:

var selectobject = document.getElementById("mySelect");
for (var i=0; i<selectobject.length; i++) {
    if (selectobject.options[i].value == 'A')
        selectobject.remove(i);
}

But - as the other answers suggest - it's a lot easier to use jQuery or some other JS library.

How to bind a List<string> to a DataGridView control?

An alternate is to use a new helper function which will take values from List and update in the DataGridView as following:

    private void DisplayStringListInDataGrid(List<string> passedList, ref DataGridView gridToUpdate, string newColumnHeader)
    {
        DataTable gridData = new DataTable();
        gridData.Columns.Add(newColumnHeader);

        foreach (string listItem in passedList)
        {
            gridData.Rows.Add(listItem);
        }

        BindingSource gridDataBinder = new BindingSource();
        gridDataBinder.DataSource = gridData;
        dgDataBeingProcessed.DataSource = gridDataBinder;
    }

Then we can call this function the following way:

    DisplayStringListInDataGrid(<nameOfListWithStrings>, ref <nameOfDataGridViewToDisplay>, <nameToBeGivenForTheNewColumn>);

Installing R with Homebrew

homebrew/science was deprecated So, you should use the following command.

brew tap brewsci/science

'True' and 'False' in Python

While the other posters addressed why is True does what it does, I wanted to respond to this part of your post:

I thought Python treats anything with value as True. Why is this happening?

Coming from Java, I got tripped up by this, too. Python does not treat anything with a value as True. Witness:

if 0:
    print("Won't get here")

This will print nothing because 0 is treated as False. In fact, zero of any numeric type evaluates to False. They also made decimal work the way you'd expect:

from decimal import *
from fractions import *

if 0 or 0.0 or 0j or Decimal(0) or Fraction(0, 1):
    print("Won't get here")

Here are the other value which evaluate to False:

if None or False or '' or () or [] or {} or set() or range(0):
    print("Won't get here")

Sources:

  1. Python Truth Value Testing is Awesome
  2. Truth Value Testing (in Built-in Types)

Storing Objects in HTML5 localStorage

You cannot store key value without String Format.

LocalStorage only support String format for key/value.

That is why you should convert your data to string whatever it is Array or Object.

To Store data in localStorage first of all stringify it using JSON.stringify() method.

var myObj = [{name:"test", time:"Date 2017-02-03T08:38:04.449Z"}];
localStorage.setItem('item', JSON.stringify(myObj));

Then when you want to retrieve data , you need to parse the String to Object again.

var getObj = JSON.parse(localStorage.getItem('item'));

Hope it helps.

How can I list all cookies for the current page with Javascript?

Some cookies, such as referrer urls, have = in them. As a result, simply splitting on = will cause irregular results, and the previous answers here will breakdown over time (or immediately depending on your depth of use).

This takes only the first instance of the equals sign. It returns an object with the cookie's key value pairs.

// Returns an object of key value pairs for this page's cookies
function getPageCookies(){

    // cookie is a string containing a semicolon-separated list, this split puts it into an array
    var cookieArr = document.cookie.split(";");

    // This object will hold all of the key value pairs
    var cookieObj = {};

    // Iterate the array of flat cookies to get their key value pair
    for(var i = 0; i < cookieArr.length; i++){

        // Remove the standardized whitespace
        var cookieSeg = cookieArr[i].trim();

        // Index of the split between key and value
        var firstEq = cookieSeg.indexOf("=");

        // Assignments
        var name = cookieSeg.substr(0,firstEq);
        var value = cookieSeg.substr(firstEq+1);
        cookieObj[name] = value;
   }
   return cookieObj;
}

C# 4.0: Convert pdf to byte[] and vice versa

using (FileStream fs = new FileStream("sample.pdf", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[fs.Length];
                int numBytesToRead = (int)fs.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    // Read may return anything from 0 to numBytesToRead.
                    int n = fs.Read(bytes, numBytesRead, numBytesToRead);

                    // Break when the end of the file is reached.
                    if (n == 0)
                    {
                        break;
                    }

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
}

SQL: Insert all records from one table to another table without specific the columns

All the answers above, for some reason or another, did not work for me on SQL Server 2012. My situation was I accidently deleted all rows instead of just one row. After our DBA restored the table to dbo.foo_bak, I used the below to restore. NOTE: This only works if the backup table (represented by dbo.foo_bak) and the table that you are writing to (dbo.foo) have the exact same column names.

This is what worked for me using a hybrid of a bunch of different answers:

USE [database_name];
GO
SET IDENTITY_INSERT dbo.foo ON;
GO
INSERT INTO [dbo].[foo]
           ([rown0]
           ,[row1]
           ,[row2]
           ,[row3]
           ,...
           ,[rown])
     SELECT * FROM [dbo].[foo_bak];
GO
SET IDENTITY_INSERT dbo.foo OFF;
GO

This version of my answer is helpful if you have primary and foreign keys.

Java Could not reserve enough space for object heap error

This was occuring for me and it is such an easy fix.

  1. you have to make sure that you have the correct java for your system such as 32bit or 64bit.
  2. if you have installed the correct software and it still occurs than goto

    control panelsystemadvanced system settings for Windows 8 or

    control panelsystem and securitysystemadvanced system settings for Windows 10.

  3. you must goto the {advanced tab} and then click on {Environment Variables}.
  4. you will click on {New} under the <system variables>
  5. you will create a new variable. Variable name: _JAVA_OPTIONS Variable Value: -Xmx512M

At least that is what worked for me.

XMLHttpRequest (Ajax) Error

I see 2 possible problems:

Problem 1

  • the XMLHTTPRequest object has not finished loading the data at the time you are trying to use it

Solution: assign a callback function to the objects "onreadystatechange" -event and handle the data in that function

xmlhttp.onreadystatechange = callbackFunctionName;

Once the state has reached DONE (4), the response content is ready to be read.

Problem 2

  • the XMLHTTPRequest object does not exist in all browsers (by that name)

Solution: Either use a try-catch for creating the correct object for correct browser ( ActiveXObject in IE) or use a framework, for example jQuery ajax-method

Note: if you decide to use jQuery ajax-method, you assign the callback-function with jqXHR.done()

How can I do an UPDATE statement with JOIN in SQL Server?

PostgreSQL:

CREATE TABLE ud (id integer, assid integer);
CREATE TABLE sales (id integer, udid integer, assid integer);

UPDATE ud
SET assid = sales.assid
FROM sales
WHERE sales.id = ud.id;

Padding is invalid and cannot be removed?

Another scenario, again for the benefit of people searching.

For me this error occurred during the Dispose() method which masked a previous error unrelated to encryption.

Once the other component was fixed, this exception went away.

Is Tomcat running?

You can check the status of tomcat with the following ways:

ps -ef | grep tomcat  

This will return the tomcat path if the tomcat is running

netstat -a | grep 8080

where 8080 is the tomcat port

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());
        }

Best practice to return errors in ASP.NET Web API

ASP.NET Web API 2 really simplified it. For example, the following code:

public HttpResponseMessage GetProduct(int id)
{
    Product item = repository.Get(id);
    if (item == null)
    {
        var message = string.Format("Product with id = {0} not found", id);
        HttpError err = new HttpError(message);
        return Request.CreateResponse(HttpStatusCode.NotFound, err);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.OK, item);
    }
}

returns the following content to the browser when the item is not found:

HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Date: Thu, 09 Aug 2012 23:27:18 GMT
Content-Length: 51

{
  "Message": "Product with id = 12 not found"
}

Suggestion: Don't throw HTTP Error 500 unless there is a catastrophic error (for example, WCF Fault Exception). Pick an appropriate HTTP status code that represents the state of your data. (See the apigee link below.)

Links:

How can I schedule a job to run a SQL query daily?

Using T-SQL: My job is executing stored procedure. You can easy change @command to run your sql.

EXEC msdb.dbo.sp_add_job  
   @job_name = N'MakeDailyJob',   
   @enabled = 1,   
   @description = N'Procedure execution every day' ; 

 EXEC msdb.dbo.sp_add_jobstep  
    @job_name = N'MakeDailyJob',   
    @step_name = N'Run Procedure',   
    @subsystem = N'TSQL',   
    @command = 'exec BackupFromConfig';

 EXEC msdb.dbo.sp_add_schedule  
    @schedule_name = N'Everyday schedule',   
    @freq_type = 4,  -- daily start
    @freq_interval = 1,
    @active_start_time = '230000' ;   -- start time 23:00:00

 EXEC msdb.dbo.sp_attach_schedule  
   @job_name = N'MakeDailyJob',  
   @schedule_name = N'Everyday schedule' ;

 EXEC msdb.dbo.sp_add_jobserver  
   @job_name = N'MakeDailyJob',  
   @server_name = @@servername ;

Add legend to ggplot2 line plot

I really like the solution proposed by @Brian Diggs. However, in my case, I create the line plots in a loop rather than giving them explicitly because I do not know apriori how many plots I will have. When I tried to adapt the @Brian's code I faced some problems with handling the colors correctly. Turned out I needed to modify the aesthetic functions. In case someone has the same problem, here is the code that worked for me.

I used the same data frame as @Brian:

data <- structure(list(month = structure(c(1317452400, 1317538800, 1317625200, 1317711600, 
                                       1317798000, 1317884400, 1317970800, 1318057200, 
                                       1318143600, 1318230000, 1318316400, 1318402800, 
                                       1318489200, 1318575600, 1318662000, 1318748400, 
                                       1318834800, 1318921200, 1319007600, 1319094000), 
                                     class = c("POSIXct", "POSIXt"), tzone = ""),
                   TempMax = c(26.58, 27.78, 27.9, 27.44, 30.9, 30.44, 27.57, 25.71, 
                               25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 26.58, 26.18, 
                               25.19, 24.19, 27.65, 23.92), 
                   TempMed = c(22.88, 22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52,
                                 19.71, 20.73, 23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 
                                 20.45, 19.42, 19.97, 19.61), 
                   TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 16.88, 16.82, 
                               14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 16.95, 
                               17.55, 15.21, 14.22, 16.42)), 
              .Names = c("month", "TempMax", "TempMed", "TempMin"), 
              row.names = c(NA, 20L), class = "data.frame")  

In my case, I generate my.cols and my.names dynamically, but I don't want to make things unnecessarily complicated so I give them explicitly here. These three lines make the ordering of the legend and assigning colors easier.

my.cols <- heat.colors(3, alpha=1)
my.names <- c("TempMin", "TempMed", "TempMax")
names(my.cols) <- my.names

And here is the plot:

p <-  ggplot(data, aes(x = month))

for (i in 1:3){
  p <- p + geom_line(aes_(y = as.name(names(data[i+1])), colour = 
colnames(data[i+1])))#as.character(my.names[i])))
}
p + scale_colour_manual("", 
                        breaks = as.character(my.names),
                        values = my.cols)
p

enter image description here

What is the => assignment in C# in a property signature

This is a new feature of C# 6 called an expression bodied member that allows you to define a getter only property using a lambda like function.

While it is considered syntactic sugar for the following, they may not produce identical IL:

public int MaxHealth
{
    get
    {
        return Memory[Address].IsValid
               ?   Memory[Address].Read<int>(Offs.Life.MaxHp)
               :   0;
    }
}

It turns out that if you compile both versions of the above and compare the IL generated for each you'll see that they are NEARLY the same.

Here is the IL for the classic version in this answer when defined in a class named TestClass:

.property instance int32 MaxHealth()
{
    .get instance int32 TestClass::get_MaxHealth()
}

.method public hidebysig specialname 
    instance int32 get_MaxHealth () cil managed 
{
    // Method begins at RVA 0x2458
    // Code size 71 (0x47)
    .maxstack 2
    .locals init (
        [0] int32
    )

    IL_0000: nop
    IL_0001: ldarg.0
    IL_0002: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
    IL_0007: ldarg.0
    IL_0008: ldfld int64 TestClass::Address
    IL_000d: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
    IL_0012: ldfld bool MemoryAddress::IsValid
    IL_0017: brtrue.s IL_001c

    IL_0019: ldc.i4.0
    IL_001a: br.s IL_0042

    IL_001c: ldarg.0
    IL_001d: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
    IL_0022: ldarg.0
    IL_0023: ldfld int64 TestClass::Address
    IL_0028: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
    IL_002d: ldarg.0
    IL_002e: ldfld class Offs TestClass::Offs
    IL_0033: ldfld class Life Offs::Life
    IL_0038: ldfld int64 Life::MaxHp
    IL_003d: callvirt instance !!0 MemoryAddress::Read<int32>(int64)

    IL_0042: stloc.0
    IL_0043: br.s IL_0045

    IL_0045: ldloc.0
    IL_0046: ret
} // end of method TestClass::get_MaxHealth

And here is the IL for the expression bodied member version when defined in a class named TestClass:

.property instance int32 MaxHealth()
{
    .get instance int32 TestClass::get_MaxHealth()
}

.method public hidebysig specialname 
    instance int32 get_MaxHealth () cil managed 
{
    // Method begins at RVA 0x2458
    // Code size 66 (0x42)
    .maxstack 2

    IL_0000: ldarg.0
    IL_0001: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
    IL_0006: ldarg.0
    IL_0007: ldfld int64 TestClass::Address
    IL_000c: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
    IL_0011: ldfld bool MemoryAddress::IsValid
    IL_0016: brtrue.s IL_001b

    IL_0018: ldc.i4.0
    IL_0019: br.s IL_0041

    IL_001b: ldarg.0
    IL_001c: ldfld class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress> TestClass::Memory
    IL_0021: ldarg.0
    IL_0022: ldfld int64 TestClass::Address
    IL_0027: callvirt instance !1 class [mscorlib]System.Collections.Generic.Dictionary`2<int64, class MemoryAddress>::get_Item(!0)
    IL_002c: ldarg.0
    IL_002d: ldfld class Offs TestClass::Offs
    IL_0032: ldfld class Life Offs::Life
    IL_0037: ldfld int64 Life::MaxHp
    IL_003c: callvirt instance !!0 MemoryAddress::Read<int32>(int64)

    IL_0041: ret
} // end of method TestClass::get_MaxHealth

See https://msdn.microsoft.com/en-us/magazine/dn802602.aspx for more information on this and other new features in C# 6.

See this post Difference between Property and Field in C# 3.0+ on the difference between a field and a property getter in C#.

Update:

Note that expression-bodied members were expanded to include properties, constructors, finalizers and indexers in C# 7.0.

How to copy and paste worksheets between Excel workbooks?

You could do something with APIs.

Private Const SW_SHOW = 5
Private Const GW_HWNDNEXT = 2

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long

Private Declare Function ShowWindow Lib "user32" _
(ByVal hWnd As Long, ByVal nCmdShow As Long) As Long

Private Declare Function GetWindow Lib "user32" _
(ByVal hWnd As Long, ByVal wCmd As Long) As Long

Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
(ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long

Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long

Function FindWindowPartialX(ByVal Title As String) As Long
    Dim hWndThis As Long
    hWndThis = FindWindow(vbNullString, vbNullString)
    While hWndThis
        Dim sTitle As String, sClass As String
        sTitle = Space$(255)
        sTitle = Left$(sTitle, GetWindowText(hWndThis, sTitle, Len(sTitle)))
        sClass = Space$(255)
        sClass = Left$(sClass, GetClassName(hWndThis, sClass, Len(sClass)))
        If InStr(sTitle, Title) > 0 Then
            FindWindowPartialX = hWndThis
            Exit Function
        End If
        hWndThis = GetWindow(hWndThis, GW_HWNDNEXT)
    Wend
End Function

Sub CopySheet()
Dim objXL As Excel.Application

' A suitable portion of the window title such as file name '
WinHandle = FindWindowPartialX("LTD.xls")

ShowWindow WinHandle, SW_SHOW

Set objXL = GetObject(, "Excel.Application")

objXL.Worksheets("Source").Activate
objXL.ActiveSheet.UsedRange.Copy

Application.ActiveSheet.Paste
End Sub

How to create a temporary directory/folder in Java?

This code should work reasonably well:

public static File createTempDir() {
    final String baseTempPath = System.getProperty("java.io.tmpdir");

    Random rand = new Random();
    int randomInt = 1 + rand.nextInt();

    File tempDir = new File(baseTempPath + File.separator + "tempDir" + randomInt);
    if (tempDir.exists() == false) {
        tempDir.mkdir();
    }

    tempDir.deleteOnExit();

    return tempDir;
}

How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

(1) check the port is in use or not, kill that process

$ lsof -i:[port]

(2) another reason is the port is used by ipv6, solution:

edit /etc/sysctl.conf

add this to the file

net.ipv6.conf.all.disable_ipv6 = 1

then make it effect

$ sudo sysctl -p /etc/sysctl.conf

or just reboot

List(of String) or Array or ArrayList

Neither collection will let you add items that way.

You can make an extension to make for examle List(Of String) have an Add method that can do that:

Imports System.Runtime.CompilerServices
Module StringExtensions

  <Extension()>
  Public Sub Add(ByVal list As List(Of String), ParamArray values As String())
    For Each s As String In values
      list.Add(s)
    Next
  End Sub

End Module

Now you can add multiple value in one call:

Dim lstOfStrings as New List(Of String)
lstOfStrings.Add(String1, String2, String3, String4)

Using switch statement with a range of value in each case?

For input number in range 0..100

int n1 = 75; // input value
String res; int n=0; 
int[] a ={0,20,35,55,70,85,101};

for(; n1>=a[n]; n++);
switch(6-n+1) {
  case 1: res="A"; break;
  case 2: res="B"; break;
  case 3: res="C"; break;
  case 4: res="D"; break;
  case 5: res="E"; break;
  default:res="F";
}
System.out.println(res);

iOS - Calling App Delegate method from ViewController

Sounds like you just need a UINavigationController setup?

You can get the AppDelegate anywhere in the program via

YourAppDelegateName* blah = (YourAppDelegateName*)[[UIApplication sharedApplication]delegate];

In your app delegate you should have your navigation controller setup, either via IB or in code.

In code, assuming you've created your 'House overview' viewcontroller already it would be something like this in your AppDelegate didFinishLaunchingWithOptions...

self.m_window = [[[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds] autorelease];
self.m_navigationController = [[[UINavigationController alloc]initWithRootViewController:homeViewController]autorelease];
[m_window addSubview:self.m_navigationController.view];

After this you just need a viewcontroller per 'room' and invoke the following when a button click event is picked up...

YourAppDelegateName* blah = (YourAppDelegateName*)[[UIApplication sharedApplication]delegate];
[blah.m_navigationController pushViewController:newRoomViewController animated:YES];

I've not tested the above code so forgive any syntax errors but hope the pseudo code is of help...

How do I divide in the Linux console?

I also had the same problem. It's easy to divide integer numbers but decimal numbers are not that easy. if you have 2 numbers like 3.14 and 2.35 and divide the numbers then, the code will be Division=echo 3.14 / 2.35 | bc echo "$Division" the quotes are different. Don't be confused, it's situated just under the esc button on your keyboard. THE ONLY DIFFERENCE IS THE | bc and also here echo works as an operator for the arithmetic calculations in stead of printing. So, I had added echo "$Division" for printing the value. Let me know if it works for you. Thank you.

how to get current month and year

Find Current Year Using Razor try this

@DateTime.Now.Year

image processing to improve tesseract OCR accuracy

I did these to get good results out of an image which has not very small text.

  1. Apply blur to the original image.
  2. Apply Adaptive Threshold.
  3. Apply Sharpening effect.

And if the still not getting good results, scale the image to 150% or 200%.

How do I parse JSON with Objective-C?

Don't reinvent the wheel. Use json-framework or something similar.

If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary:

SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];

// now you can grab data out of the dictionary using objectForKey or another dictionary method

disable all form elements inside div

If your form inside div simply contains form inputting elements, then this simple query will disable every element inside form tag:

<div id="myForm">
    <form action="">
    ...
    </form>
</div>

However, it will also disable other than inputting elements in form, as it's effects will only be seen on input type elements, therefore suitable majorly for every type of forms!

$('#myForm *').attr('disabled','disabled');

How to empty a list in C#?

You need the Clear() function on the list, like so.

List<object> myList = new List<object>();

myList.Add(new object()); // Add something to the list

myList.Clear() // Our list is now empty

How can I use Timer (formerly NSTimer) in Swift?

First declare your timer

var timer: Timer?

Then add line in viewDidLoad() or in any function you want to start the timer

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(action), userInfo: nil, repeats: false)

This is the func you will callback it to do something it must be @objc

@objc func action () {
print("done")
}

Passing base64 encoded strings in URL

I don't think that this is safe because e.g. the "=" character is used in raw base 64 and is also used in differentiating the parameters from the values in an HTTP GET.

How do I query between two dates using MySQL?

When using Date and Time values, you must cast the fields as DateTime and not Date. Try :

SELECT * FROM `objects` 
WHERE (CAST(date_field AS DATETIME) 
BETWEEN CAST('2010-09-29 10:15:55' AS DATETIME) AND CAST('2010-01-30 14:15:55' AS DATETIME))

How to stick <footer> element at the bottom of the page (HTML5 and CSS3)?

For footer change from position: relative; to position:fixed;

 footer {
            background-color: #333;
            width: 100%;
            bottom: 0;
            position: fixed;
        }

Example: http://jsfiddle.net/a6RBm/

Get top first record from duplicate records having no unique identity

Using DISTINCT should do it:

SELECT DISTINCT id, uname, tel
FROM YourTable

Though you could really do with having a primary key on that table, a way to uniquely identify each record. I'd be considering sticking an IDENTITY column on the table

How to use PHP string in mySQL LIKE query?

DO it like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");

Do not forget the % at the end

React Router with optional path parameter

Working syntax for multiple optional params:

<Route path="/section/(page)?/:page?/(sort)?/:sort?" component={Section} />

Now, url can be:

  1. /section
  2. /section/page/1
  3. /section/page/1/sort/asc

Does Python have a string 'contains' substring method?

You can use y.count().

It will return the integer value of the number of times a sub string appears in a string.

For example:

string.count("bah") >> 0
string.count("Hello") >> 1

.htaccess 301 redirect of single page

This should do it

RedirectPermanent /contact.php /contact-us.php 

How to create a toggle button in Bootstrap

Bootstrap 3 has options to create toggle buttons based on checkboxes or radio buttons: http://getbootstrap.com/javascript/#buttons

Checkboxes

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="checkbox" checked> Option 1 (pre-checked)
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> Option 2
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> Option 3
  </label>
</div>

Radio buttons

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" checked> Option 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2"> Option 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3"> Option 3
  </label>
</div>

For these to work you must initialize .btns with Bootstrap's Javascript:

$('.btn').button();

@AspectJ pointcut for all methods of a class with specific annotation

I share with you a code that can be useful, it is to create an annotation that can be used either in a class or a method.

@Target({TYPE, METHOD})
@Retention(RUNTIME)
@Documented
public @interface AnnotationLogger {
    /**
     * It is the parameter is to show arguments in the method or the class.
     */
    boolean showArguments() default false;
}


@Aspect
@Component
public class AnnotationLoggerAspect {
    
    @Autowired 
    private Logger logger;  
    
    private static final String METHOD_NAME   = "METHOD NAME: {} ";
    private static final String ARGUMENTS     = "ARGS: {} ";
    
    @Before(value = "@within(com.org.example.annotations.AnnotationLogger) || @annotation(com.org.example.annotations.AnnotationLogger)")
    public void logAdviceExecutionBefore(JoinPoint joinPoint){  
        CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
        AnnotationLogger annotationLogger = getAnnotationLogger(joinPoint);
        if(annotationLogger!= null) {
            StringBuilder annotationLoggerFormat = new StringBuilder();
            List<Object> annotationLoggerArguments = new ArrayList<>();
            annotationLoggerFormat.append(METHOD_NAME);
            annotationLoggerArguments.add(codeSignature.getName());
            
            if (annotationLogger.showArguments()) {
                annotationLoggerFormat.append(ARGUMENTS);
                List<?> argumentList = Arrays.asList(joinPoint.getArgs());
                annotationLoggerArguments.add(argumentList.toString());
            }
            logger.error(annotationLoggerFormat.toString(), annotationLoggerArguments.toArray());
        }
    }
    
    private AnnotationLogger getAnnotationLogger(JoinPoint joinPoint) {
        AnnotationLogger annotationLogger = null;
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = joinPoint.getTarget().getClass().
                    getMethod(signature.getMethod().getName(), signature.getMethod().getParameterTypes());
            
            if (method.isAnnotationPresent(AnnotationLogger.class)){
                annotationLogger = method.getAnnotation(AnnotationLoggerAspect.class);
            }else if (joinPoint.getTarget().getClass().isAnnotationPresent(AnnotationLoggerAspect.class)){
                annotationLogger = joinPoint.getTarget().getClass().getAnnotation(AnnotationLoggerAspect.class);
            }
            return annotationLogger;
        }catch(Exception e) {
            return annotationLogger;
        }
    }
}