Programs & Examples On #P np

Used for questions about the P versus NP problem.

What's "P=NP?", and why is it such a famous question?

To give the simplest answer I can think of:

Suppose we have a problem that takes a certain number of inputs, and has various potential solutions, which may or may not solve the problem for given inputs. A logic puzzle in a puzzle magazine would be a good example: the inputs are the conditions ("George doesn't live in the blue or green house"), and the potential solution is a list of statements ("George lives in the yellow house, grows peas, and owns the dog"). A famous example is the Traveling Salesman problem: given a list of cities, and the times to get from any city to any other, and a time limit, a potential solution would be a list of cities in the order the salesman visits them, and it would work if the sum of the travel times was less than the time limit.

Such a problem is in NP if we can efficiently check a potential solution to see if it works. For example, given a list of cities for the salesman to visit in order, we can add up the times for each trip between cities, and easily see if it's under the time limit. A problem is in P if we can efficiently find a solution if one exists.

(Efficiently, here, has a precise mathematical meaning. Practically, it means that large problems aren't unreasonably difficult to solve. When searching for a possible solution, an inefficient way would be to list all possible potential solutions, or something close to that, while an efficient way would require searching a much more limited set.)

Therefore, the P=NP problem can be expressed this way: If you can verify a solution for a problem of the sort described above efficiently, can you find a solution (or prove there is none) efficiently? The obvious answer is "Why should you be able to?", and that's pretty much where the matter stands today. Nobody has been able to prove it one way or another, and that bothers a lot of mathematicians and computer scientists. That's why anybody who can prove the solution is up for a million dollars from the Claypool Foundation.

We generally assume that P does not equal NP, that there is no general way to find solutions. If it turned out that P=NP, a lot of things would change. For example, cryptography would become impossible, and with it any sort of privacy or verifiability on the Internet. After all, we can efficiently take the encrypted text and the key and produce the original text, so if P=NP we could efficiently find the key without knowing it beforehand. Password cracking would become trivial. On the other hand, there's whole classes of planning problems and resource allocation problems that we could solve effectively.

You may have heard the description NP-complete. An NP-complete problem is one that is NP (of course), and has this interesting property: if it is in P, every NP problem is, and so P=NP. If you could find a way to efficiently solve the Traveling Salesman problem, or logic puzzles from puzzle magazines, you could efficiently solve anything in NP. An NP-complete problem is, in a way, the hardest sort of NP problem.

So, if you can find an efficient general solution technique for any NP-complete problem, or prove that no such exists, fame and fortune are yours.

Fastest way to flatten / un-flatten nested JSON objects

Here's another approach that runs slower (about 1000ms) than the above answer, but has an interesting idea :-)

Instead of iterating through each property chain, it just picks the last property and uses a look-up-table for the rest to store the intermediate results. This look-up-table will be iterated until there are no property chains left and all values reside on uncocatenated properties.

JSON.unflatten = function(data) {
    "use strict";
    if (Object(data) !== data || Array.isArray(data))
        return data;
    var regex = /\.?([^.\[\]]+)$|\[(\d+)\]$/,
        props = Object.keys(data),
        result, p;
    while(p = props.shift()) {
        var m = regex.exec(p),
            target;
        if (m.index) {
            var rest = p.slice(0, m.index);
            if (!(rest in data)) {
                data[rest] = m[2] ? [] : {};
                props.push(rest);
            }
            target = data[rest];
        } else {
            target = result || (result = (m[2] ? [] : {}));
        }
        target[m[2] || m[1]] = data[p];
    }
    return result;
};

It currently uses the data input parameter for the table, and puts lots of properties on it - a non-destructive version should be possible as well. Maybe a clever lastIndexOf usage performs better than the regex (depends on the regex engine).

See it in action here.

What is the difference between a generative and a discriminative algorithm?

Let's say you have input data x and you want to classify the data into labels y. A generative model learns the joint probability distribution p(x,y) and a discriminative model learns the conditional probability distribution p(y|x) - which you should read as "the probability of y given x".

Here's a really simple example. Suppose you have the following data in the form (x,y):

(1,0), (1,0), (2,0), (2, 1)

p(x,y) is

      y=0   y=1
     -----------
x=1 | 1/2   0
x=2 | 1/4   1/4

p(y|x) is

      y=0   y=1
     -----------
x=1 | 1     0
x=2 | 1/2   1/2

If you take a few minutes to stare at those two matrices, you will understand the difference between the two probability distributions.

The distribution p(y|x) is the natural distribution for classifying a given example x into a class y, which is why algorithms that model this directly are called discriminative algorithms. Generative algorithms model p(x,y), which can be transformed into p(y|x) by applying Bayes rule and then used for classification. However, the distribution p(x,y) can also be used for other purposes. For example, you could use p(x,y) to generate likely (x,y) pairs.

From the description above, you might be thinking that generative models are more generally useful and therefore better, but it's not as simple as that. This paper is a very popular reference on the subject of discriminative vs. generative classifiers, but it's pretty heavy going. The overall gist is that discriminative models generally outperform generative models in classification tasks.

How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?

As weird as this may sound, one work around is to reduce the amount of memory allocated to the JVM. Since fork() duplicates the process and its memory, if your JVM process does not really need as much memory as is allocated via -Xmx, the memory allocation to git will work.

Of course you can try other solutions mentioned here (like over-committing or upgrading to a JVM that has the fix). You can try reducing the memory if you are desperate for a solution that keeps all software intact with no environment impact. Also keep in mind that reducing -Xmx aggressively can cause OOMs. I'd recommend upgrading the JDK as a long-term stable solution.

Unable to copy a file from obj\Debug to bin\Debug

Solution1:

  1. Close the project.
  2. Delete the bin folder.
  3. Open the project.
  4. Build the project.

Solution2:

Add the following code in pre-build event:

attrib -r $(OutDir)*..\* /s

This command line code will remove the ready-only attribute of "bin" folder. Now visual studio can easily delete and copy new dlls.

ORACLE: Updating multiple columns at once

I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.

this is a generic example let me know if this explains the point i mentioned

CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
IS
    empName VARCHAR2(50);
    empSalary NUMBER(7,2);      
BEGIN
    UPDATE emp
    SET sal = sal + 1000
    WHERE empno = 7499
    RETURNING ename, sal
    INTO empName, empSalary;

    DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
    DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
END;

Make elasticsearch only return certain fields?

There are several methods that can be useful to achieve field-specific results. One can be through the source method. And another method that can also be useful to receive cleaner and more summarized answers according to our interests is filter_path:

Document Json:

"hits" : [
  {
    "_index" : "xxxxxx",
    "_type" : "_doc",
    "_id" : "xxxxxx",
    "_score" : xxxxxx,
    "_source" : {
      "year" : 2020,
      "created_at" : "2020-01-29",
      "url" : "www.github.com/mbarr0987",
      "name":"github"
    }
  }

Query:

GET bot1/_search?filter_path=hits.hits._source.url
{
  "query": {
    "bool": {
      "must": [
        {"term": {"name.keyword":"github" }}
       ]
    }
  }
}

Output:

{
  "hits" : {
    "hits" : [
      {
        "_source" : {
          "url" : "www.github.com/mbarr0987"
            }
          }
      ]
   }
}

How do I count occurrence of duplicate items in array

this code will return duplicate value in same array

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
foreach($arr as $key=>$item){
  if(array_count_values($arr)[$item] > 1){
     echo "Found Matched value : ".$item." <br />";
  }
}

How do you do Impersonation in .NET?

Here's my vb.net port of Matt Johnson's answer. I added an enum for the logon types. LOGON32_LOGON_INTERACTIVE was the first enum value that worked for sql server. My connection string was just trusted. No user name / password in the connection string.

  <PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
  Public Class Impersonation
    Implements IDisposable

    Public Enum LogonTypes
      ''' <summary>
      ''' This logon type is intended for users who will be interactively using the computer, such as a user being logged on  
      ''' by a terminal server, remote shell, or similar process.
      ''' This logon type has the additional expense of caching logon information for disconnected operations; 
      ''' therefore, it is inappropriate for some client/server applications,
      ''' such as a mail server.
      ''' </summary>
      LOGON32_LOGON_INTERACTIVE = 2

      ''' <summary>
      ''' This logon type is intended for high performance servers to authenticate plaintext passwords.
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_NETWORK = 3

      ''' <summary>
      ''' This logon type is intended for batch servers, where processes may be executing on behalf of a user without 
      ''' their direct intervention. This type is also for higher performance servers that process many plaintext
      ''' authentication attempts at a time, such as mail or Web servers. 
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_BATCH = 4

      ''' <summary>
      ''' Indicates a service-type logon. The account provided must have the service privilege enabled. 
      ''' </summary>
      LOGON32_LOGON_SERVICE = 5

      ''' <summary>
      ''' This logon type is for GINA DLLs that log on users who will be interactively using the computer. 
      ''' This logon type can generate a unique audit record that shows when the workstation was unlocked. 
      ''' </summary>
      LOGON32_LOGON_UNLOCK = 7

      ''' <summary>
      ''' This logon type preserves the name and password in the authentication package, which allows the server to make 
      ''' connections to other network servers while impersonating the client. A server can accept plaintext credentials 
      ''' from a client, call LogonUser, verify that the user can access the system across the network, and still 
      ''' communicate with other servers.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NETWORK_CLEARTEXT = 8

      ''' <summary>
      ''' This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
      ''' The new logon session has the same local identifier but uses different credentials for other network connections. 
      ''' NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NEW_CREDENTIALS = 9
    End Enum

    <DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function LogonUser(lpszUsername As [String], lpszDomain As [String], lpszPassword As [String], dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As SafeTokenHandle) As Boolean
    End Function

    Public Sub New(Domain As String, UserName As String, Password As String, Optional LogonType As LogonTypes = LogonTypes.LOGON32_LOGON_INTERACTIVE)
      Dim ok = LogonUser(UserName, Domain, Password, LogonType, 0, _SafeTokenHandle)
      If Not ok Then
        Dim errorCode = Marshal.GetLastWin32Error()
        Throw New ApplicationException(String.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode))
      End If

      WindowsImpersonationContext = WindowsIdentity.Impersonate(_SafeTokenHandle.DangerousGetHandle())
    End Sub

    Private ReadOnly _SafeTokenHandle As New SafeTokenHandle
    Private ReadOnly WindowsImpersonationContext As WindowsImpersonationContext

    Public Sub Dispose() Implements System.IDisposable.Dispose
      Me.WindowsImpersonationContext.Dispose()
      Me._SafeTokenHandle.Dispose()
    End Sub

    Public NotInheritable Class SafeTokenHandle
      Inherits SafeHandleZeroOrMinusOneIsInvalid

      <DllImport("kernel32.dll")> _
      <ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)> _
      <SuppressUnmanagedCodeSecurity()> _
      Private Shared Function CloseHandle(handle As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
      End Function

      Public Sub New()
        MyBase.New(True)
      End Sub

      Protected Overrides Function ReleaseHandle() As Boolean
        Return CloseHandle(handle)
      End Function
    End Class

  End Class

You need to Use with a Using statement to contain some code to run impersonated.

How to count rows with SELECT COUNT(*) with SQLAlchemy?

Query for just a single known column:

session.query(MyTable.col1).count()

percentage of two int?

Two options:

Do the division after the multiplication:

int n = 25;
int v = 100;
int percent = n * 100 / v;

Convert an int to a float before dividing

int n = 25;
int v = 100;
float percent = n * 100f / v;
//Or:
//  float percent = (float) n * 100 / v;
//  float percent = n * 100 / (float) v;

How to increase scrollback buffer size in tmux?

This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.

tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000

This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.

I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:

#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

ReactJS - Add custom event listener to component

I recommend using React.createRef() and ref=this.elementRef to get the DOM element reference instead of ReactDOM.findDOMNode(this). This way you can get the reference to the DOM element as an instance variable.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class MenuItem extends Component {

  constructor(props) {
    super(props);

    this.elementRef = React.createRef();
  }

  handleNVFocus = event => {
      console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
  }
    
  componentDidMount() {
    this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
  }

  componentWillUnmount() {
    this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
  }

  render() {
    return (
      <element ref={this.elementRef} />
    )
  }

}

export default MenuItem;

Most efficient way to find smallest of 3 numbers Java?

For those who find this topic much later:

If you have just three values to compare there is no significant difference. But if you have to find min of, say, thirty or sixty values, "min" could be easier for anyone to read in the code next year:

int smallest;

smallest = min(a1, a2);
smallest = min(smallest, a3);
smallest = min(smallest, a4);
...
smallest = min(smallest, a37);

But if you think of speed, maybe better way would be to put values into list, and then find min of that:

List<Integer> mySet = Arrays.asList(a1, a2, a3, ..., a37);

int smallest = Collections.min(mySet);

Would you agree?

jquery $(window).height() is returning the document height

Here's a question and answer for this: Difference between screen.availHeight and window.height()

Has pics too, so you can actually see the differences. Hope this helps.

Basically, $(window).height() give you the maximum height inside of the browser window (viewport), and$(document).height() gives you the height of the document inside of the browser. Most of the time, they will be exactly the same, even with scrollbars.

Get the Highlighted/Selected text

This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:

window.getSelection().anchorNode.textContent.substring(
  window.getSelection().extentOffset, 
  window.getSelection().anchorOffset)

How to use DISTINCT and ORDER BY in same SELECT statement?

By subquery, it should work:

    SELECT distinct(Category) from MonitoringJob  where Category in(select Category from MonitoringJob order by CreationDate desc);

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

Getting mouse position in c#

If you need to get current position in form's area(got experimentally), try:

Console.WriteLine("Current mouse position in form's area is " + 
    (Control.MousePosition.X - this.Location.X - 8).ToString() +
    "x" + 
    (Control.MousePosition.Y - this.Location.Y - 30).ToString()
);

Although, 8 and 30 integers were found by experimenting.

Would be awesome if someone could explain why exactly these numbers ^.


Also, there's another variant(considering code is in Form's CodeBehind):

Point cp = PointToClient(Cursor.Position); // Getting a cursor's position according form's area
Console.WriteLine("Cursor position: X = " + cp.X + ", Y = " + cp.Y);

Confirm password validation in Angular 6

In case you have more than just Password and Verify Password fields. Like this the Confirm password field will only highlights error when user write something on this field:

validators.ts

import { FormGroup, FormControl, Validators, FormBuilder, FormGroupDirective, NgForm } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';

export const EmailValidation = [Validators.required, Validators.email];
export const PasswordValidation = [
  Validators.required,
  Validators.minLength(6),
  Validators.maxLength(24),
];

export class RepeatPasswordEStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return (control && control.parent.get('password').value !== control.parent.get('passwordAgain').value && control.dirty)
  }
}
export function RepeatPasswordValidator(group: FormGroup) {
  const password = group.controls.password.value;
  const passwordConfirmation = group.controls.passwordAgain.value;

  return password === passwordConfirmation ? null : { passwordsNotEqual: true }     
}

register.component.ts

import { FormGroup, FormControl, Validators, FormBuilder} from '@angular/forms';
import { EmailValidation, PasswordValidation, RepeatPasswordEStateMatcher, RepeatPasswordValidator } from 'validators';

...

form: any;
passwordsMatcher = new RepeatPasswordEStateMatcher;


constructor(private formBuilder: FormBuilder) {
    this.form = this.formBuilder.group ( {
      email: new FormControl('', EmailValidation),
      password: new FormControl('', PasswordValidation),
      passwordAgain: new FormControl(''),
      acceptTerms: new FormControl('', [Validators.requiredTrue])
    }, { validator: RepeatPasswordValidator });
  }

...

register.component.html

<form [formGroup]="form" (ngSubmit)="submitAccount(form)">
    <div class="form-content">
        <div class="form-field">
            <mat-form-field>
            <input matInput formControlName="email" placeholder="Email">
            <mat-error *ngIf="form.get('email').hasError('required')">
                E-mail is mandatory.
            </mat-error>
            <mat-error *ngIf="form.get('email').hasError('email')">
                Incorrect E-mail.
            </mat-error>
            </mat-form-field>
        </div>
        <div class="form-field">
            <mat-form-field>
            <input matInput formControlName="password" placeholder="Password" type="password">
            <mat-hint class="ac-form-field-description">Between 6 and 24 characters.</mat-hint>
            <mat-error *ngIf="form.get('password').hasError('required')">
                Password is mandatory.
            </mat-error>
            <mat-error *ngIf="form.get('password').hasError('minlength')">
                Password with less than 6 characters.
            </mat-error>
            <mat-error *ngIf="form.get('password').hasError('maxlength')">
                Password with more than 24 characters.
            </mat-error>
            </mat-form-field>
        </div>
        <div class="form-field">
            <mat-form-field>
            <input matInput formControlName="passwordAgain" placeholder="Confirm the password" type="password" [errorStateMatcher]="passwordsMatcher">
            <mat-error *ngIf="form.hasError('passwordsNotEqual')" >Passwords are different. They should be equal!</mat-error>
            </mat-form-field>
        </div>
        <div class="form-field">
            <mat-checkbox name="acceptTerms" formControlName="acceptTerms">I accept terms and conditions</mat-checkbox>
        </div>
    </div>
    <div class="form-bottom">
        <button mat-raised-button [disabled]="!form.valid">Create Account</button>
    </div>
</form>

i hope it helps!

Javascript: How to check if a string is empty?

This should work:

if (variable === "") {

}

PowerShell Script to Find and Replace for all Files with a Specific Extension

PowerShell is a good choice ;) It is very easy to enumerate files in given directory, read them and process.

The script could look like this:

Get-ChildItem C:\Projects *.config -recurse |
    Foreach-Object {
        $c = ($_ | Get-Content) 
        $c = $c -replace '<add key="Environment" value="Dev"/>','<add key="Environment" value="Demo"/>'
        [IO.File]::WriteAllText($_.FullName, ($c -join "`r`n"))
    }

I split the code to more lines to be readable for you. Note that you could use Set-Content instead of [IO.File]::WriteAllText, but it adds new line at the end. With WriteAllText you can avoid it.

Otherwise the code could look like this: $c | Set-Content $_.FullName.

When are static variables initialized?

The order of initialization is:

  1. Static initialization blocks
  2. Instance initialization blocks
  3. Constructors

The details of the process are explained in the JVM specification document.

Setting transparent images background in IrfanView

If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").

Draw in Canvas by finger, Android

I think it's important to add a thing, if you use the layout inflation that constructor in the drawview is not correct, add these constructors in the class:

public DrawingView(Context c, AttributeSet attrs) {
    super(c, attrs);
    ...
}

public DrawingView(Context c, AttributeSet attrs, int defStyle) {
    super(c, attrs, defStyle);
    ...
}

or the android system fails to inflate the layout file. I hope this could to help.

Invoke a second script with arguments from a script

Much simpler actually:

Method 1:

Invoke-Expression $scriptPath $argumentList

Method 2:

& $scriptPath $argumentList

Method 3:

$scriptPath $argumentList

If you have spaces in your scriptPath, don't forget to escape them `"$scriptPath`"

Android SDK is missing, out of date, or is missing templates. Please ensure you are using SDK version 22 or later

I was able to trigger an SDK download like this:

  1. Close Android Studio
  2. Open android studio, but be ready
  3. Once you see "loading project", click cancel. (this will only appear for seconds on a fast machine)
  4. The SDK download window appeared!

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

to hide the horizontal scrollbars, you can set overflow-x to hidden, like this:

overflow-x: hidden;

Python function overloading

Either use multiple keyword arguments in the definition, or create a Bullet hierarchy whose instances are passed to the function.

Unfortunately Launcher3 has stopped working error in android studio?

May 2017; I had the same issue, could not even get to apps as it just cycled between starting and stopping. Went into avd settings, edited the multi core (unticked the box) and set graphics to software Gles. It appears to have fixed the issue

HTML table with 100% width, with vertical scroll inside tbody

In order to make <tbody> element scrollable, we need to change the way it's displayed on the page i.e. using display: block; to display that as a block level element.

Since we change the display property of tbody, we should change that property for thead element as well to prevent from breaking the table layout.

So we have:

thead, tbody { display: block; }

tbody {
    height: 100px;       /* Just for the demo          */
    overflow-y: auto;    /* Trigger vertical scroll    */
    overflow-x: hidden;  /* Hide the horizontal scroll */
}

Web browsers display the thead and tbody elements as row-group (table-header-group and table-row-group) by default.

Once we change that, the inside tr elements doesn't fill the entire space of their container.

In order to fix that, we have to calculate the width of tbody columns and apply the corresponding value to the thead columns via JavaScript.

Auto Width Columns

Here is the jQuery version of above logic:

// Change the selector if needed
var $table = $('table'),
    $bodyCells = $table.find('tbody tr:first').children(),
    colWidth;

// Get the tbody columns width array
colWidth = $bodyCells.map(function() {
    return $(this).width();
}).get();

// Set the width of thead columns
$table.find('thead tr').children().each(function(i, v) {
    $(v).width(colWidth[i]);
});    

And here is the output (on Windows 7 Chrome 32):

vertical scroll inside tbody

WORKING DEMO.

Full Width Table, Relative Width Columns

As the Original Poster needed, we could expand the table to 100% of width of its container, and then using a relative (Percentage) width for each columns of the table.

table {
    width: 100%; /* Optional */
}

tbody td, thead th {
    width: 20%;  /* Optional */
}

Since the table has a (sort of) fluid layout, we should adjust the width of thead columns when the container resizes.

Hence we should set the columns' widths once the window is resized:

// Adjust the width of thead cells when *window* resizes
$(window).resize(function() {
    /* Same as before */ 
}).resize(); // Trigger the resize handler once the script runs

The output would be:

Fluid Table with vertical scroll inside tbody

WORKING DEMO.


Browser Support and Alternatives

I've tested the two above methods on Windows 7 via the new versions of major Web Browsers (including IE10+) and it worked.

However, it doesn't work properly on IE9 and below.

That's because in a table layout, all elements should follow the same structural properties.

By using display: block; for the <thead> and <tbody> elements, we've broken the table structure.

Redesign layout via JavaScript

One approach is to redesign the (entire) table layout. Using JavaScript to create a new layout on the fly and handle and/or adjust the widths/heights of the cells dynamically.

For instance, take a look at the following examples:

Nesting tables

This approach uses two nested tables with a containing div. The first table has only one cell which has a div, and the second table is placed inside that div element.

Check the Vertical scrolling tables at CSS Play.

This works on most of web browsers. We can also do the above logic dynamically via JavaScript.

Table with fixed header on scroll

Since the purpose of adding vertical scroll bar to the <tbody> is displaying the table header at the top of each row, we could position the thead element to stay fixed at the top of the screen instead.

Here is a Working Demo of this approach performed by Julien.
It has a promising web browser support.

And here a pure CSS implementation by Willem Van Bockstal.


The Pure CSS Solution

Here is the old answer. Of course I've added a new method and refined the CSS declarations.

Table with Fixed Width

In this case, the table should have a fixed width (including the sum of columns' widths and the width of vertical scroll-bar).

Each column should have a specific width and the last column of thead element needs a greater width which equals to the others' width + the width of vertical scroll-bar.

Therefore, the CSS would be:

table {
    width: 716px; /* 140px * 5 column + 16px scrollbar width */
    border-spacing: 0;
}

tbody, thead tr { display: block; }

tbody {
    height: 100px;
    overflow-y: auto;
    overflow-x: hidden;
}

tbody td, thead th {
    width: 140px;
}

thead th:last-child {
    width: 156px; /* 140px + 16px scrollbar width */
}

Here is the output:

Table with Fixed Width

WORKING DEMO.

Table with 100% Width

In this approach, the table has a width of 100% and for each th and td, the value of width property should be less than 100% / number of cols.

Also, we need to reduce the width of thead as value of the width of vertical scroll-bar.

In order to do that, we need to use CSS3 calc() function, as follows:

table {
    width: 100%;
    border-spacing: 0;
}

thead, tbody, tr, th, td { display: block; }

thead tr {
    /* fallback */
    width: 97%;
    /* minus scroll bar width */
    width: -webkit-calc(100% - 16px);
    width:    -moz-calc(100% - 16px);
    width:         calc(100% - 16px);
}

tr:after {  /* clearing float */
    content: ' ';
    display: block;
    visibility: hidden;
    clear: both;
}

tbody {
    height: 100px;
    overflow-y: auto;
    overflow-x: hidden;
}

tbody td, thead th {
    width: 19%;  /* 19% is less than (100% / 5 cols) = 20% */
    float: left;
}

Here is the Online Demo.

Note: This approach will fail if the content of each column breaks the line, i.e. the content of each cell should be short enough.


In the following, there are two simple example of pure CSS solution which I created at the time I answered this question.

Here is the jsFiddle Demo v2.

Old version: jsFiddle Demo v1

HTML/CSS: how to put text both right and left aligned in a paragraph

Least amount of markup possible (you only need one span):

<p>This text is left. <span>This text is right.</span></p>

How you want to achieve the left/right styles is up to you, but I would recommend an external style on an ID or a class.

The full HTML:

<p class="split-para">This text is left. <span>This text is right.</span></p>

And the CSS:

.split-para      { display:block;margin:10px;}
.split-para span { display:block;float:right;width:50%;margin-left:10px;}

How to detect pressing Enter on keyboard using jQuery?

$(document).keyup(function(e) {
    if(e.key === 'Enter') {
        //Do the stuff
    }
});

Time complexity of Euclid's Algorithm

At every step, there are two cases

b >= a / 2, then a, b = b, a % b will make b at most half of its previous value

b < a / 2, then a, b = b, a % b will make a at most half of its previous value, since b is less than a / 2

So at every step, the algorithm will reduce at least one number to at least half less.

In at most O(log a)+O(log b) step, this will be reduced to the simple cases. Which yield an O(log n) algorithm, where n is the upper limit of a and b.

I have found it here

How Many Seconds Between Two Dates?

var a = new Date("2010 jan 10"),
    b = new Date("2010 jan 9");

alert(
    a + "\n" + 
    b + "\n" +
    "Difference: " + ((+a - +b) / 1000)
);

How can I generate a list of files with their absolute path in Linux?

The $PWD is a good option by Matthew above. If you want find to only print files then you can also add the -type f option to search only normal files. Other options are "d" for directories only etc. So in your case it would be (if i want to search only for files with .c ext):

find $PWD -type f -name "*.c" 

or if you want all files:

find $PWD -type f

Note: You can't make an alias for the above command, because $PWD gets auto-completed to your home directory when the alias is being set by bash.

How to put a jar in classpath in Eclipse?

Right click your project in eclipse, build path -> add external jars.

WPF Button with Image

Another way to Stretch image to full button. Can try the below code.

<Grid.Resources>
  <ImageBrush x:Key="AddButtonImageBrush" ImageSource="/Demoapp;component/Resources/AddButton.png" Stretch="UniformToFill"/>
</Grid.Resources>

<Button Content="Load Inventory 1" Background="{StaticResource AddButtonImageBrush}"/> 

Referred from Here

Also it might helps other. I posted the same with MouseOver Option here.

Setting Environment Variables for Node to retrieve

It depends on your operating system and your shell

On linux with the shell bash, you create environment variables like this(in the console):

export FOO=bar

For more information on environment variables on ubuntu (for example):

Environment variables on ubuntu

CSS Progress Circle

Another pure css based solution that is based on two clipped rounded elements that i rotate to get to the right angle:

http://jsfiddle.net/maayan/byT76/

That's the basic css that enables it:

.clip1 {
    position:absolute;
    top:0;left:0;
    width:200px;
    height:200px;
    clip:rect(0px,200px,200px,100px);
}
.slice1 {
    position:absolute;
    width:200px;
    height:200px;
    clip:rect(0px,100px,200px,0px);
    -moz-border-radius:100px;
    -webkit-border-radius:100px; 
    border-radius:100px;
    background-color:#f7e5e1;
    border-color:#f7e5e1;
    -moz-transform:rotate(0);
    -webkit-transform:rotate(0);
    -o-transform:rotate(0);
    transform:rotate(0);
}

.clip2 
{
    position:absolute;
    top:0;left:0;
    width:200px;
    height:200px;
    clip:rect(0,100px,200px,0px);
}

.slice2
{
    position:absolute;
    width:200px;
    height:200px;
    clip:rect(0px,200px,200px,100px);
    -moz-border-radius:100px;
    -webkit-border-radius:100px; 
    border-radius:100px;
    background-color:#f7e5e1;
    border-color:#f7e5e1;
    -moz-transform:rotate(0);
    -webkit-transform:rotate(0);
    -o-transform:rotate(0);
    transform:rotate(0);
}

and the js rotates it as required.

quite easy to understand..

Hope it helps, Maayan

Why can't I check if a 'DateTime' is 'Nothing'?

In any programming language, be careful when using Nulls. The example above shows another issue. If you use a type of Nullable, that means that the variables instantiated from that type can hold the value System.DBNull.Value; not that it has changed the interpretation of setting the value to default using "= Nothing" or that the Object of the value can now support a null reference. Just a warning... happy coding!

You could create a separate class containing a value type. An object created from such a class would be a reference type, which could be assigned Nothing. An example:

Public Class DateTimeNullable
Private _value As DateTime

'properties
Public Property Value() As DateTime
    Get
        Return _value
    End Get
    Set(ByVal value As DateTime)
        _value = value
    End Set
End Property

'constructors
Public Sub New()
    Value = DateTime.MinValue
End Sub

Public Sub New(ByVal dt As DateTime)
    Value = dt
End Sub

'overridables
Public Overrides Function ToString() As String
    Return Value.ToString()
End Function

End Class

'in Main():

        Dim dtn As DateTimeNullable = Nothing
    Dim strTest1 As String = "Falied"
    Dim strTest2 As String = "Failed"
    If dtn Is Nothing Then strTest1 = "Succeeded"

    dtn = New DateTimeNullable(DateTime.Now)
    If dtn Is Nothing Then strTest2 = "Succeeded"

    Console.WriteLine("test1: " & strTest1)
    Console.WriteLine("test2: " & strTest2)
    Console.WriteLine(".ToString() = " & dtn.ToString())
    Console.WriteLine(".Value.ToString() = " & dtn.Value.ToString())

    Console.ReadKey()

    ' Output:
    'test1:  Succeeded()
    'test2:  Failed()
    '.ToString() = 4/10/2012 11:28:10 AM
    '.Value.ToString() = 4/10/2012 11:28:10 AM

Then you could pick and choose overridables to make it do what you need. Lot of work - but if you really need it, you can do it.

Android: How can I pass parameters to AsyncTask's onPreExecute()?

You can either pass the parameter in the task constructor or when you call execute:

AsyncTask<Object, Void, MyTaskResult>

The first parameter (Object) is passed in doInBackground. The third parameter (MyTaskResult) is returned by doInBackground. You can change them to the types you want. The three dots mean that zero or more objects (or an array of them) may be passed as the argument(s).

public class MyActivity extends AppCompatActivity {

    TextView textView1;
    TextView textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);    
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);

        String input1 = "test";
        boolean input2 = true;
        int input3 = 100;
        long input4 = 100000000;

        new MyTask(input3, input4).execute(input1, input2);
    }

    private class MyTaskResult {
        String text1;
        String text2;
    }

    private class MyTask extends AsyncTask<Object, Void, MyTaskResult> {
        private String val1;
        private boolean val2;
        private int val3;
        private long val4;


        public MyTask(int in3, long in4) {
            this.val3 = in3;
            this.val4 = in4;

            // Do something ...
        }

        protected void onPreExecute() {
            // Do something ...
        }

        @Override
        protected MyTaskResult doInBackground(Object... params) {
            MyTaskResult res = new MyTaskResult();
            val1 = (String) params[0];
            val2 = (boolean) params[1];

            //Do some lengthy operation    
            res.text1 = RunProc1(val1);
            res.text2 = RunProc2(val2);

            return res;
        }

        @Override
        protected void onPostExecute(MyTaskResult res) {
            textView1.setText(res.text1);
            textView2.setText(res.text2);

        }
    }

}

Sorting HashMap by values

Try below code it works fine for me. You can choose both Ascending as well as descending order

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>()
        {
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2)
            {
                if (order)
                {
                    return o1.getValue().compareTo(o2.getValue());
                }
                else
                {
                    return o2.getValue().compareTo(o1.getValue());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}

Edit: Version 2

Used new java feature like stream for-each etc

Map will be sorted by keys if values are same

 import java.util.*;
 import java.util.Map.Entry;
 import java.util.stream.Collectors;

 public class SortMapByValue

 {
    private static boolean ASC = true;
    private static boolean DESC = false;
    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 20);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByValue(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descending order......");
        Map<String, Integer> sortedMapDesc = sortByValue(unsortMap, DESC);
        printMap(sortedMapDesc);
    }

    private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap, final boolean order)
    {
        List<Entry<String, Integer>> list = new LinkedList<>(unsortMap.entrySet());

        // Sorting the list based on values
        list.sort((o1, o2) -> order ? o1.getValue().compareTo(o2.getValue()) == 0
                ? o1.getKey().compareTo(o2.getKey())
                : o1.getValue().compareTo(o2.getValue()) : o2.getValue().compareTo(o1.getValue()) == 0
                ? o2.getKey().compareTo(o1.getKey())
                : o2.getValue().compareTo(o1.getValue()));
        return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a, b) -> b, LinkedHashMap::new));

    }

    private static void printMap(Map<String, Integer> map)
    {
        map.forEach((key, value) -> System.out.println("Key : " + key + " Value : " + value));
    }
}

Select row on click react-table

The answer you selected is correct, however if you are using a sorting table it will crash since rowInfo will became undefined as you search, would recommend using this function instead

                getTrGroupProps={(state, rowInfo, column, instance) => {
                    if (rowInfo !== undefined) {
                        return {
                            onClick: (e, handleOriginal) => {
                              console.log('It was in this row:', rowInfo)
                              this.setState({
                                  firstNameState: rowInfo.row.firstName,
                                  lastNameState: rowInfo.row.lastName,
                                  selectedIndex: rowInfo.original.id
                              })
                            },
                            style: {
                                cursor: 'pointer',
                                background: rowInfo.original.id === this.state.selectedIndex ? '#00afec' : 'white',
                                color: rowInfo.original.id === this.state.selectedIndex ? 'white' : 'black'
                            }
                        }
                    }}
                }

How to get week number in Python?

The ISO week suggested by others is a good one, but it might not fit your needs. It assumes each week begins with a Monday, which leads to some interesting anomalies at the beginning and end of the year.

If you'd rather use a definition that says week 1 is always January 1 through January 7, regardless of the day of the week, use a derivation like this:

>>> testdate=datetime.datetime(2010,6,16)
>>> print(((testdate - datetime.datetime(testdate.year,1,1)).days // 7) + 1)
24

How to replace values at specific indexes of a python list?

You can solve it using dictionary

to_modify = [5,4,3,2,1,0]
indexes = [0,1,3,5]
replacements = [0,0,0,0]

dic = {}
for i in range(len(indexes)):
    dic[indexes[i]]=replacements[i]
print(dic)

for index, item in enumerate(to_modify):
    for i in indexes:
        to_modify[i]=dic[i]
print(to_modify)

The output will be

{0: 0, 1: 0, 3: 0, 5: 0}
[0, 0, 3, 0, 1, 0]

"Data too long for column" - why?

With Hibernate you can create your own UserType. So thats what I did for this issue. Something as simple as this:

    public class BytesType implements org.hibernate.usertype.UserType {

         private final int[] SQL_TYPES = new int[] { java.sql.Types.VARBINARY };
     //...
    }

There of course is more to implement from extending your own UserType but I just wanted to throw that out there for anyone looking for other methods.

How to import large sql file in phpmyadmin

the answer for those with shared hosting. Best to use this little script which I just used to import a 300mb DB file to my server. The script is called Big Dump.

provides a script to import large DB's on resource-limited servers

Full examples of using pySerial package

http://web.archive.org/web/20131107050923/http://www.roman10.net/serial-port-communication-in-python/comment-page-1/

#!/usr/bin/python

import serial, time
#initialization and open the port

#possible timeout values:
#    1. None: wait forever, block call
#    2. 0: non-blocking mode, return immediately
#    3. x, x is bigger than 0, float allowed, timeout block call

ser = serial.Serial()
#ser.port = "/dev/ttyUSB0"
ser.port = "/dev/ttyUSB7"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None          #block read
ser.timeout = 1            #non-block read
#ser.timeout = 2              #timeout block read
ser.xonxoff = False     #disable software flow control
ser.rtscts = False     #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False       #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2     #timeout for write

try: 
    ser.open()
except Exception, e:
    print "error open serial port: " + str(e)
    exit()

if ser.isOpen():

    try:
        ser.flushInput() #flush input buffer, discarding all its contents
        ser.flushOutput()#flush output buffer, aborting current output 
                 #and discard all that is in buffer

        #write data
        ser.write("AT+CSQ")
        print("write data: AT+CSQ")

       time.sleep(0.5)  #give the serial port sometime to receive the data

       numOfLines = 0

       while True:
          response = ser.readline()
          print("read data: " + response)

        numOfLines = numOfLines + 1

        if (numOfLines >= 5):
            break

        ser.close()
    except Exception, e1:
        print "error communicating...: " + str(e1)

else:
    print "cannot open serial port "

How do I push to GitHub under a different username?

If under Windows and user Git for Windows and the manager for managing the credentials (aka Git-Credential-Manager-for-Windows Link) the problem is that there is no easy way to switch amongst users when pushing to GitHub over https using OAuth tokens.

The reason is that the token is stored as:

  • Internet Address: git:https://github.com
  • Username: Personal Access Token
  • Password: OAuth_Token

Variations of the URL in Internet Address don't work, for example:

The solution: namespaces. This is found in the details for the configuration of the Git-Credential-Manager-for-Windows:

Quoting from it:

namespace

Sets the namespace for stored credentials.

By default the GCM uses the 'git' namespace for all stored credentials, setting this configuration value allows for control of the namespace used globally, or per host.

git config --global credential.namespace name

Now, store your credential in the Windows Credential Manager as:

  • Internet Address: git.username:https://github.com
  • Username: Personal Access Token
  • Password: OAuth_Token

Notice that we have changed: git -> git.username (where you change username to your actual username or for the sake of it, to whatever you may want as unique identifier)

Now, inside the repository where you want to use the specific entry, execute:

git config credential.namespace git.username

(Again ... replace username with your desired value)

Your .git/config will now contain:

[credential]
    namespace = git.username

Et voilá! The right credential will be pulled from the Windows Credential Store.

This, of course, doesn't change which user/e-mail is pushing. For that you have to configure the usual user.name and user.email

Best way to show a loading/progress indicator?

ProgressDialog is deprecated from Android Oreo. Use ProgressBar instead

ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
// To dismiss the dialog
progress.dismiss();

OR

ProgressDialog.show(this, "Loading", "Wait while loading...");

Read more here.

By the way, Spinner has a different meaning in Android. (It's like the select dropdown in HTML)

How to edit nginx.conf to increase file size upload

Add client_max_body_size

Now that you are editing the file you need to add the line into the server block, like so;

server {
    client_max_body_size 8M;

    //other lines...
}

If you are hosting multiple sites add it to the http context like so;

http {
    client_max_body_size 8M;

    //other lines...
}

And also update the upload_max_filesize in your php.ini file so that you can upload files of the same size.

Saving in Vi

Once you are done you need to save, this can be done in vi with pressing esc key and typing :wq and returning.

Restarting Nginx and PHP

Now you need to restart nginx and php to reload the configs. This can be done using the following commands;

sudo service nginx restart
sudo service php5-fpm restart

Or whatever your php service is called.

How to read a local text file?

other example - my reader with FileReader class

<html>
    <head>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
        <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
        <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
    </head>
    <body>
        <script>
            function PreviewText() {
            var oFReader = new FileReader();
            oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
            oFReader.onload = function (oFREvent) {
                document.getElementById("uploadTextValue").value = oFREvent.target.result; 
                document.getElementById("obj").data = oFREvent.target.result;
            };
        };
        jQuery(document).ready(function(){
            $('#viewSource').click(function ()
            {
                var text = $('#uploadTextValue').val();
                alert(text);
                //here ajax
            });
        });
        </script>
        <object width="100%" height="400" data="" id="obj"></object>
        <div>
            <input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
            <input id="uploadText" style="width:120px" type="file" size="10"  onchange="PreviewText();" />
        </div>
        <a href="#" id="viewSource">Source file</a>
    </body>
</html>

How to trigger the window resize event in JavaScript?

I believe this should work for all browsers:

var event;
if (typeof (Event) === 'function') {
    event = new Event('resize');
} else { /*IE*/
    event = document.createEvent('Event');
    event.initEvent('resize', true, true);
}
window.dispatchEvent(event);

Unable to resolve host "<insert URL here>" No address associated with hostname

I got the same error and for the issue was that I was on VPN and I didn't realize that. After disconnecting the VPN and reconnecting the wifi resolved it.

Android ADB doesn't see device

Some of these answers are pretty old, so maybe it's changed in recent times, but I had similar issues and I solved it by:

  1. Loading the USB drivers for the device - Samsung S6
  2. Enable Developer tools on the phone.
  3. On the device, go to Settings - Applications - Development - Check USB Debugging
  4. Reboot O/S (Windows 7 - 64bit)
  5. Open Visual Studio

I think it was step 3 that had me stumped for a while. I'd enabled developer tools, but I didn't specifically enable the "USB Debugging" but.

How to detect simple geometric shapes using OpenCV

If you have only these regular shapes, there is a simple procedure as follows :

  1. Find Contours in the image ( image should be binary as given in your question)
  2. Approximate each contour using approxPolyDP function.
  3. First, check number of elements in the approximated contours of all the shapes. It is to recognize the shape. For eg, square will have 4, pentagon will have 5. Circles will have more, i don't know, so we find it. ( I got 16 for circle and 9 for half-circle.)
  4. Now assign the color, run the code for your test image, check its number, fill it with corresponding colors.

Below is my example in Python:

import numpy as np
import cv2

img = cv2.imread('shapes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret,thresh = cv2.threshold(gray,127,255,1)

contours,h = cv2.findContours(thresh,1,2)

for cnt in contours:
    approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
    print len(approx)
    if len(approx)==5:
        print "pentagon"
        cv2.drawContours(img,[cnt],0,255,-1)
    elif len(approx)==3:
        print "triangle"
        cv2.drawContours(img,[cnt],0,(0,255,0),-1)
    elif len(approx)==4:
        print "square"
        cv2.drawContours(img,[cnt],0,(0,0,255),-1)
    elif len(approx) == 9:
        print "half-circle"
        cv2.drawContours(img,[cnt],0,(255,255,0),-1)
    elif len(approx) > 15:
        print "circle"
        cv2.drawContours(img,[cnt],0,(0,255,255),-1)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Below is the output:

enter image description here

Remember, it works only for regular shapes.

Alternatively to find circles, you can use houghcircles. You can find a tutorial here.

Regarding iOS, OpenCV devs are developing some iOS samples this summer, So visit their site : www.code.opencv.org and contact them.

You can find slides of their tutorial here : http://code.opencv.org/svn/gsoc2012/ios/trunk/doc/CVPR2012_OpenCV4IOS_Tutorial.pdf

CSS Background image not loading

I'd like to share my debugging process because I was stuck on this issue for at least an hour. Image could not be found when running local host. To add some context, I am styling within a rails app in the following directory:

apps/assets/stylesheets/main.scss

I wanted to render background image in header tag. The following was my original implementation.

header {
    text-align: center;
    background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
              url('../images/header.jpg') no-repeat;
              background-blend-mode: multiply;
              background-size: cover;
}

...as a result I was getting the following error in rails server and the console in Chrome dev tools, respectively:

ActionController::RoutingError (No route matches [GET] "/images/header.jpg")
GET http://localhost:3000/images/header.jpg 404 (Not Found)

I tried different variations of the url:

url('../images/header.jpg') # DID NOT WORK
url('/../images/header.jpg') # DID NOT WORK
url('./../images/header.jpg') # DID NOT WORK

and it still did not work. At that point, I was very confused...I decided to move the image folder from the assets directory (which is the default) to within the stylesheets directory, and tried the following variations of the url:

url('/images/header.jpg') # DID NOT WORK
url('./images/header.jpg') # WORKED
url('images/header.jpg') # WORKED

I no longer got the console and rails server error. But the image still was not showing for some reason. After temporarily giving up, I found out the solution to this was to add a height property in order for the image to be shown...

header {
    text-align: center;
    height: 390px;
    background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
              url('images/header.jpg') no-repeat;
              background-blend-mode: multiply;
              background-size: cover;
}

Unfortunately, I am still not sure why the 3 initial url attempts with "../images/header.jpg" did not work on localhost, or when I should or shouldn't be adding a period at the beginning of the url.

It might have something to do with how the default link tag is setup in application.html.erb, or maybe it's a .scss vs .css thing. Or, maybe that's just how the background property with url() works (the image needs to be within same directory as the css file)? Anyhow, this is how I solved the issue with CSS background image not loading on localhost.

PLS-00103: Encountered the symbol "CREATE"

Run package declaration and body separately.

Fixing slow initial load for IIS

Options A, B and D seem to be in the same category since they only influence the initial start time, they do warmup of the website like compilation and loading of libraries in memory.

Using C, setting the idle timeout, should be enough so that subsequent requests to the server are served fast (restarting the app pool takes quite some time - in the order of seconds).

As far as I know, the timeout exists to save memory that other websites running in parallel on that machine might need. The price being that one time slow load time.

Besides the fact that the app pool gets shutdown in case of user inactivity, the app pool will also recycle by default every 1740 minutes (29 hours).

From technet:

Internet Information Services (IIS) application pools can be periodically recycled to avoid unstable states that can lead to application crashes, hangs, or memory leaks.

As long as app pool recycling is left on, it should be enough. But if you really want top notch performance for most components, you should also use something like the Application Initialization Module you mentioned.

What is cardinality in Databases?

In database, Cardinality number of rows in the table.

enter image description here img source


enter image description here img source


  • Relationships are named and classified by their cardinality (i.e. number of elements of the set).
  • Symbols which appears closes to the entity is Maximum cardinality and the other one is Minimum cardinality.
  • Entity relation, shows end of the relationship line as follows:
    enter image description here

enter image description here

image source

newline in <td title="">

The jquery colortip plugin also supports <br> tags in the title attribute, you might want to look into that one.

Is it valid to have a html form inside another html form?

No, it is not valid but you can trick your inner form position on the HTML with a help of CSS and jQuery usage. First create some container div inside your parent form and then in any other place on the page the div with your child (inner) form:

<form action="a">
    <input.../>
    <div class="row" id="other_form_container"></div>
    <input.../>
</form>

....

<div class="row" id="other_form">
    <form action="b">
        <input.../>
        <input.../>
        <input.../>
    </form>
</div>

Give your container div some stable heaght

<style>
  #other_form_container {
    height:90px;
    position:relative;
  }
</style> 

Thank trick the "other_form" position relatively to container div.

<script>
  $(document).ready(function() {
    var pos = $("#other_form_container").position();
    $("#other_form").css({
      position: "absolute",
      top: pos.top - 40,
      left: pos.left + 7,
      width: 500,
    }).show();
  });
</script>

P.S.: You'll have to play with numbers to make it look nice.

What data type to use in MySQL to store images?

This can be done from the command line. This will create a column for your image with a NOT NULL property.

CREATE TABLE `test`.`pic` (
`idpic` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`caption` VARCHAR(45) NOT NULL,
`img` LONGBLOB NOT NULL,
PRIMARY KEY(`idpic`)
)
TYPE = InnoDB; 

From here

Iterate through dictionary values?

You could search for the corresponding key or you could "invert" the dictionary, but considering how you use it, it would be best if you just iterated over key/value pairs in the first place, which you can do with items(). Then you have both directly in variables and don't need a lookup at all:

for key, value in PIX0.items():
    NUM = input("What is the Resolution of %s?"  % key)
    if NUM == value:

You can of course use that both ways then.

Or if you don't actually need the dictionary for something else, you could ditch the dictionary and have an ordinary list of pairs.

Save internal file in my own internal folder in Android

The answer of Mintir4 is fine, I would also do the following to load the file.

FileInputStream fis = myContext.openFileInput(fn);
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String s = "";

while ((s = r.readLine()) != null) {
    txt += s;
}

r.close();

HTML Display Current date

Use Date::toLocaleDateString.

new Date().toLocaleDateString()
= "9/13/2015"

You don't need to set innerHTML, just by writing

<p>
<script> document.write(new Date().toLocaleDateString()); </script>
</p>

will work.

supportness

P.S.

new Date().toDateString()
= "Sun Sep 13 2015"

How can I display a JavaScript object?

If you want to print the object for debugging purposes, use the code:

var obj = {prop1: 'prop1Value', prop2: 'prop2Value', child: {childProp1: 'childProp1Value'}}
console.log(obj)

will display:

screenshot console chrome

Note: you must only log the object. For example, this won't work:

console.log('My object : ' + obj)

Note ': You can also use a comma in the log method, then the first line of the output will be the string and after that the object will be rendered:

console.log('My object: ', obj);

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

How to display PDF file in HTML?

In html page for pc is easy to implement

<embed src="study/sample.pdf" type="application/pdf"   height="300px" width="100%">

but pdf show in mobile by this code is not possible you must need a plugin

if you have not responsive your site. Then above code pdf not show in mobile but you can put download option after the code

<embed src="study/sample.pdf" type="application/pdf"   height="300px" width="100%" class="responsive">
<a href="study/sample.pdf">download</a>

Spring Boot, Spring Data JPA with multiple DataSources

I checked the source code you provided on GitHub. There were several mistakes / typos in the configuration.

In CustomerDbConfig / OrderDbConfig you should refer to customerEntityManager and packages should point at existing packages:

@Configuration
@EnableJpaRepositories(
    entityManagerFactoryRef = "customerEntityManager",
    transactionManagerRef = "customerTransactionManager",
    basePackages = {"com.mm.boot.multidb.repository.customer"})
public class CustomerDbConfig {

The packages to scan in customerEntityManager and orderEntityManager were both not pointing at proper package:

em.setPackagesToScan("com.mm.boot.multidb.model.customer");

Also the injection of proper EntityManagerFactory did not work. It should be:

@Bean(name = "customerTransactionManager")
public PlatformTransactionManager transactionManager(EntityManagerFactory customerEntityManager){

}

The above was causing the issue and the exception. While providing the name in a @Bean method you are sure you get proper EMF injected.

The last thing I have done was to disable to automatic configuration of JpaRepositories:

@EnableAutoConfiguration(exclude = JpaRepositoriesAutoConfiguration.class)

And with all fixes the application starts as you probably expect!

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

As Mystere Man suggested, getting just a view first and then again making an ajax call again to get the json result is unnecessary in this case. that is 2 calls to the server. I think you can directly return an HTML table of Users in the first call.

We will do this in this way. We will have a strongly typed view which will return the markup of list of users to the browser and this data is being supplied by an action method which we will invoke from our browser using an http request.

Have a ViewModel for the User

public class UserViewModel
{
  public int UserID { set;get;}
  public string FirstName { set;get;}
   //add remaining properties as per your requirement

}

and in your controller have a method to get a list of Users

public class UserController : Controller
{

   [HttpGet]
   public ActionResult List()
   {
     List<UserViewModel> objList=UserService.GetUsers();  // this method should returns list of  Users
     return View("users",objList)        
   }
}

Assuming that UserService.GetUsers() method will return a List of UserViewModel object which represents the list of usres in your datasource (Tables)

and in your users.cshtml ( which is under Views/User folder),

 @model List<UserViewModel>

 <table>

 @foreach(UserViewModel objUser in Model)
 {
   <tr>
      <td>@objUser.UserId.ToString()</td>
      <td>@objUser.FirstName</td>
   </tr>
 }
 </table>

All Set now you can access the url like yourdomain/User/List and it will give you a list of users in an HTML table.

How can I count the number of elements of a given value in a matrix?

assume w contains week numbers ([1:7])

n = histc(M,w)

if you do not know the range of numbers in M:

n = histc(M,unique(M))

It is such as a SQL Group by command!

How to use table variable in a dynamic sql statement?

Your EXEC executes in a different context, therefore it is not aware of any variables that have been declared in your original context. You should be able to use a temp table instead of a table variable as shown in the simple demo below.

create table #t (id int)

declare @value nchar(1)
set @value = N'1'

declare @sql nvarchar(max)
set @sql = N'insert into #t (id) values (' + @value + N')'

exec (@sql)

select * from #t

drop table #t

manage.py runserver

Just in case any Windows users are having trouble, I thought I'd add my own experience. When running python manage.py runserver 0.0.0.0:8000, I could view urls using localhost:8000, but not my ip address 192.168.1.3:8000.

I ended up disabling ipv6 on my wireless adapter, and running ipconfig /renew. After this everything worked as expected.

How do I link to Google Maps with a particular longitude and latitude?

Open google map and show URL schemes location and location pin

UIApplication.shared.openURL(URL(string:"https://maps.google.com/?q=\(dicLocation.stringValueForKey("latitude")),\(dicLocation.stringValueForKey("longitude")),15z")!)

Pandas: sum DataFrame rows for given columns

You can simply pass your dataframe into the following function:

def sum_frame_by_column(frame, new_col_name, list_of_cols_to_sum):
    frame[new_col_name] = frame[list_of_cols_to_sum].astype(float).sum(axis=1)
    return(frame)

Example:

I have a dataframe (awards_frame) as follows:

enter image description here

...and I want to create a new column that shows the sum of awards for each row:

Usage:

I simply pass my awards_frame into the function, also specifying the name of the new column, and a list of column names that are to be summed:

sum_frame_by_column(awards_frame, 'award_sum', ['award_1','award_2','award_3'])

Result:

enter image description here

How do I add a placeholder on a CharField in Django?

After looking at your method, I used this method to solve it.

class Register(forms.Form):
    username = forms.CharField(label='???', max_length=32)
    email = forms.EmailField(label='??', max_length=64)
    password = forms.CharField(label="??", min_length=6, max_length=16)
    captcha = forms.CharField(label="???", max_length=4)

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    for field_name in self.fields:
        field = self.fields.get(field_name)
        self.fields[field_name].widget.attrs.update({
            "placeholder": field.label,
            'class': "input-control"
        })

What is the advantage of using heredoc in PHP?

First of all, all the reasons are subjective. It's more like a matter of taste rather than a reason.

Personally, I find heredoc quite useless and use it occasionally, most of the time when I need to get some HTML into a variable and don't want to bother with output buffering, to form an HTML email message for example.

Formatting doesn't fit general indentation rules, but I don't think it's a big deal.

       //some code at it's proper level
       $this->body = <<<HERE
heredoc text sticks to the left border
but it seems OK to me.
HERE;
       $this->title = "Feedback";
       //and so on

As for the examples in the accepted answer, it is merely cheating.
String examples, in fact, being more concise if one won't cheat on them

$sql = "SELECT * FROM $tablename
        WHERE id in [$order_ids_list]
        AND product_name = 'widgets'";

$x = 'The point of the "argument" was to illustrate the use of here documents';

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.

To change your Platform Toolset:

  1. Right click your project, go to Properties.
  2. Under Configuration Properties, go to General.
  3. Change your Platform Toolset to one of the available ones.

Parsing xml using powershell

[xml]$xmlfile = '<xml> <Section name="BackendStatus"> <BEName BE="crust" Status="1" /> <BEName BE="pizza" Status="1" /> <BEName BE="pie" Status="1" /> <BEName BE="bread" Status="1" /> <BEName BE="Kulcha" Status="1" /> <BEName BE="kulfi" Status="1" /> <BEName BE="cheese" Status="1" /> </Section> </xml>'

foreach ($bename in $xmlfile.xml.Section.BEName) {
    if($bename.Status -eq 1){
        #Do something
    }
}

CSS / HTML Navigation and Logo on same line

The <ul> is by default a block element, make it inline-block instead:

.navigation-bar ul {
  padding: 0px;
  margin: 0px;
  text-align: center;
  display:inline-block;
  vertical-align:top;
}

CodePen Demo

Promise.all().then() resolve?

Today NodeJS supports new async/await syntax. This is an easy syntax and makes the life much easier

async function process(promises) { // must be an async function
    let x = await Promise.all(promises);  // now x will be an array
    x = x.map( tmp => tmp * 10);              // proccessing the data.
}

const promises = [
   new Promise(resolve => setTimeout(resolve, 0, 1)),
   new Promise(resolve => setTimeout(resolve, 0, 2))
];

process(promises)

Learn more:

How to copy Docker images from one host to another without using a repository

I want to move all images with tags.

```
OUT=$(docker images --format '{{.Repository}}:{{.Tag}}')
OUTPUT=($OUT)
docker save $(echo "${OUTPUT[*]}") -o /dir/images.tar
``` 

Explanation:

First OUT gets all tags but separated with new lines. Second OUTPUT gets all tags in an array. Third $(echo "${OUTPUT[*]}") puts all tags for a single docker save command so that all images are in a single tar.

Additionally, this can be zipped using gzip. On target, run:

tar xvf images.tar.gz -O | docker load

-O option to tar puts contents on stdin which can be grabbed by docker load.

When should you NOT use a Rules Engine?

I'm a big fan of Business Rules Engines, since it can help you make your life much easier as a programmer. One of the first experiences I've had while working on a Data Warehouse project was to find Stored Procedures containing complicated CASE structures stretching over entire pages. It was a nightmare to debug, since it was very difficult to understand the logic applied in such long CASE structures, and to determine if you have an overlapping between a rule at page 1 of the code and another from page 5. Overall, we had more than 300 such rules embedded in the code.

When we've received a new development requirement, for something called Accounting Destination, which was involving treating more than 3000 rules, i knew something had to change. Back then I've been working on a prototype which later on become the parent of what now is a Custom Business Rule engine, capable of handling all SQL standard operators. Initially we've been using Excel as an authoring tool and , later on, we've created an ASP.net application which will allow the Business Users to define their own business rules, without the need of writing code. Now the system works fine, with very few bugs, and contains over 7000 rules for calculating this Accounting Destination. I don't think such scenario would have been possible by just hard-coding. And the users are pretty happy that they can define their own rules without IT becoming their bottleneck.

Still, there are limits to such approach:

  • You need to have capable business users which have an excellent understanding of the company business.
  • There is a significant workload on searching the entire system (in our case a Data Warehouse), in order to determine all hard-coded conditions which make sense to translate into rules to be handled by a Business Rule Engine. We've also had to take good care that these initial templates to be fully understandable by Business Users.
  • You need to have an application used for rules authoring, in which algorithms for detection of overlapping business rules is implemented. Otherwise you'll end up with a big mess, where no one understands anymore the results they get. When you have a bug in a generic component like a Custom Business Rule Engine, it can be very difficult to debug and involve extensive tests to make sure that things that worked before also work now.

More details on this topic can be found on a post I've written: http://dwhbp.com/post/2011/10/30/Implementing-a-Business-Rule-Engine.aspx

Overall, the biggest advantage of using a Business Rule Engines is that it allows the users to take back control over the Business Rule definitions and authoring, without the need of going to the IT department each time they need to modify something. It also the reduces the workload over IT development teams, which can now focus on building stuff with more added value.

Cheers,

Nicolae

How to select a dropdown value in Selenium WebDriver using Java

I have not tried in Selenium, but for Galen test this is working,

var list = driver.findElementByID("periodID"); // this will return web element

list.click(); // this will open the dropdown list.

list.typeText("14w"); // this will select option "14w".

You can try this in selenium, the galen and selenium working are similar.

Print DIV content by JQuery

your question doesn't sound as if you even tried it yourself, so i shouldn't even think of answering, but: if a hidden div can't be printed with that one line:

$('SelectorToPrint').printElement();

simply change it to:

$('SelectorToPrint').show().printElement();

which should make it work in all cases.

for the rest, there's no solution. the plugin will open the print-dialog for you where the user has to choose his printer. you simply can't find out if a printer is attached with javascript (and you (almost) can't print without print-dialog - if you're thinking about that).

NOTE:

The $.browser object has been removed in version 1.9.x of jQuery making this library unsupported.

Making HTTP Requests using Chrome Developer tools

To GET requests with headers, use this format.

   fetch('http://example.com', {
      method: 'GET',
      headers: new Headers({
               'Content-Type': 'application/json',
               'someheader': 'headervalue'
               })
    })
    .then(res => res.json())
    .then(console.log)

Java: Integer equals vs. ==

You can't compare two Integer with a simple == they're objects so most of the time references won't be the same.

There is a trick, with Integer between -128 and 127, references will be the same as autoboxing uses Integer.valueOf() which caches small integers.

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.


Resources :

On the same topic :

Running a cron job at 2:30 AM everyday

crontab -e

add:

30 2 * * * /your/command

AngularJS ngClass conditional

I see great examples above but they all start with curly brackets (json map). Another option is to return a result based on computation. The result can also be a list of css class names (not just map). Example:

ng-class="(status=='active') ? 'enabled' : 'disabled'"

or

ng-class="(status=='active') ? ['enabled'] : ['disabled', 'alik']"

Explanation: If the status is active, the class enabled will be used. Otherwise, the class disabled will be used.

The list [] is used for using multiple classes (not just one).

Test if a variable is a list or tuple

In principle, I agree with Ignacio, above, but you can also use type to check if something is a tuple or a list.

>>> a = (1,)
>>> type(a)
(type 'tuple')
>>> a = [1]
>>> type(a)
(type 'list')

Get IFrame's document, from JavaScript in main document

In case you get a cross-domain error:

If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'> attribute for the inner html.

For example, for the inner html, use the this html parameter (yes - this is defined and it refers to the parent window of the inner body element):

<body onload='changeForm(this)'>

In the inner html :

    function changeForm(window) {
        console.log('inner window loaded: do whatever you want with the inner html');
        window.document.getElementById('mturk_form').style.display = 'none';
    </script>

Add table row in jQuery

<table id=myTable>
    <tr><td></td></tr>
    <style="height=0px;" tfoot></tfoot>
</table>

You can cache the footer variable and reduce access to DOM (Note: may be it will be better to use a fake row instead of footer).

var footer = $("#mytable tfoot")
footer.before("<tr><td></td></tr>")

Is there a native jQuery function to switch elements?

You shouldn't need two clones, one will do. Taking Paolo Bergantino answer we have:

jQuery.fn.swapWith = function(to) {
    return this.each(function() {
        var copy_to = $(to).clone(true);
        $(to).replaceWith(this);
        $(this).replaceWith(copy_to);
    });
};

Should be quicker. Passing in the smaller of the two elements should also speed things up.

How do I set the selected item in a comboBox to match my string using C#?

For me this worked only:

foreach (ComboBoxItem cbi in someComboBox.Items)
{
    if (cbi.Content as String == "sometextIntheComboBox")
    {
        someComboBox.SelectedItem = cbi;
        break;
    }
}

MOD: and if You have your own objects as items set up in the combobox, then substitute the ComboBoxItem with one of them like:

foreach (Debitor d in debitorCombo.Items)
{
    if (d.Name == "Chuck Norris")
    {
        debitorCombo.SelectedItem = d;
        break;
    }
}

get size of json object

$(document).ready(function () {
    $('#count_my_data').click(function () {
        var count = 0;
        while (true) {
             try {
                var v1 = mydata[count].TechnologyId.toString();
                count = count + 1;
            }
            catch (e)
            { break; }
        }
        alert(count);
    });
});

An object reference is required to access a non-static member

I'm guessing you get the error on accessing audioSounds and minTime, right?

The problem is you can't access instance members from static methods. What this means is that, a static method is a method that exists only once and can be used by all other objects (if its access modifier permits it).

Instance members, on the other hand, are created for every instance of the object. So if you create ten instances, how would the runtime know out of all these instances, which audioSounds list it should access?

Like others said, make your audioSounds and minTime static, or you could make your method an instance method, if your design permits it.

How do I comment on the Windows command line?

Lines starting with "rem" (from the word remarks) are comments:

rem comment here
echo "hello"

get number of columns of a particular row in given excel using Java

There are two Things you can do

use

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();

or

int noOfColumns = sh.getRow(0).getLastCellNum();

There is a fine difference between them

  1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
  2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

android on Text Change Listener

Add background dynamically in onCreate method:

getWindow().setBackgroundDrawableResource(R.drawable.background);

also remove background from XML.

What does it mean when MySQL is in the state "Sending data"?

This is quite a misleading status. It should be called "reading and filtering data".

This means that MySQL has some data stored on the disk (or in memory) which is yet to be read and sent over. It may be the table itself, an index, a temporary table, a sorted output etc.

If you have a 1M records table (without an index) of which you need only one record, MySQL will still output the status as "sending data" while scanning the table, despite the fact it has not sent anything yet.

Sending multipart/formdata with jQuery.ajax

If your form is defined in your HTML, it is easier to pass the form into the constructor than it is to iterate and add images.

$('#my-form').submit( function(e) {
    e.preventDefault();

    var data = new FormData(this); // <-- 'this' is your form element

    $.ajax({
            url: '/my_URL/',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',     
            success: function(data){
            ...

how to set imageview src?

What you are looking for is probably this:

ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"

int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);

Let me know if this was helpful :)

Set Google Chrome as the debugging browser in Visual Studio

If you don't see the "Browse With..." option stop debugging first. =)

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

$ gcc test.c -o testc
$ file testc
testc: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped
$ ldd testc 
    linux-vdso.so.1 =>  (0x00007fff227ff000)
    libc.so.6 => /lib64/libc.so.6 (0x000000391f000000)
    /lib64/ld-linux-x86-64.so.2 (0x000000391ec00000)
$ gcc -m32 test.c -o testc
$ file testc
testc: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped
$ ldd testc
    linux-gate.so.1 =>  (0x009aa000)
    libc.so.6 => /lib/libc.so.6 (0x00780000)
    /lib/ld-linux.so.2 (0x0075b000)

In short: use the -m32 flag to compile a 32-bit binary.

Also, make sure that you have the 32-bit versions of all required libraries installed (in my case all I needed on Fedora was glibc-devel.i386)

Stop UIWebView from "bouncing" vertically?

I was looking at a project that makes it easy to create web apps as full fledged installable applications on the iPhone called QuickConnect, and found a solution that works, if you don't want your screen to be scrollable at all, which in my case I didn't.

In the above mentioned project/blog post, they mention a javascript function you can add to turn off the bouncing, which essentially boils down to this:

    document.ontouchmove = function(event){
        event.preventDefault();
    }

If you want to see more about how they implement it, simply download QuickConnect and check it out.... But basically all it does is call that javascript on page load... I tried just putting it in the head of my document, and it seems to work fine.

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

In IntelliJ:

  1. Open Project Structure (?;) > Modules > YOUR MODULE -> Language level: set 9, in your case.
  2. Repeat for each module.

screenshot

bundle install returns "Could not locate Gemfile"

Search for the Gemfile file in your project, go to that directory and then run "bundle install". prior to running this command make sure you have installed the gem "sudo gem install bundler"

Integer division with remainder in JavaScript?

Here is a way to do this. (Personally I would not do it this way, but thought it was a fun way to do it for an example)

_x000D_
_x000D_
function intDivide(numerator, denominator) {
  return parseInt((numerator/denominator).toString().split(".")[0]);
}

let x = intDivide(4,5);
let y = intDivide(5,5);
let z = intDivide(6,5);
console.log(x);
console.log(y);
console.log(z);
_x000D_
_x000D_
_x000D_

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

Preamble

below may work or may not, this is all given as-is, you and only you are responsible person in case of some damage, data loss and so on. But I hope things go smooth!

To undo make install I would do (and I did) this:

Idea: check whatever script installs and undo this with simple bash script.

  1. Reconfigure your build dir to install to some custom dir. I usually do this: --prefix=$PWD/install. For CMake, you can go to your build dir, open CMakeCache.txt, and fix CMAKE_INSTALL_PREFIX value.
  2. Install project to custom directory (just run make install again).
  3. Now we push from assumption, that make install script installs into custom dir just same contents you want to remove from somewhere else (usually /usr/local). So, we need a script. 3.1. Script should compare custom dir, with dir you want clean. I use this:

anti-install.sh

RM_DIR=$1
PRESENT_DIR=$2

echo "Remove files from $RM_DIR, which are present in $PRESENT_DIR"

pushd $RM_DIR

for fn in `find . -iname '*'`; do
#  echo "Checking $PRESENT_DIR/$fn..."
  if test -f "$PRESENT_DIR/$fn"; then
    # First try this, and check whether things go plain
    echo "rm $RM_DIR/$fn"

    # Then uncomment this, (but, check twice it works good to you).
    # rm $RM_DIR/$fn
  fi
done

popd

3.2. Now just run this script (it will go dry-run)

bash anti-install.sh <dir you want to clean> <custom installation dir>

E.g. You wan't to clean /usr/local, and your custom installation dir is /user/me/llvm.build/install, then it would be

bash anti-install.sh /usr/local /user/me/llvm.build/install

3.3. Check log carefully, if commands are good to you, uncomment rm $RM_DIR/$fn and run it again. But stop! Did you really check carefully? May be check again?

Source to instructions: https://dyatkovskiy.com/2019/11/26/anti-make-install/

Good luck!

Simple function to sort an array of objects

var data = [ 1, 2, 5, 3, 1]; data.sort(function(a,b) { return a-b });

With a small compartor and using sort, we can do it

String comparison using '==' vs. 'strcmp()'

Well..according to this php bug report , you can even get 0wned.

<?php 
    $pass = isset($_GET['pass']) ? $_GET['pass'] : '';
    // Query /?pass[]= will authorize user
    //strcmp and strcasecmp both are prone to this hack
    if ( strcasecmp( $pass, '123456' ) == 0 ){
      echo 'You successfully logged in.';
    }
 ?>

It gives you a warning , but still bypass the comparison.
You should be doing === as @postfuturist suggested.

Onclick event to remove default value in a text input field

Use onclick="this.value=''":

<input name="Name" value="Enter Your Name" onclick="this.value=''">

JQuery, select first row of table

Actually, if you try to use function "children" it will not be succesfull because it's possible to the table has a first child like 'th'. So you have to use function 'find' instead.

Wrong way:

var $row = $(this).closest('table').children('tr:first');

Correct way:

 var $row = $(this).closest('table').find('tr:first');

How do I clone a generic List in Java?

Be advised that Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.

How to specify the private SSH-key to use when executing shell command on Git?

In Windows with Git Bash you can use the following to add a repository

ssh-agent bash -c 'ssh-add "key-address"; git remote add origin "rep-address"'

for example:

ssh-agent bash -c 'ssh-add /d/test/PrivateKey.ppk; git remote add origin [email protected]:test/test.git'

Which private key is in drive D, folder test of computer. Also if you want to clone a repository, you can change git remote add origin with git clone.

After enter this to Git Bash, it will ask you for passphrase!

Be Aware that openssh private key and putty private key are different!

If you have created your keys with puttygen, you must convert your private key to openssh!

Object spread vs. Object.assign

I think one big difference between the spread operator and Object.assign that doesn't seem to be mentioned in the current answers is that the spread operator will not copy the the source object’s prototype to the target object. If you want to add properties to an object and you don't want to change what instance it is of, then you will have to use Object.assign.

Edit: I've actually realised that my example is misleading. The spread operator desugars to Object.assign with the first parameter set to an empty object. In my code example below, I put error as the first parameter of the Object.assign call so the two are not equivalent. The first parameter of Object.assign is actually modified and then returned which is why it retains its prototype. I have added another example below:

_x000D_
_x000D_
const error = new Error();
error instanceof Error // true

const errorExtendedUsingSpread = {
  ...error,
  ...{
    someValue: true
  }
};
errorExtendedUsingSpread instanceof Error; // false

// What the spread operator desugars into
const errorExtendedUsingImmutableObjectAssign = Object.assign({}, error, {
    someValue: true
});
errorExtendedUsingImmutableObjectAssign instanceof Error; // false

// The error object is modified and returned here so it keeps its prototypes
const errorExtendedUsingAssign = Object.assign(error, {
  someValue: true
});
errorExtendedUsingAssign instanceof Error; // true
_x000D_
_x000D_
_x000D_

See also: https://github.com/tc39/proposal-object-rest-spread/blob/master/Spread.md

CodeIgniter: "Unable to load the requested class"

I had a similar issue when deploying from OSx on my local to my Linux live site.

It ran fine on OSx, but on Linux I was getting:

An Error Was Encountered

Unable to load the requested class: Ckeditor

The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".

I also changed my load call to match the capitalization:

$this->load->library('CKEditor');

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

  1. Select columns A:H with A1 as the active cell.
  2. Open Home ? Styles ? Conditional Formatting ? New Rule.
  3. Choose Use a formula to determine which cells to format and supply one of the following formulas¹ in the Format values where this formula is true: text box.
    • To highlight the Account and Store Manager columns when one of the four dates is blank:
              =AND(LEN($A1), COLUMN()<3, COUNTBLANK($E1:$H1))
    • To highlight the Account, Store Manager and blank date columns when one of the four dates is blank:
              =AND(LEN($A1), OR(COLUMN()<3, AND(COLUMN()>4, COUNTBLANK(A1))), COUNTBLANK($E1:$H1))
  4. Click [Format] and select a cell Fill.
  5. Click [OK] to accept the formatting and then [OK] again to create the new rule. In both cases, the Applies to: will refer to =$A:$H.

Results should be similar to the following.

  Conditionally formatting if multiple cells are blank


¹ The COUNTBLANK function was introduced with Excel 2007. It will count both true blanks and zero-length strings left by formulas (e.g. "").

Simple way to transpose columns and rows in SQL?

Based on this solution from bluefeet here is a stored procedure that uses dynamic sql to generate the transposed table. It requires that all the fields are numeric except for the transposed column (the column that will be the header in the resulting table):

/****** Object:  StoredProcedure [dbo].[SQLTranspose]    Script Date: 11/10/2015 7:08:02 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Paco Zarate
-- Create date: 2015-11-10
-- Description: SQLTranspose dynamically changes a table to show rows as headers. It needs that all the values are numeric except for the field using for     transposing.
-- Parameters: @TableName - Table to transpose
--             @FieldNameTranspose - Column that will be the new headers
-- Usage: exec SQLTranspose <table>, <FieldToTranspose>
-- =============================================
ALTER PROCEDURE [dbo].[SQLTranspose] 
  -- Add the parameters for the stored procedure here
  @TableName NVarchar(MAX) = '', 
  @FieldNameTranspose NVarchar(MAX) = ''
AS
BEGIN
  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  DECLARE @colsUnpivot AS NVARCHAR(MAX),
  @query  AS NVARCHAR(MAX),
  @queryPivot  AS NVARCHAR(MAX),
  @colsPivot as  NVARCHAR(MAX),
  @columnToPivot as NVARCHAR(MAX),
  @tableToPivot as NVARCHAR(MAX), 
  @colsResult as xml

  select @tableToPivot = @TableName;
  select @columnToPivot = @FieldNameTranspose


  select @colsUnpivot = stuff((select ','+quotename(C.name)
       from sys.columns as C
       where C.object_id = object_id(@tableToPivot) and
             C.name <> @columnToPivot 
       for xml path('')), 1, 1, '')

  set @queryPivot = 'SELECT @colsResult = (SELECT  '','' 
                    + quotename('+@columnToPivot+')
                  from '+@tableToPivot+' t
                  where '+@columnToPivot+' <> ''''
          FOR XML PATH(''''), TYPE)'

  exec sp_executesql @queryPivot, N'@colsResult xml out', @colsResult out

  select @colsPivot = STUFF(@colsResult.value('.', 'NVARCHAR(MAX)'),1,1,'')

  set @query 
    = 'select name, rowid, '+@colsPivot+'
        from
        (
          select '+@columnToPivot+' , name, value, ROW_NUMBER() over (partition by '+@columnToPivot+' order by '+@columnToPivot+') as rowid
          from '+@tableToPivot+'
          unpivot
          (
            value for name in ('+@colsUnpivot+')
          ) unpiv
        ) src
        pivot
        (
          sum(value)
          for '+@columnToPivot+' in ('+@colsPivot+')
        ) piv
        order by rowid'
  exec(@query)
END

You can test it with the table provided with this command:

exec SQLTranspose 'yourTable', 'color'

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

People are asserting one can't remove from a Collection being iterated by a foreach loop. I just wanted to point out that is technically incorrect and describe exactly (I know the OP's question is so advanced as to obviate knowing this) the code behind that assumption:

for (TouchableObj obj : untouchedSet) {  // <--- This is where ConcurrentModificationException strikes
    if (obj.isTouched()) {
        untouchedSet.remove(obj);
        touchedSt.add(obj);
        break;  // this is key to avoiding returning to the foreach
    }
}

It isn't that you can't remove from the iterated Colletion rather that you can't then continue iteration once you do. Hence the break in the code above.

Apologies if this answer is a somewhat specialist use-case and more suited to the original thread I arrived here from, that one is marked as a duplicate (despite this thread appearing more nuanced) of this and locked.

How to set css style to asp.net button?

You can use CssClass attribute and pass a value as a css class name

<asp:Button CssClass="button" Text="Submit" runat="server"></asp:Button>` 

.button
{
     //write more styles
}

jQuery: Check if button is clicked

try something like :

var focusout = false;

$("#Button1").click(function () {
    if (focusout == true) {
        focusout = false;
        return;
    }
    else {
        GetInfo();
    }
});

$("#Text1").focusout(function () {
    focusout = true;
    GetInfo();
});

comparing strings in vb

I would suggest using the String.Compare method. Using that method you can also control whether to to have it perform case-sensitive comparisons or not.

Sample:

Dim str1 As String = "String one"
Dim str2 As String = str1
Dim str3 As String = "String three"
Dim str4 As String = str3

If String.Compare(str1, str2) = 0 And String.Compare(str3, str4) = 0 Then
    MessageBox.Show("str1 = str2 And str3 = str4")
Else
    MessageBox.Show("Else")
End If

Edit: if you want to perform a case-insensitive search you can use the StringComparison parameter:

If String.Compare(str1, str2, StringComparison.InvariantCultureIgnoreCase) = 0 And String.Compare(str3, str4, StringComparison.InvariantCultureIgnoreCase) = 0 Then

What's the syntax for mod in java

While it's possible to do a proper modulo by checking whether the value is negative and correct it if it is (the way many have suggested), there is a more compact solution.

(a % b + b) % b

This will first do the modulo, limiting the value to the -b -> +b range and then add b in order to ensure that the value is positive, letting the next modulo limit it to the 0 -> b range.

Note: If b is negative, the result will also be negative

How do I get the current username in Windows PowerShell?

[System.Security.Principal.WindowsIdentity]::GetCurrent().Name

Java reverse an int value without using array

See to get the last digit of any number we divide it by 10 so we either achieve zero or a digit which is placed on last and when we do this continuously we get the whole number as an integer reversed.

    int number=8989,last_num,sum=0;
    while(number>0){
    last_num=number%10; // this will give 8989%10=9
    number/=10;     // now we have 9 in last and now num/ by 10= 898
    sum=sum*10+last_number; //  sum=0*10+9=9;
    }
    // last_num=9.   number= 898. sum=9
    // last_num=8.   number =89.  sum=9*10+8= 98
   // last_num=9.   number=8.    sum=98*10+9=989
   // last_num=8.   number=0.    sum=989*10+8=9898
  // hence completed
   System.out.println("Reverse is"+sum);

Run a PostgreSQL .sql file using command line arguments

Via the terminal log on to your database and try this:

database-# >@pathof_mysqlfile.sql

or

database-#>-i pathof_mysqlfile.sql

or

database-#>-c pathof_mysqlfile.sql

How to show progress bar while loading, using ajax

After much searching a way to show a progress bar just to make the most elegant charging could not find any way that would serve my purpose. Check the actual status of the request showed demaziado complex and sometimes snippets not then worked created a very simple way but it gives me the experience seeking (or almost), follows the code:

$.ajax({
    type : 'GET',
    url : url,
    dataType: 'html',
    timeout: 10000,
    beforeSend: function(){
        $('.my-box').html('<div class="progress"><div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div></div>');
        $('.progress-bar').animate({width: "30%"}, 100);
    },
    success: function(data){  
        if(data == 'Unauthorized.'){
            location.href = 'logout';
        }else{
            $('.progress-bar').animate({width: "100%"}, 100);
            setTimeout(function(){
                $('.progress-bar').css({width: "100%"});
                setTimeout(function(){
                    $('.my-box').html(data);
                }, 100);
            }, 500);
        }
    },
    error: function(request, status, err) {
        alert((status == "timeout") ? "Timeout" : "error: " + request + status + err);
    }
});

What is the reason behind "non-static method cannot be referenced from a static context"?

I think it is worth pointing out that by the rules of the Java language the Java compiler inserts the equivalent of "this." when it notices that you're accessing instance methods or instance fields without an explicit instance. Of course, the compiler knows that it can only do this from within an instance method, which has a "this" variable, as static methods don't.

Which means that when you're in an instance method the following are equivalent:

instanceMethod();
this.instanceMethod();

and these are also equivalent:

... = instanceField;
... = this.instanceField;

The compiler is effectively inserting the "this." when you don't supply a specific instance.

This (pun intended) bit of "magic help" by the compiler can confuse novices: it means that instance calls and static calls sometimes appear to have the same syntax while in reality are calls of different types and underlying mechanisms.

The instance method call is sometimes referred to as a method invocation or dispatch because of the behaviors of virtual methods supporting polymorphism; dispatching behavior happens regardless of whether you wrote an explicit object instance to use or the compiler inserted a "this.".

The static method call mechanism is simpler, like a function call in a non-OOP language.

Personally, I think the error message is misleading, it could read "non-static method cannot be referenced from a static context without specifying an explicit object instance".


What the compiler is complaining about is that it cannot simply insert the standard "this." as it does within instance methods, because this code is within a static method; however, maybe the author merely forgot to supply the instance of interest for this invocation — say, an instance possibly supplied to the static method as parameter, or created within this static method.

In short, you most certainly can call instance methods from within a static method, you just need to have and specify an explicit instance object for the invocation.

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

U can also use :

var query =
    from t1 in myTABLE1List 
    join t2 in myTABLE1List
      on new { ColA=t1.ColumnA, ColB=t1.ColumnB } equals new { ColA=t2.ColumnA, ColB=t2.ColumnB }
    join t3 in myTABLE1List
      on new {ColC=t2.ColumnA, ColD=t2.ColumnB } equals new { ColC=t3.ColumnA, ColD=t3.ColumnB }

Is it possible to style html5 audio tag?

If you want to style the browsers standard music player in the CSS:

audio {
    enter code here;
}

How do I print the percent sign(%) in c

Your problem is that you have to change:

printf("%"); 

to

printf("%%");

Or you could use ASCII code and write:

printf("%c", 37);

:)

How to set the env variable for PHP?

Try display phpinfo() by file and check this var.

How to read all rows from huge table?

So it turns out that the crux of the problem is that by default, Postgres starts in "autoCommit" mode, and also it needs/uses cursors to be able to "page" through data (ex: read the first 10K results, then the next, then the next), however cursors can only exist within a transaction. So the default is to read all rows, always, into RAM, and then allow your program to start processing "the first result row, then the second" after it has all arrived, for two reasons, it's not in a transaction (so cursors don't work), and also a fetch size hasn't been set.

So how the psql command line tool achieves batched response (its FETCH_COUNT setting) for queries, is to "wrap" its select queries within a short-term transaction (if a transaction isn't yet open), so that cursors can work. You can do something like that also with JDBC:

  static void readLargeQueryInChunksJdbcWay(Connection conn, String originalQuery, int fetchCount, ConsumerWithException<ResultSet, SQLException> consumer) throws SQLException {
    boolean originalAutoCommit = conn.getAutoCommit();
    if (originalAutoCommit) {
      conn.setAutoCommit(false); // start temp transaction
    }
    try (Statement statement = conn.createStatement()) {
      statement.setFetchSize(fetchCount);
      ResultSet rs = statement.executeQuery(originalQuery);
      while (rs.next()) {
        consumer.accept(rs); // or just do you work here
      }
    } finally {
      if (originalAutoCommit) {
        conn.setAutoCommit(true); // reset it, also ends (commits) temp transaction
      }
    }
  }
  @FunctionalInterface
  public interface ConsumerWithException<T, E extends Exception> {
    void accept(T t) throws E;
  }

This gives the benefit of requiring less RAM, and, in my results, seemed to run overall faster, even if you don't need to save the RAM. Weird. It also gives the benefit that your processing of the first row "starts faster" (since it process it a page at a time).

And here's how to do it the "raw postgres cursor" way, along with full demo code, though in my experiments it seemed the JDBC way, above, was slightly faster for whatever reason.

Another option would be to have autoCommit mode off, everywhere, though you still have to always manually specify a fetchSize for each new Statement (or you can set a default fetch size in the URL string).

iPhone app signing: A valid signing identity matching this profile could not be found in your keychain

A good way to ensure that this happens cleanly is to clean your login keychain completely first.

Also, a really important step is to unlock your keychain before you import the private key and public key

 security unlock-keychain -p password ~/Library/Keychains/login.keychain 

Import private key into login keychain :

security import PrivateKey.p12 -k ~/Library/Keychains/login.keychain 

1 identity imported.

Import public key into login keychain :

security import PublicKeyName.pem -k ~/Library/Keychains/login.keychain 

1 key imported.

Blocking device rotation on mobile web pages

New API's are developing (and are currently available)!

screen.orientation.lock();   // webkit only

and

screen.lockOrientation("orientation");

Where "orientation" can be any of the following:

portrait-primary - It represents the orientation of the screen when it is in its primary portrait mode. A screen is considered in its primary portrait mode if the device is held in its normal position and that position is in portrait, or if the normal position of the device is in landscape and the device held turned by 90° clockwise. The normal position is device dependant.

portrait-secondary - It represents the orientation of the screen when it is in its secondary portrait mode. A screen is considered in its secondary portrait mode if the device is held 180° from its normal position and that position is in portrait, or if the normal position of the device is in landscape and the device held is turned by 90° anticlockwise. The normal position is device dependant.

landscape-primary - It represents the orientation of the screen when it is in its primary landscape mode. A screen is considered in its primary landscape mode if the device is held in its normal position and that position is in landscape, or if the normal position of the device is in portrait and the device held is turned by 90° clockwise. The normal position is device dependant.

landscape-secondary - It represents the orientation of the screen when it is in its secondary landscape mode. A screen is considered in its secondary landscape mode if the device held is 180° from its normal position and that position is in landscape, or if the normal position of the device is in portrait and the device held is turned by 90° anticlockwise. The normal position is device dependant.

portrait - It represents both portrait-primary and portrait-secondary.

landscape - It represents both landscape-primary and landscape-secondary.

default - It represents either portrait-primary and landscape-primary depends on natural orientation of devices. For example, if the panel resolution is 1280*800, default will make it landscape, if the resolution is 800*1280, default will make it to portrait.

Mozilla recommends adding a lockOrientationUniversal to screen to make it more cross-browser compatible.

screen.lockOrientationUniversal = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation;

Go here for more info: https://developer.mozilla.org/en-US/docs/Web/API/Screen/lockOrientation

How to execute 16-bit installer on 64-bit Win7?

Bottom line at the top: Get newer programs or get an older computer.

The solution is simple. It sucks but it's simple. For old programs keep an old computer up and running. Some times you just can't find the same game experience in the new games as the old ones. Sometimes there are programs that have no new counterparts that do the same thing. You basically have 2 choices at that point. On the bright side. Old computers can run $20 -$100 and that can buy you the whole system; monitor, tower, keyboard, mouse and speakers. If you have the patience to run old programs you should have the patience to find what you are looking for in want ads. I have 4 old computers running; 2 windows 98, 2 windows xp. The my wife and I each have win7 computers.

Find the last time table was updated

Find last time of update on a table

SELECT
tbl.name
,ius.last_user_update
,ius.user_updates
,ius.last_user_seek
,ius.last_user_scan
,ius.last_user_lookup
,ius.user_seeks
,ius.user_scans
,ius.user_lookups
FROM
sys.dm_db_index_usage_stats ius INNER JOIN
sys.tables tbl ON (tbl.OBJECT_ID = ius.OBJECT_ID)
WHERE ius.database_id = DB_ID()

http://www.sqlserver-dba.com/2012/10/sql-server-find-last-time-of-update-on-a-table.html

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

This happened to me when I upgraded. I had to downgrade back.

react-redux ^5.0.6 ? ^7.1.3

Find an element in DOM based on an attribute value

Update: In the past few years the landscape has changed drastically. You can now reliably use querySelector and querySelectorAll, see Wojtek's answer for how to do this.

There's no need for a jQuery dependency now. If you're using jQuery, great...if you're not, you need not rely it on just for selecting elements by attributes anymore.


There's not a very short way to do this in vanilla javascript, but there are some solutions available.

You do something like this, looping through elements and checking the attribute

If a library like jQuery is an option, you can do it a bit easier, like this:

$("[myAttribute=value]")

If the value isn't a valid CSS identifier (it has spaces or punctuation in it, etc.), you need quotes around the value (they can be single or double):

$("[myAttribute='my value']")

You can also do start-with, ends-with, contains, etc...there are several options for the attribute selector.

Detecting an "invalid date" Date instance in JavaScript

I use the following code to validate values for year, month and date.

function createDate(year, month, _date) {
  var d = new Date(year, month, _date);
  if (d.getFullYear() != year 
    || d.getMonth() != month
    || d.getDate() != _date) {
    throw "invalid date";
  }
  return d;
}

For details, refer to Check date in javascript

How to update an "array of objects" with Firestore?

addToCart(docId: string, prodId: string): Promise<void> {
    return this.baseAngularFirestore.collection('carts').doc(docId).update({
        products:
        firestore.FieldValue.arrayUnion({
            productId: prodId,
            qty: 1
        }),
    });
}

Truncating all tables in a Postgres database

You can do this with bash also:

#!/bin/bash
PGPASSWORD='' psql -h 127.0.0.1 -Upostgres sng --tuples-only --command "SELECT 'TRUNCATE TABLE ' || schemaname || '.' ||  tablename || ';' FROM pg_tables WHERE schemaname in ('cms_test', 'ids_test', 'logs_test', 'sps_test');" | 
tr "\\n" " " | 
xargs -I{} psql -h 127.0.0.1 -Upostgres sng --command "{}"

You will need to adjust schema names, passwords and usernames to match your schemas.

javascript: calculate x% of a number

It may be a bit pedantic / redundant with its numeric casting, but here's a safe function to calculate percentage of a given number:

function getPerc(num, percent) {
    return Number(num) - ((Number(percent) / 100) * Number(num));
}

// Usage: getPerc(10000, 25);

tSQL - Conversion from varchar to numeric works for all but integer

Actually whether there are digits or not is irrelevant. The . (dot) is forbidden if you want to cast to int. Dot can't - logically - be part of Integer definition, so even:

select cast ('7.0' as int)
select cast ('7.' as int)

will fail but both are fine for floats.

Internet Access in Ubuntu on VirtualBox

I had a similar issue in windows 7 + ubuntu 12.04 as guest. I resolved by

  • open 'network and sharing center' in windows
  • right click 'nw-bridge' -> 'properties'
  • Select "virtual box host only network" for the option "select adapters you want to use to connect computers on your local network"
  • go to virtual box.. select the network type as NAT.

Android Studio how to run gradle sync manually?

Android studio should have this button in the toolbar marked "Sync project with Gradle Files"

EDIT: I don't know when it was changed but it now looks like this:

enter image description here

EDIT: This is what it looks like on 3.3.1 enter image description here
OR by going to File -> Sync Project with Gradle Files from the menubar.

How can I link to a specific glibc version?

Link with -static. When you link with -static the linker embeds the library inside the executable, so the executable will be bigger, but it can be executed on a system with an older version of glibc because the program will use it's own library instead of that of the system.

placeholder for select tag

<select>

    <option selected="selected" class="Country">Country Name</option>

    <option value="1">India</option>

    <option value="2">us</option>

</select>

.country
{


    display:none;
}

</style>

Ng-model does not update controller value

I had the same problem.
The proper way would be setting the 'searchText' to be a property inside an object.

But what if I want to leave it as it is, a string? well, I tried every single method mentioned here, nothing worked.
But then I noticed that the problem is only in the initiation, so I've just set the value attribute and it worked.

<input type="text" ng-model="searchText" value={{searchText}} />

This way the value is just set to '$scope.searchText' value and it's being updated when the input value changes.

I know it's a workaround, but it worked for me..

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

Easiest way to do this in VBA is to create a function that takes in an array, your new amount of rows, and new amount of columns.

Run the below function to copy in all of the old data back to the array after it has been resized.

 function dynamic_preserve(array1, num_rows, num_cols)

        dim array2 as variant

        array2 = array1

        reDim array1(1 to num_rows, 1 to num_cols)

        for i = lbound(array2, 1) to ubound(array2, 2)

               for j = lbound(array2,2) to ubound(array2,2)

                      array1(i,j) = array2(i,j)

               next j

        next i

        dynamic_preserve = array1

end function

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

i have the same problem. this is how i fixed the problem. first when the error is occurred, my array data is coming form DB like this --,

{brands: Array(5), _id: "5ae9455f7f7af749cb2d3740"} 

make sure that your data is an ARRAY, not an OBJECT that carries an array. only array look like this --,

(5) [{…}, {…}, {…}, {…}, {…}]

it solved my problem.

How do I output the difference between two specific revisions in Subversion?

See svn diff in the manual:

svn diff -r 8979:11390 http://svn.collab.net/repos/svn/trunk/fSupplierModel.php

How to change colour of blue highlight on select box dropdown

Just found this whilst looking for a solution. I've only tested it FF 32.0.3

box-shadow: 0 0 10px 100px #fff inset;

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

Regular expressions are used for Pattern Matching.

To use in Excel follow these steps:

Step 1: Add VBA reference to "Microsoft VBScript Regular Expressions 5.5"

  • Select "Developer" tab (I don't have this tab what do I do?)
  • Select "Visual Basic" icon from 'Code' ribbon section
  • In "Microsoft Visual Basic for Applications" window select "Tools" from the top menu.
  • Select "References"
  • Check the box next to "Microsoft VBScript Regular Expressions 5.5" to include in your workbook.
  • Click "OK"

Step 2: Define your pattern

Basic definitions:

- Range.

  • E.g. a-z matches an lower case letters from a to z
  • E.g. 0-5 matches any number from 0 to 5

[] Match exactly one of the objects inside these brackets.

  • E.g. [a] matches the letter a
  • E.g. [abc] matches a single letter which can be a, b or c
  • E.g. [a-z] matches any single lower case letter of the alphabet.

() Groups different matches for return purposes. See examples below.

{} Multiplier for repeated copies of pattern defined before it.

  • E.g. [a]{2} matches two consecutive lower case letter a: aa
  • E.g. [a]{1,3} matches at least one and up to three lower case letter a, aa, aaa

+ Match at least one, or more, of the pattern defined before it.

  • E.g. a+ will match consecutive a's a, aa, aaa, and so on

? Match zero or one of the pattern defined before it.

  • E.g. Pattern may or may not be present but can only be matched one time.
  • E.g. [a-z]? matches empty string or any single lower case letter.

* Match zero or more of the pattern defined before it.

  • E.g. Wildcard for pattern that may or may not be present.
  • E.g. [a-z]* matches empty string or string of lower case letters.

. Matches any character except newline \n

  • E.g. a. Matches a two character string starting with a and ending with anything except \n

| OR operator

  • E.g. a|b means either a or b can be matched.
  • E.g. red|white|orange matches exactly one of the colors.

^ NOT operator

  • E.g. [^0-9] character can not contain a number
  • E.g. [^aA] character can not be lower case a or upper case A

\ Escapes special character that follows (overrides above behavior)

  • E.g. \., \\, \(, \?, \$, \^

Anchoring Patterns:

^ Match must occur at start of string

  • E.g. ^a First character must be lower case letter a
  • E.g. ^[0-9] First character must be a number.

$ Match must occur at end of string

  • E.g. a$ Last character must be lower case letter a

Precedence table:

Order  Name                Representation
1      Parentheses         ( )
2      Multipliers         ? + * {m,n} {m, n}?
3      Sequence & Anchors  abc ^ $
4      Alternation         |

Predefined Character Abbreviations:

abr    same as       meaning
\d     [0-9]         Any single digit
\D     [^0-9]        Any single character that's not a digit
\w     [a-zA-Z0-9_]  Any word character
\W     [^a-zA-Z0-9_] Any non-word character
\s     [ \r\t\n\f]   Any space character
\S     [^ \r\t\n\f]  Any non-space character
\n     [\n]          New line

Example 1: Run as macro

The following example macro looks at the value in cell A1 to see if the first 1 or 2 characters are digits. If so, they are removed and the rest of the string is displayed. If not, then a box appears telling you that no match is found. Cell A1 values of 12abc will return abc, value of 1abc will return abc, value of abc123 will return "Not Matched" because the digits were not at the start of the string.

Private Sub simpleRegex()
    Dim strPattern As String: strPattern = "^[0-9]{1,2}"
    Dim strReplace As String: strReplace = ""
    Dim regEx As New RegExp
    Dim strInput As String
    Dim Myrange As Range
    
    Set Myrange = ActiveSheet.Range("A1")
    
    If strPattern <> "" Then
        strInput = Myrange.Value
        
        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With
        
        If regEx.Test(strInput) Then
            MsgBox (regEx.Replace(strInput, strReplace))
        Else
            MsgBox ("Not matched")
        End If
    End If
End Sub

Example 2: Run as an in-cell function

This example is the same as example 1 but is setup to run as an in-cell function. To use, change the code to this:

Function simpleCellRegex(Myrange As Range) As String
    Dim regEx As New RegExp
    Dim strPattern As String
    Dim strInput As String
    Dim strReplace As String
    Dim strOutput As String
    
    
    strPattern = "^[0-9]{1,3}"
    
    If strPattern <> "" Then
        strInput = Myrange.Value
        strReplace = ""
        
        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With
        
        If regEx.test(strInput) Then
            simpleCellRegex = regEx.Replace(strInput, strReplace)
        Else
            simpleCellRegex = "Not matched"
        End If
    End If
End Function

Place your strings ("12abc") in cell A1. Enter this formula =simpleCellRegex(A1) in cell B1 and the result will be "abc".

results image


Example 3: Loop Through Range

This example is the same as example 1 but loops through a range of cells.

Private Sub simpleRegex()
    Dim strPattern As String: strPattern = "^[0-9]{1,2}"
    Dim strReplace As String: strReplace = ""
    Dim regEx As New RegExp
    Dim strInput As String
    Dim Myrange As Range
    
    Set Myrange = ActiveSheet.Range("A1:A5")
    
    For Each cell In Myrange
        If strPattern <> "" Then
            strInput = cell.Value
            
            With regEx
                .Global = True
                .MultiLine = True
                .IgnoreCase = False
                .Pattern = strPattern
            End With
            
            If regEx.Test(strInput) Then
                MsgBox (regEx.Replace(strInput, strReplace))
            Else
                MsgBox ("Not matched")
            End If
        End If
    Next
End Sub

Example 4: Splitting apart different patterns

This example loops through a range (A1, A2 & A3) and looks for a string starting with three digits followed by a single alpha character and then 4 numeric digits. The output splits apart the pattern matches into adjacent cells by using the (). $1 represents the first pattern matched within the first set of ().

Private Sub splitUpRegexPattern()
    Dim regEx As New RegExp
    Dim strPattern As String
    Dim strInput As String
    Dim Myrange As Range
    
    Set Myrange = ActiveSheet.Range("A1:A3")
    
    For Each C In Myrange
        strPattern = "(^[0-9]{3})([a-zA-Z])([0-9]{4})"
        
        If strPattern <> "" Then
            strInput = C.Value
            
            With regEx
                .Global = True
                .MultiLine = True
                .IgnoreCase = False
                .Pattern = strPattern
            End With
            
            If regEx.test(strInput) Then
                C.Offset(0, 1) = regEx.Replace(strInput, "$1")
                C.Offset(0, 2) = regEx.Replace(strInput, "$2")
                C.Offset(0, 3) = regEx.Replace(strInput, "$3")
            Else
                C.Offset(0, 1) = "(Not matched)"
            End If
        End If
    Next
End Sub

Results:

results image


Additional Pattern Examples

String   Regex Pattern                  Explanation
a1aaa    [a-zA-Z][0-9][a-zA-Z]{3}       Single alpha, single digit, three alpha characters
a1aaa    [a-zA-Z]?[0-9][a-zA-Z]{3}      May or may not have preceding alpha character
a1aaa    [a-zA-Z][0-9][a-zA-Z]{0,3}     Single alpha, single digit, 0 to 3 alpha characters
a1aaa    [a-zA-Z][0-9][a-zA-Z]*         Single alpha, single digit, followed by any number of alpha characters

</i8>    \<\/[a-zA-Z][0-9]\>            Exact non-word character except any single alpha followed by any single digit

How to parse JSON in Java

The org.json library is easy to use.

Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation

  • [ … ] represents an array, so library will parse it to JSONArray
  • { … } represents an object, so library will parse it to JSONObject

Example code below:

import org.json.*;

String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");

JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
    String post_id = arr.getJSONObject(i).getString("post_id");
    ......
}

You may find more examples from: Parse JSON in Java

Downloadable jar: http://mvnrepository.com/artifact/org.json/json

Python handling socket.error: [Errno 104] Connection reset by peer

You can try to add some time.sleep calls to your code.

It seems like the server side limits the amount of requests per timeunit (hour, day, second) as a security issue. You need to guess how many (maybe using another script with a counter?) and adjust your script to not surpass this limit.

In order to avoid your code from crashing, try to catch this error with try .. except around the urllib2 calls.

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

I fixed this issue by installing jre, I have jdk already installed but jre was not installed.

Android Studio marks R in red with error message "cannot resolve symbol R", but build succeeds

This problem occurs when you rename the package name. After renaming the package name, you must change the older package name to the newer one.

For me it solved the problem once I changed that.

After that, you might get errors in xml files, that you have to change the package name there also. That's it.

PHP: Possible to automatically get all POSTed data?

You can use $_REQUEST as well as $_POST to reach everything such as Post, Get and Cookie data.

JavaScript: location.href to open in new window/tab?

You can also open a new tab calling to an action method with parameter like this:

   var reportDate = $("#inputDateId").val();
   var url = '@Url.Action("PrintIndex", "Callers", new {dateRequested = "findme"})';
   window.open(window.location.href = url.replace('findme', reportDate), '_blank');

How to convert float number to Binary?

Consider below example

Convert 2.625 to binary.

We will consider the integer and fractional part separately.

The integral part is easy, 2 = 10. 

For the fractional part:

0.625   × 2 =   1.25    1   Generate 1 and continue with the rest.
0.25    × 2 =   0.5     0   Generate 0 and continue.
0.5     × 2 =   1.0     1   Generate 1 and nothing remains.

So 0.625 = 0.101, and 2.625 = 10.101.

See this link for more information.

How to group time by hour or by 10 minutes

I know I am late to the show with this one, but I used this - pretty simple approach. This allows you to get the 60 minute slices without any rounding issues.

Select 
   CONCAT( 
            Format(endtime,'yyyy-MM-dd_HH:'),  
            LEFT(Format(endtime,'mm'),1),
            '0' 
          ) as [Time-Slice]

Truncate (not round) decimal places in SQL Server

ROUND ( 123.456 , 2 , 1 )

When the third parameter != 0 it truncates rather than rounds

http://msdn.microsoft.com/en-us/library/ms175003(SQL.90).aspx

Syntax

ROUND ( numeric_expression , length [ ,function ] )

Arguments

  • numeric_expression Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.

  • length Is the precision to which numeric_expression is to be rounded. length must be an expression of type tinyint, smallint, or int. When length is a positive number, numeric_expression is rounded to the number of decimal positions specified by length. When length is a negative number, numeric_expression is rounded on the left side of the decimal point, as specified by length.

  • function Is the type of operation to perform. function must be tinyint, smallint, or int. When function is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.

Execution order of events when pressing PrimeFaces p:commandButton

I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:

        <p:pickList id="formPickList" 
                    value="#{mediaDetail.availableMedia}" 
                    converter="MediaPicklistConverter" 
                    widgetVar="formsPicklistWidget" 
                    var="mediaFiles" 
                    itemLabel="#{mediaFiles.mediaTitle}" 
                    itemValue="#{mediaFiles}" >
            <f:facet name="sourceCaption">Available Media</f:facet>
            <f:facet name="targetCaption">Chosen Media</f:facet>
        </p:pickList>

        <p:commandButton id="viewStream_btn" 
                         value="Stream chosen media" 
                         icon="fa fa-download"
                         ajax="true"
                         action="#{mediaDetail.prepareStreams}"                                              
                         update=":streamDialogPanel"
                         oncomplete="PF('streamingDialog').show()"
                         styleClass="ui-priority-primary"
                         style="margin-top:5px" >
            <p:ajax process="formPickList"  />
        </p:commandButton>

The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.

As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.

The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" /> bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.

Happy coding!

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

Make an existing Git branch track a remote branch?

You can do the following (assuming you are checked out on master and want to push to a remote branch master):

Set up the 'remote' if you don't have it already

git remote add origin ssh://...

Now configure master to know to track:

git config branch.master.remote origin
git config branch.master.merge refs/heads/master

And push:

git push origin master

How can I make my flexbox layout take 100% vertical space?

You should set height of html, body, .wrapper to 100% (in order to inherit full height) and then just set a flex value greater than 1 to .row3 and not on the others.

_x000D_
_x000D_
.wrapper, html, body {
    height: 100%;
    margin: 0;
}
.wrapper {
    display: flex;
    flex-direction: column;
}
#row1 {
    background-color: red;
}
#row2 {
    background-color: blue;
}
#row3 {
    background-color: green;
    flex:2;
    display: flex;
}
#col1 {
    background-color: yellow;
    flex: 0 0 240px;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col2 {
    background-color: orange;
    flex: 1 1;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col3 {
    background-color: purple;
    flex: 0 0 240px;
    min-height: 100%;/* chrome needed it a question time , not anymore */
}
_x000D_
<div class="wrapper">
    <div id="row1">this is the header</div>
    <div id="row2">this is the second line</div>
    <div id="row3">
        <div id="col1">col1</div>
        <div id="col2">col2</div>
        <div id="col3">col3</div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

DEMO

Ruby - test for array

Also consider using Array(). From the Ruby Community Style Guide:

Use Array() instead of explicit Array check or [*var], when dealing with a variable you want to treat as an Array, but you're not certain it's an array.

# bad
paths = [paths] unless paths.is_a? Array
paths.each { |path| do_something(path) }

# bad (always creates a new Array instance)
[*paths].each { |path| do_something(path) }

# good (and a bit more readable)
Array(paths).each { |path| do_something(path) }

Export DataTable to Excel with Open Xml SDK in c#

I wrote this quick example. It works for me. I only tested it with one dataset with one table inside, but I guess that may be enough for you.

Take into consideration that I treated all cells as String (not even SharedStrings). If you want to use SharedStrings you might need to tweak my sample a bit.

Edit: To make this work it is necessary to add WindowsBase and DocumentFormat.OpenXml references to project.

Enjoy,

private void ExportDataSet(DataSet ds, string destination)
        {
            using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
            {
                var workbookPart = workbook.AddWorkbookPart();

                workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();

                workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();

                foreach (System.Data.DataTable table in ds.Tables) {

                    var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
                    var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
                    sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);

                    DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
                    string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);

                    uint sheetId = 1;
                    if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
                    {
                        sheetId =
                            sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
                    }

                    DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
                    sheets.Append(sheet);

                    DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

                    List<String> columns = new List<string>();
                    foreach (System.Data.DataColumn column in table.Columns) {
                        columns.Add(column.ColumnName);

                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
                        headerRow.AppendChild(cell);
                    }


                    sheetData.AppendChild(headerRow);

                    foreach (System.Data.DataRow dsrow in table.Rows)
                    {
                        DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                        foreach (String col in columns)
                        {
                            DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                            cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                            newRow.AppendChild(cell);
                        }

                        sheetData.AppendChild(newRow);
                    }

                }
            }
        }

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

Copy the diff file to the root of your repository, and then do:

git apply yourcoworkers.diff

More information about the apply command is available on its man page.

By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch on the sender and then git am on the receiver, because it also transfers the authorship info and the commit message.

If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3 option of apply that tries to merge in the changes.

It also works with Unix pipe as follows:

git diff d892531 815a3b5 | git apply

XPath to select Element by attribute value

As a follow on, you could select "all nodes with a particular attribute" like this:

//*[@id='4']

Apply CSS Style to child elements

This code can do the trick as well, using the SCSS syntax

.parent {
  & > * {
    margin-right: 15px;
    &:last-child {
      margin-right: 0;
    }
  }
}

could not extract ResultSet in hibernate

The @JoinColumn annotation specifies the name of the column being used as the foreign key on the targeted entity.

On the Product class above, the name of the join column is set to ID_CATALOG.

@ManyToOne
@JoinColumn(name="ID_CATALOG")
private Catalog catalog;

However, the foreign key on the Product table is called catalog_id

`catalog_id` int(11) DEFAULT NULL,

You'll need to change either the column name on the table or the name you're using in the @JoinColumn so that they match. See http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-association

How to make ConstraintLayout work with percentage values?

It may be useful to have a quick reference here.

Placement of views

Use a guideline with app:layout_constraintGuide_percent like this:

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/guideline"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.5"/>

And then you can use this guideline as anchor points for other views.

or

Use bias with app:layout_constraintHorizontal_bias and/or app:layout_constraintVertical_bias to modify view location when the available space allows

<Button
    ...
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintHorizontal_bias="0.25"
    ...
    />

Size of views

Another percent based value is height and/or width of elements, with app:layout_constraintHeight_percent and/or app:layout_constraintWidth_percent:

<Button
    ...
    android:layout_width="0dp"
    app:layout_constraintWidth_percent="0.5"
    ...
    />

Javascript sleep/delay/wait function

You will have to use a setTimeout so I see your issue as

I have a script that is generated by PHP, and so am not able to put it into two different functions

What prevents you from generating two functions in your script?

function fizz() {
    var a;
    a = 'buzz';
    // sleep x desired
    a = 'complete';
}

Could be rewritten as

function foo() {
    var a; // variable raised so shared across functions below
    function bar() { // consider this to be start of fizz
        a = 'buzz';
        setTimeout(baz, x); // start wait
    } // code split here for timeout break
    function baz() { // after wait
        a = 'complete';
    } // end of fizz
    bar(); // start it
}

You'll notice that a inside baz starts as buzz when it is invoked and at the end of invocation, a inside foo will be "complete".

Basically, wrap everything in a function, move all variables up into that wrapping function such that the contained functions inherit them. Then, every time you encounter wait NUMBER seconds you echo a setTimeout, end the function and start a new function to pick up where you left off.

How to remove indentation from an unordered list item?

Doing this inline, I set the margin to 0 (ul style="margin:-0px"). The bullets align with paragraph with no overhang.

<div style display="none" > inside a table not working

Semantically what you are trying is invalid html, table element cannot have a div element as a direct child. What you can do is, get your div element inside a td element and than try to hide it

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

I have the same problem with spring 3.0.2 and spring-beans-3.0.xsd.

My solution:

Create a file META-INF/spring.schemas in the source folder and copy all necesary definitions. Create spring.handlers too.

I think that the class PluggableSchemaResolver is not working correctly.

http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/xml/PluggableSchemaResolver.html

from the javadoc:

"By default, this class will look for mapping files in the classpath using the pattern: META-INF/spring.schemas allowing for multiple files to exist on the classpath at any one time."

but in my case, this class only read the first spring.schemas finded.

Grettings. pacovr

Returning a C string from a function

Or how about this one:

void print_month(int month)
{
    switch (month)
    {
        case 0:
            printf("January");
            break;
        case 1:
            printf("february");
            break;
        ...etc...
    }
}

And call that with the month you compute somewhere else.

How to sum columns in a dataTable?

 for (int i=0;i<=dtB.Columns.Count-1;i++)
 {
   array(0, i) = dtB.Compute("SUM([" & dtB.Columns(i).ColumnName & "])", "")                   
 }

PHP, display image with Header()

Though weirdly named, you can use the getimagesize() function. This will also give you mime information:

Array
(
    [0] => 295 // width
    [1] => 295 // height
    [2] => 3 // http://php.net/manual/en/image.constants.php
    [3] => width="295" height="295" // width and height as attr's
    [bits] => 8
    [mime] => image/png
)

jQuery selector regular expressions

James Padolsey created a wonderful filter that allows regex to be used for selection.

Say you have the following div:

<div class="asdf">

Padolsey's :regex filter can select it like so:

$("div:regex(class, .*sd.*)")

Also, check the official documentation on selectors.

UPDATE: : syntax Deprecation JQuery 3.0

Since jQuery.expr[':'] used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:

jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {
    return function (elem) {
        var matchParams = expression.split(','),
            validLabels = /^(data|css):/,
            attr = {
                method: matchParams[0].match(validLabels) ?
                    matchParams[0].split(':')[0] : 'attr',
                property: matchParams.shift().replace(validLabels, '')
            },
            regexFlags = 'ig',
            regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
        return regex.test(jQuery(elem)[attr.method](attr.property));
    }
});

Difference between no-cache and must-revalidate

I think there is a difference between max-age=0, must-revalidate and no-cache:

In the must-revalidate case the client is allowed to send a If-Modified-Since request and serve the response from cache if 304 Not Modified is returned.

In the no-cache case, the client must not cache the response, so should not use If-Modified-Since.

Converting SVG to PNG using C#

There is a much easier way using the library http://svg.codeplex.com/ (Newer version @GIT, @NuGet). Here is my code

var byteArray = Encoding.ASCII.GetBytes(svgFileContents);
using (var stream = new MemoryStream(byteArray))
{
    var svgDocument = SvgDocument.Open(stream);
    var bitmap = svgDocument.Draw();
    bitmap.Save(path, ImageFormat.Png);
}

What are all codecs and formats supported by FFmpeg?

Codecs proper:

ffmpeg -codecs

Formats:

ffmpeg -formats

Display a float with two decimal places in Python

If you want to get a floating point value with two decimal places limited at the time of calling input,

Check this out ~

a = eval(format(float(input()), '.2f'))   # if u feed 3.1415 for 'a'.
print(a)                                  # output 3.14 will be printed.

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

Do not use arrow function to create functional components.

Do as one of the examples below:

function MyComponent(props) {
  const [states, setStates] = React.useState({ value: '' });

  return (
    <input
      type="text"
      value={states.value}
      onChange={(event) => setStates({ value: event.target.value })}
    />
  );
}

Or

//IMPORTANT: Repeat the function name

const MyComponent = function MyComponent(props) { 
  const [states, setStates] = React.useState({ value: '' });

  return (
    <input
      type="text"
      value={states.value}
      onChange={(event) => setStates({ value: event.target.value })}
    />
  );
};

If you have problems with "ref" (probably in loops), the solution is to use forwardRef():

// IMPORTANT: Repeat the function name
// Add the "ref" argument to the function, in case you need to use it.

const MyComponent = React.forwardRef( function MyComponent(props, ref) {
  const [states, setStates] = React.useState({ value: '' });

  return (
    <input
      type="text"
      value={states.value}
      onChange={(event) => setStates({ value: event.target.value })}
    />
  );
});

How do I validate a date in this format (yyyy-mm-dd) using jquery?

You could also just use regular expressions to accomplish a slightly simpler job if this is enough for you (e.g. as seen in [1]).

They are build in into javascript so you can use them without any libraries.

function isValidDate(dateString) {
  var regEx = /^\d{4}-\d{2}-\d{2}$/;
  return dateString.match(regEx) != null;
}

would be a function to check if the given string is four numbers - two numbers - two numbers (almost yyyy-mm-dd). But you can do even more with more complex expressions, e.g. check [2].

isValidDate("23-03-2012") // false
isValidDate("1987-12-24") // true
isValidDate("22-03-1981") // false
isValidDate("0000-00-00") // true

When correctly use Task.Run and when just async-await

One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get

public class PageViewModel : IHandle<SomeMessage>
{
   ...

   public async void Handle(SomeMessage message)
   {
      ShowLoadingAnimation();

      // makes UI very laggy, but still not dead
      await this.contentLoader.LoadContentAsync(); 

      HideLoadingAnimation();   
   }
}

public class ContentLoader 
{
    public async Task LoadContentAsync()
    {
        var tasks = new List<Task>();
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoIoBoundWorkAsync());
        tasks.Add(DoCpuBoundWorkAsync());
        tasks.Add(DoSomeOtherWorkAsync());

        await Task.WhenAll(tasks).ConfigureAwait(false);
    }
}

Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

select convert(varchar, Max(Time) - Min(Time) , 108) from logTable where id=...

creating a new list with subset of list using index in python

The following definition might be more efficient than the first solution proposed

def new_list_from_intervals(original_list, *intervals):
    n = sum(j - i for i, j in intervals)
    new_list = [None] * n
    index = 0
    for i, j in intervals :
        for k in range(i, j) :
            new_list[index] = original_list[k]
            index += 1

    return new_list

then you can use it like below

new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))

Read file from resources folder in Spring Boot

The simplest method to bring a resource from the classpath in the resources directory parsed into a String is the following one liner.

As a String(Using Spring Libraries):

         String resource = StreamUtils.copyToString(
                new ClassPathResource("resource.json").getInputStream(), defaultCharset());

This method uses the StreamUtils utility and streams the file as an input stream into a String in a concise compact way.

If you want the file as a byte array you can use basic Java File I/O libraries:

As a byte array(Using Java Libraries):

byte[] resource = Files.readAllBytes(Paths.get("/src/test/resources/resource.json"));

Delete from a table based on date

delete from YOUR_TABLE where your_date_column < '2009-01-01';

This will delete rows from YOUR_TABLE where the date in your_date_column is older than January 1st, 2009. i.e. a date with 2008-12-31 would be deleted.