Programs & Examples On #Letters

How to detect lowercase letters in Python?

There are 2 different ways you can look for lowercase characters:

  1. Use str.islower() to find lowercase characters. Combined with a list comprehension, you can gather all lowercase letters:

    lowercase = [c for c in s if c.islower()]
    
  2. You could use a regular expression:

    import re
    
    lc = re.compile('[a-z]+')
    lowercase = lc.findall(s)
    

The first method returns a list of individual characters, the second returns a list of character groups:

>>> import re
>>> lc = re.compile('[a-z]+')
>>> lc.findall('AbcDeif')
['bc', 'eif']

how to refresh Select2 dropdown menu after ajax loading different content?

Got the same problem in 11 11 19, so sorry for possible necroposting. The only what helped was next solution:

var drop = $('#product_1');   // get our element, **must be unique**;
var settings = drop.attr('data-krajee-select2');  pick krajee attrs of our elem;
var drop_id = drop.attr('id');  // take id 
settings = window[settings];  // take previous settings from window;
drop.select2(settings);  // initialize select2 element with it;
$('.kv-plugin-loading').remove(); // remove loading animation;

It's, maybe, not so good, nice and precise solution, and maybe I still did not clearly understood, how it works and why, but this was the only, what keeps my select2 dropdowns, gotten by ajax, alive. Hope, this solution will be usefull or may push you in right decision in problem fixing

Using Enum values as String literals

This method should work with any enum:

public enum MyEnum {
    VALUE1,
    VALUE2,
    VALUE3;

    public int getValue() {
        return this.ordinal();
    }

    public static DataType forValue(int value) {
        return values()[value];
    }

    public String toString() {
        return forValue(getValue()).name();
    }
}

When to catch java.lang.Error?

Generally, never.

However, sometimes you need to catch specific errors.

If you're writing framework-ish code (loading 3rd party classes), it might be wise to catch LinkageError (no class def found, unsatisfied link, incompatible class change).

I've also seen some stupid 3rd-party code throwing subclasses of Error, so you'll have to handle those as well.

By the way, I'm not sure it isn't possible to recover from OutOfMemoryError.

How do I add a linker or compile flag in a CMake file?

Suppose you want to add those flags (better to declare them in a constant):

SET(GCC_COVERAGE_COMPILE_FLAGS "-fprofile-arcs -ftest-coverage")
SET(GCC_COVERAGE_LINK_FLAGS    "-lgcov")

There are several ways to add them:

  1. The easiest one (not clean, but easy and convenient, and works only for compile flags, C & C++ at once):

    add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})
    
  2. Appending to corresponding CMake variables:

    SET(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
    SET(CMAKE_EXE_LINKER_FLAGS  "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")
    
  3. Using target properties, cf. doc CMake compile flag target property and need to know the target name.

    get_target_property(TEMP ${THE_TARGET} COMPILE_FLAGS)
    if(TEMP STREQUAL "TEMP-NOTFOUND")
      SET(TEMP "") # Set to empty string
    else()
      SET(TEMP "${TEMP} ") # A space to cleanly separate from existing content
    endif()
    # Append our values
    SET(TEMP "${TEMP}${GCC_COVERAGE_COMPILE_FLAGS}" )
    set_target_properties(${THE_TARGET} PROPERTIES COMPILE_FLAGS ${TEMP} )
    

Right now I use method 2.

How can I echo a newline in a batch file?

When echoing something to redirect to a file, multiple echo commands will not work. I think maybe the ">>" redirector is a good choice:

echo hello > temp
echo world >> temp

mat-form-field must contain a MatFormFieldControl

I'm not sure if it could be this simple but I had the same issue, changing "mat-input" to "matInput" in the input field resolved the problem. In your case I see "matinput" and it's causing my app to throw the same error.

<input _ngcontent-c4="" class="mat-input-element mat-form-field-autofill-control" matinput="" ng-reflect-placeholder="Personnummer/samordningsnummer" ng-reflect-value="" id="mat-input-2" placeholder="Personnummer/samordningsnummer" aria-invalid="false">

"matinput"

enter image description here

"matInput"

enter image description here

Creating Accordion Table with Bootstrap

This seems to be already asked before:

This might help:

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

UPDATE:

Your fiddle wasn't loading jQuery, so anything worked.

<table class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>
</thead>

<tbody>
    <tr data-toggle="collapse" data-target="#accordion" class="clickable">
        <td>Some Stuff</td>
        <td>Some more stuff</td>
        <td>And some more</td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="accordion" class="collapse">Hidden by default</div>
        </td>
    </tr>
</tbody>
</table>

Try this one: http://jsfiddle.net/Nb7wy/2/

I also added colspan='2' to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)

Get name of current class?

obj.__class__.__name__ will get you any objects name, so you can do this:

class Clazz():
    def getName(self):
        return self.__class__.__name__

Usage:

>>> c = Clazz()
>>> c.getName()
'Clazz'

How to scp in Python?

As of today, the best solution is probably AsyncSSH

https://asyncssh.readthedocs.io/en/latest/#scp-client

async with asyncssh.connect('host.tld') as conn:
    await asyncssh.scp((conn, 'example.txt'), '.', recurse=True)

Convert Go map to json

Since this question was asked/last answered, support for non string key types for maps for json Marshal/UnMarshal has been added through the use of TextMarshaler and TextUnmarshaler interfaces here. You could just implement these interfaces for your key types and then json.Marshal would work as expected.

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

// Num wraps the int value so that we can implement the TextMarshaler and TextUnmarshaler 
type Num int

func (n *Num) UnmarshalText(text []byte) error {
    i, err := strconv.Atoi(string(text))
    if err != nil {
        return err
    }
    *n = Num(i)
    return nil
}

func (n Num) MarshalText() (text []byte, err error) {
    return []byte(strconv.Itoa(int(n))), nil
}

type Foo struct {
    Number Num    `json:"number"`
    Title  string `json:"title"`
}

func main() {
    datas := make(map[Num]Foo)

    for i := 0; i < 10; i++ {
        datas[Num(i)] = Foo{Number: 1, Title: "test"}
    }

    jsonString, err := json.Marshal(datas)
    if err != nil {
        panic(err)
    }

    fmt.Println(datas)
    fmt.Println(jsonString)

    m := make(map[Num]Foo)
    err = json.Unmarshal(jsonString, &m)
    if err != nil {
        panic(err)
    }

    fmt.Println(m)
}

Output:

map[1:{1 test} 2:{1 test} 4:{1 test} 7:{1 test} 8:{1 test} 9:{1 test} 0:{1 test} 3:{1 test} 5:{1 test} 6:{1 test}]
[123 34 48 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 49 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 50 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 51 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 52 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 53 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 54 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 55 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 56 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 57 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 125]
map[4:{1 test} 5:{1 test} 6:{1 test} 7:{1 test} 0:{1 test} 2:{1 test} 3:{1 test} 1:{1 test} 8:{1 test} 9:{1 test}]

Calculate average in java

Instead of:

int count = 0;
for (int i = 0; i<args.length -1; ++i)
    count++;
System.out.println(count);

 }

you can just

int count = args.length;

The average is the sum of your args divided by the number of your args.

int res = 0;
int count = args.lenght;

for (int a : args)
{
res += a;
}
res /= count;

you can make this code shorter too, i'll let you try and ask if you need help!

This is my first answerso tell me if something wrong!

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

in webpack 4 with multiple module rules you would just do something like this in your .js rule:

{
     test: /\.(js)$/,
     loader: 'babel-loader',
     options: {
          presets: ['es2015'],    // or whatever
          plugins: [require('babel-plugin-transform-class-properties')], // or whatever
          compact: true    // or false during development
     }
},

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try this:

MessageBox.Show("Some text", "Some title", 
    MessageBoxButtons.OK, MessageBoxIcon.Error);

ValueError: math domain error

you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.

Replace whole line containing a string using Sed

All of the answers provided so far assume that you know something about the text to be replaced which makes sense, since that's what the OP asked. I'm providing an answer that assumes you know nothing about the text to be replaced and that there may be a separate line in the file with the same or similar content that you do not want to be replaced. Furthermore, I'm assuming you know the line number of the line to be replaced.

The following examples demonstrate the removing or changing of text by specific line numbers:

# replace line 17 with some replacement text and make changes in file (-i switch)
# the "-i" switch indicates that we want to change the file. Leave it out if you'd
#   just like to see the potential changes output to the terminal window.
# "17s" indicates that we're searching line 17
# ".*" indicates that we want to change the text of the entire line
# "REPLACEMENT-TEXT" is the new text to put on that line
# "PATH-TO-FILE" tells us what file to operate on
sed -i '17s/.*/REPLACEMENT-TEXT/' PATH-TO-FILE

# replace specific text on line 3
sed -i '3s/TEXT-TO-REPLACE/REPLACEMENT-TEXT/'

JQuery, Spring MVC @RequestBody and JSON - making it work together

In Addition you also need to be sure that you have

 <context:annotation-config/> 

in your SPring configuration xml.

I also would recommend you to read this blog post. It helped me alot. Spring blog - Ajax Simplifications in Spring 3.0

Update:

just checked my working code where I have @RequestBody working correctly. I also have this bean in my config:

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
  <list>
    <ref bean="jacksonMessageConverter"/>
  </list>
</property>
</bean>

May be it would be nice to see what Log4j is saying. it usually gives more information and from my experience the @RequestBody will fail if your request's content type is not Application/JSON. You can run Fiddler 2 to test it, or even Mozilla Live HTTP headers plugin can help.

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

I have a slightly different perspective on the difference between a DATETIME and a TIMESTAMP. A DATETIME stores a literal value of a date and time with no reference to any particular timezone. So, I can set a DATETIME column to a value such as '2019-01-16 12:15:00' to indicate precisely when my last birthday occurred. Was this Eastern Standard Time? Pacific Standard Time? Who knows? Where the current session time zone of the server comes into play occurs when you set a DATETIME column to some value such as NOW(). The value stored will be the current date and time using the current session time zone in effect. But once a DATETIME column has been set, it will display the same regardless of what the current session time zone is.

A TIMESTAMP column on the other hand takes the '2019-01-16 12:15:00' value you are setting into it and interprets it in the current session time zone to compute an internal representation relative to 1/1/1970 00:00:00 UTC. When the column is displayed, it will be converted back for display based on whatever the current session time zone is. It's a useful fiction to think of a TIMESTAMP as taking the value you are setting and converting it from the current session time zone to UTC for storing and then converting it back to the current session time zone for displaying.

If my server is in San Francisco but I am running an event in New York that starts on 9/1/1029 at 20:00, I would use a TIMESTAMP column for holding the start time, set the session time zone to 'America/New York' and set the start time to '2009-09-01 20:00:00'. If I want to know whether the event has occurred or not, regardless of the current session time zone setting I can compare the start time with NOW(). Of course, for displaying in a meaningful way to a perspective customer, I would need to set the correct session time zone. If I did not need to do time comparisons, then I would probably be better off just using a DATETIME column, which will display correctly (with an implied EST time zone) regardless of what the current session time zone is.

TIMESTAMP LIMITATION

The TIMESTAMP type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC and so it may not usable for your particular application. In that case you will have to use a DATETIME type. You will, of course, always have to be concerned that the current session time zone is set properly whenever you are using this type with date functions such as NOW().

Get element inside element by class and ID - JavaScript

Well, first you need to select the elements with a function like getElementById.

var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];

getElementById only returns one node, but getElementsByClassName returns a node list. Since there is only one element with that class name (as far as I can tell), you can just get the first one (that's what the [0] is for—it's just like an array).

Then, you can change the html with .textContent.

targetDiv.textContent = "Goodbye world!";

_x000D_
_x000D_
var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];_x000D_
targetDiv.textContent = "Goodbye world!";
_x000D_
<div id="foo">_x000D_
    <div class="bar">_x000D_
        Hello world!_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using async/await for multiple tasks

You can use Task.WhenAll function that you can pass n tasks; Task.WhenAll will return a task which runs to completion when all the tasks that you passed to Task.WhenAll complete. You have to wait asynchronously on Task.WhenAll so that you'll not block your UI thread:

   public async Task DoSomeThing() {

       var Task[] tasks = new Task[numTasks];
       for(int i = 0; i < numTask; i++)
       {
          tasks[i] = CallSomeAsync();
       }
       await Task.WhenAll(tasks);
       // code that'll execute on UI thread
   }

Send raw ZPL to Zebra printer via USB

I spent 8 hours to do that. It is simple...

You shoud have a code like that:

private const int GENERIC_WRITE = 0x40000000;

//private const int OPEN_EXISTING = 3;
private const int OPEN_EXISTING = 1;
private const int FILE_SHARE_WRITE = 0x2;
private StreamWriter _fileWriter;
private FileStream _outFile;
private int _hPort;

Change that variable content from 3 (open file already exist) to 1 (create a new file). It'll work at Windows 7 and XP.

Error when deploying an artifact in Nexus

In the rare event that you need to redeploy the SAME STABLE artifact to Nexus, it will fail by default. If you then delete the artifact from Nexus (via the web interface) for the purpose of deploying it again, the deploy will still fail, since just removing the e.g. jar or pom does not clear other files still laying around in the directory. You need to log onto the box and delete the directory in its entirety.

How can I add spaces between two <input> lines using CSS?

You don't need to wrap everything in a DIV to achieve basic styling on inputs.

input[type="text"] {margin: 0 0 10px 0;}

will do the trick in most cases.

Semantically, one <br/> tag is okay between elements to position them. When you find yourself using multiple <br/>'s (which are semantic elements) to achieve cosmetic effects, that's a flag that you're mixing responsibilities, and you should consider getting back to basics.

How to combine GROUP BY, ORDER BY and HAVING

Steps for Using Group by,Having By and Order by...

Select Attitude ,count(*) from Person
group by person
HAving PersonAttitude='cool and friendly'
Order by PersonName.

How can I trim leading and trailing white space?

A simple function to remove leading and trailing whitespace:

trim <- function( x ) {
  gsub("(^[[:space:]]+|[[:space:]]+$)", "", x)
}

Usage:

> text = "   foo bar  baz 3 "
> trim(text)
[1] "foo bar  baz 3"

java.util.NoSuchElementException - Scanner reading user input

This has really puzzled me for a while but this is what I found in the end.

When you call, sc.close() in first method, it not only closes your scanner but closes your System.in input stream as well. You can verify it by printing its status at very top of the second method as :

    System.out.println(System.in.available());

So, now when you re-instantiate, Scanner in second method, it doesn't find any open System.in stream and hence the exception.

I doubt if there is any way out to reopen System.in because:

public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**

The only good solution for your problem is to initiate the Scanner in your main method, pass that as argument in your two methods, and close it again in your main method e.g.:

main method related code block:

Scanner scanner = new Scanner(System.in);  

// Ask users for quantities 
PromptCustomerQty(customer, ProductList, scanner );

// Ask user for payment method
PromptCustomerPayment(customer, scanner );

//close the scanner 
scanner.close();

Your Methods:

 public static void PromptCustomerQty(Customer customer, 
                             ArrayList<Product> ProductList, Scanner scanner) {

    // no more scanner instantiation
    ...
    // no more scanner close
 }


 public static void PromptCustomerPayment (Customer customer, Scanner sc) {

    // no more scanner instantiation
    ...
    // no more scanner close
 }

Hope this gives you some insight about the failure and possible resolution.

How to tell which disk Windows Used to Boot

You type diskpart, list disk and check disks for boot.
Ex:

dispart 
list disk 
select disk 0 
detail disk

The disk with Boot volume is disk with windows installed:

enter image description here

Show loading image while $.ajax is performed

HTML Code :

<div class="ajax-loader">
  <img src="{{ url('guest/images/ajax-loader.gif') }}" class="img-responsive" />
</div>

CSS Code:

.ajax-loader {
  visibility: hidden;
  background-color: rgba(255,255,255,0.7);
  position: absolute;
  z-index: +100 !important;
  width: 100%;
  height:100%;
}

.ajax-loader img {
  position: relative;
  top:50%;
  left:50%;
}

JQUERY Code:

$.ajax({
  type:'POST',
  beforeSend: function(){
    $('.ajax-loader').css("visibility", "visible");
  },
  url:'/quantityPlus',
  data: {
   'productId':p1,
   'quantity':p2,
   'productPrice':p3},
   success:function(data){
     $('#'+p1+'value').text(data.newProductQuantity);
     $('#'+p1+'amount').text("? "+data.productAmount);
     $('#totalUnits').text(data.newNoOfUnits);
     $('#totalAmount').text("? "+data.newTotalAmount);
  },
  complete: function(){
    $('.ajax-loader').css("visibility", "hidden");
  }
});

}

No module named Image

Did you setup PIL module? Link

You can try to reinstall it on your computer.

Angular and Typescript: Can't find names - Error: cannot find name

This could be because you are missing an import.

Example:

ERROR in src/app/products/product-list.component.ts:15:15 - error TS2304: Cannot find name 'IProduct'.

Make sure you are adding the import at the top of the file:

import { IProduct } from './product';

...

export class ProductListComponent {
    pageTitle: string = 'product list!';
    imageWidth: number = 50;
    imageMargin: number = 2;
    showImage: boolean = false;
    listFilter: string = 'cart';
    products: IProduct[] = ... //cannot find name error

Best practices for API versioning?

There are a few places you can do versioning in a REST API:

  1. As noted, in the URI. This can be tractable and even esthetically pleasing if redirects and the like are used well.

  2. In the Accepts: header, so the version is in the filetype. Like 'mp3' vs 'mp4'. This will also work, though IMO it works a bit less nicely than...

  3. In the resource itself. Many file formats have their version numbers embedded in them, typically in the header; this allows newer software to 'just work' by understanding all existing versions of the filetype while older software can punt if an unsupported (newer) version is specified. In the context of a REST API, it means that your URIs never have to change, just your response to the particular version of data you were handed.

I can see reasons to use all three approaches:

  1. if you like doing 'clean sweep' new APIs, or for major version changes where you want such an approach.
  2. if you want the client to know before it does a PUT/POST whether it's going to work or not.
  3. if it's okay if the client has to do its PUT/POST to find out if it's going to work.

How to change the default encoding to UTF-8 for Apache?

Add this to your .htaccess:

IndexOptions +Charset=UTF-8

Or, if you have administrator rights, you could set it globally by editing httpd.conf and adding:

AddDefaultCharset UTF-8

(You can use AddDefaultCharset in .htaccess too, but it won’t affect Apache-generated directory listings that way.)

Can't find bundle for base name

BalusC is right. Version 1.0.13 is current, but 1.0.9 appears to have the required bundles:

$ jar tf lib/jfreechart-1.0.9.jar | grep LocalizationBundle.properties 
org/jfree/chart/LocalizationBundle.properties
org/jfree/chart/editor/LocalizationBundle.properties
org/jfree/chart/plot/LocalizationBundle.properties

How to convert POJO to JSON and vice versa?

Take below reference to convert a JSON into POJO and vice-versa

Let's suppose your JSON schema looks like:

{
  "type":"object",
  "properties": {
    "dataOne": {
      "type": "string"
    },
    "dataTwo": {
      "type": "integer"
    },
    "dataThree": {
      "type": "boolean"
    }
  }
}

Then to covert into POJO, your need to decleare some classes as explained in below style:

==================================
package ;
public class DataOne
{
    private String type;

    public void setType(String type){
        this.type = type;
    }
    public String getType(){
        return this.type;
    }
}

==================================
package ;
public class DataTwo
{
    private String type;

    public void setType(String type){
        this.type = type;
    }
    public String getType(){
        return this.type;
    }
}

==================================
package ;
public class DataThree
{
    private String type;

    public void setType(String type){
        this.type = type;
    }
    public String getType(){
        return this.type;
    }
}

==================================
package ;
public class Properties
{
    private DataOne dataOne;

    private DataTwo dataTwo;

    private DataThree dataThree;

    public void setDataOne(DataOne dataOne){
        this.dataOne = dataOne;
    }
    public DataOne getDataOne(){
        return this.dataOne;
    }
    public void setDataTwo(DataTwo dataTwo){
        this.dataTwo = dataTwo;
    }
    public DataTwo getDataTwo(){
        return this.dataTwo;
    }
    public void setDataThree(DataThree dataThree){
        this.dataThree = dataThree;
    }
    public DataThree getDataThree(){
        return this.dataThree;
    }
}

==================================
package ;
public class Root
{
    private String type;

    private Properties properties;

    public void setType(String type){
        this.type = type;
    }
    public String getType(){
        return this.type;
    }
    public void setProperties(Properties properties){
        this.properties = properties;
    }
    public Properties getProperties(){
        return this.properties;
    }
}

How do you add an SDK to Android Studio?

Download your sdk file, go to Android studio: File->New->Import Module

How to program a delay in Swift 3

Try the following function implemented in Swift 3.0 and above

func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { 
        completion()
    }
}

Usage

delayWithSeconds(1) {
   //Do something
}

How can I create database tables from XSD files?

XML Schemas describe hierarchial data models and may not map well to a relational data model. Mapping XSD's to database tables is very similar mapping objects to database tables, in fact you could use a framework like Castor that does both, it allows you to take a XML schema and generate classes, database tables, and data access code. I suppose there are now many tools that do the same thing, but there will be a learning curve and the default mappings will most like not be what you want, so you have to spend time customizing whatever tool you use.

XSLT might be the fastest way to generate exactly the code that you want. If it is a small schema hardcoding it might be faster than evaluating and learing a bunch of new technologies.

Android Spinner : Avoid onItemSelected calls during initialization

The user interaction flag can then be set to true in the onTouch method and reset in onItemSelected() once the selection change has been handled. I prefer this solution because the user interaction flag is handled exclusively for the spinner, and not for other views in the activity that may affect the desired behavior.

In code:

Create your listener for the spinner:

public class SpinnerInteractionListener implements AdapterView.OnItemSelectedListener, View.OnTouchListener {

    boolean userSelect = false;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        userSelect = true;
        return false;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        if (userSelect) { 
            userSelect = false;
            // Your selection handling code here
        }
    }

}

Add the listener to the spinner as both an OnItemSelectedListener and an OnTouchListener:

SpinnerInteractionListener listener = new SpinnerInteractionListener();
mSpinnerView.setOnTouchListener(listener);
mSpinnerView.setOnItemSelectedListener(listener);

ansible : how to pass multiple commands

If a value in YAML begins with a curly brace ({), the YAML parser assumes that it is a dictionary. So, for cases like this where there is a (Jinja2) variable in the value, one of the following two strategies needs to be adopted to avoiding confusing the YAML parser:

Quote the whole command:

- command: "{{ item }} chdir=/src/package/"
  with_items:
  - ./configure
  - /usr/bin/make
  - /usr/bin/make install    

or change the order of the arguments:

- command: chdir=/src/package/ {{ item }}
  with_items:
  - ./configure
  - /usr/bin/make
  - /usr/bin/make install

Thanks for @RamondelaFuente alternative suggestion.

How do I use a third-party DLL file in Visual Studio C++?

You only need to use LoadLibrary if you want to late bind and only resolve the imported functions at runtime. The easiest way to use a third party dll is to link against a .lib.


In reply to your edit:

Yes, the third party API should consist of a dll and/or a lib that contain the implementation and header files that declares the required types. You need to know the type definitions whichever method you use - for LoadLibrary you'll need to define function pointers, so you could just as easily write your own header file instead. Basically, you only need to use LoadLibrary if you want late binding. One valid reason for this would be if you aren't sure if the dll will be available on the target PC.

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

I had a similar problem. Using size_t was not working. I tried the other one which worked for me. (as below)

for(int i = things.size()-1;i>=0;i--)
{
 //...
}

Disable scrolling when touch moving certain element

try overflow hidden on the thing you don't want to scroll while touch event is happening. e.g set overflow hidden on Start and set it back to auto on end.

Did you try it ? I'd be interested to know if this would work.

document.addEventListener('ontouchstart', function(e) {
    document.body.style.overflow = "hidden";
}, false);

document.addEventListener('ontouchmove', function(e) {
    document.body.style.overflow = "auto";
}, false);

How do I count a JavaScript object's attributes?

You can do that by using this simple code:

Object.keys(myObject).length

Convert all first letter to upper case, rest lower for each word

I probably prefer to invoke the ToTitleCase from CultureInfo (System.Globalization) than Thread.CurrentThread (System.Threading)

string s = "THIS IS MY TEXT RIGHT NOW";
s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

but it should be the same as jspcal solution

EDIT

Actually those solutions are not the same: CurrentThread --calls--> CultureInfo!


System.Threading.Thread.CurrentThread.CurrentCulture

string s = "THIS IS MY TEXT RIGHT NOW";
s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

IL_0000:  ldstr       "THIS IS MY TEXT RIGHT NOW"
IL_0005:  stloc.0     // s
IL_0006:  call        System.Threading.Thread.get_CurrentThread
IL_000B:  callvirt    System.Threading.Thread.get_CurrentCulture
IL_0010:  callvirt    System.Globalization.CultureInfo.get_TextInfo
IL_0015:  ldloc.0     // s
IL_0016:  callvirt    System.String.ToLower
IL_001B:  callvirt    System.Globalization.TextInfo.ToTitleCase
IL_0020:  stloc.0     // s

System.Globalization.CultureInfo.CurrentCulture

string s = "THIS IS MY TEXT RIGHT NOW";
s = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());

IL_0000:  ldstr       "THIS IS MY TEXT RIGHT NOW"
IL_0005:  stloc.0     // s
IL_0006:  call        System.Globalization.CultureInfo.get_CurrentCulture
IL_000B:  callvirt    System.Globalization.CultureInfo.get_TextInfo
IL_0010:  ldloc.0     // s
IL_0011:  callvirt    System.String.ToLower
IL_0016:  callvirt    System.Globalization.TextInfo.ToTitleCase
IL_001B:  stloc.0     // s

References:

How to create a Multidimensional ArrayList in Java?

Here an answer for those who'd like to have preinitialized lists of lists. Needs Java 8+.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

class Scratch {

  public static void main(String[] args) {
    int M = 4;
    int N = 3;

    // preinitialized array (== list of lists) of strings, sizes not fixed
    List<List<String>> listOfListsOfString = initializeListOfListsOfT(M, N, "-");
    System.out.println(listOfListsOfString);

    // preinitialized array (== list of lists) of int (primitive type), sizes not fixed
    List<List<Integer>> listOfListsOfInt = initializeListOfListsOfInt(M, N, 7);
    System.out.println(listOfListsOfInt);
  }

  public static <T> List<List<T>> initializeListOfListsOfT(int m, int n, T initValue) {
    return IntStream
        .range(0, m)
        .boxed()
        .map(i -> new ArrayList<T>(IntStream
            .range(0, n)
            .boxed()
            .map(j -> initValue)
            .collect(Collectors.toList()))
        )
        .collect(Collectors.toList());
  }

  public static List<List<Integer>> initializeListOfListsOfInt(int m, int n, int initValue) {
    return IntStream
        .range(0, m)
        .boxed()
        .map(i -> new ArrayList<>(IntStream
            .range(0, n)
            .map(j -> initValue)
            .boxed()
            .collect(Collectors.toList()))
        )
        .collect(Collectors.toList());
  }
}

Output:

[[-, -, -], [-, -, -], [-, -, -], [-, -, -]]
[[7, 7, 7], [7, 7, 7], [7, 7, 7], [7, 7, 7]]

Side note for those wondering about IntStream:

IntStream
    .range(0, m)
    .boxed()

is equivalent to

Stream
    .iterate(0, j -> j + 1)
    .limit(n)

Laravel where on relationship object

@Cermbo's answer is not related to this question. In their answer, Laravel will give you all Events if each Event has 'participants' with IdUser of 1.

But if you want to get all Events with all 'participants' provided that all 'participants' have a IdUser of 1, then you should do something like this :

Event::with(["participants" => function($q){
    $q->where('participants.IdUser', '=', 1);
}])

N.B:

in where use your table name, not Model name.

How to call an async method from a getter or setter?

You can change the proerty to Task<IEnumerable>

and do something like:

get
{
    Task<IEnumerable>.Run(async()=>{
       return await getMyList();
    });
}

and use it like await MyList;

how to store Image as blob in Sqlite & how to retrieve it?

in the DBAdaper i.e Data Base helper class declare the table like this

 private static final String USERDETAILS=
    "create table userdetails(usersno integer primary key autoincrement,userid text not null ,username text not null,password text not null,photo BLOB,visibility text not null);";

insert the values like this,

first convert the images as byte[]

ByteArrayOutputStream baos = new ByteArrayOutputStream();  
Bitmap bitmap = ((BitmapDrawable)getResources().getDrawable(R.drawable.common)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);   
byte[] photo = baos.toByteArray(); 
db.insertUserDetails(value1,value2, value3, photo,value2);

in DEAdaper class

 public long insertUserDetails(String uname,String userid, String pass, byte[] photo,String visibility) 
{
    ContentValues initialValues = new ContentValues();
    initialValues.put("username", uname);
    initialValues.put("userid",userid);
    initialValues.put("password", pass);
    initialValues.put("photo",photo);
    initialValues.put("visibility",visibility);
    return db.insert("userdetails", null, initialValues);
}

retrieve the image as follows

Cursor cur=your query;
while(cur.moveToNext())
{
     byte[] photo=cur.getBlob(index of blob cloumn);
}

convert the byte[] into image

ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);

I think this content may solve your problem

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

How can I know when an EditText loses focus?

Have your Activity implement OnFocusChangeListener() if you want a factorized use of this interface, example:

public class Shops extends AppCompatActivity implements View.OnFocusChangeListener{

In your OnCreate you can add a listener for example:

editTextResearch.setOnFocusChangeListener(this);
editTextMyWords.setOnFocusChangeListener(this);
editTextPhone.setOnFocusChangeListener(this);

then android studio will prompt you to add the method from the interface, accept it... it will be like:

@Override
public void onFocusChange(View v, boolean hasFocus) {
// todo your code here...
}

and as you've got a factorized code, you'll just have to do that:

@Override
public void onFocusChange(View v, boolean hasFocus) {
   if (hasFocus) {
        editTextResearch.setText("");
        editTextMyWords.setText("");
        editTextPhone.setText("");
    }
    if (!hasFocus){
        editTextResearch.setText("BlaBlaBla");
        editTextMyWords.setText(" One Two Tree!");
        editTextPhone.setText("\"your phone here:\"");
    }
}

anything you code in the !hasFocus is for the behavior of the item that loses focus, that should do the trick! But beware that in such state, the change of focus might overwrite the user's entries!

How to Customize the time format for Python logging?

To add to the other answers, here are the variable list from Python Documentation.

Directive   Meaning Notes

%a  Locale’s abbreviated weekday name.   
%A  Locale’s full weekday name.  
%b  Locale’s abbreviated month name.     
%B  Locale’s full month name.    
%c  Locale’s appropriate date and time representation.   
%d  Day of the month as a decimal number [01,31].    
%H  Hour (24-hour clock) as a decimal number [00,23].    
%I  Hour (12-hour clock) as a decimal number [01,12].    
%j  Day of the year as a decimal number [001,366].   
%m  Month as a decimal number [01,12].   
%M  Minute as a decimal number [00,59].  
%p  Locale’s equivalent of either AM or PM. (1)
%S  Second as a decimal number [00,61]. (2)
%U  Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.    (3)
%w  Weekday as a decimal number [0(Sunday),6].   
%W  Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.    (3)
%x  Locale’s appropriate date representation.    
%X  Locale’s appropriate time representation.    
%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.   
%z  Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
%Z  Time zone name (no characters if no time zone exists).   
%%  A literal '%' character.     

Java - How to create new Entry (key, value)

You could actually go with: Map.Entry<String, String> en= Maps.immutableEntry(key, value);

Get the Selected value from the Drop down box in PHP

Couldn't you just pass the a name attribute and wrap it in a form?

<form id="form" action="do_stuff.php" method="post">
    <select id="select_catalog" name="select_catalog_query">
    <?php <<<INSERT THE SELECT OPTION LOOP>>> ?>
    </select>
</form>

And then look for $_POST['select_catalog_query'] ?

Django: save() vs update() to update the database?

Update will give you better performance with a queryset of more than one object, as it will make one database call per queryset.

However save is useful, as it is easy to override the save method in your model and add extra logic there. In my own application for example, I update a dates when other fields are changed.

Class myModel(models.Model): 
    name = models.CharField()
    date_created = models.DateField()

    def save(self):
        if not self.pk :
           ### we have a newly created object, as the db id is not set
           self.date_created = datetime.datetime.now()
        super(myModel , self).save()

What's the difference between emulation and simulation?

Here's an example - we recently developed a simulation model to measure the remote transmission response time of a yet-to-be-developed system. An emulation analysis would not have given us the answer in time to upgrade the bandwidth capacity so simulation was our approach. Because we were mostly interested in determining bandwidth needs, we cared primarily about transaction size and volume, not the processing of the system. The simulation model was on a stand-alone piece of software that was designed to model discrete-event processes. To summarize in response to your question, emulation is a type of simulation. But, in this case, simulation was NOT an emulation because it didn't fully represent the new system, only the size and volume of transactions.

How to use HTML to print header and footer on every printed page of a document?

One approach that only works for adding headers to every page is to wrap your content in a <table> and then put your header content in a <thead> tag and your content in a <tbody> tag, like so:

<table>
  <thead>
    <tr>
      <th>This content appears on every page</th>
    </tr>
   </thead>
   <tbody>
     <tr>
       <td>Put all your content here, it can span multiple pages and your header will show up at the top of each page</td>
     </tr>
   </tbody>
 </table>

This works in Chrome, not 100% sure about other browsers.

How to delete an SMS from the inbox in Android programmatically?

Also update the manifest file as to delete an sms you need write permissions.

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

How do I set a fixed background image for a PHP file?

I found my answer.

<?php
$profpic = "bg.jpg";
?>

<html>
<head>
<style type="text/css">

body {
background-image: url('<?php echo $profpic;?>');
}
</style>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hey</title>
</head>
<body>
</body>
</html>

How can I get terminal output in python?

>>> import subprocess
>>> cmd = [ 'echo', 'arg1', 'arg2' ]
>>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
>>> print output
arg1 arg2

>>> 

There is a bug in using of the subprocess.PIPE. For the huge output use this:

import subprocess
import tempfile

with tempfile.TemporaryFile() as tempf:
    proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf)
    proc.wait()
    tempf.seek(0)
    print tempf.read()

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

How to execute the start script with Nodemon

In package.json file. change file like this

"scripts":{ 
   "start": "node ./bin/www", 
   "start-dev": "nodemon ./app.js"
 },

and then execute npm run start-dev

Why is there no ForEach extension method on IEnumerable?

The discussion here gives the answer:

Actually, the specific discussion I witnessed did in fact hinge over functional purity. In an expression, there are frequently assumptions made about not having side-effects. Having ForEach is specifically inviting side-effects rather than just putting up with them. -- Keith Farmer (Partner)

Basically the decision was made to keep the extension methods functionally "pure". A ForEach would encourage side-effects when using the Enumerable extension methods, which was not the intent.

How to get just numeric part of CSS property with jQuery?

Let us assume you have a margin-bottom property set to 20px / 20% / 20em. To get the value as a number there are two options:

Option 1:

parseInt($('#some_DOM_element_ID').css('margin-bottom'), 10);

The parseInt() function parses a string and returns an integer. Don't change the 10 found in the above function (known as a "radix") unless you know what you are doing.

Example Output will be: 20 (if margin-bottom set in px) for % and em it will output the relative number based on current Parent Element / Font size.

Option 2 (I personally prefer this option)

parseFloat($('#some_DOM_element_ID').css('margin-bottom'));

Example Output will be: 20 (if margin-bottom set in px) for % and em it will output the relative number based on current Parent Element / Font size.

The parseFloat() function parses a string and returns a floating point number.

The parseFloat() function determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.

The advantage of Option 2 is that if you get decimal numbers returned (e.g. 20.32322px) you will get the number returned with the values behind the decimal point. Useful if you need specific numbers returned, for example if your margin-bottom is set in em or %

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

As mentioned by Frank, you can use Firebase Cloud Messaging (FCM) HTTP API to trigger push notification from your own back-end. But you won't be able to

  1. send notifications to a Firebase User Identifier (UID) and
  2. send notifications to user segments (targeting properties & events like you can on the user console).

Meaning: you'll have to store FCM/GCM registration ids (push tokens) yourself or use FCM topics to subscribe users. Keep also in mind that FCM is not an API for Firebase Notifications, it's a lower-level API without scheduling or open-rate analytics. Firebase Notifications is build on top on FCM.

$http.get(...).success is not a function

This might be redundant but the above most voted answer says .then(function (success) and that didn't work for me as of Angular version 1.5.8. Instead use response then inside the block response.data got me my json data I was looking for.

$http({
    method: 'get', 
    url: 'data/data.json'
}).then(function (response) {
    console.log(response, 'res');
    data = response.data;
},function (error){
    console.log(error, 'can not get data.');
});

How to get the last value of an ArrayList

The size() method returns the number of elements in the ArrayList. The index values of the elements are 0 through (size()-1), so you would use myArrayList.get(myArrayList.size()-1) to retrieve the last element.

How to pass a form input value into a JavaScript function

Well ya you can do that in this way.

    <input type="text" name="address" id="address">
        <div id="map_canvas" style="width: 500px; height: 300px"></div>
    <input type="button" onclick="showAddress(address.value)" value="ShowMap"/>

Java Script

function showAddress(address){

    alert("This is address :"+address)

}

That is one example for the same. and that will run.

Immutable vs Mutable types

If you're coming to Python from another language (except one that's a lot like Python, like Ruby), and insist on understanding it in terms of that other language, here's where people usually get confused:

>>> a = 1
>>> a = 2 # I thought int was immutable, but I just changed it?!

In Python, assignment is not mutation in Python.

In C++, if you write a = 2, you're calling a.operator=(2), which will mutate the object stored in a. (And if there was no object stored in a, that's an error.)

In Python, a = 2 does nothing to whatever was stored in a; it just means that 2 is now stored in a instead. (And if there was no object stored in a, that's fine.)


Ultimately, this is part of an even deeper distinction.

A variable in a language like C++ is a typed location in memory. If a is an int, that means it's 4 bytes somewhere that the compiler knows is supposed to be interpreted as an int. So, when you do a = 2, it changes what's stored in those 4 bytes of memory from 0, 0, 0, 1 to 0, 0, 0, 2. If there's another int variable somewhere else, it has its own 4 bytes.

A variable in a language like Python is a name for an object that has a life of its own. There's an object for the number 1, and another object for the number 2. And a isn't 4 bytes of memory that are represented as an int, it's just a name that points at the 1 object. It doesn't make sense for a = 2 to turn the number 1 into the number 2 (that would give any Python programmer way too much power to change the fundamental workings of the universe); what it does instead is just make a forget the 1 object and point at the 2 object instead.


So, if assignment isn't a mutation, what is a mutation?

  • Calling a method that's documented to mutate, like a.append(b). (Note that these methods almost always return None). Immutable types do not have any such methods, mutable types usually do.
  • Assigning to a part of the object, like a.spam = b or a[0] = b. Immutable types do not allow assignment to attributes or elements, mutable types usually allow one or the other.
  • Sometimes using augmented assignment, like a += b, sometimes not. Mutable types usually mutate the value; immutable types never do, and give you a copy instead (they calculate a + b, then assign the result to a).

But if assignment isn't mutation, how is assigning to part of the object mutation? That's where it gets tricky. a[0] = b does not mutate a[0] (again, unlike C++), but it does mutate a (unlike C++, except indirectly).

All of this is why it's probably better not to try to put Python's semantics in terms of a language you're used to, and instead learn Python's semantics on their own terms.

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Changed to:

SELECT FORMAT(SA.[RequestStartDate],'dd/MM/yyyy') as 'Service Start Date', SA.[RequestEndDate] as 'Service End Date', FROM (......)SA WHERE......

Have no idea which SQL engine you are using, for other SQL engine, CONVERT can be used in SELECT statement to change the format in the form you needed.

Ansible: get current target host's IP address

http://docs.ansible.com/ansible/latest/plugins/lookup/dig.html

so in template, for e. g.:

{{ lookup('dig', ansible_host) }}

Notes:

  • Since not only DNS name could be used in inventory a check if it's not IP already better be added
  • Obviously enough this receipt wouldn't work as intended for indirect host specifications (like using jump hosts, for e. g.)

But still it serves 99 % (figuratively speaking) of use cases.

How can I change the width and height of slides on Slick Carousel?

Basically you need to edit the JS and add (in this case, inside $('#featured-articles').slick({ ), this:

variableWidth: true,

This will allow you to edit the width in your CSS where you can, generically use:

.slick-slide {
    width: 100%;
}

or in this case:

.featured {
    width: 100%;
}

Convert list of ints to one number?

If you happen to be using numpy (with import numpy as np):

In [24]: x
Out[24]: array([1, 2, 3, 4, 5])

In [25]: np.dot(x, 10**np.arange(len(x)-1, -1, -1))
Out[25]: 12345

NPM: npm-cli.js not found when running npm

You may also have this problem if in your path you have C:\Program Files\nodejs and C:\Program Files\nodejs\node_modules\npm\bin. Remove the latter from the path

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Note that there's a weird problem if you're using Bootstrap's JS buttons and the 'loading' state. I don't know why this happens, but here's how to fix it.

Say you have a button and you set it to the loading state:

var myButton = $('#myBootstrapButton');
myButton.button('loading');

Now you want to take it out of the loading state, but also disable it (e.g. the button was a Save button, the loading state indicated an ongoing validation and the validation failed). This looks like reasonable Bootstrap JS:

myButton.button('reset').prop('disabled', true); // DOES NOT WORK

Unfortunately, that will reset the button, but not disable it. Apparently, button() performs some delayed task. So you'll also have to postpone your disabling:

myButton.button('reset');
setTimeout(function() { myButton.prop('disabled', true); }, 0);

A bit annoying, but it's a pattern I'm using a lot.

How to compile Tensorflow with SSE4.2 and AVX instructions?

To hide those warnings, you could do this before your actual code.

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf

How to remove first and last character of a string?

You can always use substring:

String loginToken = getName().toString();
loginToken = loginToken.substring(1, loginToken.length() - 1);

WPF C# button style

To solve your question definitely need to use the Style and Template for the Button. But how exactly does he look like? Decisions may be several. For example, Button are two texts to better define the relevant TextBlocks? Can be directly in the template, but then use the buttons will be limited, because the template can be only one ContentPresenter. I decided to do things differently, to identify one ContentPresenter with an icon in the form of a Path, and the content is set using the buttons on the side.

The style:

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="#373737" />
    <Setter Property="Foreground" Value="White" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="SnapsToDevicePixels" Value="True" />

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border CornerRadius="4" Background="{TemplateBinding Background}">
                    <Grid>
                        <Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
                        <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />                                
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#E59400" />
                        <Setter Property="Foreground" Value="White" />
                        <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                    </Trigger>

                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="OrangeRed" />
                        <Setter Property="Foreground" Value="White" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Sample of using:

<Button Width="200" Height="50" VerticalAlignment="Top" Margin="0,20,0,0" />
    <Button.Content>
        <StackPanel>
            <TextBlock Text="Watch Now" FontSize="20" />
            <TextBlock Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
        </StackPanel>
    </Button.Content>
</Button>

Output

enter image description here

It is best to StackPanel determine the Resources and set the Button so:

<Window.Resources>
    <StackPanel x:Key="MyStackPanel">
        <TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
        <TextBlock Name="DurationValue" Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
    </StackPanel>
</Window.Resources>

<Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />

The question remains with setting the value for TextBlock Duration, because this value must be dynamic. I implemented it using attached DependencyProperty. Set it to the window, like that:

<Window Name="MyWindow" local:MyDependencyClass.CurrentDuration="Duration: 50m" ... />

Using in TextBlock:

<TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />

In fact, there is no difference for anyone to determine the attached DependencyProperty, because it is the predominant feature.

Example of set value:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
}

A complete listing of examples:

XAML

<Window x:Class="ButtonHelp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ButtonHelp"
    Name="MyWindow"
    Title="MainWindow" Height="350" Width="525"
    WindowStartupLocation="CenterScreen"
    local:MyDependencyClass.CurrentDuration="Duration: 50m">

<Window.Resources>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="#373737" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="FontSize" Value="15" />
        <Setter Property="FontFamily" Value="./#Segoe UI" />
        <Setter Property="SnapsToDevicePixels" Value="True" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border CornerRadius="4" Background="{TemplateBinding Background}">
                        <Grid>
                            <Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
                            <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />                                
                        </Grid>
                    </Border>

                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#E59400" />
                            <Setter Property="Foreground" Value="White" />
                            <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                        </Trigger>

                        <Trigger Property="IsPressed" Value="True">
                            <Setter Property="Background" Value="OrangeRed" />
                            <Setter Property="Foreground" Value="White" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <StackPanel x:Key="MyStackPanel">
        <TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
        <TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />
    </StackPanel>
</Window.Resources>

<Grid>        
    <Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />

    <Button Content="Set some duration" Style="{x:Null}" Width="140" Height="30" VerticalAlignment="Top" HorizontalAlignment="Left" Click="Button_Click" />
</Grid>

Code behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
    }
}

public class MyDependencyClass : DependencyObject
{
    public static readonly DependencyProperty CurrentDurationProperty;        

    public static void SetCurrentDuration(DependencyObject DepObject, string value)
    {
        DepObject.SetValue(CurrentDurationProperty, value);
    }

    public static string GetCurrentDuration(DependencyObject DepObject)
    {
        return (string)DepObject.GetValue(CurrentDurationProperty);
    }

    static MyDependencyClass()
    {
        PropertyMetadata MyPropertyMetadata = new PropertyMetadata("Duration: 0m");

        CurrentDurationProperty = DependencyProperty.RegisterAttached("CurrentDuration",
                                                            typeof(string),
                                                            typeof(MyDependencyClass),
                                                            MyPropertyMetadata);
    }
}

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

Converting Varchar Value to Integer/Decimal Value in SQL Server

You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:

If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.

Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

MongoDB running but can't connect using shell

I had this problem as well. Is your MongoDB journaling? I noticed the following "preallocate" entries in the log file. Once I saw the last line "waiting for connections on port", I could connect. Notice that this "faster" mode took 12 minutes to intialize.

William

Tue Apr 17 16:48:01 [initandlisten] MongoDB starting : pid=2248 port=27017 dbpath=E:\MongoData 64-bit host=ME
Tue Apr 17 16:48:01 [initandlisten] db version v2.0.0-rc0, pdfile version 4.5
Tue Apr 17 16:48:01 [initandlisten] git version: 8d4bf50111352cee5a4f1abf25b63442d6c45dc4
Tue Apr 17 16:48:01 [initandlisten] build info: windows (6, 1, 7601, 2, 'Service Pack 1') BOOST_LIB_VERSION=1_42
Tue Apr 17 16:48:01 [initandlisten] options: { bind_ip: "ip", dbpath: "E:\MongoData", directoryperdb: true, journal: true, logpath: "E:\MongoData\mongo.log", quiet: true, rest: true, service: true }
Tue Apr 17 16:48:01 [initandlisten] journal dir=E:/MongoData/journal
Tue Apr 17 16:48:01 [initandlisten] recover : no journal files present, no recovery needed
Tue Apr 17 16:48:02 [initandlisten] preallocateIsFaster=true 9.68
Tue Apr 17 16:48:04 [initandlisten] preallocateIsFaster=true 8.44
Tue Apr 17 16:48:06 [initandlisten] preallocateIsFaster=true 9.68
Tue Apr 17 16:48:06 [initandlisten] preallocateIsFaster check took 4.921 secs
Tue Apr 17 16:48:06 [initandlisten] preallocating a journal file E:/MongoData/journal/prealloc.0
Tue Apr 17 16:52:37 [initandlisten] preallocating a journal file E:/MongoData/journal/prealloc.1
Tue Apr 17 16:56:54 [initandlisten] preallocating a journal file E:/MongoData/journal/prealloc.2
Tue Apr 17 17:01:42 [initandlisten] waiting for connections on port 27017
Tue Apr 17 17:01:42 [websvr] admin web console waiting for connections on port 28017

MVC controller : get JSON object from HTTP body?

I've been trying to get my ASP.NET MVC controller to parse some model that i submitted to it using Postman.

I needed the following to get it to work:

  • controller action

    [HttpPost]
    [PermitAllUsers]
    [Route("Models")]
    public JsonResult InsertOrUpdateModels(Model entities)
    {
        // ...
        return Json(response, JsonRequestBehavior.AllowGet);
    }
    
  • a Models class

    public class Model
    {
        public string Test { get; set; }
        // ...
    }
    
  • headers for Postman's request, specifically, Content-Type

    postman headers

  • json in the request body

    enter image description here

How to get rid of punctuation using NLTK tokenizer?

Sincerely asking, what is a word? If your assumption is that a word consists of alphabetic characters only, you are wrong since words such as can't will be destroyed into pieces (such as can and t) if you remove punctuation before tokenisation, which is very likely to affect your program negatively.

Hence the solution is to tokenise and then remove punctuation tokens.

import string

from nltk.tokenize import word_tokenize

tokens = word_tokenize("I'm a southern salesman.")
# ['I', "'m", 'a', 'southern', 'salesman', '.']

tokens = list(filter(lambda token: token not in string.punctuation, tokens))
# ['I', "'m", 'a', 'southern', 'salesman']

...and then if you wish, you can replace certain tokens such as 'm with am.

How Can I Truncate A String In jQuery?

Instead of using jQuery, use css property text-overflow:ellipsis. It will automatically truncate the string.

.truncated { display:inline-block; 
             max-width:100px; 
             overflow:hidden; 
             text-overflow:ellipsis; 
             white-space:nowrap; 
           }

Can we make unsigned byte in Java

I am trying to use this data as a parameter to a function of Java that accepts only a byte as parameter

This is not substantially different from a function accepting an integer to which you want to pass a value larger than 2^32-1.

That sounds like it depends on how the function is defined and documented; I can see three possibilities:

  1. It may explicitly document that the function treats the byte as an unsigned value, in which case the function probably should do what you expect but would seem to be implemented wrong. For the integer case, the function would probably declare the parameter as an unsigned integer, but that is not possible for the byte case.

  2. It may document that the value for this argument must be greater than (or perhaps equal to) zero, in which case you are misusing the function (passing an out-of-range parameter), expecting it to do more than it was designed to do. With some level of debugging support you might expect the function to throw an exception or fail an assertion.

  3. The documentation may say nothing, in which case a negative parameter is, well, a negative parameter and whether that has any meaning depends on what the function does. If this is meaningless then perhaps the function should really be defined/documented as (2). If this is meaningful in an nonobvious manner (e.g. non-negative values are used to index into an array, and negative values are used to index back from the end of the array so -1 means the last element) the documentation should say what it means and I would expect that it isn't what you want it to do anyway.

Python socket connection timeout

You just need to use the socket settimeout() method before attempting the connect(), please note that after connecting you must settimeout(None) to set the socket into blocking mode, such is required for the makefile . Here is the code I am using:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect(address)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)

How to revert a merge commit that's already pushed to remote branch?

You could follow these steps to revert the incorrect commit(s) or to reset your remote branch back to correct HEAD/state.

  1. checkout the remote branch to local repo.
    git checkout development
  2. copy the commit hash (i.e. id of the commit immediately before the wrong commit) from git log git log -n5

    output:

    commit 7cd42475d6f95f5896b6f02e902efab0b70e8038 "Merge branch 'wrong-commit' into 'development'"
    commit f9a734f8f44b0b37ccea769b9a2fd774c0f0c012 "this is a wrong commit"
    commit 3779ab50e72908da92d2cfcd72256d7a09f446ba "this is the correct commit"

  3. reset the branch to the commit hash copied in the previous step
    git reset <commit-hash> (i.e. 3779ab50e72908da92d2cfcd72256d7a09f446ba)

  4. run the git status to show all the changes that were part of the wrong commit.
  5. simply run git reset --hard to revert all those changes.
  6. force-push your local branch to remote and notice that your commit history is clean as it was before it got polluted.
    git push -f origin development

C# An established connection was aborted by the software in your host machine

This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

ConcurrentHashMap is preferred when you can use it - though it requires at least Java 5.

It is designed to scale well when used by multiple threads. Performance may be marginally poorer when only a single thread accesses the Map at a time, but significantly better when multiple threads access the map concurrently.

I found a blog entry that reproduces a table from the excellent book Java Concurrency In Practice, which I thoroughly recommend.

Collections.synchronizedMap makes sense really only if you need to wrap up a map with some other characteristics, perhaps some sort of ordered map, like a TreeMap.

Getting data posted in between two dates

May this helpful to you.... With Join of Three Tables

public function get_details_beetween_dates()
    {
        $from = $this->input->post('fromdate');
        $to = $this->input->post('todate');

        $this->db->select('users.first_name, users.last_name, users.email, groups.name as designation, dailyinfo.amount as Total_Fine, dailyinfo.date as Date_of_Fine, dailyinfo.desc as Description')
                    ->from('users')
                    ->where('dailyinfo.date >= ',$from)
                    ->where('dailyinfo.date <= ',$to)
                    ->join('users_groups','users.id = users_groups.user_id')
                    ->join('dailyinfo','users.id = dailyinfo.userid')
                    ->join('groups','groups.id = users_groups.group_id');

        /*
        $this->db->select('date, amount, desc')
                 ->from('dailyinfo')
                 ->where('dailyinfo.date >= ',$from)
                 ->where('dailyinfo.date <= ',$to);
        */

        $q = $this->db->get();

        $array['userDetails'] = $q->result();
        return $array;
    }

iCheck check if checkbox is checked

Use this code for iCheck:

$('.i-checks').iCheck({
    checkboxClass: 'icheckbox_square-green',
    radioClass: 'iradio_square-green',
}).on('ifChanged', function(e) {
    // Get the field name
    var isChecked = e.currentTarget.checked;

    if (isChecked == true) {

    }
});

Xcode 6.1 - How to uninstall command line tools?

An excerpt from an apple technical note (Thanks to matthias-bauch)

Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.

If your tools were downloaded separately from Xcode, then they are located at /Library/Developer/CommandLineTools on your system. Delete the CommandLineTools folder to uninstall them.

you could easily delete using terminal:

Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.

How to set .net Framework 4.5 version in IIS 7 application pool

There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.

WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server

If you are on Windows 7 or 8 then Apache might be seeing the connections coming from "::1" which is the IPv6 equivalent of 127.0.0.1.

You can check this by looking in the Apache Access Log (reachable from the WAMP menu)

::1 - - [20/Dec/2012:21:35:04 +0000] "GET /phpmyadmin/ HTTP/1.1" 403 213

The ::1 at the start is the clients address. The 403 at the end is the Access Denied code.

The answers above will remove all restrictions and open phpmyadmin to all, but if you still want to restrict phpmyadmin to your machine only (generally a good idea) then under the line...

Allow from 127.0.0.1

..add the following:

Allow from ::1

(edit: Added suggestion from Nukeface)

Docker compose port mapping

If you want to bind to the redis port from your nodejs container you will have to expose that port in the redis container:

version: '2'
services:
  nodejs:
    build:
      context: .
      dockerfile: DockerFile
    ports:
      - "4000:4000"
    links:
      - redis

  redis:
    build:
      context: .
      dockerfile: Dockerfile-redis
    expose:
      - "6379"

The expose tag will let you expose ports without publishing them to the host machine, but they will be exposed to the containers networks.

https://docs.docker.com/compose/compose-file/#expose

The ports tag will be mapping the host port with the container port HOST:CONTAINER

https://docs.docker.com/compose/compose-file/#ports

Python list directory, subdirectory, and files

It's just an addition, with this you can get the data into CSV format

import sys,os
try:
    import pandas as pd
except:
    os.system("pip3 install pandas")
    
root = "/home/kiran/Downloads/MainFolder" # it may have many subfolders and files inside
lst = []
from fnmatch import fnmatch
pattern = "*.csv"      #I want to get only csv files 
pattern = "*.*"        # Note: Use this pattern to get all types of files and folders 
for path, subdirs, files in os.walk(root):
    for name in files:
        if fnmatch(name, pattern):
            lst.append((os.path.join(path, name)))
df = pd.DataFrame({"filePaths":lst})
df.to_csv("filepaths.csv")

Running Command Line in Java

You can also watch the output like this:

final Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");

new Thread(new Runnable() {
    public void run() {
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;

        try {
            while ((line = input.readLine()) != null)
                System.out.println(line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}).start();

p.waitFor();

And don't forget, if you are running a windows command, you need to put cmd /c in front of your command.

EDIT: And for bonus points, you can also use ProcessBuilder to pass input to a program:

String[] command = new String[] {
        "choice",
        "/C",
        "YN",
        "/M",
        "\"Press Y if you're cool\""
};
String inputLine = "Y";

ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

writer.write(inputLine);
writer.newLine();
writer.close();

String line;

while ((line = reader.readLine()) != null) {
    System.out.println(line);
}

This will run the windows command choice /C YN /M "Press Y if you're cool" and respond with a Y. So, the output will be:

Press Y if you're cool [Y,N]?Y

Jquery: Checking to see if div contains text, then action

Yes, I now made think for me. And it works fine!!!

if($("div:contains('CONGRATULATIONS')").length)
                        {
                            $('#SignupForm').hide(500);
                        }

How do you create a read-only user in PostgreSQL?

Reference taken from this blog:

Script to Create Read-Only user:

CREATE ROLE Read_Only_User WITH LOGIN PASSWORD 'Test1234' 
NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION VALID UNTIL 'infinity';

Assign permission to this read only user:

GRANT CONNECT ON DATABASE YourDatabaseName TO Read_Only_User;
GRANT USAGE ON SCHEMA public TO Read_Only_User;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO Read_Only_User;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO Read_Only_User;

Assign permissions to read all newly tables created in the future

ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO Read_Only_User;

Detect browser or tab closing

From MDN Documentation

For some reasons, Webkit-based browsers don't follow the spec for the dialog box. An almost cross-working example would be close from the below example.

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});

This example for handling all browsers.

Nginx: Permission denied for nginx on Ubuntu

Nginx needs to run by command 'sudo /etc/init.d/nginx start'

Simple way to create matrix of random numbers

numpy.random.rand(row, column) generates random numbers between 0 and 1, according to the specified (m,n) parameters given. So use it to create a (m,n) matrix and multiply the matrix for the range limit and sum it with the high limit.

Analyzing: If zero is generated just the low limit will be held, but if one is generated just the high limit will be held. In order words, generating the limits using rand numpy you can generate the extreme desired numbers.

import numpy as np

high = 10
low = 5
m,n = 2,2

a = (high - low)*np.random.rand(m,n) + low

Output:

a = array([[5.91580065, 8.1117106 ],
          [6.30986984, 5.720437  ]])

Cannot set property 'innerHTML' of null

You have to place the hello div before the script, so that it exists when the script is loaded.

How to make a <div> or <a href="#"> to align center

You can use css like below;

 <a href="contact.html" style="margin:auto; text-align:center; display:block;" class="button large hpbottom">Get Started</a>

How to use onSaveInstanceState() and onRestoreInstanceState()?

This happens because you use the savedValue in the onCreate() method. The savedValue is updated in onRestoreInstanceState() method, but onRestoreInstanceState() is called after the onCreate() method. You can either:

  1. Update the savedValue in onCreate() method, or
  2. Move the code that use the new savedValue in onRestoreInstanceState() method.

But I suggest you to use the first approach, making the code like this:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int display_mode = getResources().getConfiguration().orientation;

    if (display_mode == 1) {

        setContentView(R.layout.main_grid);
        mGrid = (GridView) findViewById(R.id.gridview);
        mGrid.setColumnWidth(95);
        mGrid.setVisibility(0x00000000);
        // mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

    } else {
        setContentView(R.layout.main_grid_land);
        mGrid = (GridView) findViewById(R.id.gridview);
        mGrid.setColumnWidth(95);
        Log.d("Mode", "land");
        // mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

    }
    if (savedInstanceState != null) {
        savedUser = savedInstanceState.getString("TEXT");
    } else {
        savedUser = ""
    }
    Log.d("savedUser", savedUser);
    if (savedUser.equals("admin")) { //value 0
        adapter.setApps(appManager.getApplications());
    } else if (savedUser.equals("prof")) { //value 1
        adapter.setApps(appManager.getTeacherApplications());
    } else {// default value
        appManager = new ApplicationManager(this, getPackageManager());
        appManager.loadApplications(true);
        bindApplications();
    }
}

Laravel 4: Redirect to a given url

Yes, it's

use Illuminate\Support\Facades\Redirect;

return Redirect::to('http://heera.it');

Check the documentation.

Update: Redirect::away('url') (For external link, Laravel Version 4.19):

public function away($path, $status = 302, $headers = array())
{
    return $this->createRedirect($path, $status, $headers);
}

How to find largest objects in a SQL Server database?

In SQL Server 2008, you can also just run the standard report Disk Usage by Top Tables. This can be found by right clicking the DB, selecting Reports->Standard Reports and selecting the report you want.

How to load a resource bundle from a file resource in Java?

The file name should have .properties extension and the base directory should be in classpath. Otherwise it can also be in a jar which is in classpath Relative to the directory in classpath the resource bundle can be specified with / or . separator. "." is preferred.

Extract regression coefficient values

The package broom comes in handy here (it uses the "tidy" format).

tidy(mg) will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).

Example from broom's github repo:

lmfit <- lm(mpg ~ wt, mtcars)
require(broom)    
tidy(lmfit)

      term estimate std.error statistic   p.value
1 (Intercept)   37.285   1.8776    19.858 8.242e-19
2          wt   -5.344   0.5591    -9.559 1.294e-10

is.data.frame(tidy(lmfit))
[1] TRUE

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

"Auth Failed" error with EGit and GitHub

I wanted to make public once me too a google code fix and got the same error. Started with This video, but at Save and publish got an error. I have seen there are several question regarding to this. Some are Windows users, those are the most lucky, because usually no problems with permissions and some are Linux users.

I have a mac for mobile development use and very often meet this problems. The source for this problems is the "platform independent" solutions, which doesn't care enough for mac and they don't have access to keychain, where are stored the certificates, .pem files and so on.

All I wanted is to not make any environment settings, nor command line, just simple GUI based clicks, like a regular user.

Half part was done with Eclipse Git plugin, second part (push to Github) was done with Mac Github

Nice and easy :)

All can be done with with that native appp if I would start to learn it, I just need the push functionality from him.

Hoping it will help a mac user once.

using c# .net libraries to check for IMAP messages from gmail servers

Another alternative: HigLabo

https://higlabo.codeplex.com/documentation

Good discussion: https://higlabo.codeplex.com/discussions/479250

//====Imap sample================================//
//You can set default value by Default property
ImapClient.Default.UserName = "your server name";
ImapClient cl = new ImapClient("your server name");
cl.UserName = "your name";
cl.Password = "pass";
cl.Ssl = false;
if (cl.Authenticate() == true)
{
    Int32 MailIndex = 1;
    //Get all folder
    List<ImapFolder> l = cl.GetAllFolders();
    ImapFolder rFolder = cl.SelectFolder("INBOX");
    MailMessage mg = cl.GetMessage(MailIndex);
}

//Delete selected mail from mailbox
ImapClient pop = new ImapClient("server name", 110, "user name", "pass");
pop.AuthenticateMode = Pop3AuthenticateMode.Pop;
Int64[] DeleteIndexList = new.....//It depend on your needs
cl.DeleteEMail(DeleteIndexList);

//Get unread message list from GMail
using (ImapClient cl = new ImapClient("imap.gmail.com")) 
{
    cl.Port = 993;
    cl.Ssl = true; 
    cl.UserName = "xxxxx";
    cl.Password = "yyyyy";
    var bl = cl.Authenticate();
    if (bl == true)
    {
        //Select folder
        ImapFolder folder = cl.SelectFolder("[Gmail]/All Mail");
        //Search Unread
        SearchResult list = cl.ExecuteSearch("UNSEEN UNDELETED");
        //Get all unread mail
        for (int i = 0; i < list.MailIndexList.Count; i++)
        {
            mg = cl.GetMessage(list.MailIndexList[i]);
        }
    }
    //Change mail read state as read
    cl.ExecuteStore(1, StoreItem.FlagsReplace, "UNSEEN")
}


//Create draft mail to mailbox
using (ImapClient cl = new ImapClient("imap.gmail.com")) 
{
    cl.Port = 993;
    cl.Ssl = true; 
    cl.UserName = "xxxxx";
    cl.Password = "yyyyy";
    var bl = cl.Authenticate();
    if (bl == true)
    {
        var smg = new SmtpMessage("from mail address", "to mail addres list"
            , "cc mail address list", "This is a test mail.", "Hi.It is my draft mail");
        cl.ExecuteAppend("GMail/Drafts", smg.GetDataText(), "\\Draft", DateTimeOffset.Now); 
    }
}

//Idle
using (var cl = new ImapClient("imap.gmail.com", 993, "user name", "pass"))
{
    cl.Ssl = true;
    cl.ReceiveTimeout = 10 * 60 * 1000;//10 minute
    if (cl.Authenticate() == true)
    {
        var l = cl.GetAllFolders();
        ImapFolder r = cl.SelectFolder("INBOX");
        //You must dispose ImapIdleCommand object
        using (var cm = cl.CreateImapIdleCommand()) Caution! Ensure dispose command object
        {
            //This handler is invoked when you receive a mesage from server
            cm.MessageReceived += (Object o, ImapIdleCommandMessageReceivedEventArgs e) =>
            {
                foreach (var mg in e.MessageList)
                {
                    String text = String.Format("Type is {0} Number is {1}", mg.MessageType, mg.Number);
                    Console.WriteLine(text);
                }
            };
            cl.ExecuteIdle(cm);
            while (true)
            {
                var line = Console.ReadLine();
                if (line == "done")
                {
                    cl.ExecuteDone(cm);
                    break;
                }
            }
        }
    }
}

int array to string

You can simply use String.Join function, and as separator use string.Empty because it uses StringBuilder internally.

string result = string.Join(string.Empty, new []{0,1,2,3,0,1});

E.g.: If you use semicolon as separator, the result would be 0;1;2;3;0;1.

It actually works with null separator, and second parameter can be enumerable of any objects, like:

string result = string.Join(null, new object[]{0,1,2,3,0,"A",DateTime.Now});

How to design RESTful search/filtering?

The best way to implement a RESTful search is to consider the search itself to be a resource. Then you can use the POST verb because you are creating a search. You do not have to literally create something in a database in order to use a POST.

For example:

Accept: application/json
Content-Type: application/json
POST http://example.com/people/searches
{
  "terms": {
    "ssn": "123456789"
  },
  "order": { ... },
  ...
}

You are creating a search from the user's standpoint. The implementation details of this are irrelevant. Some RESTful APIs may not even need persistence. That is an implementation detail.

Create empty file using python

There is no way to create a file without opening it There is os.mknod("newfile.txt") (but it requires root privileges on OSX). The system call to create a file is actually open() with the O_CREAT flag. So no matter how, you'll always open the file.

So the easiest way to simply create a file without truncating it in case it exists is this:

open(x, 'a').close()

Actually you could omit the .close() since the refcounting GC of CPython will close it immediately after the open() statement finished - but it's cleaner to do it explicitely and relying on CPython-specific behaviour is not good either.

In case you want touch's behaviour (i.e. update the mtime in case the file exists):

import os
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)

You could extend this to also create any directories in the path that do not exist:

basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

How to view method information in Android Studio?

If you need only Parameter info then:

On Mac, it's assigned to Command+P

On Windows, it's assigned to Ctrl+P

If you need document info then:

On Mac, it's assigned to Command+Q

On Windows, it's assigned to Ctrl+Q

Can we call the function written in one JavaScript in another JS file?

Here's a more descriptive example with a CodePen snippet attached:

1.js

function fn1() {
  document.getElementById("result").innerHTML += "fn1 gets called";
}

2.js

function clickedTheButton() {
  fn1();
} 

index.html

<html>
  <head>
  </head>
  <body>
    <button onclick="clickedTheButton()">Click me</button>
    <script type="text/javascript" src="1.js"></script>
    <script type="text/javascript" src="2.js"></script>
  </body>
 </html>

output

Output. Button + Result

Try this CodePen snippet: link .

How can I convert an HTML table to CSV?

I'm not sure if there is pre-made library for this, but if you're willing to get your hands dirty with a little Perl, you could likely do something with Text::CSV and HTML::Parser.

How to enable cURL in PHP / XAMPP

I found the file located at:

C:\xampp\php\php.ini

Uncommented:

;extension=php_curl.dll

How to create EditText accepts Alphabets only in android?

edittext.setFilters(new InputFilter[] {
    new InputFilter() {
        public CharSequence filter(CharSequence src, int start,
                int end, Spanned dst, int dstart, int dend) {
            if(src.equals("")){ // for backspace
                return src;
            }
            if(src.toString().matches("[a-zA-Z ]+")){
                return src;
            }
            return edittext.getText().toString();
        }
    }
});

please test thoroughly though !

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

Just add this to your main all project level build.gradle file under allprojects()

 maven {
    url "https://maven.google.com"
 }

Is there something like Codecademy for Java

Check out javapassion, they have a number of courses that encompass web programming, and were free (until circumstances conspired to make the website need to support itself).

Even with the nominal fee, you get a lot for an entire year. It's a bargain compared to the amount of time you'll be investing.

The other options are to look to Oracle's online tutorials, they lack the glitz of Codeacademy, but are surprisingly good. I haven't read the one on web programming, that might be embedded in the Java EE tutorial(s), which is not tuned for a new beginner to Java.

Getting a "This application is modifying the autolayout engine from a background thread" error?

You must not change the UI offside the main thread! UIKit is not thread safe, so that above problem and also some other weird problems will arise if you do that. The app can even crash.

So, to do the UIKit operations, you need to define block and let it be executed on the main queue: such as,

NSOperationQueue.mainQueue().addOperationWithBlock {

}

Calculate the center point of multiple latitude/longitude coordinate pairs

The simple approach of just averaging them has weird edge cases with angles when they wrap from 359' back to 0'.

A much earlier question on SO asked about finding the average of a set of compass angles.

An expansion of the approach recommended there for spherical coordinates would be:

  • Convert each lat/long pair into a unit-length 3D vector.
  • Sum each of those vectors
  • Normalise the resulting vector
  • Convert back to spherical coordinates

Finding element's position relative to the document

You can use element.getBoundingClientRect() to retrieve element position relative to the viewport.

Then use document.documentElement.scrollTop to calculate the viewport offset.

The sum of the two will give the element position relative to the document:

element.getBoundingClientRect().top + document.documentElement.scrollTop

Build fails with "Command failed with a nonzero exit code"

For me this was to do with a constraint that I was removing at build time. Unticking Remove at build time fixed the issue, and I suspect the compiler had an issue determining the layout without it.

The error code will mention which Storyboard is causing the issue.

How to recursively delete an entire directory with PowerShell 2.0?

Really simple:

remove-item -path <type in file or directory name>, press Enter

What is the difference between Scala's case class and class?

Nobody mentioned that case class companion object has tupled defention, which has a type:

case class Person(name: String, age: Int)
//Person.tupled is def tupled: ((String, Int)) => Person

The only use case I can find is when you need to construct case class from tuple, example:

val bobAsTuple = ("bob", 14)
val bob = (Person.apply _).tupled(bobAsTuple) //bob: Person = Person(bob,14)

You can do the same, without tupled, by creating object directly, but if your datasets expressed as list of tuple with arity 20(tuple with 20 elements), may be using tupled is your choise.

SQL: How to to SUM two values from different tables

select region,sum(number) total
from
(
    select region,number
    from cash_table
    union all
    select region,number
    from cheque_table
) t
group by region

XPath to fetch SQL XML value

I always go back to this article SQL Server 2005 XQuery and XML-DML - Part 1 to know how to use the XML features in SQL Server 2005.

For basic XPath know-how, I'd recommend the W3Schools tutorial.

How to initialize a two-dimensional array in Python?

To initialize a two-dimensional array in Python:

a = [[0 for x in range(columns)] for y in range(rows)]

Python extract pattern matches

You need to capture from regex. search for the pattern, if found, retrieve the string using group(index). Assuming valid checks are performed:

>>> p = re.compile("name (.*) is valid")
>>> result = p.search(s)
>>> result
<_sre.SRE_Match object at 0x10555e738>
>>> result.group(1)     # group(1) will return the 1st capture (stuff within the brackets).
                        # group(0) will returned the entire matched text.
'my_user_name'

Get UserDetails object from Security Context in Spring MVC controller

That's another solution (Spring Security 3):

public String getLoggedUser() throws Exception {
    String name = SecurityContextHolder.getContext().getAuthentication().getName();
    return (!name.equals("anonymousUser")) ? name : null;
}

How can I generate a list or array of sequential integers in Java?

With Java 8 it is so simple so it doesn't even need separate method anymore:

List<Integer> range = IntStream.rangeClosed(start, end)
    .boxed().collect(Collectors.toList());

How can I find whitespace in a String?

String str = "Test Word";
            if(str.indexOf(' ') != -1){
                return true;
            } else{
                return false;
            }

JSONObject - How to get a value?

This may be helpful while searching keys present in nested objects and nested arrays. And this is a generic solution to all cases.

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyClass
{
    public static Object finalresult = null;
    public static void main(String args[]) throws JSONException
    {
        System.out.println(myfunction(myjsonstring,key));
    }

    public static Object myfunction(JSONObject x,String y) throws JSONException
    {
        JSONArray keys =  x.names();
        for(int i=0;i<keys.length();i++)
        {
            if(finalresult!=null)
            {
                return finalresult;                     //To kill the recursion
            }

            String current_key = keys.get(i).toString();

            if(current_key.equals(y))
            {
                finalresult=x.get(current_key);
                return finalresult;
            }

            if(x.get(current_key).getClass().getName().equals("org.json.JSONObject"))
            {
                myfunction((JSONObject) x.get(current_key),y);
            }
            else if(x.get(current_key).getClass().getName().equals("org.json.JSONArray"))
            {
                for(int j=0;j<((JSONArray) x.get(current_key)).length();j++)
                {
                    if(((JSONArray) x.get(current_key)).get(j).getClass().getName().equals("org.json.JSONObject"))
                    {
                        myfunction((JSONObject)((JSONArray) x.get(current_key)).get(j),y);
                    }
                }
            }
        }
        return null;
    }
}

Possibilities:

  1. "key":"value"
  2. "key":{Object}
  3. "key":[Array]

Logic :

  • I check whether the current key and search key are the same, if so I return the value of that key.
  • If it is an object, I send the value recursively to the same function.
  • If it is an array, I check whether it contains an object, if so I recursively pass the value to the same function.

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

Mutex lock threads

Below, code snippet, will help you in understanding the mutex-lock-unlock concept. Attempt dry-run on the code. (further by varying the wait-time and process-time, you can build you understanding).

Code for your reference:

#include <stdio.h>
#include <pthread.h>

void in_progress_feedback(int);

int global = 0;
pthread_mutex_t mutex;
void *compute(void *arg) {

    pthread_t ptid = pthread_self();
    printf("ptid : %08x \n", (int)ptid);    

    int i;
    int lock_ret = 1;   
    do{

        lock_ret = pthread_mutex_trylock(&mutex);
        if(lock_ret){
            printf("lock failed(%08x :: %d)..attempt again after 2secs..\n", (int)ptid,  lock_ret);
            sleep(2);  //wait time here..
        }else{  //ret =0 is successful lock
            printf("lock success(%08x :: %d)..\n", (int)ptid, lock_ret);
            break;
        }

    } while(lock_ret);

        for (i = 0; i < 10*10 ; i++) 
        global++;

    //do some stuff here
    in_progress_feedback(10);  //processing-time here..

    lock_ret = pthread_mutex_unlock(&mutex);
    printf("unlocked(%08x :: %d)..!\n", (int)ptid, lock_ret);

     return NULL;
}

void in_progress_feedback(int prog_delay){

    int i=0;
    for(;i<prog_delay;i++){
    printf(". ");
    sleep(1);
    fflush(stdout);
    }

    printf("\n");
    fflush(stdout);
}

int main(void)
{
    pthread_t tid0,tid1;
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid0, NULL, compute, NULL);
    pthread_create(&tid1, NULL, compute, NULL);
    pthread_join(tid0, NULL);
    pthread_join(tid1, NULL);
    printf("global = %d\n", global);
    pthread_mutex_destroy(&mutex);
          return 0;
}

How can I create an MSI setup?

Google "Freeware MSI installer".

e.g. https://www.advancedinstaller.com/

Several options here:

http://rbytes.net/software/development_c/install-and-setup_s/

Though being Windows, most are "shareware" rather than truly free and open source.

Any shortcut to initialize all array elements to zero?

In java all elements(primitive integer types byte short, int, long) are initialised to 0 by default. You can save the loop.

Keystore type: which one to use?

Here is a post which introduces different types of keystore in Java and the differences among different types of keystore. http://www.pixelstech.net/article/1408345768-Different-types-of-keystore-in-Java----Overview

Below are the descriptions of different keystores from the post:

JKS, Java Key Store. You can find this file at sun.security.provider.JavaKeyStore. This keystore is Java specific, it usually has an extension of jks. This type of keystore can contain private keys and certificates, but it cannot be used to store secret keys. Since it's a Java specific keystore, so it cannot be used in other programming languages.

JCEKS, JCE key store. You can find this file at com.sun.crypto.provider.JceKeyStore. This keystore has an extension of jceks. The entries which can be put in the JCEKS keystore are private keys, secret keys and certificates.

PKCS12, this is a standard keystore type which can be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.

PKCS11, this is a hardware keystore type. It servers an interface for the Java library to connect with hardware keystore devices such as Luna, nCipher. You can find this implementation at sun.security.pkcs11.P11KeyStore. When you load the keystore, you no need to create a specific provider with specific configuration. This keystore can store private keys, secret keys and cetrificates. When loading the keystore, the entries will be retrieved from the keystore and then converted into software entries.

What is an NP-complete in computer science?

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

What is the difference between & vs @ and = in angularJS

I would like to explain the concepts from the perspective of JavaScript prototype inheritance. Hopefully help to understand.

There are three options to define the scope of a directive:

  1. scope: false: Angular default. The directive's scope is exactly the one of its parent scope (parentScope).
  2. scope: true: Angular creates a scope for this directive. The scope prototypically inherits from parentScope.
  3. scope: {...}: isolated scope is explained below.

Specifying scope: {...} defines an isolatedScope. An isolatedScope does not inherit properties from parentScope, although isolatedScope.$parent === parentScope. It is defined through:

app.directive("myDirective", function() {
    return {
        scope: {
            ... // defining scope means that 'no inheritance from parent'.
        },
    }
})

isolatedScope does not have direct access to parentScope. But sometimes the directive needs to communicate with the parentScope. They communicate through @, = and &. The topic about using symbols @, = and & are talking about scenarios using isolatedScope.

It is usually used for some common components shared by different pages, like Modals. An isolated scope prevents polluting the global scope and is easy to share among pages.

Here is a basic directive: http://jsfiddle.net/7t984sf9/5/. An image to illustrate is:

enter image description here

@: one-way binding

@ simply passes the property from parentScope to isolatedScope. It is called one-way binding, which means you cannot modify the value of parentScope properties. If you are familiar with JavaScript inheritance, you can understand these two scenarios easily:

  • If the binding property is a primitive type, like interpolatedProp in the example: you can modify interpolatedProp, but parentProp1 would not be changed. However, if you change the value of parentProp1, interpolatedProp will be overwritten with the new value (when angular $digest).

  • If the binding property is some object, like parentObj: since the one passed to isolatedScope is a reference, modifying the value will trigger this error:

    TypeError: Cannot assign to read only property 'x' of {"x":1,"y":2}

=: two-way binding

= is called two-way binding, which means any modification in childScope will also update the value in parentScope, and vice versa. This rule works for both primitives and objects. If you change the binding type of parentObj to be =, you will find that you can modify the value of parentObj.x. A typical example is ngModel.

&: function binding

& allows the directive to call some parentScope function and pass in some value from the directive. For example, check JSFiddle: & in directive scope.

Define a clickable template in the directive like:

<div ng-click="vm.onCheck({valueFromDirective: vm.value + ' is from the directive'})">

And use the directive like:

<div my-checkbox value="vm.myValue" on-check="vm.myFunction(valueFromDirective)"></div>

The variable valueFromDirective is passed from the directive to the parent controller through {valueFromDirective: ....

Reference: Understanding Scopes

Common Header / Footer with static HTML

The most practical way is to use Server Side Include. It's very easy to implement and saves tons of work when you have more than a couple pages.

Generic Property in C#

public class MyProp<T>
{
...
}

public class ClassThatUsesMyProp
{
public MyProp<String> SomeProperty { get; set; }
}

How to import or copy images to the "res" folder in Android Studio?

For Android Studio:

Right click on res, new Image Asset

Select the image radio button in 3rd option i.e Asset Type

Select the path of the image and click next and then finish

All the images are added to the respective folder, its very simple

What is the most efficient way to concatenate N arrays?

Merge Array with Push:

_x000D_
_x000D_
const array1 = [2, 7, 4];_x000D_
const array2 = [3, 5,9];_x000D_
array1.push(...array2);_x000D_
console.log(array1)
_x000D_
_x000D_
_x000D_

Using Concat and Spread operator:

_x000D_
_x000D_
const array1 = [1,2];_x000D_
const array2 = [3,4];_x000D_
_x000D_
// Method 1: Concat _x000D_
const combined1 = [].concat(array1, array2);_x000D_
_x000D_
// Method 2: Spread_x000D_
const combined2 = [...array1, ...array2];_x000D_
_x000D_
console.log(combined1);_x000D_
console.log(combined2);
_x000D_
_x000D_
_x000D_

Database Structure for Tree Data Structure

You mention the most commonly implemented, which is Adjacency List: https://blogs.msdn.microsoft.com/mvpawardprogram/2012/06/25/hierarchies-convert-adjacency-list-to-nested-sets

There are other models as well, including materialized path and nested sets: http://communities.bmc.com/communities/docs/DOC-9902

Joe Celko has written a book on this subject, which is a good reference from a general SQL perspective (it is mentioned in the nested set article link above).

Also, Itzik Ben-Gann has a good overview of the most common options in his book "Inside Microsoft SQL Server 2005: T-SQL Querying".

The main things to consider when choosing a model are:

1) Frequency of structure change - how frequently does the actual structure of the tree change. Some models provide better structure update characteristics. It is important to separate structure changes from other data changes however. For example, you may want to model a company's organizational chart. Some people will model this as an adjacency list, using the employee ID to link an employee to their supervisor. This is usually a sub-optimal approach. An approach that often works better is to model the org structure separate from employees themselves, and maintain the employee as an attribute of the structure. This way, when an employee leaves the company, the organizational structure itself does not need to be changes, just the association with the employee that left.

2) Is the tree write-heavy or read-heavy - some structures work very well when reading the structure, but incur additional overhead when writing to the structure.

3) What types of information do you need to obtain from the structure - some structures excel at providing certain kinds of information about the structure. Examples include finding a node and all its children, finding a node and all its parents, finding the count of child nodes meeting certain conditions, etc. You need to know what information will be needed from the structure to determine the structure that will best fit your needs.

Can I avoid the native fullscreen video player with HTML5 on iPhone or android?

There's a property that enables/disables in line media playback in the iOS web browser (if you were writing a native app, it would be the allowsInlineMediaPlayback property of a UIWebView). By default on iPhone this is set to NO, but on iPad it's set to YES.

Fortunately for you, you can also adjust this behaviour in HTML as follows:

<video id="myVideo" width="280" height="140" webkit-playsinline>

...that should hopefully sort it out for you. I don't know if it will work on your Android devices. It's a webkit property, so it might. Worth a go, anyway.

How do I get time of a Python program's execution?

The following snippet prints elapsed time in a nice human readable <HH:MM:SS> format.

import time
from datetime import timedelta

start_time = time.time()

#
# Perform lots of computations.
#

elapsed_time_secs = time.time() - start_time

msg = "Execution took: %s secs (Wall clock time)" % timedelta(seconds=round(elapsed_time_secs))

print(msg)    

Add element to a list In Scala

I will try to explain the results of all the commands you tried.

scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)

First of all, List is a type alias to scala.collection.immutable.List (defined in Predef.scala).

Using the List companion object is more straightforward way to instantiate a List. Ex: List(1.0,5.5)

scala> l
res0: List[Double] = List(1.0, 5.5)

scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)

::: returns a list resulting from the concatenation of the given list prefix and this list

The original List is NOT modified

scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)

List(l) is a List[List[Double]] Definitely not what you want.

:+ returns a new list consisting of all elements of this list followed by elem.

The type is List[Any] because it is the common superclass between List[Double] and Double

scala> l
res3: List[Double] = List(1.0, 5.5)

l is left unmodified because no method on immutable.List modified the List.

PHP/MySQL: How to create a comment section in your website

Create a new table called comments

They should have a column containing the id of the post they are assigned to.

Make a form which adds a new comment to that table.

An example (not tested so may contain lil' syntax errors): I call a page with comments a post

Post.php

<!-- Post content here -->

<!-- Then cmments below -->
<h1>Comments</h1>
<?php
$result = mysql_query("SELECT * FROM comments WHERE postid=0");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <?php echo $row->author; //Or similar in your table ?>
<p>
<?php echo;$row->body; ?>
</p>
</div>
<?php
}
?>
<h1>Leave a comment:</h1>
<form action="insertcomment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="hidden" name="postid" value="<?php //your posts id ?>" />
<input type="submit" />
</form>

insertcomment.php

<?php
//First check if everything is filled in
if(/*some statements*/)
{
//Do a mysql_real_escape_string() to all fields

//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>

You must change the code a bit to make it work. I'n not doing your homework. Only a part of it ;)

Purge Kafka Topic

./kafka-topics.sh --describe --zookeeper zkHost:2181 --topic myTopic

This should give retention.ms configured. Then you can use above alter command to change to 1second (and later revert back to default).

Topic:myTopic   PartitionCount:6        ReplicationFactor:1     Configs:retention.ms=86400000

Get content of a cell given the row and column numbers

Try =index(ARRAY, ROW, COLUMN)

where: Array: select the whole sheet Row, Column: Your row and column references

That should be easier to understand to those looking at the formula.

Nested classes' scope?

You might be better off if you just don't use nested classes. If you must nest, try this:

x = 1
class OuterClass:
    outer_var = x
    class InnerClass:
        inner_var = x

Or declare both classes before nesting them:

class OuterClass:
    outer_var = 1

class InnerClass:
    inner_var = OuterClass.outer_var

OuterClass.InnerClass = InnerClass

(After this you can del InnerClass if you need to.)

Most efficient way to find mode in numpy array

Update

The scipy.stats.mode function has been significantly optimized since this post, and would be the recommended method

Old answer

This is a tricky problem, since there is not much out there to calculate mode along an axis. The solution is straight forward for 1-D arrays, where numpy.bincount is handy, along with numpy.unique with the return_counts arg as True. The most common n-dimensional function I see is scipy.stats.mode, although it is prohibitively slow- especially for large arrays with many unique values. As a solution, I've developed this function, and use it heavily:

import numpy

def mode(ndarray, axis=0):
    # Check inputs
    ndarray = numpy.asarray(ndarray)
    ndim = ndarray.ndim
    if ndarray.size == 1:
        return (ndarray[0], 1)
    elif ndarray.size == 0:
        raise Exception('Cannot compute mode on empty array')
    try:
        axis = range(ndarray.ndim)[axis]
    except:
        raise Exception('Axis "{}" incompatible with the {}-dimension array'.format(axis, ndim))

    # If array is 1-D and numpy version is > 1.9 numpy.unique will suffice
    if all([ndim == 1,
            int(numpy.__version__.split('.')[0]) >= 1,
            int(numpy.__version__.split('.')[1]) >= 9]):
        modals, counts = numpy.unique(ndarray, return_counts=True)
        index = numpy.argmax(counts)
        return modals[index], counts[index]

    # Sort array
    sort = numpy.sort(ndarray, axis=axis)
    # Create array to transpose along the axis and get padding shape
    transpose = numpy.roll(numpy.arange(ndim)[::-1], axis)
    shape = list(sort.shape)
    shape[axis] = 1
    # Create a boolean array along strides of unique values
    strides = numpy.concatenate([numpy.zeros(shape=shape, dtype='bool'),
                                 numpy.diff(sort, axis=axis) == 0,
                                 numpy.zeros(shape=shape, dtype='bool')],
                                axis=axis).transpose(transpose).ravel()
    # Count the stride lengths
    counts = numpy.cumsum(strides)
    counts[~strides] = numpy.concatenate([[0], numpy.diff(counts[~strides])])
    counts[strides] = 0
    # Get shape of padded counts and slice to return to the original shape
    shape = numpy.array(sort.shape)
    shape[axis] += 1
    shape = shape[transpose]
    slices = [slice(None)] * ndim
    slices[axis] = slice(1, None)
    # Reshape and compute final counts
    counts = counts.reshape(shape).transpose(transpose)[slices] + 1

    # Find maximum counts and return modals/counts
    slices = [slice(None, i) for i in sort.shape]
    del slices[axis]
    index = numpy.ogrid[slices]
    index.insert(axis, numpy.argmax(counts, axis=axis))
    return sort[index], counts[index]

Result:

In [2]: a = numpy.array([[1, 3, 4, 2, 2, 7],
                         [5, 2, 2, 1, 4, 1],
                         [3, 3, 2, 2, 1, 1]])

In [3]: mode(a)
Out[3]: (array([1, 3, 2, 2, 1, 1]), array([1, 2, 2, 2, 1, 2]))

Some benchmarks:

In [4]: import scipy.stats

In [5]: a = numpy.random.randint(1,10,(1000,1000))

In [6]: %timeit scipy.stats.mode(a)
10 loops, best of 3: 41.6 ms per loop

In [7]: %timeit mode(a)
10 loops, best of 3: 46.7 ms per loop

In [8]: a = numpy.random.randint(1,500,(1000,1000))

In [9]: %timeit scipy.stats.mode(a)
1 loops, best of 3: 1.01 s per loop

In [10]: %timeit mode(a)
10 loops, best of 3: 80 ms per loop

In [11]: a = numpy.random.random((200,200))

In [12]: %timeit scipy.stats.mode(a)
1 loops, best of 3: 3.26 s per loop

In [13]: %timeit mode(a)
1000 loops, best of 3: 1.75 ms per loop

EDIT: Provided more of a background and modified the approach to be more memory-efficient

How to export iTerm2 Profiles

If you have a look at Preferences -> General you will notice at the bottom of the panel, there is a setting Load preferences from a custom folder or URL:. There is a button next to it Save settings to Folder.

So all you need to do is save your settings first and load it after you reinstalled your OS.

If the Save settings to Folder is disabled, select a folder (e.g. empty) in the Load preferences from a custom folder or URL: text box.

In iTerm2 3.3 on OSX the sequence is: iTerm2 menu, Preferences, General tab, Preferences subtab

Encode a FileStream to base64 with c#

Since the file will be larger, you don't have very much choice in how to do this. You cannot process the file in place since that will destroy the information you need to use. You have two options that I can see:

  1. Read in the entire file, base64 encode, re-write the encoded data.
  2. Read the file in smaller pieces, encoding as you go along. Encode to a temporary file in the same directory. When you are finished, delete the original file, and rename the temporary file.

Of course, the whole point of streams is to avoid this sort of scenario. Instead of creating the content and stuffing it into a file stream, stuff it into a memory stream. Then encode that and only then save to disk.

pow (x,y) in Java

In Java x ^ y is an XOR operation.

Format JavaScript date as yyyy-mm-dd

const formatDate = d => [
    d.getFullYear(),
    (d.getMonth() + 1).toString().padStart(2, '0'),
    d.getDate().toString().padStart(2, '0')
].join('-');

You can make use of padstart.

padStart(n, '0') ensures that a minimum of n characters are in a string and prepends it with '0's until that length is reached.

join('-') concatenates an array, adding '-' symbol between every elements.

getMonth() starts at 0 hence the +1.

Disable asp.net button after click to prevent double clicking

This works with a regular html button.

    <input id="Button1"
    onclick="this.disabled='true';" type="button"
    value="Submit" name="Button1"
    runat="server" onserverclick="Button1_Click">

The button is disabled until the postback is finished, preventing double clicking.

Is there a way to run Python on Android?

Cross-Compilation & Ignifuga

My blog has instructions and a patch for cross compiling Python 2.7.2 for Android.

I've also open sourced Ignifuga, my 2D Game Engine. It's Python/SDL based, and it cross compiles for Android. Even if you don't use it for games, you might get useful ideas from the code or builder utility (named Schafer, after Tim... you know who).

How to unescape a Java string literal in Java?

The Problem

The org.apache.commons.lang.StringEscapeUtils.unescapeJava() given here as another answer is really very little help at all.

  • It forgets about \0 for null.
  • It doesn’t handle octal at all.
  • It can’t handle the sorts of escapes admitted by the java.util.regex.Pattern.compile() and everything that uses it, including \a, \e, and especially \cX.
  • It has no support for logical Unicode code points by number, only for UTF-16.
  • This looks like UCS-2 code, not UTF-16 code: they use the depreciated charAt interface instead of the codePoint interface, thus promulgating the delusion that a Java char is guaranteed to hold a Unicode character. It’s not. They only get away with this because no UTF-16 surrogate will wind up looking for anything they’re looking for.

The Solution

I wrote a string unescaper which solves the OP’s question without all the irritations of the Apache code.

/*
 *
 * unescape_perl_string()
 *
 *      Tom Christiansen <[email protected]>
 *      Sun Nov 28 12:55:24 MST 2010
 *
 * It's completely ridiculous that there's no standard
 * unescape_java_string function.  Since I have to do the
 * damn thing myself, I might as well make it halfway useful
 * by supporting things Java was too stupid to consider in
 * strings:
 * 
 *   => "?" items  are additions to Java string escapes
 *                 but normal in Java regexes
 *
 *   => "!" items  are also additions to Java regex escapes
 *   
 * Standard singletons: ?\a ?\e \f \n \r \t
 * 
 *      NB: \b is unsupported as backspace so it can pass-through
 *          to the regex translator untouched; I refuse to make anyone
 *          doublebackslash it as doublebackslashing is a Java idiocy
 *          I desperately wish would die out.  There are plenty of
 *          other ways to write it:
 *
 *              \cH, \12, \012, \x08 \x{8}, \u0008, \U00000008
 *
 * Octal escapes: \0 \0N \0NN \N \NN \NNN
 *    Can range up to !\777 not \377
 *    
 *      TODO: add !\o{NNNNN}
 *          last Unicode is 4177777
 *          maxint is 37777777777
 *
 * Control chars: ?\cX
 *      Means: ord(X) ^ ord('@')
 *
 * Old hex escapes: \xXX
 *      unbraced must be 2 xdigits
 *
 * Perl hex escapes: !\x{XXX} braced may be 1-8 xdigits
 *       NB: proper Unicode never needs more than 6, as highest
 *           valid codepoint is 0x10FFFF, not maxint 0xFFFFFFFF
 *
 * Lame Java escape: \[IDIOT JAVA PREPROCESSOR]uXXXX must be
 *                   exactly 4 xdigits;
 *
 *       I can't write XXXX in this comment where it belongs
 *       because the damned Java Preprocessor can't mind its
 *       own business.  Idiots!
 *
 * Lame Python escape: !\UXXXXXXXX must be exactly 8 xdigits
 * 
 * TODO: Perl translation escapes: \Q \U \L \E \[IDIOT JAVA PREPROCESSOR]u \l
 *       These are not so important to cover if you're passing the
 *       result to Pattern.compile(), since it handles them for you
 *       further downstream.  Hm, what about \[IDIOT JAVA PREPROCESSOR]u?
 *
 */

public final static
String unescape_perl_string(String oldstr) {

    /*
     * In contrast to fixing Java's broken regex charclasses,
     * this one need be no bigger, as unescaping shrinks the string
     * here, where in the other one, it grows it.
     */

    StringBuffer newstr = new StringBuffer(oldstr.length());

    boolean saw_backslash = false;

    for (int i = 0; i < oldstr.length(); i++) {
        int cp = oldstr.codePointAt(i);
        if (oldstr.codePointAt(i) > Character.MAX_VALUE) {
            i++; /****WE HATES UTF-16! WE HATES IT FOREVERSES!!!****/
        }

        if (!saw_backslash) {
            if (cp == '\\') {
                saw_backslash = true;
            } else {
                newstr.append(Character.toChars(cp));
            }
            continue; /* switch */
        }

        if (cp == '\\') {
            saw_backslash = false;
            newstr.append('\\');
            newstr.append('\\');
            continue; /* switch */
        }

        switch (cp) {

            case 'r':  newstr.append('\r');
                       break; /* switch */

            case 'n':  newstr.append('\n');
                       break; /* switch */

            case 'f':  newstr.append('\f');
                       break; /* switch */

            /* PASS a \b THROUGH!! */
            case 'b':  newstr.append("\\b");
                       break; /* switch */

            case 't':  newstr.append('\t');
                       break; /* switch */

            case 'a':  newstr.append('\007');
                       break; /* switch */

            case 'e':  newstr.append('\033');
                       break; /* switch */

            /*
             * A "control" character is what you get when you xor its
             * codepoint with '@'==64.  This only makes sense for ASCII,
             * and may not yield a "control" character after all.
             *
             * Strange but true: "\c{" is ";", "\c}" is "=", etc.
             */
            case 'c':   {
                if (++i == oldstr.length()) { die("trailing \\c"); }
                cp = oldstr.codePointAt(i);
                /*
                 * don't need to grok surrogates, as next line blows them up
                 */
                if (cp > 0x7f) { die("expected ASCII after \\c"); }
                newstr.append(Character.toChars(cp ^ 64));
                break; /* switch */
            }

            case '8':
            case '9': die("illegal octal digit");
                      /* NOTREACHED */

    /*
     * may be 0 to 2 octal digits following this one
     * so back up one for fallthrough to next case;
     * unread this digit and fall through to next case.
     */
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7': --i;
                      /* FALLTHROUGH */

            /*
             * Can have 0, 1, or 2 octal digits following a 0
             * this permits larger values than octal 377, up to
             * octal 777.
             */
            case '0': {
                if (i+1 == oldstr.length()) {
                    /* found \0 at end of string */
                    newstr.append(Character.toChars(0));
                    break; /* switch */
                }
                i++;
                int digits = 0;
                int j;
                for (j = 0; j <= 2; j++) {
                    if (i+j == oldstr.length()) {
                        break; /* for */
                    }
                    /* safe because will unread surrogate */
                    int ch = oldstr.charAt(i+j);
                    if (ch < '0' || ch > '7') {
                        break; /* for */
                    }
                    digits++;
                }
                if (digits == 0) {
                    --i;
                    newstr.append('\0');
                    break; /* switch */
                }
                int value = 0;
                try {
                    value = Integer.parseInt(
                                oldstr.substring(i, i+digits), 8);
                } catch (NumberFormatException nfe) {
                    die("invalid octal value for \\0 escape");
                }
                newstr.append(Character.toChars(value));
                i += digits-1;
                break; /* switch */
            } /* end case '0' */

            case 'x':  {
                if (i+2 > oldstr.length()) {
                    die("string too short for \\x escape");
                }
                i++;
                boolean saw_brace = false;
                if (oldstr.charAt(i) == '{') {
                        /* ^^^^^^ ok to ignore surrogates here */
                    i++;
                    saw_brace = true;
                }
                int j;
                for (j = 0; j < 8; j++) {

                    if (!saw_brace && j == 2) {
                        break;  /* for */
                    }

                    /*
                     * ASCII test also catches surrogates
                     */
                    int ch = oldstr.charAt(i+j);
                    if (ch > 127) {
                        die("illegal non-ASCII hex digit in \\x escape");
                    }

                    if (saw_brace && ch == '}') { break; /* for */ }

                    if (! ( (ch >= '0' && ch <= '9')
                                ||
                            (ch >= 'a' && ch <= 'f')
                                ||
                            (ch >= 'A' && ch <= 'F')
                          )
                       )
                    {
                        die(String.format(
                            "illegal hex digit #%d '%c' in \\x", ch, ch));
                    }

                }
                if (j == 0) { die("empty braces in \\x{} escape"); }
                int value = 0;
                try {
                    value = Integer.parseInt(oldstr.substring(i, i+j), 16);
                } catch (NumberFormatException nfe) {
                    die("invalid hex value for \\x escape");
                }
                newstr.append(Character.toChars(value));
                if (saw_brace) { j++; }
                i += j-1;
                break; /* switch */
            }

            case 'u': {
                if (i+4 > oldstr.length()) {
                    die("string too short for \\u escape");
                }
                i++;
                int j;
                for (j = 0; j < 4; j++) {
                    /* this also handles the surrogate issue */
                    if (oldstr.charAt(i+j) > 127) {
                        die("illegal non-ASCII hex digit in \\u escape");
                    }
                }
                int value = 0;
                try {
                    value = Integer.parseInt( oldstr.substring(i, i+j), 16);
                } catch (NumberFormatException nfe) {
                    die("invalid hex value for \\u escape");
                }
                newstr.append(Character.toChars(value));
                i += j-1;
                break; /* switch */
            }

            case 'U': {
                if (i+8 > oldstr.length()) {
                    die("string too short for \\U escape");
                }
                i++;
                int j;
                for (j = 0; j < 8; j++) {
                    /* this also handles the surrogate issue */
                    if (oldstr.charAt(i+j) > 127) {
                        die("illegal non-ASCII hex digit in \\U escape");
                    }
                }
                int value = 0;
                try {
                    value = Integer.parseInt(oldstr.substring(i, i+j), 16);
                } catch (NumberFormatException nfe) {
                    die("invalid hex value for \\U escape");
                }
                newstr.append(Character.toChars(value));
                i += j-1;
                break; /* switch */
            }

            default:   newstr.append('\\');
                       newstr.append(Character.toChars(cp));
           /*
            * say(String.format(
            *       "DEFAULT unrecognized escape %c passed through",
            *       cp));
            */
                       break; /* switch */

        }
        saw_backslash = false;
    }

    /* weird to leave one at the end */
    if (saw_backslash) {
        newstr.append('\\');
    }

    return newstr.toString();
}

/*
 * Return a string "U+XX.XXX.XXXX" etc, where each XX set is the
 * xdigits of the logical Unicode code point. No bloody brain-damaged
 * UTF-16 surrogate crap, just true logical characters.
 */
 public final static
 String uniplus(String s) {
     if (s.length() == 0) {
         return "";
     }
     /* This is just the minimum; sb will grow as needed. */
     StringBuffer sb = new StringBuffer(2 + 3 * s.length());
     sb.append("U+");
     for (int i = 0; i < s.length(); i++) {
         sb.append(String.format("%X", s.codePointAt(i)));
         if (s.codePointAt(i) > Character.MAX_VALUE) {
             i++; /****WE HATES UTF-16! WE HATES IT FOREVERSES!!!****/
         }
         if (i+1 < s.length()) {
             sb.append(".");
         }
     }
     return sb.toString();
 }

private static final
void die(String foa) {
    throw new IllegalArgumentException(foa);
}

private static final
void say(String what) {
    System.out.println(what);
}

If it helps others, you’re welcome to it — no strings attached. If you improve it, I’d love for you to mail me your enhancements, but you certainly don’t have to.

Split data frame string column into multiple columns

Yet another approach: use rbind on out:

before <- data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))  
out <- strsplit(as.character(before$type),'_and_') 
do.call(rbind, out)

     [,1]  [,2]   
[1,] "foo" "bar"  
[2,] "foo" "bar_2"
[3,] "foo" "bar"  
[4,] "foo" "bar_2"

And to combine:

data.frame(before$attr, do.call(rbind, out))

How to delete a file from SD card?

Recursively delete all children of the file ...

public static void DeleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory()) {
        for (File child : fileOrDirectory.listFiles()) {
            DeleteRecursive(child);
        }
    }

    fileOrDirectory.delete();
}

What is the difference between the 'COPY' and 'ADD' commands in a Dockerfile?

Source: https://nickjanetakis.com/blog/docker-tip-2-the-difference-between-copy-and-add-in-a-dockerile:

COPY and ADD are both Dockerfile instructions that serve similar purposes. They let you copy files from a specific location into a Docker image.

COPY takes in a src and destination. It only lets you copy in a local file or directory from your host (the machine building the Docker image) into the Docker image itself.

ADD lets you do that too, but it also supports 2 other sources. First, you can use a URL instead of a local file / directory. Secondly, you can extract a tar file from the source directly into the destination

A valid use case for ADD is when you want to extract a local tar file into a specific directory in your Docker image.

If you’re copying in local files to your Docker image, always use COPY because it’s more explicit.

How do you check that a number is NaN in JavaScript?

Another solution is mentioned in MDN's parseFloat page

It provides a filter function to do strict parsing

var filterFloat = function (value) {
    if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
      .test(value))
      return Number(value);
  return NaN;
}


console.log(filterFloat('421'));               // 421
console.log(filterFloat('-421'));              // -421
console.log(filterFloat('+421'));              // 421
console.log(filterFloat('Infinity'));          // Infinity
console.log(filterFloat('1.61803398875'));     // 1.61803398875
console.log(filterFloat('421e+0'));            // NaN
console.log(filterFloat('421hop'));            // NaN
console.log(filterFloat('hop1.61803398875'));  // NaN

And then you can use isNaN to check if it is NaN

What does the clearfix class do in css?

clearfix is the same as overflow:hidden. Both clear floated children of the parent, but clearfix will not cut off the element which overflow to it's parent. It also works in IE8 & above.

There is no need to define "." in content & .clearfix. Just write like this:

.clr:after {
    clear: both;
    content: "";
    display: block;
}

HTML

<div class="parent clr"></div>

Read these links for more

http://css-tricks.com/snippets/css/clear-fix/,

What methods of ‘clearfix’ can I use?

Display fullscreen mode on Tkinter

This will create a completely fullscreen window on mac (with no visible menubar) without messing up keybindings

import tkinter as tk
root = tk.Tk()

root.overrideredirect(True)
root.overrideredirect(False)
root.attributes('-fullscreen',True)


root.mainloop()

C# string replace

var str = "Text\",\"Text\",\"Text";
var newstr = str.Replace("\",\"", ";");

Clear text field value in JQuery

doc_val_check == "";   // == is equality check operator

should be

doc_val_check = "";    // = is assign operator. you need to set empty value

                       // so you need =

You can write you full code like this:

var doc_val_check = $.trim( $('#doc_title').val() ); // take value of text 
                                                     // field using .val()
    if (doc_val_check.length) {
        doc_val_check = ""; // this will not update your text field
    }

To update you text field with a "" you need to try

$('#doc_title').attr('value', doc_val_check); 
// or 
$('doc_title').val(doc_val_check);

But I think you don't need above process.


In short, just one line

$('#doc_title').val("");

Note

.val() use to set/ get value in text field. With parameter it acts as setter and without parameter acts as getter.

Read more about .val()

How to disable mouse scroll wheel scaling with Google Maps API

I created a more developed jQuery plugin that allows you to lock or unlock the map with a nice button.

This plugin disables the Google Maps iframe with a transparent overlay div and adds a button for unlockit. You must press for 650 milliseconds to unlock it.

You can change all the options for your convenience. Check it at https://github.com/diazemiliano/googlemaps-scrollprevent

Here's some example.

_x000D_
_x000D_
(function() {_x000D_
  $(function() {_x000D_
    $("#btn-start").click(function() {_x000D_
      $("iframe[src*='google.com/maps']").scrollprevent({_x000D_
        printLog: true_x000D_
      }).start();_x000D_
      return $("#btn-stop").click(function() {_x000D_
        return $("iframe[src*='google.com/maps']").scrollprevent().stop();_x000D_
      });_x000D_
    });_x000D_
    return $("#btn-start").trigger("click");_x000D_
  });_x000D_
}).call(this);
_x000D_
.embed-container {_x000D_
  position: relative !important;_x000D_
  padding-bottom: 56.25% !important;_x000D_
  height: 0 !important;_x000D_
  overflow: hidden !important;_x000D_
  max-width: 100% !important;_x000D_
}_x000D_
.embed-container iframe {_x000D_
  position: absolute !important;_x000D_
  top: 0 !important;_x000D_
  left: 0 !important;_x000D_
  width: 100% !important;_x000D_
  height: 100% !important;_x000D_
}_x000D_
.mapscroll-wrap {_x000D_
  position: static !important;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.rawgit.com/diazemiliano/googlemaps-scrollprevent/v.0.6.5/dist/googlemaps-scrollprevent.min.js"></script>_x000D_
<div class="embed-container">_x000D_
  <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d12087.746318586604!2d-71.64614110000001!3d-40.76341959999999!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x9610bf42e48faa93%3A0x205ebc786470b636!2sVilla+la+Angostura%2C+Neuqu%C3%A9n!5e0!3m2!1ses-419!2sar!4v1425058155802"_x000D_
  width="400" height="300" frameborder="0" style="border:0"></iframe>_x000D_
</div>_x000D_
<p><a id="btn-start" href="#">"Start Scroll Prevent"</a>  <a id="btn-stop" href="#">"Stop Scroll Prevent"</a>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Process list on Linux via Python

The sanctioned way of creating and using child processes is through the subprocess module.

import subprocess
pl = subprocess.Popen(['ps', '-U', '0'], stdout=subprocess.PIPE).communicate()[0]
print pl

The command is broken down into a python list of arguments so that it does not need to be run in a shell (By default the subprocess.Popen does not use any kind of a shell environment it just execs it). Because of this we cant simply supply 'ps -U 0' to Popen.

What's causing my java.net.SocketException: Connection reset?

I did also stumble upon this error. In my case the problem was I was using JRE6, with support for TLS1.0. The server only supported TLS1.2, so this error was thrown.

jQuery get an element by its data-id

Yes, you can find out element by data attribute.

element = $('a[data-item-id="stand-out"]');

HTML tag <a> want to add both href and onclick working

You already have what you need, with a minor syntax change:

<a href="www.mysite.com" onclick="return theFunction();">Item</a>

<script type="text/javascript">
    function theFunction () {
        // return true or false, depending on whether you want to allow the `href` property to follow through or not
    }
</script>

The default behavior of the <a> tag's onclick and href properties is to execute the onclick, then follow the href as long as the onclick doesn't return false, canceling the event (or the event hasn't been prevented)

How do I detect when someone shakes an iPhone?

Add Following methods in ViewController.m file, its working properly

    -(BOOL) canBecomeFirstResponder
    {
         /* Here, We want our view (not viewcontroller) as first responder 
         to receive shake event message  */

         return YES;
    }

    -(void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
    {
            if(event.subtype==UIEventSubtypeMotionShake)
            {
                    // Code at shake event

                    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Motion" message:@"Phone Vibrate"delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
                    [alert show];
                    [alert release];

                    [self.view setBackgroundColor:[UIColor redColor]];
             }
    }
    - (void)viewDidAppear:(BOOL)animated
    {
             [super viewDidAppear:animated];
             [self becomeFirstResponder];  // View as first responder 
     }

How to make the web page height to fit screen height

As another guy described here, all you need to do is add

height: 100vh;

to the style of whatever you need to fill the screen

List to array conversion to use ravel() function

Use numpy.asarray:

import numpy as np
myarray = np.asarray(mylist)

Java ArrayList Index

Here is how I would write it.

String[] fruit = "apple banana orange".split(" ");
System.out.println(fruit[1]);

java.nio.file.Path for a classpath resource

You can not create URI from resources inside of the jar file. You can simply write it to the temp file and then use it (java8):

Path path = File.createTempFile("some", "address").toPath();
Files.copy(ClassLoader.getSystemResourceAsStream("/path/to/resource"), path, StandardCopyOption.REPLACE_EXISTING);

html cellpadding the left side of a cell

I recently had to do this to create half decent looking emails for an email client that did not support the CSS necessary. For an HTML only solution I use a wrapping table to provide the padding.

_x000D_
_x000D_
<table border="1" cellspacing="0" cellpadding="0">_x000D_
    <tr><td height="5" colspan="3"></td></tr>_x000D_
    <tr>_x000D_
        <td width="5"></td>_x000D_
        <td>_x000D_
            This cells padding matches what you want._x000D_
            <ul>_x000D_
                <li>5px Left, Top, Bottom padding</li>_x000D_
                <li>10px on the right</li>_x000D_
            </ul>    _x000D_
            You can then put your table inside this_x000D_
            cell with no spacing or padding set.                    _x000D_
        </td>_x000D_
        <td width="10"></td>_x000D_
    </tr>_x000D_
    <tr><td height="5" colspan="3"></td></tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

As of 2017 you would only do this for old email client support, it's pretty overkill.

Create a Path from String in Java7

You can just use the Paths class:

Path path = Paths.get(textPath);

... assuming you want to use the default file system, of course.

Update multiple columns in SQL

Try this:

UPDATE table1 
SET a = t2.a, b = t2.b, .......
FROM table2 t2
WHERE table1.id = t2.id

That should work in most SQL dialects, excluding Oracle.

And yes - it's a lot of typing - it's the way SQL does this.

How to add a fragment to a programmatically generated layout?

At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml. This is just a suggestion of mine and probably one of many solutions, but it works: Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.

It could look like this:

LinearLayout rowLayout = new LinearLayout();
rowLayout.setId(whateveryouwantasid);
// add rowLayout to the root layout somewhere here

FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();   

Fragment myFrag = new ImageFragment();
fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
fragTransaction.commit();

Simply choose whatever Integer value you want for the ID:

rowLayout.setId(12345);

If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.

UPDATE:

Here is the full code of how it should be done: (this code is tested and works) I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".

MainActivity.java:

public class MainActivity extends Activity {

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

        LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);

        ll.setId(12345);

        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

        fragContainer.addView(ll);
    }
}

TestFragment.java:

public class TestFragment extends Fragment {

    public static TestFragment newInstance(String text) {

        TestFragment f = new TestFragment();

        Bundle b = new Bundle();
        b.putString("text", text);
        f.setArguments(b);
        return f;
    }

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

        View v =  inflater.inflate(R.layout.fragment, container, false);

        ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));     
        return v;
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <LinearLayout
        android:id="@+id/llFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="19dp"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

fragment.xml:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="200dp" >

    <TextView
        android:id="@+id/tvFragText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</RelativeLayout>

And this is the result of the above code: (the two Fragments are aligned next to each other) result

scrollTop animation without jquery

HTML:

<button onclick="scrollToTop(1000);"></button>

1# JavaScript (linear):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const totalScrollDistance = document.scrollingElement.scrollTop;
    let scrollY = totalScrollDistance, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollY will be -Infinity
            scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
            if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = scrollY;
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

2# JavaScript (ease in and out):

function scrollToTop (duration) {
    // cancel if already on top
    if (document.scrollingElement.scrollTop === 0) return;

    const cosParameter = document.scrollingElement.scrollTop / 2;
    let scrollCount = 0, oldTimestamp = null;

    function step (newTimestamp) {
        if (oldTimestamp !== null) {
            // if duration is 0 scrollCount will be Infinity
            scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
            if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
            document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
        }
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
  Explanation:
  - pi is the length/end point of the cosinus intervall (see below)
  - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
    (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
  - newTimestamp - oldTimestamp equals the delta time

    a * cos (bx + c) + d                        | c translates along the x axis = 0
  = a * cos (bx) + d                            | d translates along the y axis = 1 -> only positive y values
  = a * cos (bx) + 1                            | a stretches along the y axis = cosParameter = window.scrollY / 2
  = cosParameter + cosParameter * (cos bx)  | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
  = cosParameter + cosParameter * (cos scrollCount * x)
*/

Note:

  • Duration in milliseconds (1000ms = 1s)
  • Second script uses the cos function. Example curve:

enter image description here

3# Simple scrolling library on Github

How do I convert an Array to a List<object> in C#?

another way

List<YourClass> list = (arrayList.ToArray() as YourClass[]).ToList();

Single vs Double quotes (' vs ")

Actually, the best way is the way Google recommends. Double quotes: https://google.github.io/styleguide/htmlcssguide.xml?showone=HTML_Quotation_Marks#HTML_Quotation_Marks

See https://google.github.io/styleguide/htmlcssguide.xml?showone=HTML_Validity#HTML_Validity Quoted Advice from Google: "Using valid HTML is a measurable baseline quality attribute that contributes to learning about technical requirements and constraints, and that ensures proper HTML usage."

ViewDidAppear is not called when opening app from background

As per Apple's documentation:

(void)beginAppearanceTransition:(BOOL)isAppearing animated:(BOOL)animated;

Description:
Tells a child controller its appearance is about to change. If you are implementing a custom container controller, use this method to tell the child that its views are about to appear or disappear. Do not invoke viewWillAppear:, viewWillDisappear:, viewDidAppear:, or viewDidDisappear: directly.

(void)endAppearanceTransition;

Description:

Tells a child controller its appearance has changed. If you are implementing a custom container controller, use this method to tell the child that the view transition is complete.

Sample code:

(void)applicationDidEnterBackground:(UIApplication *)application
{

    [self.window.rootViewController beginAppearanceTransition: NO animated: NO];  // I commented this line

    [self.window.rootViewController endAppearanceTransition]; // I commented this line

}

Question: How I fixed?

Ans: I found this piece of lines in application. This lines made my app not recieving any ViewWillAppear notification's. When I commented these lines it's working fine.

How can I override the OnBeforeUnload dialog and replace it with my own?

While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.

I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/

$(':input').change(function() {
    if(!is_dirty){
        // When the user changes a field on this page, set our is_dirty flag.
        is_dirty = true;
    }
});

$('a').mousedown(function(e) {
    if(is_dirty) {
        // if the user navigates away from this page via an anchor link, 
        //    popup a new boxy confirmation.
        answer = Boxy.confirm("You have made some changes which you might want to save.");
    }
});

window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
            // call this if the box wasn't shown.
    return 'You have made some changes which you might want to save.';
    }
};

You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.

I have cut out code, so this may not work as is.

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.