Programs & Examples On #Ninject extensions

Ninject Extensions are a collection of open-source projects designed to extend the functionality of the Ninject open-source dependency injector for the .NET framework.

How to get the file extension in PHP?

How about

$ext = array_pop($userfile_extn);

PHP - check if variable is undefined

To check is variable is set you need to use isset function.

$lorem = 'potato';

if(isset($lorem)){
    echo 'isset true' . '<br />';
}else{
    echo 'isset false' . '<br />';
}

if(isset($ipsum)){
    echo 'isset true' . '<br />';
}else{
    echo 'isset false' . '<br />';
}

this code will print:

isset true
isset false

read more in https://php.net/manual/en/function.isset.php

NumPy first and last element from array

You can simply use take method and index of element (Last index can be -1).

arr = np.array([1,2,3])

last = arr.take(-1)
# 3

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Java Replace Line In Text File

just how to replace strings :) as i do first arg will be filename second target string third one the string to be replaced instead of targe

public class ReplaceString{
      public static void main(String[] args)throws Exception {
        if(args.length<3)System.exit(0);
        String targetStr = args[1];
        String altStr = args[2];
        java.io.File file = new java.io.File(args[0]);
        java.util.Scanner scanner = new java.util.Scanner(file);
        StringBuilder buffer = new StringBuilder();
        while(scanner.hasNext()){
          buffer.append(scanner.nextLine().replaceAll(targetStr, altStr));
          if(scanner.hasNext())buffer.append("\n");
        }
        scanner.close();
        java.io.PrintWriter printer = new java.io.PrintWriter(file);
        printer.print(buffer);
        printer.close();
      }
    }

In Python, can I call the main() of an imported module?

The answer I was searching for was answered here: How to use python argparse with args other than sys.argv?

If main.py and parse_args() is written in this way, then the parsing can be done nicely

# main.py
import argparse
def parse_args():
    parser = argparse.ArgumentParser(description="")
    parser.add_argument('--input', default='my_input.txt')
    return parser

def main(args):
    print(args.input)

if __name__ == "__main__":
    parser = parse_args()
    args = parser.parse_args()
    main(args)

Then you can call main() and parse arguments with parser.parse_args(['--input', 'foobar.txt']) to it in another python script:

# temp.py
from main import main, parse_args
parser = parse_args()
args = parser.parse_args([]) # note the square bracket
# to overwrite default, use parser.parse_args(['--input', 'foobar.txt'])
print(args) # Namespace(input='my_input.txt')
main(args)

Show/hide widgets in Flutter programmatically

As already highlighted by @CopsOnRoad, you can use the Visibility widget. But, if you want to keep its state, for example, if you want to build a viewpager and make a certain button appear and disappear based on the page, you can do it this way

void checkVisibilityButton() {
  setState(() {
  isVisibileNextBtn = indexPage + 1 < pages.length;
  });
}    

 Stack(children: <Widget>[
      PageView.builder(
        itemCount: pages.length,
        onPageChanged: (index) {
          indexPage = index;
          checkVisibilityButton();
        },
        itemBuilder: (context, index) {
          return pages[index];
        },
        controller: controller,
      ),
      Container(
        alignment: Alignment.bottomCenter,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            Visibility(
              visible: isVisibileNextBtn,
              child: "your widget"
            )
          ],
        ),
      )
    ]))

CSS selector for disabled input type="submit"

Does that work in IE6?

No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.

You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.


EDIT
If you are to ignore IE6, you could do (CSS2.1):

input[type=submit][disabled=disabled],
button[disabled=disabled] {
    ...
}

CSS3 (IE9+):

input[type=submit]:disabled,
button:disabled {
    ...
}

You can substitute [disabled=disabled] (attribute value) with [disabled] (attribute presence).

Passing Javascript variable to <a href >

Alternatively you could just use a document.write:

<script type="text\javascript">
var loc = "http://";
document.write('<a href="' + loc + '">Link text</a>');
</script>

Screen width in React Native

Only two simple steps.

  1. import { Dimensions } from 'react-native' at top of your file.
  2. const { height } = Dimensions.get('window');

now the window screen height is stored in the height variable.

What is the difference between prefix and postfix operators?

The function returns before i is incremented because you are using a post-fix operator (++). At any rate, the increment of i is not global - only to respective function. If you had used a pre-fix operator, it would be 11 and then decremented to 10.

So you then return i as 10 and decrement it in the printf function, which shows 9 not 10 as you think.

Check if a number has a decimal place/is a whole number

convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.

if(!number.split(".")[1]){
    //do stuff
}

This way you can also know what the integer and decimal actually are. a more advanced example would be.

number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1]; 

if(!dece){
    //do stuff
}

SQL Server equivalent to MySQL enum data type?

Found this interesting approach when I wanted to implement enums in SQL Server.

The approach mentioned below in the link is quite compelling, considering all your database enum needs could be satisfied with 2 central tables.

http://blog.sqlauthority.com/2010/03/22/sql-server-enumerations-in-relational-database-best-practice/

How to avoid 'cannot read property of undefined' errors?

I like Cao Shouguang's answer, but I am not fond of passing a function as parameter into the getSafe function each time I do the call. I have modified the getSafe function to accept simple parameters and pure ES5.

/**
* Safely get object properties.    
* @param {*} prop The property of the object to retrieve
* @param {*} defaultVal The value returned if the property value does not exist
* @returns If property of object exists it is returned, 
*          else the default value is returned.
* @example
* var myObj = {a : {b : 'c'} };
* var value;
* 
* value = getSafe(myObj.a.b,'No Value'); //returns c 
* value = getSafe(myObj.a.x,'No Value'); //returns 'No Value'
* 
* if (getSafe(myObj.a.x, false)){ 
*   console.log('Found')
* } else {
*  console.log('Not Found') 
* }; //logs 'Not Found'
* 
* if(value = getSafe(myObj.a.b, false)){
*  console.log('New Value is', value); //logs 'New Value is c'
* }
*/
function getSafe(prop, defaultVal) {
  return function(fn, defaultVal) {
    try {
      if (fn() === undefined) {
        return defaultVal;
      } else {
        return fn();
      }
    } catch (e) {
      return defaultVal;
    }
  }(function() {return prop}, defaultVal);
}

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

You need to tell Eclipse which JDK/JRE's you have installed and where they are located.

This is somewhat burried in the Eclipse preferences: In the Window-Menu select "Preferences". In the Preferences Tree, open the Node "Java" and select "Installed JRE's". Then click on the "Add"-Button in the Panel and select "Standard VM", "Next" and for "JRE Home" click on the "Directory"-Button and select the top level folder of the JDK you want to add.

Its easier than the description may make it look.

CSS Background Opacity

The following methods can be used to solve your problem:

  1. CSS alpha transparency method (doesn't work in Internet Explorer 8):

    #div{background-color:rgba(255,0,0,0.5);}
    
  2. Use a transparent PNG image according to your choice as background.

  3. Use the following CSS code snippet to create a cross-browser alpha-transparent background. Here is an example with #000000 @ 0.4% opacity

    .div {
        background:rgb(0,0,0);
        background: transparent\9;
        background:rgba(0,0,0,0.4);
        filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#66000000,endColorstr=#66000000);
        zoom: 1;
    }
    .div:nth-child(n) {
        filter: none;
    }
    

For more details regarding this technique, see this, which has an online CSS generator.

How to set the font size in Emacs?

(set-face-attribute 'default nil :height 100)

The value is in 1/10pt, so 100 will give you 10pt, etc.

Click a button programmatically

Let say button 1 has an event called

Button1_Click(Sender, eventarg)

If you want to call it in Button2 then call this function directly.

Button1_Click(Nothing, Nothing)

Static methods - How to call a method from another method?

If these don't depend on the class or instance, then just make them a function.

As this would seem like the obvious solution. Unless of course you think it's going to need to be overwritten, subclassed, etc. If so, then the previous answers are the best bet. Fingers crossed I won't get marked down for merely offering an alternative solution that may or may not fit someone’s needs ;).

As the correct answer will depend on the use case of the code in question ;)

Trigger change event of dropdown

Try this:

$(document).ready(function(event) {
    $('#countrylist').change(function(e){
         // put code here
     }).change();
});

Define the change event, and trigger it immediately. This ensures the event handler is defined before calling it.

Might be late to answer the original poster, but someone else might benefit from the shorthand notation, and this follows jQuery's chaining, etc

jquery chaining

How to run an external program, e.g. notepad, using hyperlink?

Try this

<html>
    <head>
        <script type="text/javascript">
        function runProgram()
        {
            var shell = new ActiveXObject("WScript.Shell");                 
            var appWinMerge = "\"C:\\Program Files\\WinMerge\\WinMergeU.exe\" /e /s /u /wl /wr /maximize";
            var fileLeft = "\"D:\\Path\\to\\your\\file\"";
            var fileRight= "\"D:\\Path\\to\\your\\file2\"";
            shell.Run(appWinMerge + " " + fileLeft + " " + fileRight);
        }
        </script>
    </head>

    <body>
        <a href="javascript:runProgram()">Run program</a>
    </body>
</html>

Can you explain the HttpURLConnection connection process?

Tim Bray presented a concise step-by-step, stating that openConnection() does not establish an actual connection. Rather, an actual HTTP connection is not established until you call methods such as getInputStream() or getOutputStream().

http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection

How can I create an array/list of dictionaries in python?

Dictionary:

dict = {'a':'a','b':'b','c':'c'}

array of dictionary

arr = (dict,dict,dict)
arr
({'a': 'a', 'c': 'c', 'b': 'b'}, {'a': 'a', 'c': 'c', 'b': 'b'}, {'a': 'a', 'c': 'c', 'b': 'b'})

String.equals() with multiple conditions (and one action on result)

If you develop for Android KitKat or newer, you could also use a switch statement (see: Android coding with switch (String)). e.g.

switch(yourString)
{
     case "john":
          //do something for john
     case "mary":
          //do something for mary
}

Sequence contains no elements?

Please use

.FirstOrDefault()

because if in the first row of the result there is no info this instruction goes to the default info.

WordPress Get the Page ID outside the loop

You can also create a generic function to get the ID of the post, whether its outside or inside the loop (handles both the cases):

<?php

/**
 * @uses WP_Query
 * @uses get_queried_object()
 * @see get_the_ID()
 * @return int
 */
function get_the_post_id() {
  if (in_the_loop()) {
       $post_id = get_the_ID();
  } else {
       global $wp_query;
       $post_id = $wp_query->get_queried_object_id();
         }
  return $post_id;
} ?>

And simply do:

$page_id = get_the_post_id();

exit application when click button - iOS

You can use exit method to quit an ios app :

exit(0);

You should say same alert message and ask him to quit

Another way is by using [[NSThread mainThread] exit]

However you should not do this way

According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.

IntelliJ: Never use wildcard imports

  1. File\Settings... (Ctrl+Alt+S)
  2. Project Settings > Editor > Code Style > Java > Imports tab
  3. Set Class count to use import with '*' to 999
  4. Set Names count to use static import with '*' to 999

After this, your configuration should look like: enter image description here

(On IntelliJ IDEA 13.x, 14.x, 15.x, 2016.x, 2017.x)

Using NSLog for debugging

Try this piece of code:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@", digit);

The message means that you have incorrect syntax for using the digit variable. If you're not sending it any message - you don't need any brackets.

contenteditable change events

Non JQuery answer...

function makeEditable(elem){
    elem.setAttribute('contenteditable', 'true');
    elem.addEventListener('blur', function (evt) {
        elem.removeAttribute('contenteditable');
        elem.removeEventListener('blur', evt.target);
    });
    elem.focus();
}

To use it, call on (say) a header element with id="myHeader"

makeEditable(document.getElementById('myHeader'))

That element will now be editable by the user until it loses focus.

How to construct a set out of list items in python?

One general way to construct set in iterative way like this:

aset = {e for e in alist}

How to pass multiple parameters in thread in VB

Pass multiple parameter for VB.NET 3.5

 Public Class MyWork

    Public Structure thread_Data            
        Dim TCPIPAddr As String
        Dim TCPIPPort As Integer            
    End Structure

    Dim STthread_Data As thread_Data
    STthread_Data.TCPIPAddr = "192.168.2.2"
    STthread_Data.TCPIPPort = 80  

    Dim multiThread As Thread = New Thread(AddressOf testthread)
    multiThread.SetApartmentState(ApartmentState.MTA)
    multiThread.Start(STthread_Data)     

    Private Function testthread(ByVal STthread_Data As thread_Data) 
        Dim IPaddr as string = STthread_Data.TCPIPAddr
        Dim IPport as integer = STthread_Data.TCPIPPort
        'Your work'        
    End Function

End Class

What is the difference between a function expression vs declaration in JavaScript?

Regarding 3rd definition:

var foo = function foo() { return 5; }

Heres an example which shows how to use possibility of recursive call:

a = function b(i) { 
  if (i>10) {
    return i;
  }
  else {
    return b(++i);
  }
}

console.log(a(5));  // outputs 11
console.log(a(10)); // outputs 11
console.log(a(11)); // outputs 11
console.log(a(15)); // outputs 15

Edit: more interesting example with closures:

a = function(c) {
 return function b(i){
  if (i>c) {
   return i;
  }
  return b(++i);
 }
}
d = a(5);
console.log(d(3)); // outputs 6
console.log(d(8)); // outputs 8

Cannot implicitly convert type from Task<>

The main issue with your example that you can't implicitly convert Task<T> return types to the base T type. You need to use the Task.Result property. Note that Task.Result will block async code, and should be used carefully.

Try this instead:

public List<int> TestGetMethod()  
{  
    return GetIdList().Result;  
}

CORS header 'Access-Control-Allow-Origin' missing

This happens generally when you try access another domain's resources.

This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain).

The header of the response, even if it's 200OK do not allow other origins (domains, port) to access the ressources.

You can fix this problem if you are the owner of both domains:

Solution 1: via .htaccess

To change that, you can write this in the .htaccess of the requested domain file:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    </IfModule>

If you only want to give access to one domain, the .htaccess should look like this:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin 'https://my-domain.tdl'
    </IfModule>

Solution 2: set headers the correct way

If you set this into the response header of the requested file, you will allow everyone to access the ressources:

Access-Control-Allow-Origin : *

OR

Access-Control-Allow-Origin : http://www.my-domain.com

Peace and code ;)

In PHP how can you clear a WSDL cache?

You can safely delete the WSDL cache files. If you wish to prevent future caching, use:

ini_set("soap.wsdl_cache_enabled", 0);

or dynamically:

$client = new SoapClient('http://somewhere.com/?wsdl', array('cache_wsdl' => WSDL_CACHE_NONE) );

Dynamic instantiation from string name of a class in dynamically imported module?

Use getattr to get an attribute from a name in a string. In other words, get the instance as

instance = getattr(modul, class_name)()

How to generate a create table script for an existing table in phpmyadmin?

This may be a late reply. But it may help others. It is very simple in MY SQL Workbench ( I am using Workbench version 6.3 and My SQL Version 5.1 Community edition): Right click on the table for which you want the create script, select 'Copy to Clipboard --> Create Statement' option. Simply paste in any text editor you want to get the create script.

HTML5 Local storage vs. Session storage

The only difference is that localStorage has a different expiration time, sessionStorage will only be accessible while and by the window that created it is open.
localStorage lasts until you delete it or the user deletes it.
Lets say that you wanted to save a login username and password you would want to use sessionStorageover localStorage for security reasons (ie. another person accessing their account at a later time).
But if you wanted to save a user's settings on their machine you would probably want localStorage. All in all:

localStorage - use for long term use.
sessionStorage - use when you need to store somthing that changes or somthing temporary

C/C++ line number

For those who might need it, a "FILE_LINE" macro to easily print file and line:

#define STRINGIZING(x) #x
#define STR(x) STRINGIZING(x)
#define FILE_LINE __FILE__ ":" STR(__LINE__)

Select data from date range between two dates

interval intersection description

As you can see, there are two ways to get things done:

  • enlist all acceptable options
  • exclude all wrong options

Obviously, second way is much more simple (only two cases against four).

Your SQL will look like:

SELECT * FROM Product_sales 
WHERE NOT (From_date > @RangeTill OR To_date < @RangeFrom)

Polling the keyboard (detect a keypress) in python

The standard approach is to use the select module.

However, this doesn't work on Windows. For that, you can use the msvcrt module's keyboard polling.

Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.

How can I get a resource content from a static context?

The Singleton:

package com.domain.packagename;

import android.content.Context;

/**
 * Created by Versa on 10.09.15.
 */
public class ApplicationContextSingleton {
    private static PrefsContextSingleton mInstance;
    private Context context;

    public static ApplicationContextSingleton getInstance() {
        if (mInstance == null) mInstance = getSync();
        return mInstance;
    }

    private static synchronized ApplicationContextSingleton getSync() {
        if (mInstance == null) mInstance = new PrefsContextSingleton();
        return mInstance;
    }

    public void initialize(Context context) {
        this.context = context;
    }

    public Context getApplicationContext() {
        return context;
    }

}

Initialize the Singleton in your Application subclass:

package com.domain.packagename;

import android.app.Application;

/**
 * Created by Versa on 25.08.15.
 */
public class mApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        ApplicationContextSingleton.getInstance().initialize(this);
    }
}

If I´m not wrong, this gives you a hook to applicationContext everywhere, call it with ApplicationContextSingleton.getInstance.getApplicationContext(); You shouldn´t need to clear this at any point, as when application closes, this goes with it anyway.

Remember to update AndroidManifest.xml to use this Application subclass:

<?xml version="1.0" encoding="utf-8"?>

<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.domain.packagename"
    >

<application
    android:allowBackup="true"
    android:name=".mApplication" <!-- This is the important line -->
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:icon="@drawable/app_icon"
    >

Now you should be able to use ApplicationContextSingleton.getInstance().getApplicationContext().getResources() from anywhere, also the very few places where application subclasses can´t.

Please let me know if you see anything wrong here, thank you. :)

How to find out if a Python object is a string?

Its simple, use the following code (we assume the object mentioned to be obj)-

if type(obj) == str:
    print('It is a string')
else:
    print('It is not a string.')

Changing Placeholder Text Color with Swift

For Swift

func setPlaceholderColor(textField: UITextField, placeholderText: String) {
    textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.pelorBlack])
}

You can use this;

self.setPlaceholderColor(textField: self.emailTextField, placeholderText: "E-Mail/Username")

CSS, Images, JS not loading in IIS

I had a similar error, my console looked like this:

error

My problem was that I was running my site in a sub folder since the company was using one top domain and no sub domains. Like this:

host.com/app1

host.com/app2

My code looked like this for including scripts which worked fine on localhost but not in app1 or app2:

<link rel="stylesheet" type="text/css" href="/Content/css/font-awesome.min.css" />

Added a tilde sign ~ to src and then everything worked:

<link rel="stylesheet" type="text/css" href="~/Content/css/font-awesome.min.css" />

Explanation of ~ vs /:

  • / - Site root
  • ~/ - Root directory of the application

/ will return the root of the site (http://host.com/),

~/ will return the root of the application (http://host.com/app1/).

Angular 2 declaring an array of objects

Datatype: array_name:datatype[]=[]; Example string: users:string[]=[];

For array of objects:

Objecttype: object_name:objecttype[]=[{}]; Example user: Users:user[]=[{}];

And if in some cases it's coming undefined in binding, make sure to initialize it on Oninit().

What does it mean by select 1 from table?

To be slightly more specific, you would use this to do

SELECT 1 FROM MyUserTable WHERE user_id = 33487

instead of doing

SELECT * FROM MyUserTable WHERE user_id = 33487

because you don't care about looking at the results. Asking for the number 1 is very easy for the database (since it doesn't have to do any look-ups).

How to bring view in front of everything?

An even simpler solution is to edit the XML of the activity. Use

android:translationZ=""

How to run ssh-add on windows?

Original answer using git's start-ssh-agent

Make sure you have Git installed and have git's cmd folder in your PATH. For example, on my computer the path to git's cmd folder is C:\Program Files\Git\cmd

Make sure your id_rsa file is in the folder c:\users\yourusername\.ssh

Restart your command prompt if you haven't already, and then run start-ssh-agent. It will find your id_rsa and prompt you for the passphrase

Update 2019 - A better solution if you're using Windows 10: OpenSSH is available as part of Windows 10 which makes using SSH from cmd/powershell much easier in my opinion. It also doesn't rely on having git installed, unlike my previous solution.

  1. Open Manage optional features from the start menu and make sure you have Open SSH Client in the list. If not, you should be able to add it.

  2. Open Services from the start Menu

  3. Scroll down to OpenSSH Authentication Agent > right click > properties

  4. Change the Startup type from Disabled to any of the other 3 options. I have mine set to Automatic (Delayed Start)

  5. Open cmd and type where ssh to confirm that the top listed path is in System32. Mine is installed at C:\Windows\System32\OpenSSH\ssh.exe. If it's not in the list you may need to close and reopen cmd.

Once you've followed these steps, ssh-agent, ssh-add and all other ssh commands should now work from cmd. To start the agent you can simply type ssh-agent.

  1. Optional step/troubleshooting: If you use git, you should set the GIT_SSH environment variable to the output of where ssh which you ran before (e.g C:\Windows\System32\OpenSSH\ssh.exe). This is to stop inconsistencies between the version of ssh you're using (and your keys are added/generated with) and the version that git uses internally. This should prevent issues that are similar to this

Some nice things about this solution:

  • You won't need to start the ssh-agent every time you restart your computer
  • Identities that you've added (using ssh-add) will get automatically added after restarts. (It works for me, but you might possibly need a config file in your c:\Users\User\.ssh folder)
  • You don't need git!
  • You can register any rsa private key to the agent. The other solution will only pick up a key named id_rsa

Hope this helps

How to align an indented line in a span that wraps into multiple lines?

You want multiple lines of text indented on the left. Try the following:

CSS:

div.info {
    margin-left: 10px;
}

span.info {
    color: #b1b1b1;
    font-size: 11px;
    font-style: italic;
    font-weight:bold;
}

HTML:

<div class="info"><span class="info">blah blah <br/> blah blah</span></div>

How do I convert from stringstream to string in C++?

Use the .str()-method:

Manages the contents of the underlying string object.

1) Returns a copy of the underlying string as if by calling rdbuf()->str().

2) Replaces the contents of the underlying string as if by calling rdbuf()->str(new_str)...

Notes

The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer...

gpg: no valid OpenPGP data found

I also got the same error. I've referred to the below mentioned link and ran this commands

gpg --import fails with no valid OpenPGP data found

gpg --import KEYS
sudo apt-get update

It worked.

I'm using Ubuntu version 12.04

Flask-SQLalchemy update a row's information

There is a method update on BaseQuery object in SQLAlchemy, which is returned by filter_by.

num_rows_updated = User.query.filter_by(username='admin').update(dict(email='[email protected]')))
db.session.commit()

The advantage of using update over changing the entity comes when there are many objects to be updated.

If you want to give add_user permission to all the admins,

rows_changed = User.query.filter_by(role='admin').update(dict(permission='add_user'))
db.session.commit()

Notice that filter_by takes keyword arguments (use only one =) as opposed to filter which takes an expression.

How to convert int to string on Arduino?

Here below is a self composed myitoa() which is by far smaller in code, and reserves a FIXED array of 7 (including terminating 0) in char *mystring, which is often desirable. It is obvious that one can build the code with character-shift instead, if one need a variable-length output-string.

void myitoa(int number, char *mystring) {
  boolean negative = number>0;

  mystring[0] = number<0? '-' : '+';
  number = number<0 ? -number : number;
  for (int n=5; n>0; n--) {
     mystring[n] = ' ';
     if(number > 0) mystring[n] = number%10 + 48;
     number /= 10;
  }  
  mystring[6]=0;
}

Is there a shortcut to make a block comment in Xcode?

Cmd + Shift + 7 will comment the selected lines.

JavaScript open in a new window, not tab

OK, after making a lot of test, here my concluson:

When you perform:

     window.open('www.yourdomain.tld','_blank');
     window.open('www.yourdomain.tld','myWindow');

or whatever you put in the destination field, this will change nothing: the new page will be opened in a new tab (so depend on user preference)

If you want the page to be opened in a new "real" window, you must put extra parameter. Like:

window.open('www.yourdomain.tld', 'mywindow','location=1,status=1,scrollbars=1, resizable=1, directories=1, toolbar=1, titlebar=1');

After testing, it seems the extra parameter you use, dont' really matter: this is not the fact you put "this parameter" or "this other one" which create the new "real window" but the fact there is new parameter(s).

But something is confused and may explain a lot of wrong answers:

This:

 win1 = window.open('myurl1', 'ID_WIN');
 win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');

And this:

 win2 = window.open('myurl2', 'ID_WIN', 'location=1,status=1,scrollbars=1');
 win1 = window.open('myurl1', 'ID_WIN');

will NOT give the same result.

In the first case, as you first open a page without extra parameter, it will open in a new tab. And in this case, the second call will be also opened in this tab because of the name you give.

In second case, as your first call is made with extra parameter, the page will be opened in a new "real window". And in that case, even if the second call is made without the extra parameter, it will also be opened in this new "real window"... but same tab!

This mean the first call is important as it decided where to put the page.

Where can I find free WPF controls and control templates?

I searched for some good themes across internet and found nothing. So I ported selected controls of GTK Hybrid theme. It's MIT licensed and you can find it here:

https://github.com/stil/candyshop

It's not enterprise grade style and probably has some flaws, but I use it in my personal projects.

demo

Trying to add adb to PATH variable OSX

enter image description here

2nd solution is explained below. But when i close the terminal the change which i made in path variable gets lost. Thus i prefer the first way!

enter image description here

Twitter Bootstrap tabs not working: when I click on them nothing happens

i had the same problem until i downloaded bootstrap-tab.js and included it in my script, download from here https://code.google.com/p/fusionleaf/source/browse/webroot/fusionleaf/com/www/inc/bootstrap/js/bootstrap-tab.js?r=82aacd63ee1f7f9a15ead3574fe2c3f45b5c1027

include the bootsrap-tab.js in the just below the jquery

<script type="text/javascript" src="bootstrap/js/bootstrap-tab.js"></script>

Final Code Looked like this:

 <!DOCTYPE html>
<html lang="en">
<head>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet">
<script type="text/javascript" src="libraries/jquery.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap-tab.js"></script>
</head>

<body>

<div class="container">

<!-------->
<div id="content">
    <ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
        <li class="active"><a href="#red" data-toggle="tab">Red</a></li>
        <li><a href="#orange" data-toggle="tab">Orange</a></li>
        <li><a href="#yellow" data-toggle="tab">Yellow</a></li>
        <li><a href="#green" data-toggle="tab">Green</a></li>
        <li><a href="#blue" data-toggle="tab">Blue</a></li>
    </ul>
    <div id="my-tab-content" class="tab-content">
        <div class="tab-pane active" id="red">
            <h1>Red</h1>
            <p>red red red red red red</p>
        </div>
        <div class="tab-pane" id="orange">
            <h1>Orange</h1>
            <p>orange orange orange orange orange</p>
        </div>
        <div class="tab-pane" id="yellow">
            <h1>Yellow</h1>
            <p>yellow yellow yellow yellow yellow</p>
        </div>
        <div class="tab-pane" id="green">
            <h1>Green</h1>
            <p>green green green green green</p>
        </div>
        <div class="tab-pane" id="blue">
            <h1>Blue</h1>
            <p>blue blue blue blue blue</p>
        </div>
    </div>
</div>


<script type="text/javascript">
    jQuery(document).ready(function ($) {
        $('#tabs').tab();
    });
</script>    
</div> <!-- container -->


<script type="text/javascript" src="bootstrap/js/bootstrap.js"></script>

</body>
</html>

How to display length of filtered ng-repeat data

You can do it with 2 ways. In template and in Controller. In template you can set your filtered array to another variable, then use it like you want. Here is how to do it:

<ul>
  <li data-ng-repeat="user in usersList = (users | gender:filterGender)" data-ng-bind="user.name"></li>
</ul>
 ....
<span>{{ usersList.length | number }}</span>

If you need examples, see the AngularJs filtered count examples/demos

Mysql adding user for remote access

In order to connect remotely you have to have MySQL bind port 3306 to your machine's IP address in my.cnf. Then you have to have created the user in both localhost and '%' wildcard and grant permissions on all DB's as such . See below:

my.cnf (my.ini on windows)

#Replace xxx with your IP Address 
bind-address        = xxx.xxx.xxx.xxx

then

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

Then

GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
flush privileges;

Depending on your OS you may have to open port 3306 to allow remote connections.

What method in the String class returns only the first N characters?

public static string TruncateLongString(this string str, int maxLength)
{
    return str.Length <= maxLength ? str : str.Remove(maxLength);
}

Pandas percentage of total with groupby

df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
               'office_id': list(range(1, 7)) * 2,
               'sales': [np.random.randint(100000, 999999)
                         for _ in range(12)]})

grouped = df.groupby(['state', 'office_id'])
100*grouped.sum()/df[["state","sales"]].groupby('state').sum()

Returns:

sales
state   office_id   
AZ  2   54.587910
    4   33.009225
    6   12.402865
CA  1   32.046582
    3   44.937684
    5   23.015735
CO  1   21.099989
    3   31.848658
    5   47.051353
WA  2   43.882790
    4   10.265275
    6   45.851935

Bat file to run a .exe at the command prompt

To start a program and then close command prompt without waiting for program to exit:

start /d "path" file.exe

Calculating Time Difference

from time import time

start_time = time()
...

end_time = time()
seconds_elapsed = end_time - start_time

hours, rest = divmod(seconds_elapsed, 3600)
minutes, seconds = divmod(rest, 60)

How to retrieve available RAM from Windows command line?

wmic OS get FreePhysicalMemory /Value

Launch Android application without main Activity and start Service on launching application

You said you didn't want to use a translucent Activity, but that seems to be the best way to do this:

  1. In your Manifest, set the Activity theme to Theme.Translucent.NoTitleBar.
  2. Don't bother with a layout for your Activity, and don't call setContentView().
  3. In your Activity's onCreate(), start your Service with startService().
  4. Exit the Activity with finish() once you've started the Service.

In other words, your Activity doesn't have to be visible; it can simply make sure your Service is running and then exit, which sounds like what you want.

I would highly recommend showing at least a Toast notification indicating to the user that you are launching the Service, or that it is already running. It is very bad user experience to have a launcher icon that appears to do nothing when you press it.

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

Selecting just one branch: fetch/merge vs. pull

People often advise you to separate "fetching" from "merging". They say instead of this:

    git pull remoteR branchB

do this:

    git fetch remoteR
    git merge remoteR branchB

What they don't mention is that such a fetch command will actually fetch all branches from the remote repo, which is not what that pull command does. If you have thousands of branches in the remote repo, but you do not want to see all of them, you can run this obscure command:

    git fetch remoteR refs/heads/branchB:refs/remotes/remoteR/branchB
    git branch -a  # to verify
    git branch -t branchB remoteR/branchB

Of course, that's ridiculously hard to remember, so if you really want to avoid fetching all branches, it is better to alter your .git/config as described in ProGit.

Huh?

The best explanation of all this is in Chapter 9-5 of ProGit, Git Internals - The Refspec (or via github). That is amazingly hard to find via Google.

First, we need to clear up some terminology. For remote-branch-tracking, there are typically 3 different branches to be aware of:

  1. The branch on the remote repo: refs/heads/branchB inside the other repo
  2. Your remote-tracking branch: refs/remotes/remoteR/branchB in your repo
  3. Your own branch: refs/heads/branchB inside your repo

Remote-tracking branches (in refs/remotes) are read-only. You do not modify those directly. You modify your own branch, and then you push to the corresponding branch at the remote repo. The result is not reflected in your refs/remotes until after an appropriate pull or fetch. That distinction was difficult for me to understand from the git man-pages, mainly because the local branch (refs/heads/branchB) is said to "track" the remote-tracking branch when .git/config defines branch.branchB.remote = remoteR.

Think of 'refs' as C++ pointers. Physically, they are files containing SHA-digests, but basically they are just pointers into the commit tree. git fetch will add many nodes to your commit-tree, but how git decides what pointers to move is a bit complicated.

As mentioned in another answer, neither

    git pull remoteR branchB

nor

    git fetch remoteR branchB

would move refs/remotes/branches/branchB, and the latter certainly cannot move refs/heads/branchB. However, both move FETCH_HEAD. (You can cat any of these files inside .git/ to see when they change.) And git merge will refer to FETCH_HEAD, while setting MERGE_ORIG, etc.

How to change theme for AlertDialog

It can done simply by using the Builder's setView(). You can create any view of your choice and feed into the builder. This works good. I use a custom TextView that is rendered by the dialog builder. I dont set the message and this space is utilized to render my custome textview.

Find and replace with a newline in Visual Studio Code

A possible workaround would be to use the multi-cursor. select the >< part of your example use Ctrl+Shift+L or select all occurrences. Then use the arrow keys to move all the cursors between the tags and press enter to insert a newline everywhere.

This won't work in all situations.

You can also use Ctrl+D for select next match, which adds the next match to the selection and adds a cursor. And use Ctrl+K Ctrl+D to skip a selection.

Can I configure a subdomain to point to a specific port on my server

With only 1 IP you can forget DNS but you can use a MineProxy because the handshake packet of the client contains the host that then he connected to and a MineProxy will ready this host and proxy the connection to a server that is registered for that host

Can I override and overload static methods in Java?

I design a code of static method overriding.I think It is override easily.Please clear me how its unable to override static members.Here is my code-

class Class1 {
    public static int Method1(){
          System.out.println("true");
          return 0;
    }
}
class Class2 extends Class1 {
    public static int Method1(){
   System.out.println("false");
          return 1;
    }

}
public class Mai {
    public static void main(String[] args){
           Class2 c=new Class2();
          //Must explicitly chose Method1 from Class1 or Class2
          //Class1.Method1();
          c.Method1();
    }
}

How to create file object from URL object (image)

You can make use of ImageIO in order to load the image from an URL and then write it to a file. Something like this:

URL url = new URL("http://google.com/pathtoaimage.jpg");
BufferedImage img = ImageIO.read(url);
File file = new File("downloaded.jpg");
ImageIO.write(img, "jpg", file);

This also allows you to convert the image to some other format if needed.

'Static readonly' vs. 'const'

One thing to note is const is restricted to primitive/value types (the exception being strings).

C# Pass Lambda Expression as Method Parameter

Use a Func<T1, T2, TResult> delegate as the parameter type and pass it in to your Query:

public List<IJob> getJobs(Func<FullTimeJob, Student, FullTimeJob> lambda)
{
  using (SqlConnection connection = new SqlConnection(getConnectionString())) {
    connection.Open();
    return connection.Query<FullTimeJob, Student, FullTimeJob>(sql, 
        lambda,
        splitOn: "user_id",
        param: parameters).ToList<IJob>();   
  }  
}

You would call it:

getJobs((job, student) => {         
        job.Student = student;
        job.StudentId = student.Id;
        return job;
        });

Or assign the lambda to a variable and pass it in.

Closing Bootstrap modal onclick

You can hide the modal and popup the window to review the carts in validateShipping() function itself.

function validateShipping(){
...
...
$('#product-options').modal('hide');
//pop the window to select items
}

HTML: How to center align a form

Just put some CSS into the stylesheet like this

form {
  text-align: center;
}

then you're done!

How can I print message in Makefile?

$(info your_text) : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text) : Fatal Error. This will stop the execution.

How to change MySQL timezone in a database connection using Java?

useTimezone is an older workaround. MySQL team rewrote the setTimestamp/getTimestamp code fairly recently, but it will only be enabled if you set the connection parameter useLegacyDatetimeCode=false and you're using the latest version of mysql JDBC connector. So for example:

String url =
 "jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false

If you download the mysql-connector source code and look at setTimestamp, it's very easy to see what's happening:

If use legacy date time code = false, newSetTimestampInternal(...) is called. Then, if the Calendar passed to newSetTimestampInternal is NULL, your date object is formatted in the database's time zone:

this.tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss", Locale.US);
this.tsdf.setTimeZone(this.connection.getServerTimezoneTZ());
timestampString = this.tsdf.format(x);

It's very important that Calendar is null - so make sure you're using:

setTimestamp(int,Timestamp).

... NOT setTimestamp(int,Timestamp,Calendar).

It should be obvious now how this works. If you construct a date: January 5, 2011 3:00 AM in America/Los_Angeles (or whatever time zone you want) using java.util.Calendar and call setTimestamp(1, myDate), then it will take your date, use SimpleDateFormat to format it in the database time zone. So if your DB is in America/New_York, it will construct the String '2011-01-05 6:00:00' to be inserted (since NY is ahead of LA by 3 hours).

To retrieve the date, use getTimestamp(int) (without the Calendar). Once again it will use the database time zone to build a date.

Note: The webserver time zone is completely irrelevant now! If you don't set useLegacyDatetimecode to false, the webserver time zone is used for formatting - adding lots of confusion.


Note:

It's possible MySQL my complain that the server time zone is ambiguous. For example, if your database is set to use EST, there might be several possible EST time zones in Java, so you can clarify this for mysql-connector by telling it exactly what the database time zone is:

String url =
 "jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false&serverTimezone=America/New_York";

You only need to do this if it complains.

How do I round a float upwards to the nearest int in C#?

You can cast to an int provided you are sure it's in the range for an int (Int32.MinValue to Int32.MaxValue).

How to select a column name with a space in MySQL

If double quotes does not work , try including the string within square brackets.

For eg:

SELECT "Business Name","Other Name" FROM your_Table

can be changed as

SELECT [Business Name],[Other Name] FROM your_Table

Should you always favor xrange() over range()?

Go with range for these reasons:

1) xrange will be going away in newer Python versions. This gives you easy future compatibility.

2) range will take on the efficiencies associated with xrange.

Is a LINQ statement faster than a 'foreach' loop?

I was interested in this question, so I did a test just now. Using .NET Framework 4.5.2 on an Intel(R) Core(TM) i3-2328M CPU @ 2.20GHz, 2200 Mhz, 2 Core(s) with 8GB ram running Microsoft Windows 7 Ultimate.

It looks like LINQ might be faster than for each loop. Here are the results I got:

Exists = True
Time   = 174
Exists = True
Time   = 149

It would be interesting if some of you could copy & paste this code in a console app and test as well. Before testing with an object (Employee) I tried the same test with integers. LINQ was faster there as well.

public class Program
{
    public class Employee
    {
        public int id;
        public string name;
        public string lastname;
        public DateTime dateOfBirth;

        public Employee(int id,string name,string lastname,DateTime dateOfBirth)
        {
            this.id = id;
            this.name = name;
            this.lastname = lastname;
            this.dateOfBirth = dateOfBirth;

        }
    }

    public static void Main() => StartObjTest();

    #region object test

    public static void StartObjTest()
    {
        List<Employee> items = new List<Employee>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(new Employee(i,"name" + i,"lastname" + i,DateTime.Today));
        }

        Test3(items, items.Count-100);
        Test4(items, items.Count - 100);

        Console.Read();
    }


    public static void Test3(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item.id == idToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test4(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Exists(e => e.id == idToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion


    #region int test
    public static void StartIntTest()
    {
        List<int> items = new List<int>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(i);
        }

        Test1(items, -100);
        Test2(items, -100);

        Console.Read();
    }

    public static void Test1(List<int> items,int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item == itemToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test2(List<int> items, int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Contains(itemToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion

}

Experimental decorators warning in TypeScript compilation

  1. Open VScode.
  2. Press ctrl+comma
  3. Follow the directions in the screen shot
    1. Search about experimentalDecorators
    2. Edit it

What does "exec sp_reset_connection" mean in Sql Server Profiler?

It's an indication that connection pooling is being used (which is a good thing).

Making div content responsive

@media screen and (max-width : 760px) (for tablets and phones) and use with this: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

How to detect IE11?

Use !(window.ActiveXObject) && "ActiveXObject" in window to detect IE11 explicitly.

To detect any IE (pre-Edge, "Trident") version, use "ActiveXObject" in window instead.

How does inline Javascript (in HTML) work?

using javascript:

here input element is used

<input type="text" id="fname" onkeyup="javascript:console.log(window.event.key)">

if you want to use multiline code use curly braces after javascript:

<input type="text" id="fname" onkeyup="javascript:{ console.log(window.event.key); alert('hello'); }">

Java sending and receiving file (byte[]) over sockets

Here is the server Open a stream to the file and send it overnetwork

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleFileServer {

  public final static int SOCKET_PORT = 5501;
  public final static String FILE_TO_SEND = "file.txt";

  public static void main (String [] args ) throws IOException {
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    OutputStream os = null;
    ServerSocket servsock = null;
    Socket sock = null;
    try {
      servsock = new ServerSocket(SOCKET_PORT);
      while (true) {
        System.out.println("Waiting...");
        try {
          sock = servsock.accept();
          System.out.println("Accepted connection : " + sock);
          // send file
          File myFile = new File (FILE_TO_SEND);
          byte [] mybytearray  = new byte [(int)myFile.length()];
          fis = new FileInputStream(myFile);
          bis = new BufferedInputStream(fis);
          bis.read(mybytearray,0,mybytearray.length);
          os = sock.getOutputStream();
          System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
          os.write(mybytearray,0,mybytearray.length);
          os.flush();
          System.out.println("Done.");
        } catch (IOException ex) {
          System.out.println(ex.getMessage()+": An Inbound Connection Was Not Resolved");
        }
        }finally {
          if (bis != null) bis.close();
          if (os != null) os.close();
          if (sock!=null) sock.close();
        }
      }
    }
    finally {
      if (servsock != null)
        servsock.close();
    }
  }
}

Here is the client Recive the file being sent overnetwork

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class SimpleFileClient {

  public final static int SOCKET_PORT = 5501;
  public final static String SERVER = "127.0.0.1";
  public final static String
       FILE_TO_RECEIVED = "file-rec.txt";

  public final static int FILE_SIZE = Integer.MAX_VALUE;

  public static void main (String [] args ) throws IOException {
    int bytesRead;
    int current = 0;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    Socket sock = null;
    try {
      sock = new Socket(SERVER, SOCKET_PORT);
      System.out.println("Connecting...");

      // receive file
      byte [] mybytearray  = new byte [FILE_SIZE];
      InputStream is = sock.getInputStream();
      fos = new FileOutputStream(FILE_TO_RECEIVED);
      bos = new BufferedOutputStream(fos);
      bytesRead = is.read(mybytearray,0,mybytearray.length);
      current = bytesRead;

      do {
         bytesRead =
            is.read(mybytearray, current, (mybytearray.length-current));
         if(bytesRead >= 0) current += bytesRead;
      } while(bytesRead > -1);

      bos.write(mybytearray, 0 , current);
      bos.flush();
      System.out.println("File " + FILE_TO_RECEIVED
          + " downloaded (" + current + " bytes read)");
    }
    finally {
      if (fos != null) fos.close();
      if (bos != null) bos.close();
      if (sock != null) sock.close();
    }
  }    
}

generating variable names on fly in python

Though I don't see much point, here it is:

for i in xrange(0, len(prices)):
    exec("price%d = %s" % (i + 1, repr(prices[i])));

How do I join two lines in vi?

In Vim you can also use gJ.

??

Downloading a picture via urllib and python

Just for the record, using requests library.

import requests
f = open('00000001.jpg','wb')
f.write(requests.get('http://www.gunnerkrigg.com//comics/00000001.jpg').content)
f.close()

Though it should check for requests.get() error.

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

You need to replace it as WHERE clockDate = { fn CURRENT_DATE() } AND userName = 'test'. Please remove extra ")" from { fn CURRENT_DATE() })

Centering a button vertically in table cell, using Twitter Bootstrap

Add vertical-align: middle; to the td element that contains the button

<td style="vertical-align:middle;">  <--add this to center vertically
  <a href="#" class="btn btn-primary">
    <i class="icon-check icon-white"></i>
  </a>
</td>

AndroidStudio gradle proxy

In my case I am behind a proxy with dynamic settings.

I had to download the settings script by picking the script address from internet settings at
Chrome > Settings > Show Advanced Settings > Change proxy Settings > Internet Properties > Connections > LAN Settings > Use automatic configuration script > Address

Opening this URL in a browser downloads a PAC file which I opened in a text editor

  • Look for a PROXY string, it should contain a hostname and port
  • Copy values into gradle.properties

systemProp.https.proxyHost=blabla.domain.com
systemProp.https.proxyPort=8081

  • I didn't have to specify a user not password.

In jQuery, how do I select an element by its name attribute?

another way

$('input:radio[name=theme]').filter(":checked").val()

REST, HTTP DELETE and parameters

No, it is not RESTful. The only reason why you should be putting a verb (force_delete) into the URI is if you would need to overload GET/POST methods in an environment where PUT/DELETE methods are not available. Judging from your use of the DELETE method, this is not the case.

HTTP error code 409/Conflict should be used for situations where there is a conflict which prevents the RESTful service to perform the operation, but there is still a chance that the user might be able to resolve the conflict himself. A pre-deletion confirmation (where there are no real conflicts which would prevent deletion) is not a conflict per se, as nothing prevents the API from performing the requested operation.

As Alex said (I don't know who downvoted him, he is correct), this should be handled in the UI, because a RESTful service as such just processes requests and should be therefore stateless (i.e. it must not rely on confirmations by holding any server-side information about of a request).

Two examples how to do this in UI would be to:

  • pre-HTML5:* show a JS confirmation dialog to the user, and send the request only if the user confirms it
  • HTML5:* use a form with action DELETE where the form would contain only "Confirm" and "Cancel" buttons ("Confirm" would be the submit button)

(*) Please note that HTML versions prior to 5 do not support PUT and DELETE HTTP methods natively, however most modern browsers can do these two methods via AJAX calls. See this thread for details about cross-browser support.


Update (based on additional investigation and discussions):

The scenario where the service would require the force_delete=true flag to be present violates the uniform interface as defined in Roy Fielding's dissertation. Also, as per HTTP RFC, the DELETE method may be overridden on the origin server (client), implying that this is not done on the target server (service).

So once the service receives a DELETE request, it should process it without needing any additional confirmation (regardless if the service actually performs the operation).

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

I must have arrived at the party late, none of the solutions here seemed helpful to me - too messy and felt like too much of a workaround.

What I ended up doing is using Angular 4.0.0-beta.6's ngComponentOutlet.

This gave me the shortest, simplest solution all written in the dynamic component's file.

  • Here is a simple example which just receives text and places it in a template, but obviously you can change according to your need:
import {
  Component, OnInit, Input, NgModule, NgModuleFactory, Compiler
} from '@angular/core';

@Component({
  selector: 'my-component',
  template: `<ng-container *ngComponentOutlet="dynamicComponent;
                            ngModuleFactory: dynamicModule;"></ng-container>`,
  styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit {
  dynamicComponent;
  dynamicModule: NgModuleFactory<any>;

  @Input()
  text: string;

  constructor(private compiler: Compiler) {
  }

  ngOnInit() {
    this.dynamicComponent = this.createNewComponent(this.text);
    this.dynamicModule = this.compiler.compileModuleSync(this.createComponentModule(this.dynamicComponent));
  }

  protected createComponentModule (componentType: any) {
    @NgModule({
      imports: [],
      declarations: [
        componentType
      ],
      entryComponents: [componentType]
    })
    class RuntimeComponentModule
    {
    }
    // a module for just this Type
    return RuntimeComponentModule;
  }

  protected createNewComponent (text:string) {
    let template = `dynamically created template with text: ${text}`;

    @Component({
      selector: 'dynamic-component',
      template: template
    })
    class DynamicComponent implements OnInit{
       text: any;

       ngOnInit() {
       this.text = text;
       }
    }
    return DynamicComponent;
  }
}
  • Short explanation:
    1. my-component - the component in which a dynamic component is rendering
    2. DynamicComponent - the component to be dynamically built and it is rendering inside my-component

Don't forget to upgrade all the angular libraries to ^Angular 4.0.0

Hope this helps, good luck!

UPDATE

Also works for angular 5.

How to convert JSON to string?

JSON.stringify()

Convert a value to JSON, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

What does a lazy val do?

The difference between them is, that a val is executed when it is defined whereas a lazy val is executed when it is accessed the first time.

scala> val x = { println("x"); 15 }
x
x: Int = 15

scala> lazy val y = { println("y"); 13 }
y: Int = <lazy>

scala> x
res2: Int = 15

scala> y
y
res3: Int = 13

scala> y
res4: Int = 13

In contrast to a method (defined with def) a lazy val is executed once and then never again. This can be useful when an operation takes long time to complete and when it is not sure if it is later used.

scala> class X { val x = { Thread.sleep(2000); 15 } }
defined class X

scala> class Y { lazy val y = { Thread.sleep(2000); 13 } }
defined class Y

scala> new X
res5: X = X@262505b7 // we have to wait two seconds to the result

scala> new Y
res6: Y = Y@1555bd22 // this appears immediately

Here, when the values x and y are never used, only x unnecessarily wasting resources. If we suppose that y has no side effects and that we do not know how often it is accessed (never, once, thousands of times) it is useless to declare it as def since we don't want to execute it several times.

If you want to know how lazy vals are implemented, see this question.

Export MySQL database using PHP only

I would Suggest that you do the folllowing,

<?php

function EXPORT_TABLES($host, $user, $pass, $name, $tables = false, $backup_name = false)
{
    $mysqli      = new mysqli($host, $user, $pass, $name);
    $mysqli->select_db($name);
    $mysqli->query("SET NAMES 'utf8'");
    $queryTables = $mysqli->query('SHOW TABLES');
    while ($row         = $queryTables->fetch_row())
    {
        $target_tables[] = $row[0];
    }
    if ($tables !== false)
    {
        $target_tables = array_intersect($target_tables, $tables);
    }
    $content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--Database: `" . $name . "`\r\n\r\n\r\n";
    foreach ($target_tables as $table)
    {
        $result        = $mysqli->query('SELECT * FROM ' . $table);
        $fields_amount = $result->field_count;
        $rows_num      = $mysqli->affected_rows;
        $res           = $mysqli->query('SHOW CREATE TABLE ' . $table);
        $TableMLine    = $res->fetch_row();
        $content .= "\n\n" . $TableMLine[1] . ";\n\n";
        for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0)
        {
            while ($row = $result->fetch_row())
            { //when started (and every after 100 command cycle):
                if ($st_counter % 100 == 0 || $st_counter == 0)
                {
                    $content .= "\nINSERT INTO " . $table . " VALUES";
                }
                $content .= "\n(";
                for ($j = 0; $j < $fields_amount; $j++)
                {
                    $row[$j] = str_replace("\n", "\\n", addslashes($row[$j]));
                    if (isset($row[$j]))
                    {
                        $content .= '"' . $row[$j] . '"';
                    }
                    else
                    {
                        $content .= '""';
                    } if ($j < ($fields_amount - 1))
                    {
                        $content.= ',';
                    }
                }
                $content .=")";
                //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                if ((($st_counter + 1) % 100 == 0 && $st_counter != 0) || $st_counter + 1 == $rows_num)
                {
                    $content .= ";";
                }
                else
                {
                    $content .= ",";
                } $st_counter = $st_counter + 1;
            }
        } $content .="\n\n\n";
    }
    $content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
    $backup_name = $backup_name ? $backup_name : $name . "___(" . date('H-i-s') . "_" . date('d-m-Y') . ")__rand" . rand(1, 11111111) . ".sql";
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary");
    header("Content-disposition: attachment; filename=\"" . $backup_name . "\"");
    echo $content;
    exit;
}
?>

The enitre project for export and import can be found at https://github.com/tazotodua/useful-php-scripts.

Fragment onResume() & onPause() is not called on backstack

You can try this,

Step1: Override the Tabselected method in your activity

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    try {
    if(MyEventsFragment!=null && tab.getPosition()==3)
    {
        MyEvents.fragmentChanged();
    }
    }
    catch (Exception e)
    {

    }
    mViewPager.setCurrentItem(tab.getPosition());
}

Step 2: Using static method do what you want in your fragment,

public static void fragmentChanged()
{
    Toast.makeText(actvity, "Fragment Changed", Toast.LENGTH_SHORT).show();
}

html5 input for money/currency

Well in the end I had to compromise by implementing a HTML5/CSS solution, forgoing increment buttons in IE (they're a bit broke in FF anyway!), but gaining number validation that the JQuery spinner doesn't provide. Though I have had to go with a step of whole numbers.

_x000D_
_x000D_
span.gbp {_x000D_
    float: left;_x000D_
    text-align: left;_x000D_
}_x000D_
_x000D_
span.gbp::before {_x000D_
    float: left;_x000D_
    content: "\00a3"; /* £ */_x000D_
    padding: 3px 4px 3px 3px;_x000D_
}_x000D_
_x000D_
span.gbp input {_x000D_
     width: 280px !important;_x000D_
}
_x000D_
<label for="broker_fees">Broker Fees</label>_x000D_
<span class="gbp">_x000D_
    <input type="number" placeholder="Enter whole GBP (&pound;) or zero for none" min="0" max="10000" step="1" value="" name="Broker_Fees" id="broker_fees" required="required" />_x000D_
</span>
_x000D_
_x000D_
_x000D_

The validation is a bit flaky across browsers, where IE/FF allow commas and decimal places (as long as it's .00), where as Chrome/Opera don't and want just numbers.

I guess it's a shame that the JQuery spinner won't work with a number type input, but the docs explicitly state not to do that :-( and I'm puzzled as to why a number spinner widget allows input of any ascii char?

Are "while(true)" loops so bad?

I use something similar, but with opposite logic, in a lot of my functions.

DWORD dwError = ERROR_SUCCESS;

do
{
    if ( (dwError = SomeFunction()) != ERROR_SUCCESS )
    {
         /* handle error */
         continue;
    }

    if ( (dwError = SomeOtherFunction()) != ERROR_SUCCESS )
    {
         /* handle error */
         continue;
    }
}
while ( 0 );

if ( dwError != ERROR_SUCCESS )
{
    /* resource cleanup */
}

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

try this

String url = "jdbc:mysql://localhost:3306/<dbname>";
String user = "<username>";
String password = "<password>";
conn = DriverManager.getConnection(url, user, password); 

Pick any kind of file via an Intent in Android

The other answers are not incorrect. However, now there are more options for opening files. For example, if you want the app to have long term, permanent acess to a file, you can use ACTION_OPEN_DOCUMENT instead. Refer to the official documentation: Open files using storage access framework. Also refer to this answer.

How to advance to the next form input when the current input has a value?

function nextField(current){
    for (i = 0; i < current.form.elements.length; i++){
        if (current.form.elements[i].tabIndex - current.tabIndex == 1){
            current.form.elements[i].focus();
            if (current.form.elements[i].type == "text"){
                current.form.elements[i].select();
            }
        }
    }
}

This, when supplied with the current field, will jump focus to the field with the next tab index. Usage would be as follows

<input type="text" onEvent="nextField(this);" />

User Control - Custom Properties

Just add public properties to the user control.

You can add [Category("MyCategory")] and [Description("A property that controls the wossname")] attributes to make it nicer, but as long as it's a public property it should show up in the property panel.

Insert data through ajax into mysql database

Try this:

  $(document).on('click','#save',function(e) {
  var data = $("#form-search").serialize();
  $.ajax({
         data: data,
         type: "post",
         url: "insertmail.php",
         success: function(data){
              alert("Data Save: " + data);
         }
});
 });

and in insertmail.php:

<?php 
if(isset($_REQUEST))
{
        mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");
error_reporting(E_ALL && ~E_NOTICE);

$email=$_POST['email'];
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
}
?>

Don't use mysql_ it's deprecated.

another method:

Actually if your problem is null value inserted into the database then try this and here no need of ajax.

<?php
if($_POST['email']!="")
{
    mysql_connect("localhost","root","");
    mysql_select_db("eciticket_db");
    error_reporting(E_ALL && ~E_NOTICE);
    $email=$_POST['email'];
    $sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
    $result=mysql_query($sql);
    if($result){
    //echo "You have been successfully subscribed.";
              setcookie("msg","You have been successfully subscribed.",time()+5,"/");
              header("location:yourphppage.php");
    }
     if(!$sql)
    die(mysql_error());
    mysql_close();
}
?>
    <?php if(isset($_COOKIE['msg'])){?>
       <span><?php echo $_COOKIE['msg'];setcookie("msg","",time()-5,"/");?></span> 
    <?php }?>
<form id="form-search" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
    <span><span class="style2">Enter you email here</span>:</span>
    <input name="email" type="email" id="email" required/>
    <input type="submit" value="subscribe" class="submit"/>
</form>

Nginx 403 error: directory index of [folder] is forbidden

Because you're using php-fpm, you should make sure that php-fpm user is the same as nginx user.

Check /etc/php-fpm.d/www.conf and set php user and group to nginx if it's not.

The php-fpm user needs write permission.

file_put_contents: Failed to open stream, no such file or directory

There is definitly a problem with the destination folder path.

Your above error message says, it wants to put the contents to a file in the directory /files/grantapps/, which would be beyond your vhost, but somewhere in the system (see the leading absolute slash )

You should double check:

  • Is the directory /home/username/public_html/files/grantapps/ really present.
  • Contains your loop and your file_put_contents-Statement the absolute path /home/username/public_html/files/grantapps/

How to show only next line after the matched one?

I don't know of any way to do this with grep, but it is possible to use awk to achieve the same result:

awk '/blah/ {getline;print}' < logfile

Excel VBA Macro: User Defined Type Not Defined

Sub DeleteEmptyRows()  

    Worksheets("YourSheetName").Activate
    On Error Resume Next
    Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

End Sub

The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.

EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.

How to Free Inode Usage?

We faced similar issue recently, In case if a process refers to a deleted file, the Inode shall not be released, so you need to check lsof /, and kill/ restart the process will release the inodes.

Correct me if am wrong here.

Android - how to replace part of a string by another string?

It is working, but it wont modify the caller object, but returning a new String.
So you just need to assign it to a new String variable, or to itself:

string = string.replace("to", "xyz");

or

String newString = string.replace("to", "xyz");

API Docs

public String replace (CharSequence target, CharSequence replacement) 

Since: API Level 1

Copies this string replacing occurrences of the specified target sequence with another sequence. The string is processed from the beginning to the end.

Parameters

  • target the sequence to replace.
  • replacement the replacement sequence.

Returns the resulting string.
Throws NullPointerException if target or replacement is null.

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

  • I just went to Properties -> Java Build Path -> Libraries and removed the blue entries starting with M2_REPO.

  • After that, I could use Maven -> Update Project again

How to get UTC time in Python?

you could use datetime library to get UTC time even local time.

import datetime

utc_time = datetime.datetime.utcnow() 
print(utc_time.strftime('%Y%m%d %H%M%S'))

Use sudo with password as parameter

echo -e "YOURPASSWORD\n" | sudo -S yourcommand

Creating for loop until list.length

You could learn about Python loops here: http://en.wikibooks.org/wiki/Python_Programming/Loops

You have to know that Python doesn't have { and } for start and end of loop, instead it depends on tab chars you enter in first of line, I mean line indents.

So you can do loop inside loop with double tab (indent)

An example of double loop is like this:

onetoten = range(1,11)
tentotwenty = range(10,21)
for count in onetoten:
    for count2 in tentotwenty
        print(count2)

Postgresql GROUP_CONCAT equivalent?

Try like this:

select field1, array_to_string(array_agg(field2), ',')
from table1
group by field1;

Right way to write JSON deserializer in Spring or extend it

I've searched a lot and the best way I've found so far is on this article:

Class to serialize

package net.sghill.example;

import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonDeserialize(using = UserDeserializer.class)
public class User {
    private ObjectId id;
    private String   username;
    private String   password;

    public User(ObjectId id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public ObjectId getId()       { return id; }
    public String   getUsername() { return username; }
    public String   getPassword() { return password; }
}

Deserializer class

package net.sghill.example;

import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import java.io.IOException;

public class UserDeserializer extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
    }
}

Edit: Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.

Mount current directory as a volume in Docker on Windows 10

docker run --rm -v /c/Users/Christian/manager/bin:/app --workdir=/app  php:7.2-cli php  app.php

Git bash

 cd /c/Users/Christian/manager
    docker run --rm -v  ${PWD}:/app  --workdir=/app  php:7.2-cli php  bin/app.php

echo ${PWD} result:

/c/Users/Christian/manager

cmd or PowerShell

  cd C:\Users\Christian\manager

echo ${PWD} result:

Path ---- C:\Users\Christian\manager

as we see in cmd or PowerShell $ {PWD} will not work

Copying Code from Inspect Element in Google Chrome

You can copy by inspect element and target the div you want to copy. Just press ctrl+c and then your div will be copy and paste in your code it will run easily.

How to view AndroidManifest.xml from APK file?

You can also use my app, App Detective to view the manifest file of any app you have installed on your device.

android on Text Change Listener

I know this is old but someone might come across this again someday.

I had a similar problem where I would call setText on a EditText and onTextChanged would be called when I didn't want it to. My first solution was to write some code after calling setText() to undo the damage done by the listener. But that wasn't very elegant. After doing some research and testing I discovered that using getText().clear() clears the text in much the same way as setText(""), but since it isn't setting the text the listener isn't called, so that solved my problem. I switched all my setText("") calls to getText().clear() and I didn't need the bandages anymore, so maybe that will solve your problem too.

Try this:

Field1 = (EditText)findViewById(R.id.field1);
Field2 = (EditText)findViewById(R.id.field2);

Field1.addTextChangedListener(new TextWatcher() {

   public void afterTextChanged(Editable s) {}

   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }

   public void onTextChanged(CharSequence s, int start,
     int before, int count) {
      Field2.getText().clear();
   }
  });

Field2.addTextChangedListener(new TextWatcher() {

   public void afterTextChanged(Editable s) {}

   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }

   public void onTextChanged(CharSequence s, int start,
     int before, int count) {
     Field1.getText().clear();
   }
  });

How to clear mysql screen console in windows?

Well, if you installed MySql Server e.g. Version 5.5. which has it's folder located in:

C:\Program Files\MySQL\MySQL Server 5.5\bin

The best way would be to include it in your paths.

  • First run sysdm.cpl applet from run i.e. WinKey + R

  • Navigate to Advanced -> Environment Variables

  • Select PATH and Click Edit.

  • Scroll to the end of the text, and add ";C:\Program Files\MySQL\MySQL Server 5.5\bin" without quotes (Notice the semicolon starting the text, this should only be added if it's not already there),

Now you can just call:

start /b /wait mysql -u root -p

via command prompt.

To clear the screen now, you can just exit in mysql & call cls

Kinda trickish hack but does the job.

If you're using WAMP or other tool, it's even easier!

Open command prompt and type:

C:\wamp\mysql\bin\mysql -u root -p

Enter as normal, then whenever you want to clear screen, do:

exit or quit

And then clear using DOS:

cls

You can easily re-enter by pressing up twice to get your mysql call command

logger configuration to log to file and print to stdout

Logging to stdout and rotating file with different levels and formats:

import logging
import logging.handlers
import sys

if __name__ == "__main__":

    # Change root logger level from WARNING (default) to NOTSET in order for all messages to be delegated.
    logging.getLogger().setLevel(logging.NOTSET)

    # Add stdout handler, with level INFO
    console = logging.StreamHandler(sys.stdout)
    console.setLevel(logging.INFO)
    formater = logging.Formatter('%(name)-13s: %(levelname)-8s %(message)s')
    console.setFormatter(formater)
    logging.getLogger().addHandler(console)

    # Add file rotating handler, with level DEBUG
    rotatingHandler = logging.handlers.RotatingFileHandler(filename='rotating.log', maxBytes=1000, backupCount=5)
    rotatingHandler.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    rotatingHandler.setFormatter(formatter)
    logging.getLogger().addHandler(rotatingHandler)

    log = logging.getLogger("app." + __name__)

    log.debug('Debug message, should only appear in the file.')
    log.info('Info message, should appear in file and stdout.')
    log.warning('Warning message, should appear in file and stdout.')
    log.error('Error message, should appear in file and stdout.')

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Make header and footer files to be included in multiple html pages

Must you use html file structure with JavaScript? Have you considered using PHP instead so that you can use simple PHP include object?

If you convert the file names of your .html pages to .php - then at the top of each of your .php pages you can use one line of code to include the content from your header.php

<?php include('header.php'); ?>

Do the same in the footer of each page to include the content from your footer.php file

<?php include('footer.php'); ?>

No JavaScript / Jquery or additional included files required.

NB You could also convert your .html files to .php files using the following in your .htaccess file

# re-write html to php
RewriteRule ^(.*)\.html$ $1.php [L]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]


# re-write no extension to .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Vue component event after render

updated might be what you're looking for. https://vuejs.org/v2/api/#updated

hadoop copy a local file system folder to HDFS

You could try:

hadoop fs -put /path/in/linux /hdfs/path

or even

hadoop fs -copyFromLocal /path/in/linux /hdfs/path

By default both put and copyFromLocal would upload directories recursively to HDFS.

SQL Combine Two Columns in Select Statement

SELECT StaffId,(Title+''+FirstName+''+LastName) AS FullName 
FROM StaffInformation

Where do you write with in the brackets this will be appear in the one single column. Where do you want a dot into the middle of the Title and First Name write syntax below,

SELECT StaffId,(Title+'.'+FirstName+''+LastName) AS FullName 
FROM StaffInformation

These syntax works with MS SQL Server 2008 R2 Express Edition.

How to handle a lost KeyStore password in Android?

I had the same problem at once. Even though with App signing by Google Play, loosing keystore or it's password is not a big deal like earlier, Still as a developer we rather prefer to change it's password and use a generated keystore file without waiting for few days to google to handle it. ( To handle this issue with google use this link to make a request) To handle this issue by ourselves, First download two .java files from this link. Then compile the ChangePassword.java by javac ChangePassword.java command. Then after you may run

java ChangePassword <oldKeystoreFileName.keystore> <newKeystoreFileName.keystore>

Change oldKeystoreFileName.keystore with the path/ name of your current keystore file, and newKeystoreFileName.keystore with path/name for the new generated new keystore file. This will promot you to

Enter keystore password:

. Just enter whatever you prefer :) no need to be the original password that lost. Then Enter the new password with *

new keystore password:

  • Voila, that's it. This won't change the checksum of your keystore and won't make any issues in app signing or uploading to play.google events.

Bootstrap Align Image with text

_x000D_
_x000D_
<div class="container">_x000D_
     <h1>About Me</h1>_x000D_
    <div class="row">_x000D_
        <div class="col-md-4">_x000D_
            <div class="imgAbt">_x000D_
                <img width="100%" height="100%" src="img/me.jpg" />_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-md-8">_x000D_
            <p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to center a label text in WPF?

use the HorizontalContentAlignment property.

Sample

<Label HorizontalContentAlignment="Center"/>

tar: Error is not recoverable: exiting now

use sudo

sudo tar -zxvf xxxxxxxxx.tar.gz

When should I use h:outputLink instead of h:commandLink?

The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

<h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

How to Maximize window in chrome using webDriver (python)

For MAC or Linux:

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--kiosk");
driver = new ChromeDriver(chromeOptions);

For Windows:

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--start-maximized");
driver = new ChromeDriver(chromeOptions);

How to find prime numbers between 0 - 100?

A version without any loop. Use this against any array you have. ie.,

[1,2,3...100].filter(x=>isPrime(x));
const isPrime = n => {
if(n===1){
return false;
}
if([2,3,5,7].includes(n)){
return true;
}
return n%2!=0 && n%3!=0 && n%5!=0 && n%7!=0;
}

How to dynamically change header based on AngularJS partial view?

Simplistic solution for angular-ui-router :

HTML :

<html ng-app="myApp">
  <head>
     <title ng-bind="title"></title>
     .....
     .....  
  </head>
</html>

App.js > myApp.config block

$stateProvider
    .state("home", {
        title: "My app title this will be binded in html title",
        url: "/home",
        templateUrl: "/home.html",
        controller: "homeCtrl"
    })

App.js>myApp.run

myApp.run(['$rootScope','$state', function($rootScope,$state) {
   $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
    $rootScope.title = $state.current.title;
    console.log($state);
   });
}]);

C - freeing structs

You can't free types that aren't dynamically allocated. Although arrays are syntactically similar (int* x = malloc(sizeof(int) * 4) can be used in the same way that int x[4] is), calling free(firstName) would likely cause an error for the latter.

For example, take this code:

int x;
free(&x);

free() is a function which takes in a pointer. &x is a pointer. This code may compile, even though it simply won't work.

If we pretend that all memory is allocated in the same way, x is "allocated" at the definition, "freed" at the second line, and then "freed" again after the end of the scope. You can't free the same resource twice; it'll give you an error.

This isn't even mentioning the fact that for certain reasons, you may be unable to free the memory at x without closing the program.

tl;dr: Just free the struct and you'll be fine. Don't call free on arrays; only call it on dynamically allocated memory.

Annotations from javax.validation.constraints not working

You need to add @Valid to each member variable, which was also an object that contained validation constraints.

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;
     position:absolute;
     top:0;
     right:0;
 }

jsFiddle example

Preventing an image from being draggable or selectable without using JS

A generic solution especially for Windows Edge browser (as the -ms-user-select: none; CSS rule doesn't work):

window.ondragstart = function() {return false}

Note: This can save you having to add draggable="false" to every img tag when you still need the click event (i.e. you can't use pointer-events: none), but don't want the drag icon image to appear.

Declaring variables inside loops, good practice or bad practice?

Declaring variables inside or outside of a loop, It's the result of JVM specifications But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used). Declaring objects in the smallest scope improve readability. The scope of local variables should always be the smallest possible. In your example I presume str is not used outside of the while loop, otherwise you would not be asking the question, because declaring it inside the while loop would not be an option, since it would not compile.

Does it make a difference if I declare variables inside or outside a , Does it make a difference if I declare variables inside or outside a loop in Java? Is this for(int i = 0; i < 1000; i++) { int At the level of the individual variable there is no significant difference in effeciency, but if you had a function with 1000 loops and 1000 variables (never mind the bad style implied) there could be systemic differences because all the lives of all the variables would be the same instead of overlapped.

Declaring Loop Control Variables Inside the for Loop, When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.) This Java Example shows how to declare multiple variables in Java For loop using declaration block.

How does #include <bits/stdc++.h> work in C++?

That header file is not part of the C++ standard, is therefore non-portable, and should be avoided.

Moreover, even if there were some catch-all header in the standard, you would want to avoid it in lieu of specific headers, since the compiler has to actually read in and parse every included header (including recursively included headers) every single time that translation unit is compiled.

How to convert milliseconds to "hh:mm:ss" format?

You were really close:

String.format("%02d:%02d:%02d", 
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -  
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // The change is in this line
TimeUnit.MILLISECONDS.toSeconds(millis) - 
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));   

You were converting hours to millisseconds using minutes instead of hours.

BTW, I like your use of the TimeUnit API :)

Here's some test code:

public static void main(String[] args) throws ParseException {
    long millis = 3600000;
    String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
            TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
            TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
    System.out.println(hms);
}

Output:

01:00:00

I realised that my code above can be greatly simplified by using a modulus division instead of subtraction:

String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
    TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
    TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));

Still using the TimeUnit API for all magic values, and gives exactly the same output.

Singleton design pattern vs Singleton beans in Spring container

Let's take the simplest example: you have an application and you just use the default classloader. You have a class which, for whatever reason, you decide that it should not have more than one instance in the application. (Think of a scenario where several people work on pieces of the application).

If you are not using the Spring framework, the Singleton pattern ensures that there will not be more than one instance of a class in your application. That is because you cannot instantiate instances of the class by doing 'new' because the constructor is private. The only way to get an instance of the class is to call some static method of the class (usually called 'getInstance') which always returns the same instance.

Saying that you are using the Spring framework in your application, just means that in addition to the regular ways of obtaining an instance of the class (new or static methods that return an instance of the class), you can also ask Spring to get you an instance of that class and Spring will ensure that whenever you ask it for an instance of that class it will always return the same instance, even if you didn't write the class using the Singleton pattern. In other words, even if the class has a public constructor, if you always ask Spring for an instance of that class, Spring will only call that constructor once during the life of your application.

Normally if you are using Spring, you should only use Spring to create instances, and you can have a public constructor for the class. But if your constructor is not private you are not really preventing anyone from creating new instances of the class directly, by bypassing Spring.

If you truly want a single instance of the class, even if you use Spring in your application and define the class in Spring to be a singleton, the only way to ensure that is also implement the class using the Singleton pattern. That ensures that there will be a single instance, whether people use Spring to get an instance or bypass Spring.

How to check if MySQL returns null/empty?

select FOUND_ROWS();

will return no. of records selected by select query.

How to hide action bar before activity is created, and then show it again?

this is the best way I used Go to java file, after onCreate:

@Override
    protected void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 

        // Take instance of Action Bar 
        // using getSupportActionBar and 
        // if it is not Null 
        // then call hide function 
        if (getSupportActionBar() != null) { 
            getSupportActionBar().hide(); 
        } 
    }

How to rollback a specific migration?

Migrations change the state of the database using the command

$ bundle exec rake db:migrate

We can undo a single migration step using

  $ bundle exec rake db:rollback

To go all the way back to the beginning, we can use

  $ bundle exec rake db:migrate VERSION=0

As you might guess, substituting any other number for 0 migrates to that version number, where the version numbers come from listing the migrations sequentially

Type Checking: typeof, GetType, or is?

Used to obtain the System.Type object for a type. A typeof expression takes the following form:

System.Type type = typeof(int);

Example:

    public class ExampleClass
    {
       public int sampleMember;
       public void SampleMethod() {}

       static void Main()
       {
          Type t = typeof(ExampleClass);
          // Alternatively, you could use
          // ExampleClass obj = new ExampleClass();
          // Type t = obj.GetType();

          Console.WriteLine("Methods:");
          System.Reflection.MethodInfo[] methodInfo = t.GetMethods();

          foreach (System.Reflection.MethodInfo mInfo in methodInfo)
             Console.WriteLine(mInfo.ToString());

          Console.WriteLine("Members:");
          System.Reflection.MemberInfo[] memberInfo = t.GetMembers();

          foreach (System.Reflection.MemberInfo mInfo in memberInfo)
             Console.WriteLine(mInfo.ToString());
       }
    }
    /*
     Output:
        Methods:
        Void SampleMethod()
        System.String ToString()
        Boolean Equals(System.Object)
        Int32 GetHashCode()
        System.Type GetType()
        Members:
        Void SampleMethod()
        System.String ToString()
        Boolean Equals(System.Object)
        Int32 GetHashCode()
        System.Type GetType()
        Void .ctor()
        Int32 sampleMember
    */

This sample uses the GetType method to determine the type that is used to contain the result of a numeric calculation. This depends on the storage requirements of the resulting number.

    class GetTypeTest
    {
        static void Main()
        {
            int radius = 3;
            Console.WriteLine("Area = {0}", radius * radius * Math.PI);
            Console.WriteLine("The type is {0}",
                              (radius * radius * Math.PI).GetType()
            );
        }
    }
    /*
    Output:
    Area = 28.2743338823081
    The type is System.Double
    */

How to get and set the current web page scroll position?

There are some inconsistencies in how browsers expose the current window scrolling coordinates. Google Chrome on Mac and iOS seems to always return 0 when using document.documentElement.scrollTop or jQuery's $(window).scrollTop().

However, it works consistently with:

// horizontal scrolling amount
window.pageXOffset

// vertical scrolling amount
window.pageYOffset

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

Foreign keys work by joining a column to a unique key in another table, and that unique key must be defined as some form of unique index, be it the primary key, or some other unique index.

At the moment, the only unique index you have is a compound one on ISBN, Title which is your primary key.

There are a number of options open to you, depending on exactly what BookTitle holds and the relationship of the data within it.

I would hazard a guess that the ISBN is unique for each row in BookTitle. ON the assumption this is the case, then change your primary key to be only on ISBN, and change BookCopy so that instead of Title you have ISBN and join on that.

If you need to keep your primary key as ISBN, Title then you either need to store the ISBN in BookCopy as well as the Title, and foreign key on both columns, OR you need to create a unique index on BookTitle(Title) as a distinct index.

More generally, you need to make sure that the column or columns you have in your REFERENCES clause match exactly a unique index in the parent table: in your case it fails because you do not have a single unique index on Title alone.

How do I put variable values into a text string in MATLAB?

You can use fprintf/sprintf with familiar C syntax. Maybe something like:

fprintf('x = %d, y = %d \n x+y=%d \n x*y=%d \n x/y=%f\n', x,y,d,e,f)

reading your comment, this is how you use your functions from the main program:

x = 2;
y = 2;
[d e f] = answer(x,y);
fprintf('%d + %d = %d\n', x,y,d)
fprintf('%d * %d = %d\n', x,y,e)
fprintf('%d / %d = %f\n', x,y,f)

Also for the answer() function, you can assign the output values to a vector instead of three distinct variables:

function result=answer(x,y)
result(1)=addxy(x,y);
result(2)=mxy(x,y);
result(3)=dxy(x,y);

and call it simply as:

out = answer(x,y);

Submit form using <a> tag

you can do it like this with raw javascript

<html>
    <body>
        <form id="my_form" method="post" action="mailto://[email protected]">
            <a href="javascript:{}" onclick="document.getElementById('my_form').submit();">submit</a>
        </form>
    </body>
</html>

For those asking why I have a href element in my anchor tag, its because it's a compulsory part of an anchor tag, it may well work without but it's not to spec. So if you want to guarantee rendering etc you must give the engine a fully formed tag. So the above achieves this. You will see href="#" used sometimes but this is not always wanted as the browser will change the page position.

jQuery keypress() event not firing?

Ofcourse this is a closed issue, i would like to add something to your discussion

In mozilla i have observed a weird behaviour for this code

$(document).keydown(function(){
//my code 
});

the code is being triggered twice. When debugged i found that actually there are two events getting fired: 'keypress' and 'keydown'. I disabled one of the event and the code shown me expected behavior.

$(document).unbind('keypress');
$(document).keydown(function(){
//my code
});

This works for all browsers and also there is no need to check for browser specific(if($.browser.mozilla){ }).

Hope this might be useful for someone

Java Multithreading concept and join() method

when ob1 is created then the constructor is called where "t.start()" is written but still run() method is not executed rather main() method is executed further. So why is this happening?

here your threads and main thread has equal priority.Execution of equal priority thread totally depends on the Thread schedular.You can't expect which to execute first.

join() method is used to wait until the thread on which it is called does not terminates, but here in output we see alternate outputs of the thread why??

Here your calling below statements from main thread.

     ob1.t.join();
     ob2.t.join();
     ob3.t.join();

So main thread waits for ob1.t,ob2.t,ob3.t threads to die(look into Thread#join doc).So all three threads executes successfully and main thread completes after that

How can I format a nullable DateTime with ToString()?

You can use dt2.Value.ToString("format"), but of course that requires that dt2 != null, and that negates th use of a nullable type in the first place.

There are several solutions here, but the big question is: How do you want to format a null date?

How to change letter spacing in a Textview?

More space:

  android:letterSpacing="0.1"

Less space:

 android:letterSpacing="-0.07"

How to show one layout on top of the other programmatically in my case?

Use a FrameLayout with two children. The two children will be overlapped. This is recommended in one of the tutorials from Android actually, it's not a hack...

Here is an example where a TextView is displayed on top of an ImageView:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <ImageView  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 

    android:scaleType="center"
    android:src="@drawable/golden_gate" />

  <TextView
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginBottom="20dip"
    android:layout_gravity="center_horizontal|bottom"

    android:padding="12dip"

    android:background="#AA000000"
    android:textColor="#ffffffff"

    android:text="Golden Gate" />

</FrameLayout>

Here is the result

How can one see the structure of a table in SQLite?

You should be able to see the schema by running

.schema <table>

Must declare the scalar variable

If someone else comes across this question while no solution here made my sql file working, here's what my mistake was:

I have been exporting the contents of my database via the 'Generate Script' command of Microsofts' Server Management Studio and then doing some operations afterwards while inserting the generated data in another instance.

Due to the generated export, there have been a bunch of "GO" statements in the sql file.

What I didn't know was that variables declared at the top of a file aren't accessible as far as a GO statement is executed. Therefore I had to remove the GO statements in my sql file and the error "Must declare the scalar variable xy" was gone!

Add CSS box shadow around the whole DIV

Yes, don't offset vertically or horizontally, and use a relatively large blur radius: fiddle

Also, you can use multiple box-shadows if you separate them with a comma. This will allow you to fine-tune where they blur and how much they extend. The example I provide is indistinguishable from a large outline, but it can be fine-tuned significantly more: fiddle

You missed the last and most relevant property of box-shadow, which is spread-distance. You can specify a value for how much the shadow expands or contracts (makes my second example obsolete): fiddle

The full property list is:

box-shadow: [horizontal-offset] [vertical-offset] [blur-radius] [spread-distance] [color] inset?

But even better, read through the spec.

Linq with group by having count

For anyone looking to do this in vb (as I was and couldn't find anything)

From c In db.Company 
Select c.Name Group By Name Into Group 
Where Group.Count > 1

How to check certificate name and alias in keystore files?

You can run the following command to list the content of your keystore file (and alias name):

keytool -v -list -keystore .keystore

If you are looking for a specific alias, you can also specify it in the command:

keytool -list -keystore .keystore -alias foo

If the alias is not found, it will display an exception:

keytool error: java.lang.Exception: Alias does not exist

How does a PreparedStatement avoid or prevent SQL injection?

Prepared statement is more secure. It will convert a parameter to the specified type.

For example stmt.setString(1, user); will convert the user parameter to a String.

Suppose that the parameter contains a SQL string containing an executable command: using a prepared statement will not allow that.

It adds metacharacter (a.k.a. auto conversion) to that.

This makes it is more safe.

Error converting data types when importing from Excel to SQL Server 2008

When Excel finds mixed data types in same column it guesses what is the right format for the column (the majority of the values determines the type of the column) and dismisses all other values by inserting NULLs. But Excel does it far badly (e.g. if a column is considered text and Excel finds a number then decides that the number is a mistake and insert a NULL instead, or if some cells containing numbers are "text" formatted, one may get NULL values into an integer column of the database).

Solution:

  1. Create a new excel sheet with the name of the columns in the first row
  2. Format the columns as text
  3. Paste the rows without format (use CVS format or copy/paste in Notepad to get only text)

Note that formatting the columns on an existing Excel sheet is not enough.

Difference between timestamps with/without time zone in PostgreSQL

Here is an example that should help. If you have a timestamp with a timezone, you can convert that timestamp into any other timezone. If you haven't got a base timezone it won't be converted correctly.

SELECT now(),
   now()::timestamp,
   now() AT TIME ZONE 'CST',
   now()::timestamp AT TIME ZONE 'CST'

Output:

-[ RECORD 1 ]---------------------------
now      | 2018-09-15 17:01:36.399357+03
now      | 2018-09-15 17:01:36.399357
timezone | 2018-09-15 08:01:36.399357
timezone | 2018-09-16 02:01:36.399357+03

How to access the ith column of a NumPy multidimensional array?

And if you want to access more than one column at a time you could do:

>>> test = np.arange(9).reshape((3,3))
>>> test
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> test[:,[0,2]]
array([[0, 2],
       [3, 5],
       [6, 8]])

PostgreSQL: how to convert from Unix epoch to date?

/* Current time */
 select now(); 

/* Epoch from current time;
   Epoch is number of seconds since 1970-01-01 00:00:00+00 */
 select extract(epoch from now()); 

/* Get back time from epoch */
 -- Option 1 - use to_timestamp function
 select to_timestamp( extract(epoch from now()));
 -- Option 2 - add seconds to 'epoch'
 select timestamp with time zone 'epoch' 
         + extract(epoch from now()) * interval '1 second';

/* Cast timestamp to date */
 -- Based on Option 1
 select to_timestamp(extract(epoch from now()))::date;
 -- Based on Option 2
 select (timestamp with time zone 'epoch' 
          + extract(epoch from now()) * interval '1 second')::date; 

 /* For column epoch_ms */
 select to_timestamp(extract(epoch epoch_ms))::date;

PostgreSQL Docs

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

According to the latest updates for OpenCV 3.0 and higher, you need to change the Property Identifiers as follows in the code by Mehran:

cv2.cv.CV_CAP_PROP_POS_FRAMES

to

cv2.CAP_PROP_POS_FRAMES

and same applies to cv2.CAP_PROP_POS_FRAME_COUNT.

Hope it helps.

MVC 4 - how do I pass model data to a partial view?

Also, this could make it works:

@{
Html.RenderPartial("your view", your_model, ViewData);
}

or

@{
Html.RenderPartial("your view", your_model);
}

For more information on RenderPartial and similar HTML helpers in MVC see this popular StackOverflow thread

How to fix "unable to open stdio.h in Turbo C" error?

Since you did not mention which version of Turbo C this method below will cover both v2 and v3.

  • Click on 'Options', 'Directories', enter the proper location for the Include and Lib directories.

How to deal with http status codes other than 200 in Angular 2

Include required imports and you can make ur decision in handleError method Error status will give the error code

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import {Observable, throwError} from "rxjs/index";
import { catchError, retry } from 'rxjs/operators';
import {ApiResponse} from "../model/api.response";
import { TaxType } from '../model/taxtype.model'; 

private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
  // A client-side or network error occurred. Handle it accordingly.
  console.error('An error occurred:', error.error.message);
} else {
  // The backend returned an unsuccessful response code.
  // The response body may contain clues as to what went wrong,
  console.error(
    `Backend returned code ${error.status}, ` +
    `body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
  'Something bad happened; please try again later.');
  };

  getTaxTypes() : Observable<ApiResponse> {
return this.http.get<ApiResponse>(this.baseUrl).pipe(
  catchError(this.handleError)
);
  }

Checking for empty queryset in Django

I disagree with the predicate

if not orgs:

It should be

if not orgs.count():

I was having the same issue with a fairly large result set (~150k results). The operator is not overloaded in QuerySet, so the result is actually unpacked as a list before the check is made. In my case execution time went down by three orders.

Send email using the GMail SMTP server from a PHP page

Your code does not appear to be using TLS (SSL), which is necessary to deliver mail to Google (and using ports 465 or 587).

You can do this by setting

$host = "ssl://smtp.gmail.com";

Your code looks suspiciously like this example which refers to ssl:// in the hostname scheme.

How to execute a shell script in PHP?

Residuum did provide a correct answer to how you should get shell exec to find your script, but in regards to security, there are a couple of points.

I would imagine you don't want your shell script to be in your web root, as it would be visible to anyone with web access to your server.

I would recommend moving the shell script to outside of the webroot

    <?php
      $tempFolder = '/tmp';
      $webRootFolder = '/var/www';
      $scriptName = 'myscript.sh';
      $moveCommand = "mv $webRootFolder/$scriptName $tempFolder/$scriptName";
      $output = shell_exec($moveCommand);
    ?>

In regards to the:

i added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers works

You can modify this to only cover the specific commands in your script which require sudo. Otherwise, if none of the commands in your sh script require sudo to execute, you don't need to do this at all anyway.

Try running the script as the apache user (use the su command to switch to the apache user) and if you are not prompted for sudo or given permission denied, etc, it'll be fine.

ie:

sudo su apache (or www-data)
cd /var/www
sh ./myscript

Also... what brought me here was that I wanted to run a multi line shell script using commands that are dynamically generated. I wanted all of my commands to run in the same shell, which won't happen using multiple calls to shell_exec(). The answer to that one is to do it like Jenkins - create your dynamically generated multi line of commands, put it in a variable, save it to a file in a temp folder, execute that file (using shell_exec in() php as Jenkins is Java), then do whatever you want with the output, and delete the temp file

... voila

Java Best Practices to Prevent Cross Site Scripting

The normal practice is to HTML-escape any user-controlled data during redisplaying in JSP, not during processing the submitted data in servlet nor during storing in DB. In JSP you can use the JSTL (to install it, just drop jstl-1.2.jar in /WEB-INF/lib) <c:out> tag or fn:escapeXml function for this. E.g.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<p>Welcome <c:out value="${user.name}" /></p>

and

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="username" value="${fn:escapeXml(param.username)}">

That's it. No need for a blacklist. Note that user-controlled data covers everything which comes in by a HTTP request: the request parameters, body and headers(!!).

If you HTML-escape it during processing the submitted data and/or storing in DB as well, then it's all spread over the business code and/or in the database. That's only maintenance trouble and you will risk double-escapes or more when you do it at different places (e.g. & would become &amp;amp; instead of &amp; so that the enduser would literally see &amp; instead of & in view. The business code and DB are in turn not sensitive for XSS. Only the view is. You should then escape it only right there in view.

See also:

What is a difference between unsigned int and signed int in C?

Here is the very nice link which explains the storage of signed and unsigned INT in C -

http://answers.yahoo.com/question/index?qid=20090516032239AAzcX1O

Taken from this above article -

"process called two's complement is used to transform positive numbers into negative numbers. The side effect of this is that the most significant bit is used to tell the computer if the number is positive or negative. If the most significant bit is a 1, then the number is negative. If it's 0, the number is positive."

Download an SVN repository?

Install svn, navigate to your directory then run the command svn checkout <url-to-repostitory> ..

Please provide us with some details like your operating system and what/where you want to download.

Updating an object with setState in React

You can try with this:

this.setState(prevState => {
   prevState = JSON.parse(JSON.stringify(this.state.jasper));
   prevState.name = 'someOtherName';
   return {jasper: prevState}
})

or for other property:

this.setState(prevState => {
   prevState = JSON.parse(JSON.stringify(this.state.jasper));
   prevState.age = 'someOtherAge';
   return {jasper: prevState}
})

Or you can use handleChage function:

handleChage(event) {
   const {name, value} = event.target;
    this.setState(prevState => {
       prevState = JSON.parse(JSON.stringify(this.state.jasper));
       prevState[name] = value;
       return {jasper: prevState}
    })
}

and HTML code:

<input 
   type={"text"} 
   name={"name"} 
   value={this.state.jasper.name} 
   onChange={this.handleChange}
/>
<br/>
<input 
   type={"text"} 
   name={"age"} 
   value={this.state.jasper.age} 
   onChange={this.handleChange}
/>

How to align a div to the top of its parent but keeping its inline-block behaviour?

Or you could just add some content to the div and use inline-table

SQL How to replace values of select return?

If you want the column as string values, then:

SELECT id, name, CASE WHEN hide = 0 THEN 'false' ELSE 'true' END AS hide
  FROM anonymous_table

If the DBMS supports BOOLEAN, you can use instead:

SELECT id, name, CASE WHEN hide = 0 THEN false ELSE true END AS hide
  FROM anonymous_table

That's the same except that the quotes around the names false and true were removed.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

I just added an @ symbol and it started working. Like this: @$product->save();

Docker: How to use bash with an Alpine based docker image?

To Install bash you can do:

RUN apk add --update bash && rm -rf /var/cache/apk/*

If you do not want to add extra size to your image, you can use ash or sh that ships with alpine.

Reference: https://github.com/smebberson/docker-alpine/issues/43

ASP.NET MVC Global Variables

Technically any static variable or Property on a class, anywhere in your project, will be a Global variable e.g.

public static class MyGlobalVariables
{
    public static string MyGlobalString { get; set; }
}

But as @SLaks says, they can 'potentially' be bad practice and dangerous, if not handled correctly. For instance, in that above example, you would have multiple requests (threads) trying to access the same Property, which could be an issue if it was a complex type or a collection, you would have to implement some form of locking.

how to enable sqlite3 for php?

The accepted answer is not complete without the remainder of instructions (paraphrased below) from the forum thread linked to:

cd /etc/php5/conf.d

cat > sqlite3.ini
# configuration for php SQLite3 module
extension=sqlite3.so
^D

sudo /etc/init.d/apache2 restart

Python can't find module in the same folder

Change your import in test.py to:

from .hello import hello1

What is the most efficient/quickest way to loop through rows in VBA (excel)?

EDIT Summary and reccomendations

Using a for each cell in range construct is not in itself slow. What is slow is repeated access to Excel in the loop (be it reading or writing cell values, format etc, inserting/deleting rows etc).

What is too slow depends entierly on your needs. A Sub that takes minutes to run might be OK if only used rarely, but another that takes 10s might be too slow if run frequently.

So, some general advice:

  1. keep it simple at first. If the result is too slow for your needs, then optimise
  2. focus on optimisation of the content of the loop
  3. don't just assume a loop is needed. There are sometime alternatives
  4. if you need to use cell values (a lot) inside the loop, load them into a variant array outside the loop.
  5. a good way to avoid complexity with inserts is to loop the range from the bottom up
    (for index = max to min step -1)
  6. if you can't do that and your 'insert a row here and there' is not too many, consider reloading the array after each insert
  7. If you need to access cell properties other than value, you are stuck with cell references
  8. To delete a number of rows consider building a range reference to a multi area range in the loop, then delete that range in one go after the loop

eg (not tested!)

Dim rngToDelete as range
for each rw in rng.rows
    if need to delete rw then

        if rngToDelete is nothing then
            set rngToDelete = rw
        else
            set rngToDelete = Union(rngToDelete, rw)
        end if

    endif
next
rngToDelete.EntireRow.Delete

Original post

Conventional wisdom says that looping through cells is bad and looping through a variant array is good. I too have been an advocate of this for some time. Your question got me thinking, so I did some short tests with suprising (to me anyway) results:

test data set: a simple list in cells A1 .. A1000000 (thats 1,000,000 rows)

Test case 1: loop an array

Dim v As Variant
Dim n As Long

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
    'i = i + 1
    'i = r.Cells(n, 1).Value 'i + 1
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Array Count = " & Format(n, "#,###")

Result:

Array Time = 0.249 sec
Array Count = 1,000,001

Test Case 2: loop the range

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000#
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")

Result:

Range Time = 0.296 sec
Range Count = 1,000,000

So,looping an array is faster but only by 19% - much less than I expected.

Test 3: loop an array with a cell reference

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
v = r
For n = LBound(v, 1) To UBound(v, 1)
    i = r.Cells(n, 1).Value
Next
Debug.Print "Array Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Array Count = " & Format(i, "#,###")

Result:

Array Time = 5.897 sec
Array Count = 1,000,000

Test case 4: loop range with a cell reference

T1 = GetTickCount
Set r = Range("$A$1", Cells(Rows.Count, "A").End(xlUp)).Cells
For Each c In r
    i = c.Value
Next c
Debug.Print "Range Time = " & (GetTickCount - T1) / 1000# & " sec"
Debug.Print "Range Count = " & Format(r.Cells.Count, "#,###")

Result:

Range Time = 2.356 sec
Range Count = 1,000,000

So event with a single simple cell reference, the loop is an order of magnitude slower, and whats more, the range loop is twice as fast!

So, conclusion is what matters most is what you do inside the loop, and if speed really matters, test all the options

FWIW, tested on Excel 2010 32 bit, Win7 64 bit All tests with

  • ScreenUpdating off,
  • Calulation manual,
  • Events disabled.

Creating and throwing new exception

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}

How does MySQL process ORDER BY and LIMIT in a query?

You can use this code SELECT article FROM table1 ORDER BY publish_date LIMIT 0,10 where 0 is a start limit of record & 10 number of record

Add to Array jQuery

push is a native javascript method. You could use it like this:

var array = [1, 2, 3];
array.push(4); // array now is [1, 2, 3, 4]
array.push(5, 6, 7); // array now is [1, 2, 3, 4, 5, 6, 7]

SQL select statements with multiple tables

Like that:

SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299'

How to execute an oracle stored procedure?

Both 'is' and 'as' are valid syntax. Output is disabled by default. Try a procedure that also enables output...

create or replace procedure temp_proc is
begin
  DBMS_OUTPUT.ENABLE(1000000);
  DBMS_OUTPUT.PUT_LINE('Test');
end;

...and call it in a PLSQL block...

begin
  temp_proc;
end;

...as SQL is non-procedural.

How do I get list of methods in a Python class?

I just keep this there, because top rated answers are not clear.

This is simple test with not usual class based on Enum.

# -*- coding: utf-8 -*-
import sys, inspect
from enum import Enum

class my_enum(Enum):
    """Enum base class my_enum"""
    M_ONE = -1
    ZERO = 0
    ONE = 1
    TWO = 2
    THREE = 3

    def is_natural(self):
            return (self.value > 0)
    def is_negative(self):
            return (self.value < 0)

def is_clean_name(name):
    return not name.startswith('_') and not name.endswith('_')
def clean_names(lst):
    return [ n for n in lst if is_clean_name(n) ]
def get_items(cls,lst):
    try:
            res = [ getattr(cls,n) for n in lst ]
    except Exception as e:
            res = (Exception, type(e), e)
            pass
    return res


print( sys.version )

dir_res = clean_names( dir(my_enum) )
inspect_res = clean_names( [ x[0] for x in inspect.getmembers(my_enum) ] )
dict_res = clean_names( my_enum.__dict__.keys() )

print( '## names ##' )
print( dir_res )
print( inspect_res )
print( dict_res )

print( '## items ##' )
print( get_items(my_enum,dir_res) )
print( get_items(my_enum,inspect_res) )
print( get_items(my_enum,dict_res) )

And this is output results.

3.7.7 (default, Mar 10 2020, 13:18:53) 
[GCC 9.2.1 20200306]
## names ##
['M_ONE', 'ONE', 'THREE', 'TWO', 'ZERO']
['M_ONE', 'ONE', 'THREE', 'TWO', 'ZERO', 'name', 'value']
['is_natural', 'is_negative', 'M_ONE', 'ZERO', 'ONE', 'TWO', 'THREE']
## items ##
[<my_enum.M_ONE: -1>, <my_enum.ONE: 1>, <my_enum.THREE: 3>, <my_enum.TWO: 2>, <my_enum.ZERO: 0>]
(<class 'Exception'>, <class 'AttributeError'>, AttributeError('name'))
[<function my_enum.is_natural at 0xb78a1fa4>, <function my_enum.is_negative at 0xb78ae854>, <my_enum.M_ONE: -1>, <my_enum.ZERO: 0>, <my_enum.ONE: 1>, <my_enum.TWO: 2>, <my_enum.THREE: 3>]

So what we have:

  • dir provide not complete data
  • inspect.getmembers provide not complete data and provide internal keys that are not accessible with getattr()
  • __dict__.keys() provide complete and reliable result

Why are votes so erroneous? And where i'm wrong? And where wrong other people which answers have so low votes?