Programs & Examples On #Mathematical optimization

Mathematical optimization deals with maximizing or minimizing an objective function by choosing values from within an allowed feasible set of possible values. Mathematical optimization is often also referred to as mathematical programming or simply as optimization.

What is an NP-complete in computer science?

NP-complete problems are a set of problems to each of which any other NP-problem can be reduced in polynomial time, and whose solution may still be verified in polynomial time. That is, any NP problem can be transformed into any of the NP-complete problems. – Informally, an NP-complete problem is an NP problem that is at least as "tough" as any other problem in NP.

How to interpret "loss" and "accuracy" for a machine learning model

Just to clarify the Training/Validation/Test data sets: The training set is used to perform the initial training of the model, initializing the weights of the neural network.

The validation set is used after the neural network has been trained. It is used for tuning the network's hyperparameters, and comparing how changes to them affect the predictive accuracy of the model. Whereas the training set can be thought of as being used to build the neural network's gate weights, the validation set allows fine tuning of the parameters or architecture of the neural network model. It's useful as it allows repeatable comparison of these different parameters/architectures against the same data and networks weights, to observe how parameter/architecture changes affect the predictive power of the network.

Then the test set is used only to test the predictive accuracy of the trained neural network on previously unseen data, after training and parameter/architecture selection with the training and validation data sets.

What is Node.js?

Two good examples are regarding how you manage templates and use progressive enhancements with it. You just need a few lightweight pieces of JavaScript code to make it work perfectly.

I strongly recommend that you watch and read these articles:

Pick up any language and try to remember how you would manage your HTML file templates and what you had to do to update a single CSS class name in your DOM structure (for instance, a user clicked on a menu item and you want that marked as "selected" and update the content of the page).

With Node.js it is as simple as doing it in client-side JavaScript code. Get your DOM node and apply your CSS class to that. Get your DOM node and innerHTML your content (you will need some additional JavaScript code to do this. Read the article to know more).

Another good example, is that you can make your web page compatible both with JavaScript turned on or off with the same piece of code. Imagine you have a date selection made in JavaScript that would allow your users to pick up any date using a calendar. You can write (or use) the same piece of JavaScript code to make it work with your JavaScript turned ON or OFF.

How can I get CMake to find my alternative Boost installation?

I just added the environment variable Boost_INCLUDE_DIR or add it to the cmake command -DBoost_INCLUDE_DIR and point to the include folder.

How can I completely uninstall nodejs, npm and node in Ubuntu

Those who installed node.js via the package manager can just run:

sudo apt-get purge nodejs

Optionally if you have installed it by adding the official NodeSource repository as stated in Installing Node.js via package manager, do:

sudo rm /etc/apt/sources.list.d/nodesource.list

If you want to clean up npm cache as well:

rm -rf ~/.npm

It is bad practice to try to remove things manually, as it can mess up the package manager, and the operating system itself. This answer is completely safe to follow

What's the better (cleaner) way to ignore output in PowerShell?

I would consider using something like:

function GetList
{
  . {
     $a = new-object Collections.ArrayList
     $a.Add(5)
     $a.Add('next 5')
  } | Out-Null
  $a
}
$x = GetList

Output from $a.Add is not returned -- that holds for all $a.Add method calls. Otherwise you would need to prepend [void] before each the call.

In simple cases I would go with [void]$a.Add because it is quite clear that output will not be used and is discarded.

Class has no objects member

By doing Question = new Question() (I assume the new is a typo) you are overwriting the Question model with an intance of Question. Like Sayse said in the comments: don't use the same name for your variable as the name of the model. So change it to something like my_question = Question().

Observable.of is not a function

I am using Angular 5.2 and RxJS 5.5.6

This code did not work:

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

     getHeroes(): Observable<Hero[]> {
        return of(Hero[]) HEROES;

      }

Below code worked:

    import { Observable } from 'rxjs/Observable';
    import { Subscriber } from 'rxjs/Subscriber';

     getHeroes(): Observable<Hero[]> 
     {
          return Observable.create((observer: Subscriber<any>) => {
              observer.next(HEROES);
              observer.complete();
          });

      }

Calling method:

this.heroService.getHeroes()
      .subscribe(heroes => this.heroes = heroes);

I think they might moved/changed of() functionality in RxJS 5.5.2

Cannot change version of project facet Dynamic Web Module to 3.0?

Open the org.eclipse.wst.common.project.facet.core.xml file and change the jst.web version to 3.0. Also update the web.xml to version 3.0. Save and update the project. Hope this helps. I am using Eclipse Juno

Debug/run standard java in Visual Studio Code IDE and OS X?

There is a much easier way to run Java, no configuration needed:

  1. Install the Code Runner Extension
  2. Open your Java code file in Text Editor, then use shortcut Ctrl+Alt+N, or press F1 and then select/type Run Code, or right click the Text Editor and then click Run Code in context menu, the code will be compiled and run, and the output will be shown in the Output Window.

runJave

Avoid web.config inheritance in child web application using inheritInChildApplications

I put everything into:

<location path="." inheritInChildApplications="false">
....
</location>

except: <configSections/>, <connectionStrings/> and <runtime/>.

There are some cases when we don't want to inherit some secions from <configSections />, but we can't put <section/> tag into <location/>, so we have to create a <secionGroup /> and put our unwanted sections into that group. Section groups can be later inserted into a location tag.

So we have to change this:

<configSections>
  <section name="unwantedSection" />
</configSections>

Into:

<configSections>
  <sectionGroup name="myNotInheritedSections">
    <section name="unwantedSection" />
  </sectionGroup>
</configSections>

<location path="." inheritInChildApplications="false">
    <myNotInheritedSections>
        <unwantedSection />
    </myNotInheritedSections>
</location>

How to test if a double is zero?

The safest way would be bitwise OR ing your double with 0. Look at this XORing two doubles in Java

Basically you should do if ((Double.doubleToRawLongBits(foo.x) | 0 ) ) (if it is really 0)

how to change php version in htaccess in server

To switch to PHP 4.4:

AddHandler application/x-httpd-php4 .php .php4 .php3

To switch to PHP 5.0:

AddHandler application/x-httpd-php5 .php .php5 .php4 .php3

To switch to PHP 5.1:

AddHandler application/x-httpd-php51 .php .php5 .php4 .php3

To switch to PHP 5.2:

AddHandler application/x-httpd-php52 .php .php5 .php4 .php3

To switch to PHP 5.3:

AddHandler application/x-httpd-php53 .php .php5 .php4 .php3

To switch to PHP 5.4:

AddHandler application/x-httpd-php54 .php .php5 .php4 .php3

To switch to PHP 5.5:

AddHandler application/x-httpd-php55 .php .php5 .php4 .php3

To switch to the secure PHP 5.2 with Suhosin patch:

AddHandler application/x-httpd-php52s .php .php5 .php4 .php3

how to change listen port from default 7001 to something different?

That file has a listen-port element - that should be what you need to change, although it is currently set to 8080, not 7001.

Checking if a list is empty with LINQ

I just wrote up a quick test, try this:

 IEnumerable<Object> myList = new List<Object>();

 Stopwatch watch = new Stopwatch();

 int x;

 watch.Start();
 for (var i = 0; i <= 1000000; i++)
 {
    if (myList.Count() == 0) x = i; 
 }
 watch.Stop();

 Stopwatch watch2 = new Stopwatch();

 watch2.Start();
 for (var i = 0; i <= 1000000; i++)
 {
     if (!myList.Any()) x = i;
 }
 watch2.Stop();

 Console.WriteLine("myList.Count() = " + watch.ElapsedMilliseconds.ToString());
 Console.WriteLine("myList.Any() = " + watch2.ElapsedMilliseconds.ToString());
 Console.ReadLine();

The second is almost three times slower :)

Trying the stopwatch test again with a Stack or array or other scenarios it really depends on the type of list it seems - because they prove Count to be slower.

So I guess it depends on the type of list you're using!

(Just to point out, I put 2000+ objects in the List and count was still faster, opposite with other types)

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

With help from these answers, I finally got reverse proxy for Node-RED running on a Raspberry Pi with Ubuntu Mate and Apache2 working, using this Apache2 site config:

<VirtualHost *:80>
    ServerName nodered.domain.com
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule /(.*)           ws://localhost:1880/$1 [P,L]
    RewriteCond %{HTTP:Upgrade} !=websocket [NC]
    RewriteRule /(.*)           http://localhost:1880/$1 [P,L]
</VirtualHost>

I also had to enable modules like this:

sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_wstunnel

How do you reverse a string in place in C or C++?

It's been a while and I don't remember which book taught me this algorithm, but I thought it was quite ingenious and simple to understand:

char input[] = "moc.wolfrevokcats";

int length = strlen(input);
int last_pos = length-1;
for(int i = 0; i < length/2; i++)
{
    char tmp = input[i];
    input[i] = input[last_pos - i];
    input[last_pos - i] = tmp;
}

printf("%s\n", input);

A visualization of this algorithm, courtesy of slashdottir:

Visualization of the algorithm to reverse a string in place

How to check if a column exists in Pandas

To check if one or more columns all exist, you can use set.issubset, as in:

if set(['A','C']).issubset(df.columns):
   df['sum'] = df['A'] + df['C']                

As @brianpck points out in a comment, set([]) can alternatively be constructed with curly braces,

if {'A', 'C'}.issubset(df.columns):

See this question for a discussion of the curly-braces syntax.

Or, you can use a list comprehension, as in:

if all([item in df.columns for item in ['A','C']]):

C++ calling base class constructors

The short answer for this is, "because that's what the C++ standard specifies".

Note that you can always specify a constructor that's different from the default, like so:

class Shape  {

  Shape()  {...} //default constructor
  Shape(int h, int w) {....} //some custom constructor


};

class Rectangle : public Shape {
  Rectangle(int h, int w) : Shape(h, w) {...} //you can specify which base class constructor to call

}

The default constructor of the base class is called only if you don't specify which one to call.

JDBC ODBC Driver Connection

As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have

  • an implementation of ODBC itself, and
  • an appropriate ODBC driver for the target database (ACE/Jet, a.k.a. "Access")

So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).

There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see

Manipulating an Access database from Java without ODBC

How do I get the current timezone name in Postgres 9.3?

It seems to work fine in Postgresql 9.5:

SELECT current_setting('TIMEZONE');

How to get attribute of element from Selenium?

Python

element.get_attribute("attribute name")

Java

element.getAttribute("attribute name")

Ruby

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");

What is the difference between dict.items() and dict.iteritems() in Python2?

If you want a way to iterate the item pairs of a dictionary that works with both Python 2 and 3, try something like this:

DICT_ITER_ITEMS = (lambda d: d.iteritems()) if hasattr(dict, 'iteritems') else (lambda d: iter(d.items()))

Use it like this:

for key, value in DICT_ITER_ITEMS(myDict):
    # Do something with 'key' and/or 'value'.

make iframe height dynamic based on content inside- JQUERY/Javascript

you could also add a repeating requestAnimationFrame to your resizeIframe (e.g. from @BlueFish's answer) which would always be called before the browser paints the layout and you could update the height of the iframe when its content have changed their heights. e.g. input forms, lazy loaded content etc.

<script type="text/javascript">
  function resizeIframe(iframe) {
    iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
    window.requestAnimationFrame(() => resizeIframe(iframe));
  }
</script>  

<iframe onload="resizeIframe(this)" ...

your callback should be fast enough to have no big impact on your overall performance

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

I had same problem about SaveChanges() in EF but in my case I forget to update my sql table then after I used migration my problem solved so maybe updating your tables will solve problem.

How to quietly remove a directory with content in PowerShell

Remove-Item -LiteralPath "foldertodelete" -Force -Recurse

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

Update: Genymotion's 2.5.1 release (https://www.genymotion.com/#!/release-notes/251#251) seems to have fixed this issue. (thanks for the heads up @Roger!)


For those that may be stumbling upon this a bit later, I resolved this by installing VirtualBox 4.3.28 (https://www.virtualbox.org/wiki/Download_Old_Builds_4_3). The new 5.0.0 and 4.3.30 versions didn't work for me with Genymotion 2.5. None of the above solutions worked :(

It's also worth noting that at the time of writing, Genymotion's FAQ states the following:

However, for performance reasons, we recommend using version 4.3.12

Convert a RGB Color Value to a Hexadecimal String

This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.

This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.

public class HexColor
{

  public static void main (String[] args)
  {
   JSlider sRed = new JSlider(0,255,1);
   JSlider sGreen = new JSlider(0,255,1);
   JSlider sBlue = new JSlider(0,255,1);
   JLabel hexCode = new JLabel();
   JPanel myPanel = new JPanel();
   GridBagLayout layout = new GridBagLayout();
   JFrame frame = new JFrame();

   //set frame to organize components using GridBagLayout 
   frame.setLayout(layout);

   //create gray filled rectangle 
   myPanel.paintComponent();
   myPanel.setBackground(Color.GRAY);

   //In practice this code is replicated and applied to sGreen and sBlue. 
   //For the sake of brevity I only show sRed in this post.
   sRed.addChangeListener(
         new ChangeListener()
         {
             @Override
             public void stateChanged(ChangeEvent e){
                 myPanel.setBackground(changeColor());
                 myPanel.repaint();
                 hexCode.setText(toHex());
         }
         }
     );
   //add each component to JFrame
   frame.add(myPanel);
   frame.add(sRed);
   frame.add(sGreen);
   frame.add(sBlue);
   frame.add(hexCode);
} //end of main

  //creates JPanel filled rectangle
  protected void paintComponent(Graphics g)
  {
      super.paintComponent(g);
      g.drawRect(360, 300, 10, 10);
      g.fillRect(360, 300, 10, 10);
  }

  //changes the display color in JPanel
  private Color changeColor()
  {
    int r = sRed.getValue();
    int b = sBlue.getValue();
    int g = sGreen.getValue();
    Color c;
    return  c = new Color(r,g,b);
  }

  //Displays hex representation of displayed color
  private String toHex()
  {
      Integer r = sRed.getValue();
      Integer g = sGreen.getValue();
      Integer b = sBlue.getValue();
      Color hC;
      hC = new Color(r,g,b);
      String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
      while(hex.length() < 6){
          hex = "0" + hex;
      }
      hex = "Hex Code: #" + hex;
      return hex;
  }
}

A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.

Creating a simple login form

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <title>Login Page</title>
      <style>
         /* Basics */
         html, body {
         width: 100%;
         height: 100%;
         font-family: "Helvetica Neue", Helvetica, sans-serif;
         color: #444;
         -webkit-font-smoothing: antialiased;
         background: #f0f0f0;
         }
         #container {
         position: fixed;
         width: 340px;
         height: 280px;
         top: 50%;
         left: 50%;
         margin-top: -140px;
         margin-left: -170px;
         background: #fff;
         border-radius: 3px;
         border: 1px solid #ccc;
         box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
         }
         form {
         margin: 0 auto;
         margin-top: 20px;
         }
         label {
         color: #555;
         display: inline-block;
         margin-left: 18px;
         padding-top: 10px;
         font-size: 14px;
         }
         p a {
         font-size: 11px;
         color: #aaa;
         float: right;
         margin-top: -13px;
         margin-right: 20px;
         -webkit-transition: all .4s ease;
         -moz-transition: all .4s ease;
         transition: all .4s ease;
         }
         p a:hover {
         color: #555;
         }
         input {
         font-family: "Helvetica Neue", Helvetica, sans-serif;
         font-size: 12px;
         outline: none;
         }
         input[type=text],
         input[type=password] ,input[type=time]{
         color: #777;
         padding-left: 10px;
         margin: 10px;
         margin-top: 12px;
         margin-left: 18px;
         width: 290px;
         height: 35px;
         border: 1px solid #c7d0d2;
         border-radius: 2px;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
         -webkit-transition: all .4s ease;
         -moz-transition: all .4s ease;
         transition: all .4s ease;
         }
         input[type=text]:hover,
         input[type=password]:hover,input[type=time]:hover {
         border: 1px solid #b6bfc0;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
         }
         input[type=text]:focus,
         input[type=password]:focus,input[type=time]:focus {
         border: 1px solid #a8c9e4;
         box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
         }
         #lower {
         background: #ecf2f5;
         width: 100%;
         height: 69px;
         margin-top: 20px;
         box-shadow: inset 0 1px 1px #fff;
         border-top: 1px solid #ccc;
         border-bottom-right-radius: 3px;
         border-bottom-left-radius: 3px;
         }
         input[type=checkbox] {
         margin-left: 20px;
         margin-top: 30px;
         }
         .check {
         margin-left: 3px;
         font-size: 11px;
         color: #444;
         text-shadow: 0 1px 0 #fff;
         }
         input[type=submit] {
         float: right;
         margin-right: 20px;
         margin-top: 20px;
         width: 80px;
         height: 30px;
         font-size: 14px;
         font-weight: bold;
         color: #fff;
         background-color: #acd6ef; /*IE fallback*/
         background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
         background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
         background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
         border-radius: 30px;
         border: 1px solid #66add6;
         box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
         cursor: pointer;
         }
         input[type=submit]:hover {
         background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
         background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
         background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
         }
         input[type=submit]:active {
         background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
         background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
         background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
         }
      </style>
   </head>
   <body>
      <!-- Begin Page Content -->
      <div id="container">
         <form action="login_process.php" method="post">
            <label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php  echo @$_GET['msg'];?></label>
            <label for="username">Username:</label>
            <input type="text" id="username" name="username">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password">
            <div id="lower">
               <input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
               <input type="submit" value="Login">
            </div>
            <!--/ lower-->
         </form>
      </div>
      <!--/ container-->
      <!-- End Page Content -->
   </body>
</html>

Setting the correct PATH for Eclipse

I am using Windows 8.1 environment. I had the same problem while running my first java program after installing Eclipse recently. I had installed java on d drive at d:\java. But Eclipse was looking at the default installation c:\programfiles\java. I did the following:

  1. Modified my eclipse.ini file and added the following after open:

    -vm
    d:\java\jdk1.8.0_161\bin 
    
  2. While creating the java program I have to unselect default build path and then select d:\java.

After this, the program ran well and got the hello world to work.

String escape into XML

WARNING: Necromancing

Still Darin Dimitrov's answer + System.Security.SecurityElement.Escape(string s) isn't complete.

In XML 1.1, the simplest and safest way is to just encode EVERYTHING.
Like &#09; for \t.
It isn't supported at all in XML 1.0.
For XML 1.0, one possible workaround is to base-64 encode the text containing the character(s).

//string EncodedXml = SpecialXmlEscape("?????? ???");
//Console.WriteLine(EncodedXml);
//string DecodedXml = XmlUnescape(EncodedXml);
//Console.WriteLine(DecodedXml);
public static string SpecialXmlEscape(string input)
{
    //string content = System.Xml.XmlConvert.EncodeName("\t");
    //string content = System.Security.SecurityElement.Escape("\t");
    //string strDelimiter = System.Web.HttpUtility.HtmlEncode("\t"); // XmlEscape("\t"); //XmlDecode("&#09;");
    //strDelimiter = XmlUnescape("&#59;");
    //Console.WriteLine(strDelimiter);
    //Console.WriteLine(string.Format("&#{0};", (int)';'));
    //Console.WriteLine(System.Text.Encoding.ASCII.HeaderName);
    //Console.WriteLine(System.Text.Encoding.UTF8.HeaderName);


    string strXmlText = "";

    if (string.IsNullOrEmpty(input))
        return input;


    System.Text.StringBuilder sb = new StringBuilder();

    for (int i = 0; i < input.Length; ++i)
    {
        sb.AppendFormat("&#{0};", (int)input[i]);
    }

    strXmlText = sb.ToString();
    sb.Clear();
    sb = null;

    return strXmlText;
} // End Function SpecialXmlEscape

XML 1.0:

public static string Base64Encode(string plainText)
{
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
    return System.Convert.ToBase64String(plainTextBytes);
}

public static string Base64Decode(string base64EncodedData)
{
    var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
    return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

How to get the number of days of difference between two dates on mysql?

Get days between Current date to destination Date

 SELECT DATEDIFF('2019-04-12', CURDATE()) AS days;

output

days

 335

Tomcat request timeout

You can set the default time out in the server.xml

<Connector URIEncoding="UTF-8" 
    acceptCount="100" 
    connectionTimeout="20000" 
    disableUploadTimeout="true" 
    enableLookups="false" 
    maxHttpHeaderSize="8192" 
    maxSpareThreads="75" 
    maxThreads="150" 
    minSpareThreads="25" 
    port="7777" 
    redirectPort="8443"/>

Git commit date

if you got troubles with windows cmd command and .bat just escape percents like that

git show -s --format=%%ct

The % character has a special meaning for command line parameters and FOR parameters. To treat a percent as a regular character, double it: %%

Syntax : Escape Characters, Delimiters and Quotes

Excel VBA App stops spontaneously with message "Code execution has been halted"

If it's a phantom breakpoint:

1 Delete the offending line of code

2 Run the code again

3 Repaste the line

I found this laughably simple solution after spending a couple days wading through all the answers here and elsewhere. I figured, if I link it to my original question it might help some other poor chap, since the question it's on is VBA break execution when there's no break key on keyboard and this is more applicable.

Link to original answer

what's data-reactid attribute in html?

The data-reactid attribute is a custom attribute used so that React can uniquely identify its components within the DOM.

This is important because React applications can be rendered at the server as well as the client. Internally React builds up a representation of references to the DOM nodes that make up your application (simplified version is below).

{
  id: '.1oqi7occu80',
  node: DivRef,
  children: [
    {
      id: '.1oqi7occu80.0',
      node: SpanRef,
      children: [
        {
          id: '.1oqi7occu80.0.0',
          node: InputRef,
          children: []
        }
      ]
    }
  ]
}

There's no way to share the actual object references between the server and the client and sending a serialized version of the entire component tree is potentially expensive. When the application is rendered at the server and React is loaded at the client, the only data it has are the data-reactid attributes.

<div data-reactid='.loqi70ccu80'>
  <span data-reactid='.loqi70ccu80.0'>
    <input data-reactid='.loqi70ccu80.0' />
  </span>
</div>

It needs to be able to convert that back into the data structure above. The way it does that is with the unique data-reactid attributes. This is called inflating the component tree.

You might also notice that if React renders at the client-side, it uses the data-reactid attribute, even though it doesn't need to lose its references. In some browsers, it inserts your application into the DOM using .innerHTML then it inflates the component tree straight away, as a performance boost.

The other interesting difference is that client-side rendered React ids will have an incremental integer format (like .0.1.4.3), whereas server-rendered ones will be prefixed with a random string (such as .loqi70ccu80.1.4.3). This is because the application might be rendered across multiple servers and it's important that there are no collisions. At the client-side, there is only one rendering process, which means counters can be used to ensure unique ids.

React 15 uses document.createElement instead, so client rendered markup won't include these attributes anymore.

is it possible to add colors to python output?

If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.

Here an example:

print ('This is \x1b[31mred\x1b[0m.') 

Matplotlib/pyplot: How to enforce axis range?

Try putting the call to axis after all plotting commands.

How to check if a string is null in python

Try this:

if cookie and not cookie.isspace():
    # the string is non-empty
else:
    # the string is empty

The above takes in consideration the cases where the string is None or a sequence of white spaces.

How to catch curl errors in PHP

If CURLOPT_FAILONERROR is false, http errors will not trigger curl errors.

<?php
if (@$_GET['curl']=="yes") {
  header('HTTP/1.1 503 Service Temporarily Unavailable');
} else {
  $ch=curl_init($url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."?curl=yes");
  curl_setopt($ch, CURLOPT_FAILONERROR, true);
  $response=curl_exec($ch);
  $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $curl_errno= curl_errno($ch);
  if ($http_status==503)
    echo "HTTP Status == 503 <br/>";
  echo "Curl Errno returned $curl_errno <br/>";
}

Redirect to a page/URL after alert button is pressed

You're missing semi-colons after your javascript lines. Also, window.location should have .href or .replace etc to redirect - See this post for more information.

echo '<script type="text/javascript">'; 
echo 'alert("review your answer");'; 
echo 'window.location.href = "index.php";';
echo '</script>';

For clarity, try leaving PHP tags for this:

?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php

NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.

Measuring elapsed time with the Time module

For the best measure of elapsed time (since Python 3.3), use time.perf_counter().

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

For measurements on the order of hours/days, you don't care about sub-second resolution so use time.monotonic() instead.

Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

In many implementations, these may actually be the same thing.

Before 3.3, you're stuck with time.clock().

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.


Update for Python 3.7

New in Python 3.7 is PEP 564 -- Add new time functions with nanosecond resolution.

Use of these can further eliminate rounding and floating-point errors, especially if you're measuring very short periods, or your application (or Windows machine) is long-running.

Resolution starts breaking down on perf_counter() after around 100 days. So for example after a year of uptime, the shortest interval (greater than 0) it can measure will be bigger than when it started.


Update for Python 3.8

time.clock is now gone.

In SQL, is UPDATE always faster than DELETE+INSERT?

One command on the same row should always be faster than two on that same row. So the UPDATE only would be better.

EDIT set up the table:

create table YourTable
(YourName  varchar(50)  primary key
,Tag int
)

insert into YourTable values ('first value',1)

run this, which takes 1 second on my system (sql server 2005):

SET NOCOUNT ON
declare @x int
declare @y int
select @x=0,@y=0
UPDATE YourTable set YourName='new name'
while @x<10000
begin
    Set @x=@x+1
    update YourTable set YourName='new name' where YourName='new name'
    SET @y=@y+@@ROWCOUNT
end
print @y

run this, which took 2 seconds on my system:

SET NOCOUNT ON
declare @x int
declare @y int
select @x=0,@y=0
while @x<10000
begin
    Set @x=@x+1
    DELETE YourTable WHERE YourName='new name'
    insert into YourTable values ('new name',1)
    SET @y=@y+@@ROWCOUNT
end
print @y

Unable to allocate array with shape and data type

In my case, adding a dtype attribute changed dtype of the array to a smaller type(from float64 to uint8), decreasing array size enough to not throw MemoryError in Windows(64 bit).

from

mask = np.zeros(edges.shape)

to

mask = np.zeros(edges.shape,dtype='uint8')

Show loading screen when navigating between routes in Angular 2

You could also use this existing solution. The demo is here. It looks like youtube loading bar. I just found it and added it to my own project.

Using an integer as a key in an associative array in JavaScript

Try using an Object, not an Array:

var test = new Object(); test[2300] = 'Some string';

How do I get first name and last name as whole name in a MYSQL query?

When you have three columns : first_name, last_name, mid_name:

SELECT CASE 
    WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
        CONCAT_WS( " ", first_name, last_name ) 
    ELSE 
        CONCAT_WS( " ", first_name, mid_name, last_name ) 
    END 
FROM USER;

Simple dictionary in C++

Here's the map solution:

#include <iostream>
#include <map>

typedef std::map<char, char> BasePairMap;

int main()
{
    BasePairMap m;
    m['A'] = 'T';
    m['T'] = 'A';
    m['C'] = 'G';
    m['G'] = 'C';

    std::cout << "A:" << m['A'] << std::endl;
    std::cout << "T:" << m['T'] << std::endl;
    std::cout << "C:" << m['C'] << std::endl;
    std::cout << "G:" << m['G'] << std::endl;

    return 0;
}

Make HTML5 video poster be same size as video itself

Or you can use simply preload="none" attribute to make VIDEO background visible. And you can use background-size: cover; here.

 video {
   background: transparent url('video-image.jpg') 50% 50% / cover no-repeat ;
 }

 <video preload="none" controls>
   <source src="movie.mp4" type="video/mp4">
   <source src="movie.ogg" type="video/ogg">
 </video>

Get source JARs from Maven repository

In eclipse - click on the project then:

enter image description here.

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Display a RecyclerView in Fragment

Make sure that you have the correct layout, and that the RecyclerView id is inside the layout. Otherwise, you will be getting this error. I had the same problem, then I noticed the layout was wrong.

    public class ColorsFragment extends Fragment {

         public ColorsFragment() {}

         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {

==> make sure you are getting the correct layout here. R.layout...

             View rootView = inflater.inflate(R.layout.fragment_colors, container, false); 

What is the correct way to free memory in C#

Here's a quick overview:

  • Once references are gone, your object will likely be garbage collected.
  • You can only count on statistical collection that keeps your heap size normal provided all references to garbage are really gone. In other words, there is no guarantee a specific object will ever be garbage collected.
    • It follows that your finalizer will also never be guaranteed to be called. Avoid finalizers.
  • Two common sources of leaks:
    • Event handlers and delegates are references. If you subscribe to an event of an object, you are referencing to it. If you have a delegate to an object's method, you are referencing it.
    • Unmanaged resources, by definition, are not automatically collected. This is what the IDisposable pattern is for.
  • Finally, if you want a reference that does not prevent the object from getting collected, look into WeakReference.

One last thing: If you declare Foo foo; without assigning it you don't have to worry - nothing is leaked. If Foo is a reference type, nothing was created. If Foo is a value type, it is allocated on the stack and thus will automatically be cleaned up.

Immutable array in Java

In some situations, it will be lighter weight to use this static method from Google Guava library: List<Integer> Ints.asList(int... backingArray)

Examples:

  • List<Integer> x1 = Ints.asList(0, 1, 2, 3)
  • List<Integer> x1 = Ints.asList(new int[] { 0, 1, 2, 3})

Difference between database and schema

Schema says what tables are in database, what columns they have and how they are related. Each database has its own schema.

HTML - Display image after selecting filename

You can achieve this with the following code:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

Demo: http://jsfiddle.net/ugPDx/

python: unhashable type error

counter[row[11]]+=1

You don't show what data is, but apparently when you loop through its rows, row[11] is turning out to be a list. Lists are mutable objects which means they cannot be used as dictionary keys. Trying to use row[11] as a key causes the defaultdict to complain that it is a mutable, i.e. unhashable, object.

The easiest fix is to change row[11] from a list to a tuple. Either by doing

counter[tuple(row[11])] += 1

or by fixing it in the caller before data is passed to medications_minimum3. A tuple simply an immutable list, so it behaves exactly like a list does except you cannot change it once it is created.

How to use timeit module

The way timeit works is to run setup code once and then make repeated calls to a series of statements. So, if you want to test sorting, some care is required so that one pass at an in-place sort doesn't affect the next pass with already sorted data (that, of course, would make the Timsort really shine because it performs best when the data already partially ordered).

Here is an example of how to set up a test for sorting:

>>> import timeit

>>> setup = '''
import random

random.seed('slartibartfast')
s = [random.random() for i in range(1000)]
timsort = list.sort
'''

>>> print min(timeit.Timer('a=s[:]; timsort(a)', setup=setup).repeat(7, 1000))
0.334147930145

Note that the series of statements makes a fresh copy of the unsorted data on every pass.

Also, note the timing technique of running the measurement suite seven times and keeping only the best time -- this can really help reduce measurement distortions due to other processes running on your system.

Those are my tips for using timeit correctly. Hope this helps :-)

php - insert a variable in an echo string

You can try this

$i = 1
echo '<p class="paragraph'.$i.'"></p>';
++i; 

Excel: Use a cell value as a parameter for a SQL query

If you are using microsoft query, you can add "?" to your query...

select name from user where id= ?

that will popup a small window asking for the cell/data/etc when you go back to excel.

In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.

How to avoid the "divide by zero" error in SQL?

There is no magic global setting 'turn division by 0 exceptions off'. The operation has to to throw, since the mathematical meaning of x/0 is different from the NULL meaning, so it cannot return NULL. I assume you are taking care of the obvious and your queries have conditions that should eliminate the records with the 0 divisor and never evaluate the division. The usual 'gotcha' is than most developers expect SQL to behave like procedural languages and offer logical operator short-circuit, but it does NOT. I recommend you read this article: http://www.sqlmag.com/Articles/ArticleID/9148/pg/2/2.html

How to implement a binary tree?

# simple binary tree
# in this implementation, a node is inserted between an existing node and the root


class BinaryTree():

    def __init__(self,rootid):
      self.left = None
      self.right = None
      self.rootid = rootid

    def getLeftChild(self):
        return self.left
    def getRightChild(self):
        return self.right
    def setNodeValue(self,value):
        self.rootid = value
    def getNodeValue(self):
        return self.rootid

    def insertRight(self,newNode):
        if self.right == None:
            self.right = BinaryTree(newNode)
        else:
            tree = BinaryTree(newNode)
            tree.right = self.right
            self.right = tree

    def insertLeft(self,newNode):
        if self.left == None:
            self.left = BinaryTree(newNode)
        else:
            tree = BinaryTree(newNode)
            tree.left = self.left
            self.left = tree


def printTree(tree):
        if tree != None:
            printTree(tree.getLeftChild())
            print(tree.getNodeValue())
            printTree(tree.getRightChild())



# test tree

def testTree():
    myTree = BinaryTree("Maud")
    myTree.insertLeft("Bob")
    myTree.insertRight("Tony")
    myTree.insertRight("Steven")
    printTree(myTree)

Read more about it Here:-This is a very simple implementation of a binary tree.

This is a nice tutorial with questions in between

creating charts with angularjs

angular-charts is a library I wrote for creating charts with angular and D3.

It encapsulates basic charts that can be created using D3 in one angular directive. Also it offers features such as

  1. One click chart change;
  2. Auto tooltips;
  3. Auto adjustment to containers;
  4. Legends;
  5. Simple data format: only define what you on x and what you need on y;

There is a angular-charts demo available.

Find all elements with a certain attribute value in jquery

Use string concatenation. Try this:

$('div[imageId="'+imageN +'"]').each(function() {
    $(this);   
});

What is the difference between Bootstrap .container and .container-fluid classes?

Quick version: .container has one fixed width for each screen size in bootstrap (xs,sm,md,lg); .container-fluid expands to fill the available width.


The difference between container and container-fluid comes from these lines of CSS:

@media (min-width: 568px) {
  .container {
    width: 550px;
  }
}
@media (min-width: 992px) {
  .container {
    width: 970px;
  }
}
@media (min-width: 1200px) {
  .container {
    width: 1170px;
  }
}

Depending on the width of the viewport that the webpage is being viewed on, the container class gives its div a specific fixed width. These lines don't exist in any form for container-fluid, so its width changes every time the viewport width changes.

So for example, say your browser window is 1000px wide. As it's greater than the min-width of 992px, your .container element will have a width of 970px. You then slowly widen your browser window. The width of your .container won't change until you get to 1200px, at which it will jump to 1170px wide and stay that way for any larger browser widths.

Your .container-fluid element, on the other hand, will constantly resize as you make even the smallest changes to your browser width.

html <input type="text" /> onchange event not working

Checking for keystrokes is only a partial solution, because it's possible to change the contents of an input field using mouse clicks. If you right-click into a text field you'll have cut and paste options that you can use to change the value without making a keystroke. Likewise, if autocomplete is enabled then you can left-click into a field and get a dropdown of previously entered text, and you can select from among your choices using a mouse click. Keystroke trapping will not detect either of these types of changes.

Sadly, there is no "onchange" event that reports changes immediately, at least as far as I know. But there is a solution that works for all cases: set up a timing event using setInterval().

Let's say that your input field has an id and name of "city":

<input type="text" name="city" id="city" />

Have a global variable named "city":

var city = "";

Add this to your page initialization:

setInterval(lookForCityChange, 100);

Then define a lookForCityChange() function:

function lookForCityChange()
{
    var newCity = document.getElementById("city").value;
    if (newCity != city) {
        city = newCity;
        doSomething(city);     // do whatever you need to do
    }
}

In this example, the value of "city" is checked every 100 milliseconds, which you can adjust according to your needs. If you like, use an anonymous function instead of defining lookForCityChange(). Be aware that your code or even the browser might provide an initial value for the input field so you might be notified of a "change" before the user does anything; adjust your code as necessary.

If the idea of a timing event going off every tenth of a second seems ungainly, you can initiate the timer when the input field receives the focus and terminate it (with clearInterval()) upon a blur. I don't think it's possible to change the value of an input field without its receiving the focus, so turning the timer on and off in this fashion should be safe.

How do I escape a single quote in SQL Server?

Just insert a ' before anything to be inserted. It will be like a escape character in sqlServer

Example: When you have a field as, I'm fine. you can do: UPDATE my_table SET row ='I''m fine.';

DateTime2 vs DateTime in SQL Server

Here is an example that will show you the differences in storage size (bytes) and precision between smalldatetime, datetime, datetime2(0), and datetime2(7):

DECLARE @temp TABLE (
    sdt smalldatetime,
    dt datetime,
    dt20 datetime2(0),
    dt27 datetime2(7)
)

INSERT @temp
SELECT getdate(),getdate(),getdate(),getdate()

SELECT sdt,DATALENGTH(sdt) as sdt_bytes,
    dt,DATALENGTH(dt) as dt_bytes,
    dt20,DATALENGTH(dt20) as dt20_bytes,
    dt27, DATALENGTH(dt27) as dt27_bytes FROM @temp

which returns

sdt                  sdt_bytes  dt                       dt_bytes  dt20                 dt20_bytes  dt27                         dt27_bytes
-------------------  ---------  -----------------------  --------  -------------------  ----------  ---------------------------  ----------
2015-09-11 11:26:00  4          2015-09-11 11:25:42.417  8         2015-09-11 11:25:42  6           2015-09-11 11:25:42.4170000  8

So if I want to store information down to the second - but not to the millisecond - I can save 2 bytes each if I use datetime2(0) instead of datetime or datetime2(7).

How can I make a thumbnail <img> show a full size image when clicked?

Use this as an example

https://www.w3schools.com/jquerymobile/tryit.asp?filename=tryjqmob_popup_image

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div data-role="page">_x000D_
  <div data-role="header">_x000D_
    <h1>Welcome To My Homepage</h1>_x000D_
  </div>_x000D_
_x000D_
  <div id="pageone" data-role="main" class="ui-content">_x000D_
    <p>Click on the image to enlarge it.</p>_x000D_
    <p>Notice that we have added a "back button" in the top right corner.</p>_x000D_
    <a href="#myPopup" data-rel="popup" data-position-to="window">_x000D_
    <img src="https://lh3.googleusercontent.com/8XQPMmZImaDsSyEPbAptXOHQYZKP_rggu_tr9EPl3jpPnuXOd5gGP5kQKqFT0ZLXQ36-=s136" alt="Skaret View" style="width:200px;"></a>_x000D_
_x000D_
    <div data-role="popup" id="myPopup">_x000D_
      <p>This is my picture!</p> _x000D_
      <a href="#pageone" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-right">Close</a><img src="https://lh3.googleusercontent.com/8XQPMmZImaDsSyEPbAptXOHQYZKP_rggu_tr9EPl3jpPnuXOd5gGP5kQKqFT0ZLXQ36-=s136" style="width:800px;height:400px;" alt="Skaret View">_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div data-role="footer">_x000D_
    <h1>Footer Text</h1>_x000D_
  </div>_x000D_
</div> _x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Display only date and no time

You can modify your ViewModel as below:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",ApplyFormatInEditMode = true)]

How do you open a file in C++?

#include <fstream>

ifstream infile;
infile.open(**file path**);
while(!infile.eof())
{
   getline(infile,data);
}
infile.close();

ng-mouseover and leave to toggle item using mouse in angularjs

Here is example with only CSS for that. In example I'm using SASS and SLIM.

https://codepen.io/Darex1991/pen/zBxPxe

Slim:

a.btn.btn--joined-state
  span joined
  span leave

SASS:

=animate($property...)
  @each $vendor in ('-webkit-', '')
    #{$vendor}transition-property: $property
    #{$vendor}transition-duration: .3s
    #{$vendor}transition-timing-function: ease-in

=visible
  +animate(opacity, max-height, visibility)
  max-height: 150px
  opacity: 1
  visibility: visible

=invisible
  +animate(opacity, max-height, visibility)
  max-height: 0
  opacity: 0
  visibility: hidden

=transform($var)
  @each $vendor in ('-webkit-', '-ms-', '')
    #{$vendor}transform: $var

.btn
  border: 1px solid blue

  &--joined-state
    position: relative
    span
      +animate(opacity)

    span:last-of-type
      +invisible
      +transform(translateX(-50%))
      position: absolute
      left: 50%

    &:hover
      span:first-of-type
        +invisible
      span:last-of-type
        +visible
        border-color: blue

Including jars in classpath on commandline (javac or apt)

Try the following:

java -cp jar1:jar2:jar3:dir1:. HelloWorld

The default classpath (unless there is a CLASSPATH environment variable) is the current directory so if you redefine it, make sure you're adding the current directory (.) to the classpath as I have done.

How may I align text to the left and text to the right in the same line?

If you don't want to use floating elements and want to make sure that both blocks do not overlap, try:

<p style="text-align: left; width:49%; display: inline-block;">LEFT</p>
<p style="text-align: right; width:50%;  display: inline-block;">RIGHT</p>

jQuery: How to detect window width on the fly?

Put your if condition inside resize function:

var windowsize = $(window).width();

$(window).resize(function() {
  windowsize = $(window).width();
  if (windowsize > 440) {
    //if the window is greater than 440px wide then turn on jScrollPane..
      $('#pane1').jScrollPane({
         scrollbarWidth:15, 
         scrollbarMargin:52
      });
  }
});

Remove all classes that begin with a certain string

http://www.mail-archive.com/[email protected]/msg03998.html says:

...and .removeClass() would remove all classes...

It works for me ;)

cheers

How to compare pointers?

Yes, that is the definition of raw pointer equality: they both point to the same location (or are pointer aliases); usually in the virtual address space of the process running your application coded in C++ and managed by some operating system (but C++ can also be used for programming embedded devices with micro-controllers having a Harward architecture: on such microcontrollers some pointer casts are forbidden and makes no sense - since read only data could sit in code ROM)

For C++, read a good C++ programming book, see this C++ reference website, read the documentation of your C++ compiler (perhaps GCC or Clang) and consider coding with smart pointers. Maybe read also some draft C++ standard, like n4713 or buy the official standard from your ISO representative.

The concepts and terminology of garbage collection are also relevant when managing pointers and memory zones obtained by dynamic allocation (e.g. ::operator new), so read perhaps the GC handbook.

For pointers on Linux machines, see also this.

I have filtered my Excel data and now I want to number the rows. How do I do that?

I had the same problem. I'm no expert but this is the solution we used: Before you filter your data, first create a temporary column to populate your entire data set with your original sort order. Auto number the temporary "original sort order" column. Now filter your data. Copy and paste the filtered data into a new worksheet. This will move only the filtered data to the new sheet so that your row numbers will become consecutive. Now auto number your desired field. Go back to your original worksheet and delete the filtered rows. Copy and paste the newly numbered data from the secondary sheet onto the bottom of your original worksheet. Then clear your filter and sort the worksheet by the temporary "original sort order" column. This will put your newly numbered data back into its original order and you can then delete the temporary column.

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

check the no. of record in parent table that matches with child table and also primary key must match with foreign key reference. This works for me.

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

Why is there an unexplainable gap between these inline-block div elements?

Found a solution not involving Flex, because Flex doesn't work in older Browsers. Example:

.container {
    display:block;
    position:relative;
    height:150px;
    width:1024px;
    margin:0 auto;
    padding:0px;
    border:0px;
    background:#ececec;
    margin-bottom:10px;
    text-align:justify;
    box-sizing:border-box;
    white-space:nowrap;
    font-size:0pt;
    letter-spacing:-1em;
}

.cols {
    display:inline-block;
    position:relative;
    width:32%;
    height:100%;
    margin:0 auto;
    margin-right:2%;
    border:0px;
    background:lightgreen;  
    box-sizing:border-box;
    padding:10px;
    font-size:10pt;
    letter-spacing:normal;
}

.cols:last-child {
    margin-right:0;
}

ThreeJS: Remove object from scene

I think seeing your usage for addEntity and removeEntity code would be helpful, but my first thought is are you actually setting the object.name? Try in your loader just before scene.add(object); something like this:

object.name = "test_name";
scene.add(object);

What might be happening is the default "name" for an Object3D is "", so when you then call your removeEntity function it fails due to the scene objects name being ""

Also, I notice you pass in object.name to your loader? Is this where your storing the URL to the resource? If so, I would recommend using the Object3D's built in .userData method to store that information and keep the name field for scene identification purposes.

Edit: Response to newly added Code

First thing to note is it's not a great idea to have "/" in your object name, it seems to work fine but you never know if some algorithm will decide to escape that string and break your project.

Second item is now that I've seen your code, its actually straight forward whats going on. Your delete function is trying to delete by name, you need an Object3D to delete. Try this:

function removeEntity(object) {
    var selectedObject = scene.getObjectByName(object.name);
    scene.remove( selectedObject );
    animate();
}

Here you see I lookup your Object3D in the Three.js Scene by passing in your object tag's name attribute. Hope that helps

How do I check that a number is float or integer?

Here's my code. It checks to make sure it's not an empty string (which will otherwise pass) and then converts it to numeric format. Now, depending on whether you want '1.1' to be equal to 1.1, this may or may not be what you're looking for.

var isFloat = function(n) {
    n = n.length > 0 ? Number(n) : false;
    return (n === parseFloat(n));
};
var isInteger = function(n) {
    n = n.length > 0 ? Number(n) : false;
    return (n === parseInt(n));
};

var isNumeric = function(n){

   if(isInteger(n) || isFloat(n)){
        return true;
   }
   return false;

};

Access properties file programmatically with Spring?

This will resolve any nested properties.

public class Environment extends PropertyPlaceholderConfigurer {

/**
 * Map that hold all the properties.
 */
private Map<String, String> propertiesMap; 

/**
 * Iterate through all the Property keys and build a Map, resolve all the nested values before building the map.
 */
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
    super.processProperties(beanFactory, props);

    propertiesMap = new HashMap<String, String>();
    for (Object key : props.keySet()) {
        String keyStr = key.toString();
        String valueStr = beanFactory.resolveEmbeddedValue(placeholderPrefix + keyStr.trim() + DEFAULT_PLACEHOLDER_SUFFIX);
        propertiesMap.put(keyStr, valueStr);
    }
} 

/**
 * This method gets the String value for a given String key for the property files.
 * 
 * @param name - Key for which the value needs to be retrieved.
 * @return Value
 */
public String getProperty(String name) {
    return propertiesMap.get(name).toString();
}

How to solve privileges issues when restore PostgreSQL Database

Shorter answer: ignore it.

This module is the part of Postgres that processes the SQL language. The error will often pop up as part of copying a remote database, such as with a 'heroku pg:pull'. It does not overwrite your SQL processor and warns you about that.

Parsing time string in Python

Here's a stdlib solution that supports a variable utc offset in the input time string:

>>> from email.utils import parsedate_tz, mktime_tz
>>> from datetime import datetime, timedelta
>>> timestamp = mktime_tz(parsedate_tz('Tue May 08 15:14:45 +0800 2012'))
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
>>> utc_time
datetime.datetime(2012, 5, 8, 7, 14, 45)

WARNING: Can't verify CSRF token authenticity rails

If you are not using jQuery and using something like fetch API for requests you can use the following to get the csrf-token:

document.querySelector('meta[name="csrf-token"]').getAttribute('content')

fetch('/users', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content')},
    credentials: 'same-origin',
    body: JSON.stringify( { id: 1, name: 'some user' } )
    })
    .then(function(data) {
      console.log('request succeeded with JSON response', data)
    }).catch(function(error) {
      console.log('request failed', error)
    })

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

IF you want to to manipulate the ::before or ::after sudo elements entirely through CSS, you could do it JS. See below;

jQuery('head').append('<style id="mystyle" type="text/css"> /* your styles here */ </style>');

Notice how the <style> element has an ID, which you can use to remove it and append to it again if your style changes dynamically.

This way, your element is style exactly how you want it through CSS, with the help of JS.

return value after a promise

The best way to do this would be to use the promise returning function as it is, like this

lookupValue(file).then(function(res) {
    // Write the code which depends on the `res.val`, here
});

The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.

So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

How to programmatically set the Image source

Try to assign the image that way instead:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));

What's the safest way to iterate through the keys of a Perl hash?

A few miscellaneous thoughts on this topic:

  1. There is nothing unsafe about any of the hash iterators themselves. What is unsafe is modifying the keys of a hash while you're iterating over it. (It's perfectly safe to modify the values.) The only potential side-effect I can think of is that values returns aliases which means that modifying them will modify the contents of the hash. This is by design but may not be what you want in some circumstances.
  2. John's accepted answer is good with one exception: the documentation is clear that it is not safe to add keys while iterating over a hash. It may work for some data sets but will fail for others depending on the hash order.
  3. As already noted, it is safe to delete the last key returned by each. This is not true for keys as each is an iterator while keys returns a list.

How to keep an iPhone app running on background fully operational

If any background task runs more than 10 minutes,then the task will be suspended and code block specified with beginBackgroundTaskWithExpirationHandler is called to clean up the task. background remaining time can be checked with [[UIApplication sharedApplication] backgroundTimeRemaining]. Initially when the App is in foreground backgroundTimeRemaining is set to bigger value. When the app goes to background, you can see backgroundTimeRemaining value decreases from 599.XXX ( 1o minutes). once the backgroundTimeRemaining becomes ZERO, the background task will be suspended.

        //1)Creating iOS Background Task
        __block UIBackgroundTaskIdentifier background_task;
        background_task = [application beginBackgroundTaskWithExpirationHandler:^ {

               //This code block is execute when the application’s 
               //remaining background time reaches ZERO.
          }];


        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //### background task starts

            //#### background task ends
        });

        //2)Making background task Asynchronous
        if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)])
        {
            NSLog(@"Multitasking Supported");

            __block UIBackgroundTaskIdentifier background_task;
            background_task = [application beginBackgroundTaskWithExpirationHandler:^ {

                //Clean up code. Tell the system that we are done.
                [application endBackgroundTask: background_task];
                background_task = UIBackgroundTaskInvalid;
            }];


        **//Putting All together**
            //To make the code block asynchronous
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                //### background task starts
                NSLog(@"Running in the background\n");
                while(TRUE)
                {
                    NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
                    [NSThread sleepForTimeInterval:1]; //wait for 1 sec
                }
                //#### background task ends

                //Clean up code. Tell the system that we are done.
                [application endBackgroundTask: background_task];
                background_task = UIBackgroundTaskInvalid; 
            });
        }
        else
        {
            NSLog(@"Multitasking Not Supported");
        }

Import Script from a Parent Directory

If you want to run the script directly, you can:

  1. Add the FolderA's path to the environment variable (PYTHONPATH).
  2. Add the path to sys.path in the your script.

Then:

import module_you_wanted

How can I plot a confusion matrix?

@bninopaul 's answer is not completely for beginners

here is the code you can "copy and run"

import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt

array = [[13,1,1,0,2,0],
         [3,9,6,0,1,0],
         [0,0,16,2,0,0],
         [0,0,0,13,0,0],
         [0,0,0,0,15,0],
         [0,0,1,0,0,15]]

df_cm = pd.DataFrame(array, range(6), range(6))
# plt.figure(figsize=(10,7))
sn.set(font_scale=1.4) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 16}) # font size

plt.show()

result

The APK file does not exist on disk

modify the file:build.gradle(app directory). in fact:you should not change this file , only by this to get sync tips,then sync project.

Excel VBA: AutoFill Multiple Cells with Formulas

Based on my Comment here is one way to get what you want done:

Start byt selecting any cell in your range and Press Ctrl + T

This will give you this pop up:

enter image description here

make sure the Where is your table text is correct and click ok you will now have:

enter image description here

Now If you add a column header in D it will automatically be added to the table all the way to the last row:

enter image description here

Now If you enter a formula into this column:

enter image description here

After you enter it, the formula will be auto filled all the way to last row:

enter image description here

Now if you add a new row at the next row under your table:

enter image description here

Once entered it will be resized to the width of your table and all columns with formulas will be added also:

enter image description here

Hope this solves your problem!

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

django order_by query set, ascending and descending

67

Reserved.objects.filter(client=client_id).order_by('-check_in')

'-' is indicates Descending order and for Ascending order just give class attribute

to remove first and last element in array

You used Fruits.shift() method to first element remove . Fruits.pop() method used for last element remove one by one if you used button click. Fruits.slice( start position, delete element)You also used slice method for remove element in middle start.

What is the cause for "angular is not defined"

You have not placed the script tags for angular js

you can do so by using cdn or downloading the angularjs for your project and then referencing it

after this you have to add your own java script in your case main.js

that should do

How npm start runs a server on port 8000

To start the port correctly in your desired port use:

npm start -- --port 8000

Python Matplotlib Y-Axis ticks on Right Side of Plot

Use ax.yaxis.tick_right()

for example:

from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()

enter image description here

How to POST form data with Spring RestTemplate?

How to POST mixed data: File, String[], String in one request.

You can use only what you need.

private String doPOST(File file, String[] array, String name) {
    RestTemplate restTemplate = new RestTemplate(true);

    //add file
    LinkedMultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("file", new FileSystemResource(file));

    //add array
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://my_url");
    for (String item : array) {
        builder.queryParam("array", item);
    }

    //add some String
    builder.queryParam("name", name);

    //another staff
    String result = "";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
            new HttpEntity<>(params, headers);

    ResponseEntity<String> responseEntity = restTemplate.exchange(
            builder.build().encode().toUri(),
            HttpMethod.POST,
            requestEntity,
            String.class);

    HttpStatus statusCode = responseEntity.getStatusCode();
    if (statusCode == HttpStatus.ACCEPTED) {
        result = responseEntity.getBody();
    }
    return result;
}

The POST request will have File in its Body and next structure:

POST https://my_url?array=your_value1&array=your_value2&name=bob 

How to evaluate http response codes from bash/shell script?

I haven't tested this on a 500 code, but it works on others like 200, 302 and 404.

response=$(curl --write-out '%{http_code}' --silent --output /dev/null servername)

Note, format provided for --write-out should be quoted. As suggested by @ibai, add --head to make a HEAD only request. This will save time when the retrieval is successful since the page contents won't be transmitted.

Node.js Error: connect ECONNREFUSED

Same error occurs in localhost, i'm just changing the mysql port (8080 into localhost mysql port 5506). it works for me.

PHP - Move a file into a different folder on the server

Some solution is first to copy() the file (as mentioned above) and when the destination file exists - unlink() file from previous localization. Additionally you can validate the MD5 checksum before unlinking to be sure

Best practice multi language website

Implementing i18n Without The Performance Hit Using a Pre-Processor as suggested by Thomas Bley

At work, we recently went through implementation of i18n on a couple of our properties, and one of the things we kept struggling with was the performance hit of dealing with on-the-fly translation, then I discovered this great blog post by Thomas Bley which inspired the way we're using i18n to handle large traffic loads with minimal performance issues.

Instead of calling functions for every translation operation, which as we know in PHP is expensive, we define our base files with placeholders, then use a pre-processor to cache those files (we store the file modification time to make sure we're serving the latest content at all times).

The Translation Tags

Thomas uses {tr} and {/tr} tags to define where translations start and end. Due to the fact that we're using TWIG, we don't want to use { to avoid confusion so we use [%tr%] and [%/tr%] instead. Basically, this looks like this:

`return [%tr%]formatted_value[%/tr%];`

Note that Thomas suggests using the base English in the file. We don't do this because we don't want to have to modify all of the translation files if we change the value in English.

The INI Files

Then, we create an INI file for each language, in the format placeholder = translated:

// lang/fr.ini
formatted_value = number_format($value * Model_Exchange::getEurRate(), 2, ',', ' ') . '€'

// lang/en_gb.ini
formatted_value = '£' . number_format($value * Model_Exchange::getStgRate())

// lang/en_us.ini
formatted_value = '$' . number_format($value)

It would be trivial to allow a user to modify these inside the CMS, just get the keypairs by a preg_split on \n or = and making the CMS able to write to the INI files.

The Pre-Processor Component

Essentially, Thomas suggests using a just-in-time 'compiler' (though, in truth, it's a preprocessor) function like this to take your translation files and create static PHP files on disk. This way, we essentially cache our translated files instead of calling a translation function for every string in the file:

// This function was written by Thomas Bley, not by me
function translate($file) {
  $cache_file = 'cache/'.LANG.'_'.basename($file).'_'.filemtime($file).'.php';
  // (re)build translation?
  if (!file_exists($cache_file)) {
    $lang_file = 'lang/'.LANG.'.ini';
    $lang_file_php = 'cache/'.LANG.'_'.filemtime($lang_file).'.php';

    // convert .ini file into .php file
    if (!file_exists($lang_file_php)) {
      file_put_contents($lang_file_php, '<?php $strings='.
        var_export(parse_ini_file($lang_file), true).';', LOCK_EX);
    }
    // translate .php into localized .php file
    $tr = function($match) use (&$lang_file_php) {
      static $strings = null;
      if ($strings===null) require($lang_file_php);
      return isset($strings[ $match[1] ]) ? $strings[ $match[1] ] : $match[1];
    };
    // replace all {t}abc{/t} by tr()
    file_put_contents($cache_file, preg_replace_callback(
      '/\[%tr%\](.*?)\[%\/tr%\]/', $tr, file_get_contents($file)), LOCK_EX);
  }
  return $cache_file;
}

Note: I didn't verify that the regex works, I didn't copy it from our company server, but you can see how the operation works.

How to Call It

Again, this example is from Thomas Bley, not from me:

// instead of
require("core/example.php");
echo (new example())->now();

// we write
define('LANG', 'en_us');
require(translate('core/example.php'));
echo (new example())->now();

We store the language in a cookie (or session variable if we can't get a cookie) and then retrieve it on every request. You could combine this with an optional $_GET parameter to override the language, but I don't suggest subdomain-per-language or page-per-language because it'll make it harder to see which pages are popular and will reduce the value of inbound links as you'll have them more scarcely spread.

Why use this method?

We like this method of preprocessing for three reasons:

  1. The huge performance gain from not calling a whole bunch of functions for content which rarely changes (with this system, 100k visitors in French will still only end up running translation replacement once).
  2. It doesn't add any load to our database, as it uses simple flat-files and is a pure-PHP solution.
  3. The ability to use PHP expressions within our translations.

Getting Translated Database Content

We just add a column for content in our database called language, then we use an accessor method for the LANG constant which we defined earlier on, so our SQL calls (using ZF1, sadly) look like this:

$query = select()->from($this->_name)
                 ->where('language = ?', User::getLang())
                 ->where('id       = ?', $articleId)
                 ->limit(1);

Our articles have a compound primary key over id and language so article 54 can exist in all languages. Our LANG defaults to en_US if not specified.

URL Slug Translation

I'd combine two things here, one is a function in your bootstrap which accepts a $_GET parameter for language and overrides the cookie variable, and another is routing which accepts multiple slugs. Then you can do something like this in your routing:

"/wilkommen" => "/welcome/lang/de"
... etc ...

These could be stored in a flat file which could be easily written to from your admin panel. JSON or XML may provide a good structure for supporting them.

Notes Regarding A Few Other Options

PHP-based On-The-Fly Translation

I can't see that these offer any advantage over pre-processed translations.

Front-end Based Translations

I've long found these interesting, but there are a few caveats. For example, you have to make available to the user the entire list of phrases on your website that you plan to translate, this could be problematic if there are areas of the site you're keeping hidden or haven't allowed them access to.

You'd also have to assume that all of your users are willing and able to use Javascript on your site, but from my statistics, around 2.5% of our users are running without it (or using Noscript to block our sites from using it).

Database-Driven Translations

PHP's database connectivity speeds are nothing to write home about, and this adds to the already high overhead of calling a function on every phrase to translate. The performance & scalability issues seem overwhelming with this approach.

How to create an Excel File with Nodejs?

I just figured a simple way out . This works -

Just create a file with Tabs as delimiters ( similar to CSV but replace comma with Tab ). Save it with extension .XLS . The file can be opened in Excel .

Some code to help --

var fs = require('fs');
var writeStream = fs.createWriteStream("file.xls");

var header="Sl No"+"\t"+" Age"+"\t"+"Name"+"\n";
var row1 = "0"+"\t"+" 21"+"\t"+"Rob"+"\n";
var row2 = "1"+"\t"+" 22"+"\t"+"bob"+"\n";

writeStream.write(header);
writeStream.write(row1);
writeStream.write(row2);

writeStream.close();

This creates the file in XLS file format . It doesnt work if you try XLSX instead of XLS .

Selecting/excluding sets of columns in pandas

You have 4 columns A,B,C,D

Here is a better way to select the columns you need for the new dataframe:-

df2 = df1[['A','D']]

if you wish to use column numbers instead, use:-

df2 = df1[[0,3]]

why I can't get value of label with jquery and javascript?

Label's aren't form elements. They don't have a value. They have innerHTML and textContent.

Thus,

$('#telefon').html() 
// or
$('#telefon').text()

or

var telefon = document.getElementById('telefon');
telefon.innerHTML;

If you are starting with your form element, check out the labels list of it. That is,

var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea

Call Python function from JavaScript code

From the document.getElementsByTagName I guess you are running the javascript in a browser.

The traditional way to expose functionality to javascript running in the browser is calling a remote URL using AJAX. The X in AJAX is for XML, but nowadays everybody uses JSON instead of XML.

For example, using jQuery you can do something like:

$.getJSON('http://example.com/your/webservice?param1=x&param2=y', 
    function(data, textStatus, jqXHR) {
        alert(data);
    }
)

You will need to implement a python webservice on the server side. For simple webservices I like to use Flask.

A typical implementation looks like:

@app.route("/your/webservice")
def my_webservice():
    return jsonify(result=some_function(**request.args)) 

You can run IronPython (kind of Python.Net) in the browser with silverlight, but I don't know if NLTK is available for IronPython.

How to sort an array of associative arrays by value of a given key in PHP?

From Sort an array of associative arrays by value of given key in php:

by using usort (http://php.net/usort) , we can sort an array in ascending and descending order. just we need to create a function and pass it as parameter in usort. As per below example used greater than for ascending order if we passed less than condition then it's sort in descending order. Example :

$array = array(
  array('price'=>'1000.50','product'=>'test1'),
  array('price'=>'8800.50','product'=>'test2'),
  array('price'=>'200.0','product'=>'test3')
);

function cmp($a, $b) {
  return $a['price'] > $b['price'];
}

usort($array, "cmp");
print_r($array);

Output:

Array
 (
    [0] => Array
        (
            [price] => 200.0
            [product] => test3
        )

    [1] => Array
        (
            [price] => 1000.50
            [product] => test1
        )

    [2] => Array
        (
            [price] => 8800.50
            [product] => test2
        )
  )

How do I terminate a thread in C++11?

  1. You could call std::terminate() from any thread and the thread you're referring to will forcefully end.

  2. You could arrange for ~thread() to be executed on the object of the target thread, without a intervening join() nor detach() on that object. This will have the same effect as option 1.

  3. You could design an exception which has a destructor which throws an exception. And then arrange for the target thread to throw this exception when it is to be forcefully terminated. The tricky part on this one is getting the target thread to throw this exception.

Options 1 and 2 don't leak intra-process resources, but they terminate every thread.

Option 3 will probably leak resources, but is partially cooperative in that the target thread has to agree to throw the exception.

There is no portable way in C++11 (that I'm aware of) to non-cooperatively kill a single thread in a multi-thread program (i.e. without killing all threads). There was no motivation to design such a feature.

A std::thread may have this member function:

native_handle_type native_handle();

You might be able to use this to call an OS-dependent function to do what you want. For example on Apple's OS's, this function exists and native_handle_type is a pthread_t. If you are successful, you are likely to leak resources.

Searching a list of objects in Python

Another way you could do it is using the next() function.

matched_obj = next(x for x in list if x.n == 10)

In Jinja2, how do you test if a variable is undefined?

From the Jinja2 template designer documentation:

{% if variable is defined %}
    value of variable: {{ variable }}
{% else %}
    variable is not defined
{% endif %}

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

The above options works for Google big query file also. I exported a table data to goodle cloud storage and downloaded from there. While loading the same to sql server was facing this issue and could successfully load the file after specifying the row delimiter as

ROWTERMINATOR = '0x0a' 

Pay attention to header record as well and specify

FIRSTROW = 2

My final block for data file export from google bigquery looks like this.

BULK INSERT TABLENAME
        FROM 'C:\ETL\Data\BigQuery\In\FILENAME.csv'
        WITH
        (
         FIRSTROW = 2,
         FIELDTERMINATOR = ',',  --CSV field delimiter
         ROWTERMINATOR = '0x0a',--Files are generated with this row terminator in Google Bigquery
         TABLOCK
        )

Push Notifications in Android Platform

(cross-posting from an answer I gave to a similar question - Does Android support near real time push notification? )

I recently started playing with MQTT http://mqtt.org for Android as a way of doing this sort of thing (i.e. push notification that is not SMS but data driven, almost immediate message delivery, not polling, etc.)

I have a blog post with background information on this in case it's helpful

http://dalelane.co.uk/blog/?p=938

(Note: MQTT is an IBM technology, and I should point out that I work for IBM.)

SSRS expression to format two decimal places does not show zeros

Please try the following code snippet,

IIF(Round(Avg(Fields!Vision_Score.Value)) = Avg(Fields!Vision_Score.Value), 
Format(Avg(Fields!Vision_Score.Value)), 
FORMAT(Avg(Fields!Vision_Score.Value),"##.##"))

hope it will help, Thank-you.

The zip() function in Python 3

The zip() function in Python 3 returns an iterator. That is the reason why when you print test1 you get - <zip object at 0x1007a06c8>. From documentation -

Make an iterator that aggregates elements from each of the iterables.

But once you do - list(test1) - you have exhausted the iterator. So after that anytime you do list(test1) would only result in empty list.

In case of test2, you have already created the list once, test2 is a list, and hence it will always be that list.

Double value to round up in Java

You can use format like here,

  public static double getDoubleValue(String value,int digit){
    if(value==null){
        value="0";
     }
    double i=0;
     try {
         DecimalFormat digitformat = new DecimalFormat("#.##");
         digitformat.setMaximumFractionDigits(digit);
        return Double.valueOf(digitformat.format(Double.parseDouble(value)));

    } catch (NumberFormatException numberFormatExp) {
        return i;   
    }
}

Forbidden: You don't have permission to access / on this server, WAMP Error

I find the best (and least frustrating) path is to start with Allow from All, then, when you know it will work that way, scale it back to the more secure Allow from 127.0.0.1 or Allow from ::1 (localhost).

As long as your firewall is configured properly, Allow from all shouldn't cause any problems, but it is better to only allow from localhost if you don't need other computers to be able to access your site.

Don't forget to restart Apache whenever you make changes to httpd.conf. They will not take effect until the next start.

Hopefully this is enough to get you started, there is lots of documentation available online.

Installing a local module using npm?

Neither of these approaches (npm link or package.json file dependency) work if the local module has peer dependencies that you only want to install in your project's scope.

For example:

/local/mymodule/package.json:
  "name": "mymodule",
  "peerDependencies":
  {
    "foo": "^2.5"
  }

/dev/myproject/package.json:
  "dependencies":
  {
    "mymodule": "file:/local/mymodule",
    "foo": "^2.5"
  }

In this scenario, npm sets up myproject's node_modules/ like this:

/dev/myproject/node_modules/
  foo/
  mymodule -> /local/mymodule

When node loads mymodule and it does require('foo'), node resolves the mymodule symlink, and then only looks in /local/mymodule/node_modules/ (and its ancestors) for foo, which it doen't find. Instead, we want node to look in /local/myproject/node_modules/, since that's where were running our project from, and where foo is installed.

So, we either need a way to tell node to not resolve this symlink when looking for foo, or we need a way to tell npm to install a copy of mymodule when the file dependency syntax is used in package.json. I haven't found a way to do either, unfortunately :(

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

wanna add to main answer above
I tried to follow it but my recyclerView began to stretch every item to a screen
I had to add next line after inflating for reach to goal

itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));

I already added these params by xml but it didnot work correctly
and with this line all is ok

What is Mocking?

Mocking is generating pseudo-objects that simulate real objects behaviour for tests

$lookup on ObjectId's in an array

use $unwind you will get the first object instead of array of objects

query:

db.getCollection('vehicles').aggregate([
  {
    $match: {
      status: "AVAILABLE",
      vehicleTypeId: {
        $in: Array.from(newSet(d.vehicleTypeIds))
      }
    }
  },
  {
    $lookup: {
      from: "servicelocations",
      localField: "locationId",
      foreignField: "serviceLocationId",
      as: "locations"
    }
  },
  {
    $unwind: "$locations"
  }
]);

result:

{
    "_id" : ObjectId("59c3983a647101ec58ddcf90"),
    "vehicleId" : "45680",
    "regionId" : 1.0,
    "vehicleTypeId" : "10TONBOX",
    "locationId" : "100",
    "description" : "Isuzu/2003-10 Ton/Box",
    "deviceId" : "",
    "earliestStart" : 36000.0,
    "latestArrival" : 54000.0,
    "status" : "AVAILABLE",
    "accountId" : 1.0,
    "locations" : {
        "_id" : ObjectId("59c3afeab7799c90ebb3291f"),
        "serviceLocationId" : "100",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "Masafi Park Al Quoz",
        "locationPriority" : 1.0,
        "accountTypeId" : 0.0,
        "locationType" : "DEPOT",
        "location" : {
            "makani" : "",
            "lat" : 25.123091,
            "lng" : 55.21082
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : {
            "timeWindowTypeId" : "1"
        },
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1"
    }
}


{
    "_id" : ObjectId("59c3983a647101ec58ddcf91"),
    "vehicleId" : "81765",
    "regionId" : 1.0,
    "vehicleTypeId" : "10TONBOX",
    "locationId" : "100",
    "description" : "Hino/2004-10 Ton/Box",
    "deviceId" : "",
    "earliestStart" : 36000.0,
    "latestArrival" : 54000.0,
    "status" : "AVAILABLE",
    "accountId" : 1.0,
    "locations" : {
        "_id" : ObjectId("59c3afeab7799c90ebb3291f"),
        "serviceLocationId" : "100",
        "regionId" : 1.0,
        "zoneId" : "DXBZONE1",
        "description" : "Masafi Park Al Quoz",
        "locationPriority" : 1.0,
        "accountTypeId" : 0.0,
        "locationType" : "DEPOT",
        "location" : {
            "makani" : "",
            "lat" : 25.123091,
            "lng" : 55.21082
        },
        "deliveryDays" : "MTWRFSU",
        "timeWindow" : {
            "timeWindowTypeId" : "1"
        },
        "address1" : "",
        "address2" : "",
        "phone" : "",
        "city" : "",
        "county" : "",
        "state" : "",
        "country" : "",
        "zipcode" : "",
        "imageUrl" : "",
        "contact" : {
            "name" : "",
            "email" : ""
        },
        "status" : "",
        "createdBy" : "",
        "updatedBy" : "",
        "updateDate" : "",
        "accountId" : 1.0,
        "serviceTimeTypeId" : "1"
    }
}

get the selected index value of <select> tag in php

Your form is valid. Only thing that comes to my mind is, after seeing your full html, is that you're passing your "default" value (which is not set!) instead of selecting something. Try as suggested by @Vina in the comment, i.e. giving it a selected option, or writing a default value

<select name="gender">
<option value="default">Select </option>    
<option value="male">   Male   </option>
<option value="female"> Female </option>
</select>

OR

<select name="gender">
<option value="male" selected="selected">   Male   </option>
<option value="female"> Female </option>
</select>

When you get your $_POST vars, check for them being set; you can assign a default value, or just an empty string in case they're not there.

Most important thing, AVOID SQL INJECTIONS:

//....
$fname   = isset($_POST["fname"]) ? mysql_real_escape_string($_POST['fname']) : '';
$lname   = isset($_POST['lname']) ? mysql_real_escape_string($_POST['lname']) : '';
$email   = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : '';
you might also want to validate e-mail:
if($mail = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
  $email = mysql_real_escape_string($_POST['email']);
}
else
{
  //die ('invalid email address');
  // or whatever, a default value? $email = '';
}
$paswod  = isset($_POST["paswod"]) ? mysql_real_escape_string($_POST['paswod']) : '';
$gender  = isset($_POST['gender']) ? mysql_real_escape_string($_POST['gender']) : '';

$query = mysql_query("SELECT Email FROM users WHERE Email = '".$email."')";
if(mysql_num_rows($query)> 0)
{
  echo 'userid is already there';
}
else
{
 $sql = "INSERT INTO users (FirstName, LastName, Email, Password, Gender)
         VALUES ('".$fname."','".$lname."','".$email."','".paswod."','".$gender."')";
$res = mysql_query($sql) or die('Error:'.mysql_error());
echo 'created';

What do the return values of Comparable.compareTo mean in Java?

I use this mnemonic :

a.compareTo(b) < 0 // a < b

a.compareTo(b) > 0 // a > b

a.compareTo(b) == 0 // a == b

You keep the signs and always compare the result of compareTo() to 0

Purge or recreate a Ruby on Rails database

Use like

rake db:drop db:create db:migrate db:seed

All in one line. This is faster since the environment doesn't get reloaded again and again.

db:drop - will drop database.

db:create - will create database (host/db/password will be taken from config/database.yml)

db:migrate - will run existing migrations from directory (db/migration/.rb)*.

db:seed - will run seed data possible from directory (db/migration/seed.rb)..

I usually prefer:

rake db:reset

to do all at once.

Cheers!

How to add 10 days to current time in Rails

Try this on Ruby. It will return a new date/time the specified number of days in the future

DateTime.now.days_since(10)

Parameter in like clause JPQL

I don't use named parameters for all queries. For example it is unusual to use named parameters in JpaRepository.

To workaround I use JPQL CONCAT function (this code emulate start with):

@Repository
public interface BranchRepository extends JpaRepository<Branch, String> {
    private static final String QUERY = "select b from Branch b"
       + " left join b.filial f"
       + " where f.id = ?1 and b.id like CONCAT(?2, '%')";
    @Query(QUERY)
    List<Branch> findByFilialAndBranchLike(String filialId, String branchCode);
}

I found this technique in excellent docs: http://openjpa.apache.org/builds/1.0.1/apache-openjpa-1.0.1/docs/manual/jpa_overview_query.html

Failed to connect to mailserver at "localhost" port 25

First of all, you aren't forced to use an SMTP on your localhost, if you change that localhost entry into the DNS name of the MTA from your ISP provider (who will let you relay mail) it will work right away, so no messing about with your own email service. Just try to use your providers SMTP servers, it will work right away.

how to change class name of an element by jquery

$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');

Case in method names is important, so no addclass.

jQuery addClass()
jQuery removeClass()

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.

Warning: push.default is unset; its implicit value is changing in Git 2.0

It's explained in great detail in the docs, but I'll try to summarize:

  • matching means git push will push all your local branches to the ones with the same name on the remote. This makes it easy to accidentally push a branch you didn't intend to.

  • simple means git push will push only the current branch to the one that git pull would pull from, and also checks that their names match. This is a more intuitive behavior, which is why the default is getting changed to this.

This setting only affects the behavior of your local client, and can be overridden by explicitly specifying which branches you want to push on the command line. Other clients can have different settings, it only affects what happens when you don't specify which branches you want to push.

How to make UIButton's text alignment center? Using IB

UIButton will not support setTextAlignment. So You need to go with setContentHorizontalAlignment for button text alignment

For your reference

[buttonName setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];

How to do an Integer.parseInt() for a decimal number?

String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;

The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3 to a int is nonsense. A double or a float datatype can hold rational numbers.

The way Java casts a double to an int is done by removing the part after the decimal separator by rounding towards zero.

int i = (int) 0.9999;

i will be zero.

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

  1. Delete all temp files
    • search %TEMP%
    • delete all
  2. Perform a clean boot. see How to perform a clean boot in Windows
  3. Install vc_redist.x64 see Download Visual C++ Redistributable for Visual Studio 2015
  4. Restart without clean boot

How does one convert a grayscale image to RGB in OpenCV (Python)?

Alternatively, cv2.merge() can be used to turn a single channel binary mask layer into a three channel color image by merging the same layer together as the blue, green, and red layers of the new image. We pass in a list of the three color channel layers - all the same in this case - and the function returns a single image with those color channels. This effectively transforms a grayscale image of shape (height, width, 1) into (height, width, 3)

To address your problem

I did some thresholding on an image and want to label the contours in green, but they aren't showing up in green because my image is in black and white.

This is because you're trying to display three channels on a single channel image. To fix this, you can simply merge the three single channels

image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])

Example

We create a color image with dimensions (200,200,3)

enter image description here

image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)

Next we convert it to grayscale and create another image using cv2.merge() with three gray channels

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])

We now draw a filled contour onto the single channel grayscale image (left) with shape (200,200,1) and the three channel grayscale image with shape (200,200,3) (right). The left image showcases the problem you're experiencing since you're trying to display three channels on a single channel image. After merging the grayscale image into three channels, we can now apply color onto the image

enter image description here enter image description here

contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])

Full code

import cv2
import numpy as np

# Create random color image
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)

# Convert to grayscale (1 channel)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Merge channels to create color image (3 channels)
gray_three = cv2.merge([gray,gray,gray])

# Fill a contour on both the single channel and three channel image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])

cv2.imshow('image', image)
cv2.imshow('gray', gray)
cv2.imshow('gray_three', gray_three)
cv2.waitKey()

What is the difference between persist() and merge() in JPA and Hibernate?

Persist should be called only on new entities, while merge is meant to reattach detached entities.

If you're using the assigned generator, using merge instead of persist can cause a redundant SQL statement.

Also, calling merge for managed entities is also a mistake since managed entities are automatically managed by Hibernate, and their state is synchronized with the database record by the dirty checking mechanism upon flushing the Persistence Context.

Merge a Branch into Trunk

Your svn merge syntax is wrong.

You want to checkout a working copy of trunk and then use the svn merge --reintegrate option:

$ pwd
/home/user/project-trunk

$ svn update  # (make sure the working copy is up to date)
At revision <N>.

$ svn merge --reintegrate ^/project/branches/branch_1
--- Merging differences between repository URLs into '.':
U    foo.c
U    bar.c
 U   .

$ # build, test, verify, ...

$ svn commit -m "Merge branch_1 back into trunk!"
Sending        .
Sending        foo.c
Sending        bar.c
Transmitting file data ..
Committed revision <N+1>.

See the SVN book chapter on merging for more details.


Note that at the time it was written, this was the right answer (and was accepted), but things have moved on. See the answer of topek, and http://subversion.apache.org/docs/release-notes/1.8.html#auto-reintegrate

What is a correct MIME type for .docx, .pptx, etc.?

This post will explore various approaches of fetching MIME Type across various programming languages with their CONS in one-line description as header. So, use them accordingly and the one which works for you.

For eg. the code below is especially helpful when user may supply either of .xls, .xlsx or .xlsm and you don't want to write code testing extension and supplying MIME-type for each of them. Let the system do this job.

Python 3

Using python-magic

>>> pip install python-magic
>>> import magic
>>> magic.from_file("Employee.pdf", mime=True)
'application/pdf'

Using built-in mimeypes module - Map filenames to MimeTypes modules

>>> import mimetypes
>>> mimetypes.init()
>>> mimetypes.knownfiles
['/etc/mime.types', '/etc/httpd/mime.types', ... ]
>>> mimetypes.suffix_map['.tgz']
'.tar.gz'
>>> mimetypes.encodings_map['.gz']
'gzip'
>>> mimetypes.types_map['.tgz']
'application/x-tar-gz'

JAVA 7

Source: Baeldung's blog on File MIME Types in Java

Operating System dependent

@Test
public void get_JAVA7_mimetype() {
    Path path = new File("Employee.xlsx").toPath();
    String mimeType = Files.probeContentType(path);

    assertEquals(mimeType, "application/vnd.ms-excel");
}

It will use FileTypeDetector implementations to probe the MIME type and invokes the probeContentType of each implementation to resolve the type. Hence, if the file is known to the implementations then the content type is returned. However, if that doesn’t happen, a system-default file type detector is invoked.


Resolve using first few characters of the input stream

@Test
public void getMIMEType_from_Extension(){
    File file = new File("Employee.xlsx");
    String mimeType = URLConnection.guessContentTypeFromName(file.getName());

    assertEquals(mimeType, "application/vnd.ms-excel");
}

Using built-in table of MIME types

@Test
public void getMIMEType_UsingGetFileNameMap(){
    File file = new File("Employee.xlsx");
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    String mimeType = fileNameMap.getContentTypeFor(file.getName());

    assertEquals(mimeType, "image/png");
}

It returns the matrix of MIME types used by all instances of URLConnection which then is used to resolve the input file type. However, this matrix of MIME types is very limited when it comes to URLConnection.

By default, the class uses content-types.properties file in JRE_HOME/lib. We can, however, extend it, by specifying a user-specific table using the content.types.user.table property:

System.setProperty("content.types.user.table","<path-to-file>");

JavaScript

Source: FileReader API & Medium's article on using Magic Numbers in JavaScript to get Mime Types

Interpret the Magic Number fetched using FileReader API

Final result looks something like this when one use javaScript to fetch the MimeType based on filestream. Open the embedded jsFiddle to see and understand this approach.

Bonus: It's accessible for most of the MIME Types and also you can add custom Mime Types in the getMimetype function. Also, it has FULL SUPPORT for MS Office Files Mime Types.

FileReader API Result

The steps to calculate mime type for a file in this example would be:

  1. The user selects a file.
  2. Take the first 4 bytes of the file using the slice method.
  3. Create a new FileReader instance
  4. Use the FileReader to read the 4 bytes you sliced out as an array buffer.
  5. Since the array buffer is just a generic way to represent a binary buffer we need to create a TypedArray, in this case an Uint8Array.
  6. With a TypedArray at our hands we can retrieve every byte and transform it to hexadecimal (by using toString(16)).
  7. We now have a way to get the magic numbers from a file by reading the first four bytes. The final step is to map it to a real mime type.

Browser Support (Above 95% overall and Close to 100% in all modern browsers): FileReader API

File Reader API Browser Support

_x000D_
_x000D_
const uploads = []_x000D_
_x000D_
const fileSelector = document.getElementById('file-selector')_x000D_
fileSelector.addEventListener('change', (event) => {_x000D_
  console.time('FileOpen')_x000D_
  const file = event.target.files[0]_x000D_
_x000D_
  const filereader = new FileReader()_x000D_
_x000D_
  filereader.onloadend = function(evt) {_x000D_
    if (evt.target.readyState === FileReader.DONE) {_x000D_
      const uint = new Uint8Array(evt.target.result)_x000D_
      let bytes = []_x000D_
      uint.forEach((byte) => {_x000D_
        bytes.push(byte.toString(16))_x000D_
      })_x000D_
      const hex = bytes.join('').toUpperCase()_x000D_
_x000D_
      uploads.push({_x000D_
        filename: file.name,_x000D_
        filetype: file.type ? file.type : 'Unknown/Extension missing',_x000D_
        binaryFileType: getMimetype(hex),_x000D_
        hex: hex_x000D_
      })_x000D_
      render()_x000D_
    }_x000D_
_x000D_
    console.timeEnd('FileOpen')_x000D_
  }_x000D_
_x000D_
_x000D_
  const blob = file.slice(0, 4);_x000D_
  filereader.readAsArrayBuffer(blob);_x000D_
})_x000D_
_x000D_
const render = () => {_x000D_
  const container = document.getElementById('files')_x000D_
_x000D_
  const uploadedFiles = uploads.map((file) => {_x000D_
    return `<div class=result><hr />_x000D_
                    <span class=filename>Filename: <strong>${file.filename}</strong></span><br>_x000D_
                    <span class=fileObject>File Object (Mime Type):<strong> ${file.filetype}</strong></span><br>_x000D_
                    <span class=binaryObject>Binary (Mime Type):<strong> ${file.binaryFileType}</strong></span><br>_x000D_
                    <span class=HexCode>Hex Code (Magic Number):<strong> <em>${file.hex}</strong></span></em>_x000D_
                    </div>`_x000D_
  })_x000D_
_x000D_
  container.innerHTML = uploadedFiles.join('')_x000D_
}_x000D_
_x000D_
const getMimetype = (signature) => {_x000D_
  switch (signature) {_x000D_
    case '89504E47':_x000D_
      return 'image/png'_x000D_
    case '47494638':_x000D_
      return 'image/gif'_x000D_
    case '25504446':_x000D_
      return 'application/pdf'_x000D_
    case 'FFD8FFDB':_x000D_
    case 'FFD8FFE0':_x000D_
    case 'FFD8FFE1':_x000D_
      return 'image/jpeg'_x000D_
    case '504B0304':_x000D_
      return 'application/zip'_x000D_
    case '504B34':_x000D_
      return 'application/vnd.ms-excel.sheet.macroEnabled.12'_x000D_
    default:_x000D_
      return 'Unknown filetype'_x000D_
  }_x000D_
}
_x000D_
.result {_x000D_
  font-family: Palatino, "Palatino Linotype", "Palatino LT STD", "Book Antiqua", Georgia, serif;_x000D_
  line-height: 20px;_x000D_
  font-size: 14px;_x000D_
  margin: 10px 0;_x000D_
}_x000D_
_x000D_
.filename {_x000D_
  color: #333;_x000D_
  font-size: 16px;_x000D_
}_x000D_
_x000D_
.fileObject {_x000D_
  color: #a53;_x000D_
}_x000D_
_x000D_
.binaryObject {_x000D_
  color: #63f;_x000D_
}_x000D_
_x000D_
.HexCode {_x000D_
  color: #262;_x000D_
}_x000D_
_x000D_
em {_x000D_
  padding: 2px 4px;_x000D_
  background-color: #efefef;_x000D_
  font-style: normal;_x000D_
}_x000D_
_x000D_
input[type=file] {_x000D_
  background-color: #4CAF50;_x000D_
  border: none;_x000D_
  color: white;_x000D_
  padding: 8px 16px;_x000D_
  text-decoration: none;_x000D_
  margin: 4px 2px;_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<body>_x000D_
_x000D_
  <input type="file" id="file-selector">_x000D_
_x000D_
  <div id="files"></div>
_x000D_
_x000D_
_x000D_

How to add manifest permission to an application?

Permission name is CASE-SENSITIVE

In case somebody will struggle with same issue, it is case sensitive statement, so wrong case means your application won't get the permission.

WRONG

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

CORRECT

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

This issue may happen ie. on autocomplete in IDE

C# string replace

Try this:

line.Replace("\",\"", ";")

DOUBLE vs DECIMAL in MySQL

Actually it's quite different. DOUBLE causes rounding issues. And if you do something like 0.1 + 0.2 it gives you something like 0.30000000000000004. I personally would not trust financial data that uses floating point math. The impact may be small, but who knows. I would rather have what I know is reliable data than data that were approximated, especially when you are dealing with money values.

Which exception should I raise on bad/illegal argument combinations in Python?

I would inherit from ValueError

class IllegalArgumentError(ValueError):
    pass

It is sometimes better to create your own exceptions, but inherit from a built-in one, which is as close to what you want as possible.

If you need to catch that specific error, it is helpful to have a name.

How to select an element with 2 classes

Just chain them together:

.a.b {
  color: #666;
}

When should I use Memcache instead of Memcached?

Memcached is a newer API, it also provides memcached as a session provider which could be great if you have a farm of server.

After the version is still really low 0.2 but I have used both and I didn't encounter major problem, so I would go to memcached since it's new.

What does "atomic" mean in programming?

"Atomic operation" means an operation that appears to be instantaneous from the perspective of all other threads. You don't need to worry about a partly complete operation when the guarantee applies.

Nginx location "not equal to" regex

According to nginx documentation

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else

So you could define something like

location ~ (dir1|file2\.php) { 
    # empty
}

location / {
    rewrite ^/(.*) http://example.com/$1 permanent; 
}

Limit the height of a responsive image with css

The trick is to add both max-height: 100%; and max-width: 100%; to .container img. Example CSS:

.container {
  width: 300px;
  border: dashed blue 1px;
}

.container img {
  max-height: 100%;
  max-width: 100%;
}

In this way, you can vary the specified width of .container in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)

Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/

How to disable RecyclerView scrolling?

There is a more straightforward way to disable scrolling (technically it is more rather interception of a scrolling event and ending it when a condition is met), using just standard functionality. RecyclerView has the method called addOnScrollListener(OnScrollListener listener), and using just this you can stop it from scrolling, just so:

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if (viewModel.isItemSelected) {
            recyclerView.stopScroll();
        }
    }
});

Use case: Let's say that you want to disable scrolling when you click on one of the items within RecyclerView so you could perform some actions with it, without being distracted by accidentally scrolling to another item, and when you are done with it, just click on the item again to enable scrolling. For that, you would want to attach OnClickListener to every item within RecyclerView, so when you click on an item, it would toggle isItemSelected from false to true. This way when you try to scroll, RecyclerView will automatically call method onScrollStateChanged and since isItemSelected set to true, it will stop immediately, before RecyclerView got the chance, well... to scroll.

Note: for better usability, try to use GestureListener instead of OnClickListener to prevent accidental clicks.

Binary Data Posting with curl

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

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

Note that GET request does not support content body widely.

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

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

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

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

You probably request this:

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

Replace missing values with column mean

lapply can be used instead of a for loop.

d1[] <- lapply(d1, function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))

This doesn't really have any advantages over the for loop, though maybe it's easier if you have non-numeric columns as well, in which case

d1[sapply(d1, is.numeric)] <- lapply(d1[sapply(d1, is.numeric)], function(x) ifelse(is.na(x), mean(x, na.rm = TRUE), x))

is almost as easy.

How to check if an app is installed from a web-page on an iPhone?

After compiling a few answers, I've come up with the following code. What surprised me was that the timer does not get frozen on a PC (Chrome, FF) or Android Chrome - the trigger worked in the background, and the visibility check was the only reliable info.

var timestamp             = new Date().getTime();
var timerDelay              = 5000;
var processingBuffer  = 2000;

var redirect = function(url) {
  //window.location = url;
  log('ts: ' + timestamp + '; redirecting to: ' + url);
}
var isPageHidden = function() {
    var browserSpecificProps = {hidden:1, mozHidden:1, msHidden:1, webkitHidden:1};
    for (var p in browserSpecificProps) {
        if(typeof document[p] !== "undefined"){
        return document[p];
      }
    }
    return false; // actually inconclusive, assuming not
}
var elapsedMoreTimeThanTimerSet = function(){
    var elapsed = new Date().getTime() - timestamp;
  log('elapsed: ' + elapsed);
  return timerDelay + processingBuffer < elapsed;
}
var redirectToFallbackIfBrowserStillActive = function() {
  var elapsedMore = elapsedMoreTimeThanTimerSet();
  log('hidden:' + isPageHidden() +'; time: '+ elapsedMore);
  if (isPageHidden() || elapsedMore) {
    log('not redirecting');
  }else{
    redirect('appStoreUrl');
  }
}
var log = function(msg){
    document.getElementById('log').innerHTML += msg + "<br>";
}

setTimeout(redirectToFallbackIfBrowserStillActive, timerDelay);
redirect('nativeApp://');

JS Fiddle

How to convert XML to java.util.Map and vice versa

I have tried different kinds of maps and the Conversion Box worked. I have used your map and have pasted an example below with some inner maps. Hope it is helpful to you ....

import java.util.HashMap;
import java.util.Map;

import cjm.component.cb.map.ToMap;
import cjm.component.cb.xml.ToXML;

public class Testing
{
public static void main(String[] args)
{
    try
    {
        Map<String, Object> map = new HashMap<String, Object>(); // ORIGINAL MAP

        map.put("name", "chris");
        map.put("island", "faranga");

        Map<String, String> mapInner = new HashMap<String, String>(); // SAMPLE INNER MAP

        mapInner.put("a", "A");
        mapInner.put("b", "B");
        mapInner.put("c", "C");

        map.put("innerMap", mapInner);

        Map<String, Object> mapRoot = new HashMap<String, Object>(); // ROOT MAP

        mapRoot.put("ROOT", map);

        System.out.println("Map: " + mapRoot);

        System.out.println();

        ToXML toXML = new ToXML();

        String convertedXML = String.valueOf(toXML.convertToXML(mapRoot, true)); // CONVERTING ROOT MAP TO XML

        System.out.println("Converted XML: " + convertedXML);

        System.out.println();

        ToMap toMap = new ToMap();

        Map<String, Object> convertedMap = toMap.convertToMap(convertedXML); // CONVERTING CONVERTED XML BACK TO MAP

        System.out.println("Converted Map: " + convertedMap);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

Output:

Map: {ROOT={name=chris, innerMap={b=B, c=C, a=A}, island=faranga}}

 -------- Map Detected -------- 
 -------- XML created Successfully -------- 
Converted XML: <ROOT><name>chris</name><innerMap><b>B</b><c>C</c><a>A</a></innerMap><island>faranga</island></ROOT>

 -------- XML Detected -------- 
 -------- Map created Successfully -------- 
Converted Map: {ROOT={name=chris, innerMap={b=B, c=C, a=A}, island=faranga}}

Run a single migration file

If you've implemented a change method like this:

class AddPartNumberToProducts < ActiveRecord::Migration
  def change
    add_column :products, :part_number, :string
  end
end

You can create an instance of the migration and run migrate(:up) or migrate(:down) on an instance, like this:

$ rails console
>> require "db/migrate/20090408054532_add_part_number_to_products.rb"
>> AddPartNumberToProducts.new.migrate(:down)

Timestamp with a millisecond precision: How to save them in MySQL

You need to be at MySQL version 5.6.4 or later to declare columns with fractional-second time datatypes. Not sure you have the right version? Try SELECT NOW(3). If you get an error, you don't have the right version.

For example, DATETIME(3) will give you millisecond resolution in your timestamps, and TIMESTAMP(6) will give you microsecond resolution on a *nix-style timestamp.

Read this: https://dev.mysql.com/doc/refman/8.0/en/fractional-seconds.html

NOW(3) will give you the present time from your MySQL server's operating system with millisecond precision.

If you have a number of milliseconds since the Unix epoch, try this to get a DATETIME(3) value

FROM_UNIXTIME(ms * 0.001)

Javascript timestamps, for example, are represented in milliseconds since the Unix epoch.

(Notice that MySQL internal fractional arithmetic, like * 0.001, is always handled as IEEE754 double precision floating point, so it's unlikely you'll lose precision before the Sun becomes a white dwarf star.)

If you're using an older version of MySQL and you need subsecond time precision, your best path is to upgrade. Anything else will force you into doing messy workarounds.

If, for some reason you can't upgrade, you could consider using BIGINT or DOUBLE columns to store Javascript timestamps as if they were numbers. FROM_UNIXTIME(col * 0.001) will still work OK. If you need the current time to store in such a column, you could use UNIX_TIMESTAMP() * 1000

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

Counting in a FOR loop using Windows Batch script

It's not working because the entire for loop (from the for to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.

In other words, %count% is replaced with its value 1 before running the loop.

What you need is something like:

setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
  set /a count += 1
  echo !count!
)
endlocal

Delayed expansion using ! instead of % will give you the expected behaviour. See also here.


Also keep in mind that setlocal/endlocal actually limit scope of things changed inside so that they don't leak out. If you want to use count after the endlocal, you have to use a "trick" made possible by the very problem you're having:

endlocal && set count=%count%

Let's say count has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:

endlocal && set count=7

Then, when it's executed, the inner scope is closed off, returning count to it's original value. But, since the setting of count to seven happens in the outer scope, it's effectively leaking the information you need.

You can string together multiple sub-commands to leak as much information as you need:

endlocal && set count=%count% && set something_else=%something_else%

SyntaxError: Unexpected token o in JSON at position 1

the first parameters of function JSON.parse should be a String, and your data is a JavaScript object, so it will convert to a String [object object], you should use JSON.stringify before pass the data

JSON.parse(JSON.stringify(userData))

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

Delete all Duplicate Rows except for One in MySQL?

If you want to keep the row with the lowest id value:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MIN(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

If you want the id value that is the highest:

DELETE FROM NAMES
 WHERE id NOT IN (SELECT * 
                    FROM (SELECT MAX(n.id)
                            FROM NAMES n
                        GROUP BY n.name) x)

The subquery in a subquery is necessary for MySQL, or you'll get a 1093 error.

How to format a number as percentage in R?

Check out the percent function from the formattable package:

library(formattable)
x <- c(0.23, 0.95, 0.3)
percent(x)
[1] 23.00% 95.00% 30.00%

Any implementation of Ordered Set in Java?

Take a look at the Java standard API doc. Right next to LinkedHashMap, there is a LinkedHashSet. But note that the order in those is the insertion order, not the natural order of the elements. And you can only iterate in that order, not do random access (except by counting iteration steps).

There is also an interface SortedSet implemented by TreeSet and ConcurrentSkipListSet. Both allow iteration in the natural order of their elements or a Comparator, but not random access or insertion order.

For a data structure that has both efficient access by index and can efficiently implement the set criterium, you'd need a skip list, but there is no implementation with that functionality in the Java Standard API, though I am certain it's easy to find one on the internet.

Is it possible to focus on a <div> using JavaScript focus() function?

<div id="inner" tabindex="0">
    this div can now have focus and receive keyboard events
</div>

Convert ascii value to char

for (int i = 0; i < 5; i++){
    int asciiVal = rand()%26 + 97;
    char asciiChar = asciiVal;
    cout << asciiChar << " and ";
}

Stylesheet not updating

Easiest way to see if the file is being cached is to append a query string to the <link /> element so that the browser will re-load it.

To do this you can change your stylesheet reference to something like

<link rel="stylesheet" type="text/css" href="/css/stylesheet.css?v=1" />

Note the v=1 part. You can update this each time you make a new version to see if it is indeed being cached.

Div Background Image Z-Index Issue

To solve the issue, you are using the z-index on the footer and header, but you forgot about the position, if a z-index is to be used, the element must have a position:

Add to your footer and header this CSS:

position: relative; 

EDITED:

Also noticed that the background image on the #backstretch has a negative z-index, don't use that, some browsers get really weird...

Remove From the #backstretch:

z-index: -999999;

Read a little bit about Z-Index here!

Check if an element is present in a Bash array

1) Initialize array arr and add elements

2) set variable to search for SEARCH_STRING

3) check if your array contains element

arr=()
arr+=('a')
arr+=('b')
arr+=('c')

SEARCH_STRING='b'

if [[ " ${arr[*]} " == *"$SEARCH_STRING"* ]];
then
    echo "YES, your arr contains $SEARCH_STRING"
else
    echo "NO, your arr does not contain $SEARCH_STRING"
fi

dismissModalViewControllerAnimated deprecated

The warning is still there. In order to get rid of it I put it into a selector like this:

if ([self respondsToSelector:@selector(dismissModalViewControllerAnimated:)]) {
    [self performSelector:@selector(dismissModalViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES]];
} else {
    [self dismissViewControllerAnimated:YES completion:nil];
}

It benefits people with OCD like myself ;)

How to check internet access on Android? InetAddress never times out

I have applied the solution provided by @Levit and created function that will not call the extra Http Request.

It will solve the error Unable to Resolve Host

public static boolean isInternetAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork == null) return false;

    switch (activeNetwork.getType()) {
        case ConnectivityManager.TYPE_WIFI:
            if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED ||
                    activeNetwork.getState() == NetworkInfo.State.CONNECTING) &&
                    isInternet())
                return true;
            break;
        case ConnectivityManager.TYPE_MOBILE:
            if ((activeNetwork.getState() == NetworkInfo.State.CONNECTED ||
                    activeNetwork.getState() == NetworkInfo.State.CONNECTING) &&
                    isInternet())
                return true;
            break;
        default:
            return false;
    }
    return false;
}

private static boolean isInternet() {

    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        Debug.i(exitValue + "");
        return (exitValue == 0);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }

    return false;
}

Now call it like,

if (!isInternetAvailable(getActivity())) {
     //Show message
} else {
     //Perfoem the api request
}

How do I use NSTimer?

#import "MyViewController.h"

@interface MyViewController ()

@property (strong, nonatomic) NSTimer *timer;

@end

@implementation MyViewController

double timerInterval = 1.0f;

- (NSTimer *) timer {
    if (!_timer) {
        _timer = [NSTimer timerWithTimeInterval:timerInterval target:self selector:@selector(onTick:) userInfo:nil repeats:YES];
    }
    return _timer;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

-(void)onTick:(NSTimer*)timer
{
    NSLog(@"Tick...");
}

@end

how to import csv data into django models

Use the Pandas library to create a dataframe of the csv data.
Name the fields either by including them in the csv file's first line or in code by using the dataframe's columns method.
Then create a list of model instances.
Finally use the django method .bulk_create() to send your list of model instances to the database table.

The read_csv function in pandas is great for reading csv files and gives you lots of parameters to skip lines, omit fields, etc.

import pandas as pd

tmp_data=pd.read_csv('file.csv',sep=';')
#ensure fields are named~ID,Product_ID,Name,Ratio,Description
#concatenate name and Product_id to make a new field a la Dr.Dee's answer
products = [
    Product(
        name = tmp_data.ix[row]['Name'] 
        description = tmp_data.ix[row]['Description'],
        price = tmp_data.ix[row]['price'],
    )
    for row in tmp_data['ID']
]
Product.objects.bulk_create(products)

I was using the answer by mmrs151 but saving each row (instance) was very slow and any fields containing the delimiting character (even inside of quotes) were not handled by the open() -- line.split(';') method.

Pandas has so many useful caveats, it is worth getting to know

how to filter out a null value from spark dataframe

Another easy way to filter out null values from multiple columns in spark dataframe. Please pay attention there is AND between columns.

df.filter(" COALESCE(col1, col2, col3, col4, col5, col6) IS NOT NULL")

If you need to filter out rows that contain any null (OR connected) please use

df.na.drop()

Fill username and password using selenium in python

Use WebElement.send_keys method to simulate key typing.

name in the code (Username, Password) does not match actual name of the elements (username, password).


username = browser.find_element_by_name('username')
username.send_keys('user1')

password = browser.find_element_by_name('password')
password.send_keys('secret')

form = browser.find_element_by_id('loginForm')
form.submit()

# OR  browser.find_element_by_id('submit').click()

Angular bootstrap datepicker date format does not format ng-model value

You may use formatters after picking value inside your datepicker directive. For example

angular.module('foo').directive('bar', function() {
    return {
        require: '?ngModel',
        link: function(scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            ctrl.$formatters.push(function(value) {
                if (value) {
                    // format and return date here
                }

                return undefined;
            });
        }
    };
});

LINK.

AngularJS - Animate ng-view transitions

Check this code:

Javascript:

app.config( ["$routeProvider"], function($routeProvider){
    $routeProvider.when("/part1", {"templateUrl" : "part1"});
    $routeProvider.when("/part2", {"templateUrl" : "part2"});
    $routeProvider.otherwise({"redirectTo":"/part1"});
  }]
);

function HomeFragmentController($scope) {
    $scope.$on("$routeChangeSuccess", function (scope, next, current) {
        $scope.transitionState = "active"
    });
}

CSS:

.fragmentWrapper {
    overflow: hidden;
}

.fragment {
    position: relative;
    -moz-transition-property: left;
    -o-transition-property: left;
    -webkit-transition-property: left;
    transition-property: left;
    -moz-transition-duration: 0.1s;
    -o-transition-duration: 0.1s;
    -webkit-transition-duration: 0.1s;
    transition-duration: 0.1s
}

.fragment:not(.active) {
    left: 540px;
}

.fragment.active {
    left: 0px;
}

Main page HTML:

<div class="fragmentWrapper" data-ng-view data-ng-controller="HomeFragmentController">
</div>

Partials HTML example:

<div id="part1" class="fragment {{transitionState}}">
</div>

If Python is interpreted, what are .pyc files?

tldr; it's a converted code form the source code, which the python VM interprets for execution.

Bottom-up understanding: the final stage of any program is to run/execute the program's instructions on the hardware/machine. So here are the stages preceding execution:

  1. Executing/running on CPU

  2. Converting bytcode to machine code.

    • Machine code is the final stage of conversion.

    • Instructions to be executed on CPU are given in machine code. Machine code can be executed directly by CPU.

  3. Converting Bytecode to machine code.

    • Bytecode is a medium stage. It could be skipped for efficiency, but sacrificing portability.
  4. Converting Source code to bytcode.

    • Source code is a human readable code. This is what is used when working on IDEs (code editors) such as Pycharm.

Now the actual plot. There are two approaches when carrying any of these stages: convert [or execute] a code all at once (aka compile) and convert [or execute] the code line by line (aka interpret).

  • For example, we could compile a source code to bytcoe, compile bytecode to machine code, interpret machine code for execution.

  • Some implementations of languages skip stage 3 for efficiency, i.e. compile source code into machine code and then interpret machine code for execution.

  • Some implementations skip all middle steps and interpret the source code directly for execution.

  • Modern languages often involve both compiling an interpreting.

  • JAVA for example, compile source code to bytcode [that is how JAVA source is stored, as a bytcode], compile bytcode to machine code [using JVM], and interpret machine code for execution. [Thus JVM is implemented differently for different OSs, but the same JAVA source code could be executed on different OS that have JVM installed.]

  • Python for example, compile source code to bytcode [usually found as .pyc files accompanying the .py source codes], compile bytocde to machine code [done by a virtual machine such as PVM and the result is an executable file], interpret the machine code/executable for execution.

  • When we can say that a language is interpreted or compiled?

    • The answer is by looking into the approach used in execution. If it executes the machine code all at once (== compile), then it's a compiled language. On the other hand, if it executes the machine code line-by-line (==interpret) then it's an interpreted language.
  • Therefore, JAVA and Python are interpreted languages.

  • A confusion might occur because of the third stage, that's converting bytcode to machine code. Often this is done using a software called a virtual machine. The confusion occurs because a virtual machine acts like a machine, but it's actually not! Virtual machines are introduced for portability, having a VM on any REAL machine will allow us to execute the same source code. The approach used in most VMs [that's the third stage] is compiling, thus some people would say it's a compiled language. For the importance of VMs, we often say that such languages are both compiled and interpreted.

How to parse a JSON object to a TypeScript Object

You can cast the the json as follows:

Given your class:

export class Employee{
    firstname: string= '';
}

and the json:

let jsonObj = {
    "firstname": "Hesham"
};

You can cast it as follows:

let e: Employee = jsonObj as Employee;

And the output of console.log(e); is:

{ firstname: 'Hesham' }

How to change the timeout on a .NET WebClient object

For completeness, here's kisp's solution ported to VB (can't add code to a comment)

Namespace Utils

''' <summary>
''' Subclass of WebClient to provide access to the timeout property
''' </summary>
Public Class WebClient
    Inherits System.Net.WebClient

    Private _TimeoutMS As Integer = 0

    Public Sub New()
        MyBase.New()
    End Sub
    Public Sub New(ByVal TimeoutMS As Integer)
        MyBase.New()
        _TimeoutMS = TimeoutMS
    End Sub
    ''' <summary>
    ''' Set the web call timeout in Milliseconds
    ''' </summary>
    ''' <value></value>
    Public WriteOnly Property setTimeout() As Integer
        Set(ByVal value As Integer)
            _TimeoutMS = value
        End Set
    End Property


    Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
        Dim w As System.Net.WebRequest = MyBase.GetWebRequest(address)
        If _TimeoutMS <> 0 Then
            w.Timeout = _TimeoutMS
        End If
        Return w
    End Function

End Class

End Namespace

Switch statement fallthrough in C#?

Switch fallthrough is historically one of the major source of bugs in modern softwares. The language designer decided to make it mandatory to jump at the end of the case, unless you are defaulting to the next case directly without processing.

switch(value)
{
    case 1:// this is still legal
    case 2:
}

Cannot execute RUN mkdir in a Dockerfile

You can also simply use

WORKDIR /var/www/app

It will automatically create the folders if they don't exist.

Then switch back to the directory you need to be in.

"Strict Standards: Only variables should be passed by reference" error

I had a similar problem.

I think the problem is that when you try to enclose two or more functions that deals with an array type of variable, php will return an error.

Let's say for example this one.

$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose');

// This function returns the last key of an array (in this case it's $data)
$lastKey = array_pop(array_keys($data));

// Output is "key3" which is the last array.
// But php will return “Strict Standards: Only variables should 
// be passed by reference” error.
// So, In order to solve this one... is that you try to cut 
// down the process one by one like this.

$data1  = array_keys($data);
$lastkey = array_pop($data1);

echo $lastkey;

There you go!

What is a "web service" in plain English?

A simple definition: A web service is a function that can be accessed by other programs over the web (HTTP).

For example, when you create a website in PHP that outputs HTML, its target is the browser and by extension the human reading the page in the browser. A web service is not targeted at humans but rather at other programs.

So your PHP site that generates a random integer could be a web service if it outputs the integer in a format that may be consumed by another program. It might be in an XML format or another format, as long as other programs can understand the output.

The full definition is obviously more complex but you asked for plain English.

How to get the clicked link's href with jquery?

Suppose we have three anchor tags like ,

<a  href="ID=1" class="testClick">Test1.</a>
<br />
<a  href="ID=2" class="testClick">Test2.</a>
<br />
<a  href="ID=3" class="testClick">Test3.</a>

now in script

$(".testClick").click(function () {
        var anchorValue= $(this).attr("href");
        alert(anchorValue);
});

use this keyword instead of className (testClick)

Reloading/refreshing Kendo Grid

You can always use $('#GridName').data('kendoGrid').dataSource.read();. You don't really need to .refresh(); after that, .dataSource.read(); will do the trick.

Now if you want to refresh your grid in a more angular way, you can do:

<div kendo-grid="vm.grid" id="grid" options="vm.gridOptions"></div>

vm.grid.dataSource.read();`

OR

vm.gridOptions.dataSource.read();

And don't forget to declare your datasource as kendo.data.DataSource type

How to use filesaver.js

Here is a guide to JSZIP to create ZIP files by JavaScript. To download files you need to have filesaver.js, You can include those libraries by:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.4/jszip.min.js"  type="text/javascript"></script>
<script type="text/javascript" src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.js" ></script>

Now copy this code and this code will download a zip file with a file hello.txt having content Hello World. If everything thing works fine, this will download a file.

<script type="text/javascript">
    var zip = new JSZip();
    zip.file("Hello.txt", "Hello World\n");
    zip.generateAsync({type:"blob"})
    .then(function(content) {
        // see FileSaver.js
        saveAs(content, "file.zip");
    });
</script>

Now let's get in to deeper. Create an instance of JSZip.

var zip = new JSZip();

Add a file with a Hello World text:

zip.file("hello.txt", "Hello World\n");

Download the filie with name archive.zip

zip.generateAsync({type:"blob"}).then(function(zip) {
    saveAs(zip, "archive.zip");
});

Read More from here: http://www.wapgee.com/story/248/guide-to-create-zip-files-using-javascript-by-using-jszip-library

What is the difference between String and StringBuffer in Java?

String is immutable. 

Why? Check here.

StringBuffer is not. It is thread safe. 

Further questions like when to use which and other concepts can be figured out following this.

Hope this helps.

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

PostgreSQL wildcard LIKE for any of a list of words

All currently supported versions (9.5 and up) allow pattern matching in addition to LIKE.

Reference: https://www.postgresql.org/docs/current/functions-matching.html

Install specific version using laravel installer

You can use composer method like

composer create-project laravel/laravel blog "5.1"

Or here is the composer file

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "pre-update-cmd": [
            "php artisan clear-compiled"
        ],
        "post-update-cmd": [
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

PUT vs. POST in REST

So, which one should be used to create a resource? Or one needs to support both?

You should use PATCH. You PATCH the list of questions like

PATCH /questions HTTP/1.1

with a list containing your to be created object like

[
    {
        "title": "I said semantics!",
        "content": "Is this serious?",
        "answer": "Not really"
    }
]

It's a PATCH request as

  • you modify the existing list of resources without providing the whole new content
  • you change the state of your new question from non-existing to existing without providing all the data (the server will most probably add an id).

A great advantage of this method is that you can create multiple entities using a single request, simply by providing them all in the list.

This is something PUT obviously can't. You could use POST for creating multiple entities as it's the kitchen sink of HTTP and can do basically everything.

A disadvantage is that probably nobody uses PATCH this way. I'm afraid, I just invented it, but I hope, I provided a good argumentation.

You could use CREATE instead, as custom HTTP verbs are allowed, it's just that they mayn't work with some tools.

Concerning semantics, CREATE is IMHO the only right choice, everything else is a square peg in a round hole. Unfortunately, all we have are round holes.

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

Just set usesCleartextTraffic flag in the application tag of AndroidManifest.xml file. No need to create config file for Android.

 <application
   android:usesCleartextTraffic="true"
   .
   .
   .>

maven error: package org.junit does not exist

I fixed this error by inserting these lines of code:

<dependency>
  <groupId>junit</groupId>     <!-- NOT org.junit here -->
  <artifactId>junit-dep</artifactId>
  <version>4.8.2</version>
  <scope>test</scope>
</dependency>

into <dependencies> node.

more details refer to: http://mvnrepository.com/artifact/junit/junit-dep/4.8.2

How to make an introduction page with Doxygen

Add any file in the documentation which will include your content, for example toc.h:

@ mainpage Manual SDK
<hr/>
@ section pageTOC Content
  -# @ref Description
  -# @ref License
  -# @ref Item
...

And in your Doxyfile:

INPUT = toc.h \

Example (in Russian):

How to convert list to string

>>> L = [1,2,3]       
>>> " ".join(str(x) for x in L)
'1 2 3'

Solving "adb server version doesn't match this client" error

I fixed this by doing the following:

  1. going into GenyMotion settings -> ADB tab,
  2. instead of Use Genymotion Android tools (default), I chose Use custom Android SDK Tools and then browsed to my installed SDK.

How to import a module given its name as string?

With Python older than 2.7/3.1, that's pretty much how you do it.

For newer versions, see importlib.import_module for Python 2 and and Python 3.

You can use exec if you want to as well.

Or using __import__ you can import a list of modules by doing this:

>>> moduleNames = ['sys', 'os', 're', 'unittest'] 
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)

Ripped straight from Dive Into Python.

How to set text size in a button in html

Without using inline CSS you could set the text size of all your buttons using:

input[type="submit"], input[type="button"] {
  font-size: 14px;
}

ADB device list is empty

This helped me at the end:

Quick guide:

  • Download Google USB Driver

  • Connect your device with Android Debugging enabled to your PC

  • Open Device Manager of Windows from System Properties.

  • Your device should appear under Other devices listed as something like Android ADB Interface or 'Android Phone' or similar. Right-click that and click on Update Driver Software...

  • Select Browse my computer for driver software

  • Select Let me pick from a list of device drivers on my computer

  • Double-click Show all devices

  • Press the Have disk button

  • Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf

  • Select Android ADB Interface from the list of device types.

  • Press the Yes button

  • Press the Install button

  • Press the Close button

Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.

Getting user input

In python 3.x, use input() instead of raw_input()