Programs & Examples On #Template function

docker command not found even though installed with apt-get

SET UP THE REPOSITORY

For Ubuntu 14.04/16.04/16.10/17.04:

sudo add-apt-repository "deb [arch=amd64] \
     https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

For Ubuntu 17.10:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable"

Add Docker’s official GPG key:

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Then install

$ sudo apt-get update && sudo apt-get -y install docker-ce

reading from app.config file

This:

Console.WriteLine( "StartingMonthColumn is {0}", ConfigurationManager.AppSettings["StartingMonthColumn"]);

works fine for me.

Note that ConfigurationManager is in the System.Configuration namespace (so you'll likely want a using System.Configuration; statement), and that since what you read in has a string type you'll need to parse what you read in to use it as a number.

Also, be sure you set system.configuration.dll as a reference in your project or build script.

Zoom to fit: PDF Embedded in HTML

Use iframe tag do display pdf file with zoom fit

<iframe src="filename.pdf" width="" height="" border="0"></iframe>

php error: Class 'Imagick' not found

On an EC2 at AWS, I did this:

 yum list | grep imagick

Then found a list of ones I could install...

 php -v

told me which version of php I had and thus which version of imagick

yum install php56-pecl-imagick.x86_64

Did the trick. Enjoy!

How to generate classes from wsdl using Maven and wsimport?

I see some people prefer to generate sources into the target via jaxws-maven-plugin AND make this classes visible in source via build-helper-maven-plugin. As an argument for this structure

the version management system (svn/etc.) would always notice changed sources

With git it is not true. So you can just configure jaxws-maven-plugin to put them into your sources, but not under the target folder. Next time you build your project, git will not mark these generated files as changed. Here is the simple solution with only one plugin:

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxws-maven-plugin</artifactId>
        <version>2.6</version>

    <dependencies>
      <dependency>
        <groupId>org.jvnet.jaxb2_commons</groupId>
        <artifactId>jaxb2-fluent-api</artifactId>
        <version>3.0</version>
      </dependency>
      <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-tools</artifactId>
        <version>2.3.0</version>
      </dependency>
    </dependencies>

    <executions>
      <execution>
        <goals>
          <goal>wsimport</goal>
        </goals>
        <configuration>
          <packageName>som.path.generated</packageName>
          <xjcArgs>
            <xjcArg>-Xfluent-api</xjcArg>
          </xjcArgs>
          <verbose>true</verbose>
          <keep>true</keep> <!--used by default-->
          <sourceDestDir>${project.build.sourceDirectory}</sourceDestDir>
          <wsdlDirectory>src/main/resources/META-INF/wsdl</wsdlDirectory>
          <wsdlLocation>META-INF/wsdl/soap.wsdl</wsdlLocation>
        </configuration>
      </execution>
    </executions>
  </plugin>

Additionally (just to note) in this example SOAP classes are generated with Fluent API, so you can create them like:

A a = new A()
  .withField1(value1)
  .withField2(value2);

SQL like search string starts with

You need to use the wildcard % :

SELECT * from games WHERE (lower(title) LIKE 'age of empires III%');

JavaScript chop/slice/trim off last character in string

Performance

Today 2020.05.13 I perform tests of chosen solutions on Chrome v81.0, Safari v13.1 and Firefox v76.0 on MacOs High Sierra v10.13.6.

Conclusions

  • the slice(0,-1)(D) is fast or fastest solution for short and long strings and it is recommended as fast cross-browser solution
  • solutions based on substring (C) and substr(E) are fast
  • solutions based on regular expressions (A,B) are slow/medium fast
  • solutions B, F and G are slow for long strings
  • solution F is slowest for short strings, G is slowest for long strings

enter image description here

Details

I perform two tests for solutions A, B, C, D, E(ext), F, G(my)

  • for 8-char short string (from OP question) - you can run it HERE
  • for 1M long string - you can run it HERE

Solutions are presented in below snippet

_x000D_
_x000D_
function A(str) {
  return str.replace(/.$/, '');
}

function B(str) {
  return str.match(/(.*).$/)[1];
}

function C(str) {
  return str.substring(0, str.length - 1);
}

function D(str) {
  return str.slice(0, -1); 
}

function E(str) {
  return str.substr(0, str.length - 1);
}

function F(str) {
  let s= str.split("");
  s.pop();
  return s.join("");
}

function G(str) {
  let s='';
  for(let i=0; i<str.length-1; i++) s+=str[i];
  return s;
 }



// ---------
// TEST
// ---------

let log = (f)=>console.log(`${f.name}: ${f("12345.00")}`);

[A,B,C,D,E,F,G].map(f=>log(f));
_x000D_
This snippet only presents soutions
_x000D_
_x000D_
_x000D_

Here are example results for Chrome for short string

enter image description here

How do I implement a callback in PHP?

I cringe every time I use create_function() in php.

Parameters are a coma separated string, the whole function body in a string... Argh... I think they could not have made it uglier even if they tried.

Unfortunately, it is the only choice when creating a named function is not worth the trouble.

R: Plotting a 3D surface from x, y, z

You could look at using Lattice. In this example I have defined a grid over which I want to plot z~x,y. It looks something like this. Note that most of the code is just building a 3D shape that I plot using the wireframe function.

The variables "b" and "s" could be x or y.

require(lattice)

# begin generating my 3D shape
b <- seq(from=0, to=20,by=0.5)
s <- seq(from=0, to=20,by=0.5)
payoff <- expand.grid(b=b,s=s)
payoff$payoff <- payoff$b - payoff$s
payoff$payoff[payoff$payoff < -1] <- -1
# end generating my 3D shape


wireframe(payoff ~ s * b, payoff, shade = TRUE, aspect = c(1, 1),
    light.source = c(10,10,10), main = "Study 1",
    scales = list(z.ticks=5,arrows=FALSE, col="black", font=10, tck=0.5),
    screen = list(z = 40, x = -75, y = 0))

Angular cli generate a service and include the provider in one step

In Angular 5.12 and latest Angular CLI, do

ng generate service my-service -m app.module

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

I have just faced the same problem. First, you need to install the appropriate Oracle client for your OS. In my case, to install it on Ubuntu x64 I have followed this instructions https://help.ubuntu.com/community/Oracle%20Instant%20Client#Install_RPMs

Then, you need to install cx_Oracle, a Python module to connect to the Oracle client. Again, assuming you are running Ubuntu in a 64bit machine, you should type in a shell:

wget -c http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm
sudo alien -i cx_Oracle-5.0.4-11g-unicode-py27-1.x86_64.rpm

This will work for Oracle 11g if you have installed Python 2.7.x, but you can download a different cx_Oracle version in http://cx-oracle.sourceforge.net/ To check which Python version do you have, type in a terminal:

python -V

I hope it helps

How to call a method in MainActivity from another class?

You have to pass instance of MainActivity into another class, then you can call everything public (in MainActivity) from everywhere.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    // Instance of AnotherClass for future use
    private AnotherClass anotherClass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Create new instance of AnotherClass and
        // pass instance of MainActivity by "this"
        anotherClass = new AnotherClass(this);
    }

    // Method you want to call from another class
    public void startChronometer(){
        ...
    }
}

AnotherClass.java

public class AnotherClass {

    // Main class instance
    private MainActivity mainActivity;  

    // Constructor
    public AnotherClass(MainActivity activity) {

        // Save instance of main class for future use
        mainActivity = activity;  

        // Call method in MainActivity
        mainActivity.startChronometer();
    }
}

Remove multiple items from a Python list in just one statement

I don't know why everyone forgot to mention the amazing capability of sets in python. You can simply cast your list into a set and then remove whatever you want to remove in a simple expression like so:

>>> item_list = ['item', 5, 'foo', 3.14, True]
>>> item_list = set(item_list) - {'item', 5}
>>> item_list
{True, 3.14, 'foo'}
>>> # you can cast it again in a list-from like so
>>> item_list = list(item_list)
>>> item_list
[True, 3.14, 'foo']

Float a div above page content

Yes, the higher the z-index, the better. It will position your content element on top of every other element on the page. Say you have z-index to some elements on your page. Look for the highest and then give a higher z-index to your popup element. This way it will flow even over the other elements with z-index. If you don't have a z-index in any element on your page, you should give like z-index:2; or something higher.

Why do we have to specify FromBody and FromUri?

Just addition to above answers ..

[FromUri] can also be used to bind complex types from uri parameters instead of passing parameters from querystring

For Ex..

public class GeoPoint
{
    public double Latitude { get; set; } 
    public double Longitude { get; set; }
}

[RoutePrefix("api/Values")]
public ValuesController : ApiController
{
    [Route("{Latitude}/{Longitude}")]
    public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}

Can be called like:

http://localhost/api/values/47.678558/-122.130989

How to use clock() in C++

Probably you might be interested in timer like this : H : M : S . Msec.

the code in Linux OS:

#include <iostream>
#include <unistd.h>

using namespace std;
void newline(); 

int main() {

int msec = 0;
int sec = 0;
int min = 0;
int hr = 0;


//cout << "Press any key to start:";
//char start = _gtech();

for (;;)
{
        newline();
                if(msec == 1000)
                {
                        ++sec;
                        msec = 0;
                }
                if(sec == 60)
                {
                        ++min;
                        sec = 0; 
                }
                if(min == 60)
                {
                        ++hr;
                        min = 0;
                }
        cout << hr << " : " << min << " : " << sec << " . " << msec << endl;
        ++msec;
        usleep(100000); 

}

    return 0;
}

void newline()
{
        cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
}

An efficient way to Base64 encode a byte array?

Here is the code to base64 encode directly to byte array (tested to be performing +-10% of .Net Implementation, but allocates half the memory):

    static public void testBase64EncodeToBuffer()
    {
        for (int i = 1; i < 200; ++i)
        {
            // prep test data
            byte[] testData = new byte[i];
            for (int j = 0; j < i; ++j)
                testData[j] = (byte)(j ^ i);

            // test
            testBase64(testData);
        }
    }

    static void testBase64(byte[] data)
    {
        if (!appendBase64(data, 0, data.Length, false).SequenceEqual(System.Text.Encoding.ASCII.GetBytes(Convert.ToBase64String(data)))) throw new Exception("Base 64 encoding failed");
    }

    static public byte[] appendBase64(byte[] data
                              , int offset
                              , int size
                              , bool addLineBreaks = false)
    {
        byte[] buffer;
        int bufferPos = 0;
        int requiredSize = (4 * ((size + 2) / 3));
        // size/76*2 for 2 line break characters    
        if (addLineBreaks) requiredSize += requiredSize + (requiredSize / 38);

        buffer = new byte[requiredSize];

        UInt32 octet_a;
        UInt32 octet_b;
        UInt32 octet_c;
        UInt32 triple;
        int lineCount = 0;
        int sizeMod = size - (size % 3);
        // adding all data triplets
        for (; offset < sizeMod;)
        {
            octet_a = data[offset++];
            octet_b = data[offset++];
            octet_c = data[offset++];

            triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

            buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];
            if (addLineBreaks)
            {
                if (++lineCount == 19)
                {
                    buffer[bufferPos++] = 13;
                    buffer[bufferPos++] = 10;
                    lineCount = 0;
                }
            }
        }

        // last bytes
        if (sizeMod < size)
        {
            octet_a = offset < size ? data[offset++] : (UInt32)0;
            octet_b = offset < size ? data[offset++] : (UInt32)0;
            octet_c = (UInt32)0; // last character is definitely padded

            triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

            buffer[bufferPos++] = base64EncodingTable[(triple >> 3 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 2 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 1 * 6) & 0x3F];
            buffer[bufferPos++] = base64EncodingTable[(triple >> 0 * 6) & 0x3F];

            // add padding '='
            sizeMod = size % 3;
            // last character is definitely padded
            buffer[bufferPos - 1] = (byte)'=';
            if (sizeMod == 1) buffer[bufferPos - 2] = (byte)'=';
        }
        return buffer;
    }

How to add onload event to a div element

I am learning javascript and jquery and was going through all the answer, i faced same issue when calling javascript function for loading div element. I tried $('<divid>').ready(function(){alert('test'}) and it worked for me. I want to know is this good way to perform onload call on div element in the way i did using jquery selector.

thanks

How to find the type of an object in Go?

I found 3 ways to return a variable's type at runtime:

Using string formatting

func typeof(v interface{}) string {
    return fmt.Sprintf("%T", v)
}

Using reflect package

func typeof(v interface{}) string {
    return reflect.TypeOf(v).String()
}

Using type assertions

func typeof(v interface{}) string {
    switch v.(type) {
    case int:
        return "int"
    case float64:
        return "float64"
    //... etc
    default:
        return "unknown"
    }
}

Every method has a different best use case:

  • string formatting - short and low footprint (not necessary to import reflect package)

  • reflect package - when need more details about the type we have access to the full reflection capabilities

  • type assertions - allows grouping types, for example recognize all int32, int64, uint32, uint64 types as "int"

Selected value for JSP drop down using JSTL

Below is Example of simple dropdown using jstl tag

 <form:select path="cityFrom">  
    <form:option value="Ghaziabad" label="Ghaziabad"/>  
    <form:option value="Modinagar" label="Modinagar"/>  
    <form:option value="Meerut" label="Meerut"/>  
    <form:option value="Amristar" label="Amristar"/>  
 </form:select>

Get json value from response

If response is in json and not a string then

alert(response.id);
or
alert(response['id']);

otherwise

var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301

Import pfx file into particular certificate store from command line

To anyone else looking for this, I wasn't able to use certutil -importpfx into a specific store, and I didn't want to download the importpfx tool supplied by jaspernygaard's answer in order to avoid the requirement of copying the file to a large number of servers. I ended up finding my answer in a powershell script shown here.

The code uses System.Security.Cryptography.X509Certificates to import the certificate and then moves it into the desired store:

function Import-PfxCertificate { 

    param([String]$certPath,[String]$certRootStore = “localmachine”,[String]$certStore = “My”,$pfxPass = $null) 
    $pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 

    if ($pfxPass -eq $null) 
    {
        $pfxPass = read-host "Password" -assecurestring
    } 

    $pfx.import($certPath,$pfxPass,"Exportable,PersistKeySet") 

    $store = new-object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore) 
    $store.open("MaxAllowed") 
    $store.add($pfx) 
    $store.close() 
}

Oracle - Insert New Row with Auto Incremental ID

You can use either SEQUENCE or TRIGGER to increment automatically the value of a given column in your database table however the use of TRIGGERS would be more appropriate. See the following documentation of Oracle that contains major clauses used with triggers with suitable examples.

Use the CREATE TRIGGER statement to create and enable a database trigger, which is:

  • A stored PL/SQL block associated with a table, a schema, or the database or

  • An anonymous PL/SQL block or a call to a procedure implemented in PL/SQL or Java

Oracle Database automatically executes a trigger when specified conditions occur. See.


Following is a simple TRIGGER just as an example for you that inserts the primary key value in a specified table based on the maximum value of that column. You can modify the schema name, table name etc and use it. Just give it a try.

/*Create a database trigger that generates automatically primary key values on the CITY table using the max function.*/

CREATE OR REPLACE TRIGGER PROJECT.PK_MAX_TRIGGER_CITY
BEFORE INSERT ON PROJECT.CITY
FOR EACH ROW
DECLARE 
    CNT NUMBER;
    PKV CITY.CITY_ID%TYPE;
    NO NUMBER;
BEGIN
    SELECT COUNT(*)INTO CNT FROM CITY;

    IF CNT=0 THEN
        PKV:='CT0001';
    ELSE
        SELECT 'CT'||LPAD(MAX(TO_NUMBER(SUBSTR(CITY_ID,3,LENGTH(CITY_ID)))+1),4,'0') INTO PKV
        FROM CITY;
    END IF; 
    :NEW.CITY_ID:=PKV;
END;

Would automatically generates values such as CT0001, CT0002, CT0002 and so on and inserts into the given column of the specified table.

Calling a method inside another method in same class

Java implicitly assumes a reference to the current object for methods called like this. So

// Test2.java
public class Test2 {
    public void testMethod() {
        testMethod2();
    }

    // ...
}

Is exactly the same as

// Test2.java
public class Test2 {
    public void testMethod() {
        this.testMethod2();
    }

    // ...
}

I prefer the second version to make more clear what you want to do.

php stdClass to array

use this function to get a standard array back of the type you are after...

return get_object_vars($booking);

JQUERY ajax passing value from MVC View to Controller

Try using the data option of the $.ajax function. More info here.

$('#btnSaveComments').click(function () {
    var comments = $('#txtComments').val();
    var selectedId = $('#hdnSelectedId').val();

    $.ajax({
        url: '<%: Url.Action("SaveComments")%>',
        data: { 'id' : selectedId, 'comments' : comments },
        type: "post",
        cache: false,
        success: function (savingStatus) {
            $("#hdnOrigComments").val($('#txtComments').val());
            $('#lblCommentsNotification').text(savingStatus);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#lblCommentsNotification').text("Error encountered while saving the comments.");
        }
    });
});

CSS Animation onClick

Try this:

<div>
 <p onclick="startAnimation()">Start</p><!--O botão para iniciar (start)-->
 <div id="animation">Hello!</div> <!--O elemento que você quer animar-->
</div>

<style>
@keyframes animationName {
from {margin-left:-30%;}
}
</style>

<script>
function startAnimation() {
    document.getElementById("animation").style.animation = "animationName 2s linear 1";
}
</script>

Git - Ignore files during merge

Here git-update-index - Register file contents in the working tree to the index.

git update-index --assume-unchanged <PATH_OF_THE_FILE>

Example:-

git update-index --assume-unchanged somelocation/pom.xml

Why would we call cin.clear() and cin.ignore() after reading input?

use cin.ignore(1000,'\n') to clear all of chars of the previous cin.get() in the buffer and it will choose to stop when it meet '\n' or 1000 chars first.

Disable form auto submit on button click

You could just try using return false (return false overrides default behaviour on every DOM element) like that :

myform.onsubmit = function ()
{ 
  // do what you want
  return false
}

and then submit your form using myform.submit()

or alternatively :

mybutton.onclick = function () 
{
   // do what you want
   return false
}

Also, if you use type="button" your form will not be submitted.

How can I select random files from a directory in bash?

If you have more files in your folder, you can use the below piped command I found in unix stackexchange.

find /some/dir/ -type f -print0 | xargs -0 shuf -e -n 8 -z | xargs -0 cp -vt /target/dir/

Here I wanted to copy the files, but if you want to move files or do something else, just change the last command where I have used cp.

Truncate (not round off) decimal numbers in javascript

Here is simple but working function to truncate number upto 2 decimal places.

           function truncateNumber(num) {
                var num1 = "";
                var num2 = "";
                var num1 = num.split('.')[0];
                num2 = num.split('.')[1];
                var decimalNum = num2.substring(0, 2);
                var strNum = num1 +"."+ decimalNum;
                var finalNum = parseFloat(strNum);
                return finalNum;
            }

How can the default node version be set using NVM?

This will set the default to be the most current version of node

nvm alias default node

and then you'll need to run

nvm use default

or exit and open a new tab

How to program a delay in Swift 3

Try the following function implemented in Swift 3.0 and above

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

Usage

delayWithSeconds(1) {
   //Do something
}

How can I configure Logback to log different levels for a logger to different destinations?

The simplest solution is to use ThresholdFilter on the appenders:

    <appender name="..." class="...">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>

Full example:

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d %-5level: %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
        <target>System.err</target>
        <encoder>
            <pattern>%d %-5level: %msg%n</pattern>
        </encoder>
    </appender>

    <root>
        <appender-ref ref="STDOUT" />
        <appender-ref ref="STDERR" />
    </root>
</configuration>

Update: As Mike pointed out in the comment, messages with ERROR level are printed here both to STDOUT and STDERR. Not sure what was the OP's intent, though. You can try Mike's answer if this is not what you wanted.

How to create a table from select query result in SQL Server 2008

Select [Column Name] into [New Table] from [Source Table]

Responsive Images with CSS

the best way i found was to set the image you want to view responsively as a background image and sent a css property for the div as cover.

background-image : url('YOUR URL');
background-size : cover

How to enable Ad Hoc Distributed Queries

If ad hoc updates to system catalog is "not supported", or if you get a "Msg 5808" then you will need to configure with override like this:

EXEC sp_configure 'show advanced options', 1
RECONFIGURE with override
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE with override
GO

How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)

ax.axis('off'), will as Joe Kington pointed out, remove everything except the plotted line.

For those wanting to only remove the frame (border), and keep labels, tickers etc, one can do that by accessing the spines object on the axis. Given an axis object ax, the following should remove borders on all four sides:

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)

And, in case of removing x and y ticks from the plot:

 ax.get_xaxis().set_ticks([])
 ax.get_yaxis().set_ticks([])

How can I manually generate a .pyc file from a .py file

In Python2 you could use:

python -m compileall <pythonic-project-name>

which compiles all .py files to .pyc files in a project which contains packages as well as modules.


In Python3 you could use:

python3 -m compileall <pythonic-project-name>

which compiles all .py files to __pycache__ folders in a project which contains packages as well as modules.

Or with browning from this post:

You can enforce the same layout of .pyc files in the folders as in Python2 by using:

python3 -m compileall -b <pythonic-project-name>

The option -b triggers the output of .pyc files to their legacy-locations (i.e. the same as in Python2).

How to make button fill table cell

For starters:

<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.

This would be the optimal solution:

<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>

Convert int to ASCII and back in Python

>>> ord("a")
97
>>> chr(97)
'a'

OrderBy descending in Lambda expression?

Try this another way:

var qry = Employees
          .OrderByDescending (s => s.EmpFName)
          .ThenBy (s => s.Address)
          .Select (s => s.EmpCode);

Queryable.ThenBy

StringStream in C#

You can use a StringWriter to write values to a string. It provides a stream-like syntax (though does not derive from Stream) which works with an underlying StringBuilder.

Remove duplicates in the list using linq

Use Distinct() but keep in mind that it uses the default equality comparer to compare values, so if you want anything beyond that you need to implement your own comparer.

Please see http://msdn.microsoft.com/en-us/library/bb348436.aspx for an example.

How can I nullify css property?

To get rid of the fixed height property you can set it to the default value:

height: auto;

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

Following environment variables worked for me on Debian Wheezy 7 and Tomcat 7:

CATALINA_HOME=/usr/share/tomcat7
CATALINA_BASE=/var/lib/tomcat7
CATALINA_TMPDIR=/tmp/tomcat7

(I did create /tmp/tomcat7 manually)

Code to loop through all records in MS Access

Found a good code with comments explaining each statement. Code found at - accessallinone

Sub DAOLooping()
On Error GoTo ErrorHandler

Dim strSQL As String
Dim rs As DAO.Recordset

strSQL = "tblTeachers"
'For the purposes of this post, we are simply going to make 
'strSQL equal to tblTeachers.
'You could use a full SELECT statement such as:
'SELECT * FROM tblTeachers (this would produce the same result in fact).
'You could also add a Where clause to filter which records are returned:
'SELECT * FROM tblTeachers Where ZIPPostal = '98052'
' (this would return 5 records)

Set rs = CurrentDb.OpenRecordset(strSQL)
'This line of code instantiates the recordset object!!! 
'In English, this means that we have opened up a recordset 
'and can access its values using the rs variable.

With rs


    If Not .BOF And Not .EOF Then
    'We don’t know if the recordset has any records, 
    'so we use this line of code to check. If there are no records 
    'we won’t execute any code in the if..end if statement.    

        .MoveLast
        .MoveFirst
        'It is not necessary to move to the last record and then back 
        'to the first one but it is good practice to do so.

        While (Not .EOF)
        'With this code, we are using a while loop to loop 
        'through the records. If we reach the end of the recordset, .EOF 
        'will return true and we will exit the while loop.

            Debug.Print rs.Fields("teacherID") & " " & rs.Fields("FirstName")
            'prints info from fields to the immediate window

            .MoveNext
            'We need to ensure that we use .MoveNext, 
            'otherwise we will be stuck in a loop forever… 
            '(or at least until you press CTRL+Break)
        Wend

    End If

    .close
    'Make sure you close the recordset...
End With

ExitSub:
    Set rs = Nothing
    '..and set it to nothing
    Exit Sub
ErrorHandler:
    Resume ExitSub
End Sub

Recordsets have two important properties when looping through data, EOF (End-Of-File) and BOF (Beginning-Of-File). Recordsets are like tables and when you loop through one, you are literally moving from record to record in sequence. As you move through the records the EOF property is set to false but after you try and go past the last record, the EOF property becomes true. This works the same in reverse for the BOF property.

These properties let us know when we have reached the limits of a recordset.

How to Maximize a firefox browser window using Selenium WebDriver with node.js

First instantiate a firefox driver

WebDriver driver = new FirefoxDriver();

then maximize it

 driver.manage().window().maximize();

Retrieving an element from array list in Android?

public class DemoActivity extends Activity {
    /** Called when the activity is first created. */
    ArrayList<String> al = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);



        // add elements to the array list

        al.add("C");
        al.add("A");
        al.add("E");
        al.add("B");
        al.add("D");
        al.add("F");

        // retrieve elements from array

        String data = al.get(pass the index here);
        System.out.println("Data is "+ data);

This is another way of getting element

        Iterator<String> it = al.iterator();
        while (it.hasNext()) {
            System.out.println("Data is "+ it.next());
        }
    }

PHP + MySQL transactions examples

Please check which storage engine you are using. If it is MyISAM, then Transaction('COMMIT','ROLLBACK') will not be supported because only the InnoDB storage engine, not MyISAM, supports transactions.

RSA Public Key format

Starting from the decoded base64 data of an OpenSSL rsa-ssh Key, i've been able to guess a format:

  • 00 00 00 07: four byte length prefix (7 bytes)
  • 73 73 68 2d 72 73 61: "ssh-rsa"
  • 00 00 00 01: four byte length prefix (1 byte)
  • 25: RSA Exponent (e): 25
  • 00 00 01 00: four byte length prefix (256 bytes)
  • RSA Modulus (n):

    7f 9c 09 8e 8d 39 9e cc d5 03 29 8b c4 78 84 5f
    d9 89 f0 33 df ee 50 6d 5d d0 16 2c 73 cf ed 46 
    dc 7e 44 68 bb 37 69 54 6e 9e f6 f0 c5 c6 c1 d9 
    cb f6 87 78 70 8b 73 93 2f f3 55 d2 d9 13 67 32 
    70 e6 b5 f3 10 4a f5 c3 96 99 c2 92 d0 0f 05 60 
    1c 44 41 62 7f ab d6 15 52 06 5b 14 a7 d8 19 a1 
    90 c6 c1 11 f8 0d 30 fd f5 fc 00 bb a4 ef c9 2d 
    3f 7d 4a eb d2 dc 42 0c 48 b2 5e eb 37 3c 6c a0 
    e4 0a 27 f0 88 c4 e1 8c 33 17 33 61 38 84 a0 bb 
    d0 85 aa 45 40 cb 37 14 bf 7a 76 27 4a af f4 1b 
    ad f0 75 59 3e ac df cd fc 48 46 97 7e 06 6f 2d 
    e7 f5 60 1d b1 99 f8 5b 4f d3 97 14 4d c5 5e f8 
    76 50 f0 5f 37 e7 df 13 b8 a2 6b 24 1f ff 65 d1 
    fb c8 f8 37 86 d6 df 40 e2 3e d3 90 2c 65 2b 1f 
    5c b9 5f fa e9 35 93 65 59 6d be 8c 62 31 a9 9b 
    60 5a 0e e5 4f 2d e6 5f 2e 71 f3 7e 92 8f fe 8b
    

The closest validation of my theory i can find it from RFC 4253:

The "ssh-rsa" key format has the following specific encoding:

  string    "ssh-rsa"
  mpint     e
  mpint     n

Here the 'e' and 'n' parameters form the signature key blob.

But it doesn't explain the length prefixes.


Taking the random RSA PUBLIC KEY i found (in the question), and decoding the base64 into hex:

30 82 01 0a 02 82 01 01 00 fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
63 02 03 01 00 01

From RFC3447 - Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1:

A.1.1 RSA public key syntax

An RSA public key should be represented with the ASN.1 type RSAPublicKey:

  RSAPublicKey ::= SEQUENCE {
     modulus           INTEGER,  -- n
     publicExponent    INTEGER   -- e
  }

The fields of type RSAPublicKey have the following meanings:

  • modulus is the RSA modulus n.
  • publicExponent is the RSA public exponent e.

Using Microsoft's excellent (and the only real) ASN.1 documentation:

30 82 01 0a       ;SEQUENCE (0x010A bytes: 266 bytes)
|  02 82 01 01    ;INTEGER  (0x0101 bytes: 257 bytes)
|  |  00          ;leading zero because high-bit, but number is positive
|  |  fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
|  |  e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
|  |  11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
|  |  dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
|  |  fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
|  |  23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
|  |  9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
|  |  4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
|  |  41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
|  |  97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
|  |  fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
|  |  63 
|  02 03          ;INTEGER (3 bytes)
|     01 00 01

giving the public key modulus and exponent:

  • modulus = 0xfb1199ff0733f6e805a4fd3b36ca68...837a63
  • exponent = 65,537

Update: My expanded form of this answer in another question

GitLab git user password

if you are sure that you have uploaded the content of key.pub into GitLab, then: 1- Open Git Bash "Not CMD" 2- Browse to Solution Folder "CD Path" 3- Type Git Init 4- Type Git Add . 4- Type Git Commit 6- Type Git Push

and it will work.. another hint: make sure the path of the file where you copied the key is correct and equivalent to the same path it showed on CMD when creating the keys

Combining two sorted lists in Python

If you want to do it in a manner more consistent with learning what goes on in the iteration try this

def merge_arrays(a, b):
    l= []

    while len(a) > 0 and len(b)>0:
        if a[0] < b[0]: l.append(a.pop(0))    
        else:l.append(b.pop(0))

    l.extend(a+b)
    print( l )

How can I create Min stl priority_queue?

Multiply values with -1 and use max heap to get the effect of min heap

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

How to get the last element of a slice?

For just reading the last element of a slice:

sl[len(sl)-1]

For removing it:

sl = sl[:len(sl)-1]

See this page about slice tricks

increase font size of hyperlink text html

You can do like this:

a {font-size: 100px}

Try avoid using font tag because it's deprecated. Use CSS like above instead. You can give your anchors specific class and apply any style for them.

The server encountered an internal error or misconfiguration and was unable to complete your request

You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)

usually the log file is in

/var/log/apache2/error.log

or

/var/log/httpd/error.log

Remove specific characters from a string in Javascript

if it is not the first two chars and you wanna remove F0 from the whole string then you gotta use this regex

_x000D_
_x000D_
   let string = 'F0123F0456F0';_x000D_
   let result = string.replace(/F0/ig, '');_x000D_
   console.log(result);
_x000D_
_x000D_
_x000D_

Alter a MySQL column to be AUTO_INCREMENT

You can apply the atuto_increment constraint to the data column by the following query:

ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;

But, if the columns are part of a foreign key constraint you, will most probably receive an error. Therefore, it is advised to turn off foreign_key_checks by using the following query:

SET foreign_key_checks = 0;

Therefore, use the following query instead:

SET foreign_key_checks = 0;
ALTER TABLE customers MODIFY COLUMN customer_id BIGINT NOT NULL AUTO_INCREMENT;
SET foreign_key_checks = 1;

windows batch file rename

I found this solution via PowerShell :

dir | rename-item -NewName {$_.name -replace "replaceME","MyNewTxt"}

This will rename parts of all the files in the current folder.

How to generate a core dump in Linux on a segmentation fault?

Ubuntu 19.04

All other answers themselves didn't help me. But the following sum up did the job

Create ~/.config/apport/settings with the following content:

[main]
unpackaged=true

(This tells apport to also write core dumps for custom apps)

check: ulimit -c. If it outputs 0, fix it with

ulimit -c unlimited

Just for in case restart apport:

sudo systemctl restart apport

Crash files are now written in /var/crash/. But you cannot use them with gdb. To use them with gdb, use

apport-unpack <location_of_report> <target_directory>

Further information:

  • Some answers suggest changing core_pattern. Be aware, that that file might get overwritten by the apport service on restarting.
  • Simply stopping apport did not do the job
  • The ulimit -c value might get changed automatically while you're trying other answers of the web. Be sure to check it regularly during setting up your core dump creation.

References:

CocoaPods Errors on Project Build

I got rid of the same problem by doing following steps:

  • Xcode->Product->Clean Build Folder (hold alt key on Product to see it)
  • Open Xcode->Window->Organizer and select Projects tab. Then find your project and delete derived data of the project.

How do I debug error ECONNRESET in Node.js?

Try adding these options to socket.io:

const options = { transports: ['websocket'], pingTimeout: 3000, pingInterval: 5000 };

I hope this will help you !

How do I fix the npm UNMET PEER DEPENDENCY warning?

Ok so i struggled for a long time trying to figure this out. Here is the nuclear option, for when you have exhausted all other ways..

When you are done, and it still works, import your actual code into this new project. Fix any compile errors the newer version of angular causes.

Thats what did it for me.. 1 hour of rework vs 6 hours of trying to figure out wtf was wrong.. wish i did it this way to start..

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

What is the Angular equivalent to an AngularJS $watch?

If you want to make it 2 way binding, you can use [(yourVar)], but you have to implement yourVarChange event and call it everytime your variable change.

Something like this to track the hero change

@Output() heroChange = new EventEmitter();

and then when your hero get changed, call this.heroChange.emit(this.hero);

the [(hero)] binding will do the rest for you

see example here:

http://plnkr.co/edit/efOGIJ0POh1XQeRZctSx?p=preview

How do I use .toLocaleTimeString() without displaying seconds?

The value returned by Date.prototype.toLocaleString is implementation dependent, so you get what you get. You can try to parse the string to remove seconds, but it may be different in different browsers so you'd need to make allowance for every browser in use.

Creating your own, unambiguous format isn't difficult using Date methods. For example:

function formatTimeHHMMA(d) {
  function z(n){return (n<10?'0':'')+n}
  var h = d.getHours();
  return (h%12 || 12) + ':' + z(d.getMinutes()) + ' ' + (h<12? 'AM' :'PM');
}

Is there a way to get colored text in GitHubflavored Markdown?

You cannot get green/red text, but you can get green/red highlighted text using the diff language template. Example:

```diff
+ this text is highlighted in green
- this text is highlighted in red
```

How to call base.base.method()?

My 2c for this is to implement the functionality you require to be called in a toolkit class and call that from wherever you need:

// Util.cs
static class Util 
{
    static void DoSomething( FooBase foo ) {}
}

// FooBase.cs
class FooBase
{
    virtual void Do() { Util.DoSomething( this ); }
}


// FooDerived.cs
class FooDerived : FooBase
{
    override void Do() { ... }
}

// FooDerived2.cs
class FooDerived2 : FooDerived
{
    override void Do() { Util.DoSomething( this ); }
}

This does require some thought as to access privilege, you may need to add some internal accessor methods to facilitate the functionality.

Create ArrayList from array

Even though there are many perfectly written answers to this question, I will add my inputs.

Say you have Element[] array = { new Element(1), new Element(2), new Element(3) };

New ArrayList can be created in the following ways

ArrayList<Element> arraylist_1 = new ArrayList<>(Arrays.asList(array));
ArrayList<Element> arraylist_2 = new ArrayList<>(
    Arrays.asList(new Element[] { new Element(1), new Element(2), new Element(3) }));

// Add through a collection
ArrayList<Element> arraylist_3 = new ArrayList<>();
Collections.addAll(arraylist_3, array);

And they very well support all operations of ArrayList

arraylist_1.add(new Element(4)); // or remove(): Success
arraylist_2.add(new Element(4)); // or remove(): Success
arraylist_3.add(new Element(4)); // or remove(): Success

But the following operations returns just a List view of an ArrayList and not actual ArrayList.

// Returns a List view of array and not actual ArrayList
List<Element> listView_1 = (List<Element>) Arrays.asList(array);
List<Element> listView_2 = Arrays.asList(array);
List<Element> listView_3 = Arrays.asList(new Element(1), new Element(2), new Element(3));

Therefore, they will give error when trying to make some ArrayList operations

listView_1.add(new Element(4)); // Error
listView_2.add(new Element(4)); // Error
listView_3.add(new Element(4)); // Error

More on List representation of array link.

Clone() vs Copy constructor- which is recommended in java

clone() was designed with several mistakes (see this question), so it's best to avoid it.

From Effective Java 2nd Edition, Item 11: Override clone judiciously

Given all of the problems associated with Cloneable, it’s safe to say that other interfaces should not extend it, and that classes designed for inheritance (Item 17) should not implement it. Because of its many shortcomings, some expert programmers simply choose never to override the clone method and never to invoke it except, perhaps, to copy arrays. If you design a class for inheritance, be aware that if you choose not to provide a well-behaved protected clone method, it will be impossible for subclasses to implement Cloneable.

This book also describes the many advantages copy constructors have over Cloneable/clone.

  • They don't rely on a risk-prone extralinguistic object creation mechanism
  • They don't demand unenforceable adherence to thinly documented conventions
  • They don't conflict with the proper use of final fields
  • They don't throw unnecessary checked exceptions
  • They don't require casts.

All standard collections have copy constructors. Use them.

List<Double> original = // some list
List<Double> copy = new ArrayList<Double>(original);

Why does z-index not work?

The z-index property only works on elements with a position value other than static (e.g. position: absolute;, position: relative;, or position: fixed).

There is also position: sticky; that is supported in Firefox, is prefixed in Safari, worked for a time in older versions of Chrome under a custom flag, and is under consideration by Microsoft to add to their Edge browser.

Important
For regular positioning, be sure to include position: relative on the elements where you also set the z-index. Otherwise, it won't take effect.

How to embed a SWF file in an HTML page?

<object type="application/x-shockwave-flash" data="http://www.youtube.com/v/VhtIydTmOVU&amp;hl=en&amp;fs=1&amp;color1=0xe1600f&amp;color2=0xfebd01" 
style="width:640px;height:480px;margin:10px 36px;">

<param name="movie" value="http://www.youtube.com/v/VhtIydTmOVU&amp;hl=en&amp;fs=1&amp;color1=0xe1600f&amp;color2=0xfebd01" />
<param name="allowfullscreen" value="true" />
<param name="allowscriptaccess" value="always" />
<param name="wmode" value="opaque" />
<param name="quality" value="high" />
<param name="menu" value="false" />

</object>

IOPub data rate exceeded in Jupyter notebook (when viewing image)

Try this:

jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10

Or this:

yourTerminal:prompt> jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10 

How to update Identity Column in SQL Server?

You can also use SET IDENTITY INSERT to allow you to insert values into an identity column.

Example:

SET IDENTITY_INSERT dbo.Tool ON
GO

And then you can insert into an identity column the values you need.

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

In many applications, like MsOffice (until version 2000 or 2002), the maximum number of characters per cell was 255. Moving data from programs able of handling more than 255 characters per field to/from those applications was a nightmare. Currently, the limit is less and less hindering.

how to add value to combobox item

Instead of adding Reader("Name") you add a new ListItem. ListItem has a Text and a Value property that you can set.

Adding an .env file to React Project

So I'm myself new to React and I found a way to do it.

This solution does not require any extra packages.

Step 1 ReactDocs

In the above docs they mention export in Shell and other options, the one I'll attempt to explain is using .env file

1.1 create Root/.env

#.env file
REACT_APP_SECRET_NAME=secretvaluehere123

Important notes it MUST start with REACT_APP_

1.2 Access ENV variable

#App.js file or the file you need to access ENV
<p>print env secret to HTML</p>
<pre>{process.env.REACT_APP_SECRET_NAME}</pre>

handleFetchData() { // access in API call
  fetch(`https://awesome.api.io?api-key=${process.env.REACT_APP_SECRET_NAME}`)
    .then((res) => res.json())
    .then((data) => console.log(data))
}

1.3 Build Env Issue

So after I did step 1.1|2 it was not working, then I found the above issue/solution. React read/creates env when is built so you need to npm run start every time you modify the .env file so the variables get updated.

Can one class extend two classes?

If you are interested in using methods from multiple classes, the best way to approach to it is to use Composition instead of Inheritence

Creating a list of pairs in java

just fixing some small mistakes in Mark Elliot's code:

public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r){
        this.l = l;
        this.r = r;
    }
    public L getL(){ return l; }
    public R getR(){ return r; }
    public void setL(L l){ this.l = l; }
    public void setR(R r){ this.r = r; }
}

How do I create a branch?

svn cp /trunk/ /branch/NEW_Branch

If you have some local changes in trunk then use Rsync to sync changes

rsync -r -v -p --exclude ".svn" /trunk/ /branch/NEW_Branch

Replace non-numeric with empty string

Definitely regex:

string CleanPhone(string phone)
{
    Regex digitsOnly = new Regex(@"[^\d]");   
    return digitsOnly.Replace(phone, "");
}

or within a class to avoid re-creating the regex all the time:

private static Regex digitsOnly = new Regex(@"[^\d]");   

public static string CleanPhone(string phone)
{
    return digitsOnly.Replace(phone, "");
}

Depending on your real-world inputs, you may want some additional logic there to do things like strip out leading 1's (for long distance) or anything trailing an x or X (for extensions).

Vagrant ssh authentication failure

I am using Vagrant with a Puphpet setup from May 2015 and had this problem. It appears that the configuration that was generated didn't handle Vagrant 1.7.4 (or maybe a bit earlier?) behavior of regenerating ssh keys if it detects an insecure key.

I solved it by adding the following in my Puphpet generated Vagrantfile (local setup) inside the "if File.file?(customKey)" clause:

config.ssh.insert_key = false

Reference commit

"Unable to locate tools.jar" when running ant

Make sure you use the root folder of the JDK. Don't add "\lib" to the end of the path, where tools.jar is physically located. It took me an hour to figure that one out. Also, this post will help show you where Ant is looking for tools.jar:

Why does ANT tell me that JAVA_HOME is wrong when it is not?

Bootstrap 3: Keep selected tab on page refresh

I tried the code offered by Xavi Martínez. It worked but not for IE7. The problem is - tabs don't refer to any relevant content.
So, I prefer this code for solving that problem.

function pageLoad() {
  $(document).ready(function() {

    var tabCookieName = "ui-tabs-1"; //cookie name
    var location = $.cookie(tabCookieName); //take tab's href

    if (location) {
      $('#Tabs a[href="' + location + '"]').tab('show'); //activate tab
    }

    $('#Tabs a').click(function(e) {
      e.preventDefault()
      $(this).tab('show')
    })

    //when content is alredy shown - event activate 
    $('#Tabs a').on('shown.bs.tab', function(e) {
      location = e.target.hash; // take current href
      $.cookie(tabCookieName, location, {
        path: '/'
      }); //write href in cookie
    })
  });
};

"google is not defined" when using Google Maps V3 in Firefox remotely

Add the type for the script

<script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>

So the important part is the type text/javascript.

$_POST Array from html form

Change

$info=$_POST['id[]'];

to

$info=$_POST['id'];

by adding [] to the end of your form field names, PHP will automatically convert these variables into arrays.

Get UserDetails object from Security Context in Spring MVC controller

if you are using spring security then you can get the current logged in user by

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
     String name = auth.getName(); //get logged in username

Very Simple Image Slider/Slideshow with left and right button. No autoplay

Why try to reinvent the wheel? There are more lightweight jQuery slideshow solutions out there then you could poke a stick at, and someone has already done the hard work for you and thought about issues that you might run into (cross-browser compatability etc).

jQuery Cycle is one of my favourite light weight libraries.

What you want to achieve could be done in just

    jQuery("#slideshow").cycle({
    timeout:0, // no autoplay
    fx: 'fade', //fade effect, although there are heaps
    next: '#next',
    prev: '#prev'
    });

JSFIDDLE TO SEE HOW EASY IT IS

Converting string to double in C#

You can try this example out. A simple C# progaram to convert string to double

class Calculations{

protected double length;
protected double height;
protected double width;

public void get_data(){

this.length = Convert.ToDouble(Console.ReadLine());
this.width  = Convert.ToDouble(Console.ReadLine());
this.height = Convert.ToDouble(Console.ReadLine());

   }
}

How do I use extern to share variables between source files?

                 declare | define   | initialize |
                ----------------------------------

extern int a;    yes          no           no
-------------
int a = 2019;    yes          yes          yes
-------------
int a;           yes          yes          no
-------------

Declaration won't allocate memory (the variable must be defined for memory allocation) but the definition will. This is just another simple view on the extern keyword since the other answers are really great.

What is the "continue" keyword and how does it work in Java?

Generally, I see continue (and break) as a warning that the code might use some refactoring, especially if the while or for loop declaration isn't immediately in sight. The same is true for return in the middle of a method, but for a slightly different reason.

As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.

These can be maintenance timebombs because there is no immediate link between the continue/break and the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue/break failing.

IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.

continue, break, and return (other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.

How to remove focus without setting focus to another control?

Using clearFocus() didn't seem to be working for me either as you found (saw in comments to another answer), but what worked for me in the end was adding:

<LinearLayout 
    android:id="@+id/my_layout" 
    android:focusable="true" 
    android:focusableInTouchMode="true" ...>

to my very top level Layout View (a linear layout). To remove focus from all Buttons/EditTexts etc, you can then just do

LinearLayout myLayout = (LinearLayout) activity.findViewById(R.id.my_layout);
myLayout.requestFocus();

Requesting focus did nothing unless I set the view to be focusable.

selenium get current url after loading a page

It's been a little while since I coded with selenium, but your code looks ok to me. One thing to note is that if the element is not found, but the timeout is passed, I think the code will continue to execute. So you can do something like this:

boolean exists = driver.findElements(By.xpath("//*[@id='someID']")).size() != 0

What does the above boolean return? And are you sure selenium actually navigates to the expected page? (That may sound like a silly question but are you actually watching the pages change... selenium can be run remotely you know...)

how to get curl to output only http response body (json) and no other headers etc

I was executing a get request an also want to see just the response and nothing else, seems like magic is done with -silent,-s option.

From the curl man page:

-s, --silent Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.

Below the examples:

curl -s "http://host:8080/some/resource"
curl -silent "http://host:8080/some/resource"

Using custom headers

curl -s -H "Accept: application/json" "http://host:8080/some/resource")

Using POST method with a header

curl -s -X POST -H "Content-Type: application/json" "http://host:8080/some/resource") -d '{ "myBean": {"property": "value"}}'

You can also customize the output for specific values with -w, below the options I use to get just response codes of the curl:

curl -s -o /dev/null -w "%{http_code}" "http://host:8080/some/resource"

How can I disable the bootstrap hover color for links?

a {background-color:transparent !important;}

Match everything except for specified strings

All except word "red"

_x000D_
_x000D_
var href = '(text-1) (red) (text-3) (text-4) (text-5)';_x000D_
_x000D_
var test = href.replace(/\((\b(?!red\b)[\s\S]*?)\)/g, testF); _x000D_
_x000D_
function testF(match, p1, p2, offset, str_full) {_x000D_
  p1 = "-"+p1+"-";_x000D_
  return p1;_x000D_
}_x000D_
_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

All except word "red"

_x000D_
_x000D_
var href = '(text-1) (frede) (text-3) (text-4) (text-5)';_x000D_
_x000D_
var test = href.replace(/\(([\s\S]*?)\)/g, testF); _x000D_
_x000D_
function testF(match, p1, p2, offset, str_full) {_x000D_
  p1 = p1.replace(/red/g, '');_x000D_
  p1 = "-"+p1+"-";_x000D_
  return p1;_x000D_
}_x000D_
_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

How can I limit ngFor repeat to some number of items in Angular?

For example, lets say we want to display only the first 10 items of an array, we could do this using the SlicePipe like so:

<ul>
     <li *ngFor="let item of items | slice:0:10">
      {{ item }}
     </li>
</ul>

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

Convert an enum to List<string>

Use Enum's static method, GetNames. It returns a string[], like so:

Enum.GetNames(typeof(DataSourceTypes))

If you want to create a method that does only this for only one type of enum, and also converts that array to a List, you can write something like this:

public List<string> GetDataSourceTypes()
{
    return Enum.GetNames(typeof(DataSourceTypes)).ToList();
}

You will need Using System.Linq; at the top of your class to use .ToList()

Python 3 turn range to a list

The reason why Python3 lacks a function for directly getting a ranged list is because the original Python3 designer was quite novice in Python2. He only considered the use of range() function in a for loop, thus, the list should never need to be expanded. In fact, very often we do need to use the range() function to produce a list and pass into a function.

Therefore, in this case, Python3 is less convenient as compared to Python2 because:

  • In Python2, we have xrange() and range();
  • In Python3, we have range() and list(range())

Nonetheless, you can still use list expansion in this way:

[*range(N)]

Viewing localhost website from mobile device

Use Conveyor by Keyoti (extensión de Visual Studio). Extension visual studio

Convert Long into Integer

You'll need to type cast it.

long i = 100L;
int k = (int) i;

Bear in mind that a long has a bigger range than an int so you might lose data.

If you are talking about the boxed types, then read the documentation.

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

Following from Ryan's answer, I think that the interface you are looking for is defined as follows:

interface Param {
    title: string;
    callback: () => void;
}

How do I run Redis on Windows?

One of the most easy way to run Redis on windows host is to use Docker Redis container. Just fire up Hyper-V, Download Docker and run Redis

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

Adding the following block of code in web.config solves my problem

 <system.net>
    <defaultProxy enabled="false" >
    </defaultProxy>
  </system.net>

Connect to network drive with user name and password

Use this code for Impersonation its tested in MVC.NET maybe for dot net core it required some change, If you want to dot net core let me know I will share.

 public static class ImpersonationAuthenticationNew
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool LogonUser(string usernamee, string domain, string password, LogonType dwLogonType, LogonProvider dwLogonProvider, ref IntPtr phToken);
        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hObject);
        public static bool Login(string domain,string username, string password)
        {                
            IntPtr token = IntPtr.Zero;
            var IsSuccess = LogonUser(username, domain, password, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50, ref token);
            if (IsSuccess)
            {
                using (WindowsImpersonationContext person = new WindowsIdentity(token).Impersonate())
                {
                    var xIdentity = WindowsIdentity.GetCurrent();
                    #region Start ImpersonationContext  Scope
                    try
                    {

                        // TYPE YOUR CODE HERE 
                      return true;
                    }
                    catch (Exception ex) { throw (ex); }
                    finally {
                        person.Undo();
                        CloseHandle(token);
                       
                    }
                    #endregion
                }
            }
            return false;
        }
    }

    #region Enums
    public enum LogonType
    {
        /// <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,
    }
    public enum LogonProvider
    {
        /// <summary>
        /// Use the standard logon provider for the system.
        /// The default security provider is negotiate, unless you pass NULL for the domain name and the user name
        /// is not in UPN format. In this case, the default provider is NTLM.
        /// NOTE: Windows 2000/NT:   The default security provider is NTLM.
        /// </summary>
        LOGON32_PROVIDER_DEFAULT = 0,
        LOGON32_PROVIDER_WINNT35 = 1,
        LOGON32_PROVIDER_WINNT40 = 2,
        LOGON32_PROVIDER_WINNT50 = 3
    }
    #endregion

How to parse a CSV file in Bash?

You need to use IFS instead of -d:

while IFS=, read -r col1 col2
do
    echo "I got:$col1|$col2"
done < myfile.csv

Note that for general purpose CSV parsing you should use a specialized tool which can handle quoted fields with internal commas, among other issues that Bash can't handle by itself. Examples of such tools are cvstool and csvkit.

What is the difference between i++ and ++i?

The way the operator works is that it gets incremented at the same time, but if it is before a variable, the expression will evaluate with the incremented/decremented variable:

int x = 0;   //x is 0
int y = ++x; //x is 1 and y is 1

If it is after the variable the current statement will get executed with the original variable, as if it had not yet been incremented/decremented:

int x = 0;   //x is 0
int y = x++; //'y = x' is evaluated with x=0, but x is still incremented. So, x is 1, but y is 0

I agree with dcp in using pre-increment/decrement (++x) unless necessary. Really the only time I use the post-increment/decrement is in while loops or loops of that sort. These loops are the same:

while (x < 5)  //evaluates conditional statement
{
    //some code
    ++x;       //increments x
}

or

while (x++ < 5) //evaluates conditional statement with x value before increment, and x is incremented
{
    //some code
}

You can also do this while indexing arrays and such:

int i = 0;
int[] MyArray = new int[2];
MyArray[i++] = 1234; //sets array at index 0 to '1234' and i is incremented
MyArray[i] = 5678;   //sets array at index 1 to '5678'
int temp = MyArray[--i]; //temp is 1234 (becasue of pre-decrement);

Etc, etc...

How to disassemble a binary executable in Linux to get the assembly code?

there's also ndisasm, which has some quirks, but can be more useful if you use nasm. I agree with Michael Mrozek that objdump is probably best.

[later] you might also want to check out Albert van der Horst's ciasdis: http://home.hccnet.nl/a.w.m.van.der.horst/forthassembler.html. it can be hard to understand, but has some interesting features you won't likely find anywhere else.

Visual Studio Community 2015 expiration date

In my case, even after sign up to Visual Studio account, I cant sign in and the license still expired.

Solution from across the internet: Download iso version of the installer. Then run installer, select repair. That would solve the problem for most case.

In my case, I got an iso version of ms Visual Studio 2013. Installed it and I can successfully sign in and its forever free.

Header and footer in CodeIgniter

CodeIgniter-Assets is easy to configure repository to have custom header and footer with CodeIgniter I hope this will solve your problem.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

I had the same problem but it had nothing to do with annotations. The problem happened while indexing beans in my container (Jboss EAP 6.3). One of my beans could not be indexed because it used Java 8 features an I got this sneaky little warning while deploying:

WARN [org.jboss.as.server.deployment] ... Could not index class ... java.lang.IllegalStateException: Unknown tag! pos=20 poolCount = 133

Then at the injection point I got the error:

Unsatisfied dependencies for type ... with qualifiers @Default

The solution is to update the Java annotations index. download new version of jandex (jandex-1.2.3.Final or newer) then put it into

JBOSS_HOME\modules\system\layers\base\org\jboss\jandex\main and then update reference to the new file in module.xml

NOTE: EAP 6.4.x already have this fixed

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

The steps you took are not appropriate because the cell you want formatted is not the trigger cell (presumably won't normally be blank). In your case you want formatting to apply to one set of cells according to the status of various other cells. I suggest with data layout as shown in the image (and with thanks to @xQbert for a start on a suitable formula) you select ColumnA and:

HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::

=AND(LEN(E1)*LEN(F1)*LEN(G1)*LEN(H1)=0,NOT(ISBLANK(A1)))

Format..., select formatting, OK, OK.

SO22487695 example

where I have filled yellow the cells that are triggering the red fill result.

Is this very likely to create a memory leak in Tomcat?

This problem appears when we are using any third party solution, without using the handlers for the cleanup activitiy. For me this was happening for EhCache. We were using EhCache in our project for caching. And often we used to see following error in the logs

 SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.

And we often noticed tomcat failing for OutOfMemory error during development where we used to do backend changes and deploy the application multiple times for reflecting our changes.

This is the fix we did

<listener>
  <listener-class>
     net.sf.ehcache.constructs.web.ShutdownListener
  </listener-class>
</listener>

So point I am trying to make is check the documentation of the third party libraries which you are using. They should be providing some mechanisms to clean up the threads during shutdown. Which you need to use in your application. No need to re-invent the wheel unless its not provided by them. The worst case is to provide your own implementation.

Reference for EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html

Get button click inside UITableViewCell

// Add action in cell for row at index path -tableView

cell.buttonName.addTarget(self, action: #selector(ViewController.btnAction(_:)), for: .touchUpInside)

// Button Action

  @objc func btnAction(_ sender: AnyObject) {



        var position: CGPoint = sender.convert(.zero, to: self.tableView)


        let indexPath = self.tableView.indexPathForRow(at: position)
        let cell: UITableViewCell = tableView.cellForRow(at: indexPath!)! as
        UITableViewCell




}

Jquery selector input[type=text]')

$('input[type=text],select', '.sys');

for looping:

$('input[type=text],select', '.sys').each(function() {
   // code
});

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use the IP instead:

DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.

To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):

mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.

How to view the current heap size that an application is using?

Use this code:

// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory(); 

// Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();

 // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory(); 

It was useful to me to know it.

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

This also can happen if the device you are trying to run on has some older version of the provisioning profile you are using that points to an old, expired or revoked certificate or a certificate without associated private key. Delete any invalid Provisioning Profiles under your device section in Xcode organizer.

Laravel - Pass more than one variable to view

This is how you do it:

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();

    return $view->with('persons', $persons)->with('ms', $ms);
}

You can also use compact():

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();

    return $view->with(compact('persons', 'ms'));
}

Or do it in one line:

function view($view)
{
    return $view
            ->with('ms', Person::where('name', '=', 'Foo Bar')->first())
            ->with('persons', Person::order_by('list_order', 'ASC')->get());
}

Or even send it as an array:

function view($view)
{
    $ms = Person::where('name', '=', 'Foo Bar')->first();

    $persons = Person::order_by('list_order', 'ASC')->get();

    return $view->with('data', ['ms' => $ms, 'persons' => $persons]));
}

But, in this case, you would have to access them this way:

{{ $data['ms'] }}

What is the meaning of CTOR?

To expand a little more, there are two kinds of constructors: instance initializers (.ctor), type initializers (.cctor). Build the code below, and explore the IL code in ildasm.exe. You will notice that the static field 'b' will be initialized through .cctor() whereas the instance field will be initialized through .ctor()

internal sealed class CtorExplorer
{
   protected int a = 0;
   protected static int b = 0;
}

How to get a microtime in Node.js?

There's also https://github.com/wadey/node-microtime:

> var microtime = require('microtime')
> microtime.now()
1297448895297028

How to make a SIMPLE C++ Makefile

Why does everyone like to list out source files? A simple find command can take care of that easily.

Here's an example of a dirt simple C++ Makefile. Just drop it in a directory containing .C files and then type make...

appname := myapp

CXX := clang++
CXXFLAGS := -std=c++11

srcfiles := $(shell find . -name "*.C")
objects  := $(patsubst %.C, %.o, $(srcfiles))

all: $(appname)

$(appname): $(objects)
    $(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)

depend: .depend

.depend: $(srcfiles)
    rm -f ./.depend
    $(CXX) $(CXXFLAGS) -MM $^>>./.depend;

clean:
    rm -f $(objects)

dist-clean: clean
    rm -f *~ .depend

include .depend

Transpose a data frame

df.aree <- as.data.frame(t(df.aree))
colnames(df.aree) <- df.aree[1, ]
df.aree <- df.aree[-1, ]
df.aree$myfactor <- factor(row.names(df.aree))

Force DOM redraw/refresh on Chrome/Mac

Sample Html:

<section id="parent">
  <article class="child"></article>
  <article class="child"></article>
</section>

Js:

  jQuery.fn.redraw = function() {
        return this.hide(0,function() {$(this).show(100);});
        // hide immediately and show with 100ms duration

    };

call function:

$('article.child').redraw(); //<==bad idea

$('#parent').redraw();

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

Pie chart with jQuery

jqPlot looks pretty good and it is open source.

Here's a link to the most impressive and up-to-date jqPlot examples.

How to clear browsing history using JavaScript?

No,that would be a security issue.


However, it's possible to clear the history in JavaScript within a Google chrome extension. chrome.history.deleteAll().
Use

window.location.replace('pageName.html');

similar behavior as an HTTP redirect

Read How to redirect to another webpage in JavaScript/jQuery?

Javascript Src Path

Use an relative path to the root of your site, for example:

If clock.js is on http://domain.com/javascript/clock.js

Include :

<script language="JavaScript" src="/javascript/clock.js"></script>

If it's on your domain root directory:

<script language="JavaScript" src="/clock.js"></script>

Replace all 0 values to NA

Because someone asked for the Data.Table version of this, and because the given data.frame solution does not work with data.table, I am providing the solution below.

Basically, use the := operator --> DT[x == 0, x := NA]

library("data.table")

status = as.data.table(occupationalStatus)

head(status, 10)
    origin destination  N
 1:      1           1 50
 2:      2           1 16
 3:      3           1 12
 4:      4           1 11
 5:      5           1  2
 6:      6           1 12
 7:      7           1  0
 8:      8           1  0
 9:      1           2 19
10:      2           2 40


status[N == 0, N := NA]

head(status, 10)
    origin destination  N
 1:      1           1 50
 2:      2           1 16
 3:      3           1 12
 4:      4           1 11
 5:      5           1  2
 6:      6           1 12
 7:      7           1 NA
 8:      8           1 NA
 9:      1           2 19
10:      2           2 40

Laravel Checking If a Record Exists

if (User::where('email', '[email protected]')->first()) {
    // It exists
} else {
    // It does not exist
}

Use first(), not count() if you only need to check for existence.

first() is faster because it checks for a single match whereas count() counts all matches.

TypeError: 'int' object is not callable

I was also facing this issue but in a little different scenario.

Scenario:

param = 1

def param():
    .....
def func():
    if param:
        var = {passing a dict here}
        param(var)

It looks simple and a stupid mistake here, but due to multiple lines of codes in the actual code, it took some time for me to figure out that the variable name I was using was same as my function name because of which I was getting this error.

Changed function name to something else and it worked.

So, basically, according to what I understood, this error means that you are trying to use an integer as a function or in more simple terms, the called function name is also used as an integer somewhere in the code. So, just try to find out all occurrences of the called function name and look if that is being used as an integer somewhere.

I struggled to find this, so, sharing it here so that someone else may save their time, in case if they get into this issue.

Hope this helps!

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

Variables in php are case sensitive. Please replace your while loop with following:

while ($rows = mysql_fetch_array($query)):

           $name = $rows['Name'];
           $address = $rows['Address'];
           $email = $rows['Email'];
           $subject = $rows['Subject'];
           $comment = $rows['Comment']

           echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";

           endwhile;

How to iterate over rows in a DataFrame in Pandas

For both viewing and modifying values, I would use iterrows(). In a for loop and by using tuple unpacking (see the example: i, row), I use the row for only viewing the value and use i with the loc method when I want to modify values. As stated in previous answers, here you should not modify something you are iterating over.

for i, row in df.iterrows():
    df_column_A = df.loc[i, 'A']
    if df_column_A == 'Old_Value':
        df_column_A = 'New_value'  

Here the row in the loop is a copy of that row, and not a view of it. Therefore, you should NOT write something like row['A'] = 'New_Value', it will not modify the DataFrame. However, you can use i and loc and specify the DataFrame to do the work.

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

Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified his example to do this here: http://jsfiddle.net/QLfMU/116/

single line comment in HTML

Let's keep it simple. Loved @digitaldreamer 's answer but it might leave the beginners confused. So, I am going to try and simplify it.

The only HTML comment is <!-- --> It can be used as a single line comment or double, it is really up to the developer.

So, an HTML comment starts with <!-- and ends with -->. It is really that simple. You should not use any other format, to avoid any compatibility issue even if the comment format is legit or not.

How to read a text-file resource into Java unit test?

Here's what i used to get the text files with text. I used commons' IOUtils and guava's Resources.

public static String getString(String path) throws IOException {
    try (InputStream stream = Resources.getResource(path).openStream()) {
        return IOUtils.toString(stream);
    }
}

How to listen to route changes in react router v4?

v5.1 introduces the useful hook useLocation

https://reacttraining.com/blog/react-router-v5-1/#uselocation

import { Switch, useLocation } from 'react-router-dom'

function usePageViews() {
  let location = useLocation()

  useEffect(
    () => {
      ga.send(['pageview', location.pathname])
    },
    [location]
  )
}

function App() {
  usePageViews()
  return <Switch>{/* your routes here */}</Switch>
}

Redirect from asp.net web api post action

Here is another way you can get to the root of your website without hard coding the url:

var response = Request.CreateResponse(HttpStatusCode.Moved);
string fullyQualifiedUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority);
response.Headers.Location = new Uri(fullyQualifiedUrl);

Note: Will only work if both your MVC website and WebApi are on the same URL

Using Switch Statement to Handle Button Clicks

    XML CODE FOR TWO BUTTONS  
     <Button
            android:id="@+id/btn_save"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SAVE"
            android:onClick="process"
            />
        <Button
            android:id="@+id/btn_show"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SHOW"
            android:onClick="process"/> 

  Java Code
 <pre> public void process(View view) {
            switch (view.getId()){
                case R.id.btn_save:
                  //add your own code
                    break;
                case R.id.btn_show:
                   //add your own code
                    break;
            }</pre>

Static Vs. Dynamic Binding in Java

Because the compiler knows the binding at compile time. If you invoke a method on an interface, for example, then the compiler can't know and the binding is resolved at runtime because the actual object having a method invoked on it could possible be one of several. Therefore that is runtime or dynamic binding.

Your invocation is bound to the Animal class at compile time because you've specified the type. If you passed that variable into another method somewhere else, noone would know (apart from you because you wrote it) what actual class it would be. The only clue is the declared type of Animal.

Using CSS for a fade-in effect on page load

Looking forward to Web Animations in 2020.

_x000D_
_x000D_
async function moveToPosition(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        transform: `translateY(${el.getBoundingClientRect().top}px)`
      },
    ], {
      duration: durationInMs,
      easing: 'ease-in',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeIn(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        opacity: '0.5',
        offset: 0.5
      },
      {
        opacity: '1',
        offset: 1
      }
    ], {
      duration: durationInMs,
      easing: 'linear',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeInSections() {
  for (const section of document.getElementsByTagName('section')) {
    await fadeIn(section, 200);
  }
}

window.addEventListener('load', async() => {
  await moveToPosition(document.getElementById('headerContent'), 500);
  await fadeInSections();
  await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
  height: 100vh;
}

header {
  height: 20%;
}

.text-center {
  text-align: center;
}

.leading-none {
  line-height: 1;
}

.leading-3 {
  line-height: .75rem;
}

.leading-2 {
  line-height: .25rem;
}

.bg-black {
  background-color: rgba(0, 0, 0, 1);
}

.bg-gray-50 {
  background-color: rgba(249, 250, 251, 1);
}

.pt-12 {
  padding-top: 3rem;
}

.pt-2 {
  padding-top: 0.5rem;
}

.text-lightGray {
  color: lightGray;
}

.container {
  display: flex;
  /* or inline-flex */
  justify-content: space-between;
}

.container section {
  padding: 0.5rem;
}

.opacity-0 {
  opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="description" content="Web site created using create-snowpack-app" />
  <link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>

<body>
  <header class="bg-gray-50">
    <div id="headerContent">
      <h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
      <p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
    </div>
  </header>
  <div class="container">
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 1</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 2</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>

    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 3</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
  </div>
  <footer class="opacity-0">
    <h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
    <p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
  </footer>
</body>

</html>
_x000D_
_x000D_
_x000D_

`col-xs-*` not working in Bootstrap 4

In Bootstrap 4.3, col-xs-{value} is replaced by col-{value}

There is no change in sm, md, lg, xl remains the same.

.col-{value}
.col-sm-{value}
.col-md-{value}
.col-lg-{value}
.col-xl-{value}

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

Hi same problem i have solved you can try this

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.NETWORK

 // SET SSL
public static OkClient setSSLFactoryForClient(OkHttpClient client) {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();


        client.setSslSocketFactory(sslSocketFactory);
        client.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return new OkClient(client);
}

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

I will put a small comparison table here (just to have it somewhere):

Servlet is mapped as /test%3F/* and the application is deployed under /app.

http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a

Method              URL-Decoded Result           
----------------------------------------------------
getContextPath()        no      /app
getLocalAddr()                  127.0.0.1
getLocalName()                  30thh.loc
getLocalPort()                  8480
getMethod()                     GET
getPathInfo()           yes     /a?+b
getProtocol()                   HTTP/1.1
getQueryString()        no      p+1=c+d&p+2=e+f
getRequestedSessionId() no      S%3F+ID
getRequestURI()         no      /app/test%3F/a%3F+b;jsessionid=S+ID
getRequestURL()         no      http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
getScheme()                     http
getServerName()                 30thh.loc
getServerPort()                 8480
getServletPath()        yes     /test?
getParameterNames()     yes     [p 2, p 1]
getParameter("p 1")     yes     c d

In the example above the server is running on the localhost:8480 and the name 30thh.loc was put into OS hosts file.

Comments

  • "+" is handled as space only in the query string

  • Anchor "#a" is not transferred to the server. Only the browser can work with it.

  • If the url-pattern in the servlet mapping does not end with * (for example /test or *.jsp), getPathInfo() returns null.

If Spring MVC is used

  • Method getPathInfo() returns null.

  • Method getServletPath() returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b

  • Be careful with URL encoded parts of @RequestMapping and @RequestParam in Spring. It is buggy (current version 3.2.4) and is usually not working as expected.

error C2220: warning treated as error - no 'object' file generated

The error says that a warning was treated as an error, therefore your problem is a warning message! The object file is then not created because there was an error. So you need to check your warnings and fix them.

In case you don't know how to find them: Open the Error List (View > Error List) and click on Warning.

urlencoded Forward slash is breaking URL

On my hosting account this problem was caused by a ModSecurity rule that was set for all accounts automatically. Upon my reporting this problem, their admin quickly removed this rule for my account.

If REST applications are supposed to be stateless, how do you manage sessions?

REST is stateless and doesn’t maintain any states between the requests. Client cookies / headers are set to maintain the user state like authentication. Say Client username/password are validated by third part authentication mechanism – 2nd level OTP gerneation etc. Once user get authenticated – headers /cookies comes to rest service end point exposed and we can assume user as auth since user is coming with valid headers/cookies. Now certain info of user like IP is either maintained in the cache and after that if request is coming from same Ip (mac address) for listed resources User is allowed. And cache is maintained for some particular time which get invalidated once time lapses. So either cache can be used or DB entries can be used to persist info b/w the requests.

SQL select max(date) and corresponding value

There's no easy way to do this, but something like this will work:

SELECT ET.TrainingID, 
  ET.CompletedDate, 
  ET.Notes
FROM 
HR_EmployeeTrainings ET
inner join
(
  select TrainingID, Max(CompletedDate) as CompletedDate
  FROM HR_EmployeeTrainings
  WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
  GROUP BY AvantiRecID, TrainingID  
) ET2 
  on ET.TrainingID = ET2.TrainingID
  and ET.CompletedDate = ET2.CompletedDate

How to push changes to github after jenkins build completes?

Once you set your Global Jenkins credentials, you can apply this step:

stage('Update GIT') {
  steps {
    script {
      catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
        withCredentials([usernamePassword(credentialsId: 'example-secure', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
            def encodedPassword = URLEncoder.encode("$GIT_PASSWORD",'UTF-8')
            sh "git config user.email [email protected]"
            sh "git config user.name example"
            sh "git add ."
            sh "git commit -m 'Triggered Build: ${env.BUILD_NUMBER}'"
            sh "git push https://${GIT_USERNAME}:${encodedPassword}@github.com/${GIT_USERNAME}/example.git"
        }
      }
    }
  }
}

C++ JSON Serialization

Does anything, easy like that, exists?? THANKS :))

C++ does not store class member names in compiled code, and there's no way to discover (at runtime) which members (variables/methods) class contains. In other words, you cannot iterate through members of a struct. Because there's no such mechanism, you won't be able to automatically create "JSONserialize" for every object.

You can, however, use any json library to serialize objects, BUT you'll have to write serialization/deserialization code yourself for every class. Either that, or you'll have to create serializeable class similar to QVariantMap that'll be used instead of structs for all serializeable objects.

In other words, if you're okay with using specific type for all serializeable objects (or writing serialization routines yourself for every class), it can be done. However, if you want to automatically serialize every possible class, you should forget about it. If this feature is important to you, try another language.

Sort hash by key, return hash in Ruby

I liked the solution in the earlier post.

I made a mini-class, called it class AlphabeticalHash. It also has a method called ap, which accepts one argument, a Hash, as input: ap variable. Akin to pp (pp variable)

But it will (try and) print in alphabetical list (its keys). Dunno if anyone else wants to use this, it's available as a gem, you can install it as such: gem install alphabetical_hash

For me, this is simple enough. If others need more functionality, let me know, I'll include it into the gem.

EDIT: Credit goes to Peter, who gave me the idea. :)

Wamp Server not goes to green color

CMD > netstat -ao > look for any line like 0.0.0.0:80 and look at the PID value (e.g. 4796)

Open Task Manager > Processes tab > View > Select Column > Tick on PID (Process Identifier) > OK to create new column

Look at the processes list in Task Manager > Sort by PID (the new column) and find the 4796 to know which program is using Port 80. Mine is Bit-Torrent. After close (exit) Bit-Torrent, Wampserver should work as usual.

PHP Converting Integer to Date, reverse of strtotime

I guess you are asking why is 1388516401 equal to 2014-01-01...?

There is an historical reason for that. There is a 32-bit integer variable, called time_t, that keeps the count of the time elapsed since 1970-01-01 00:00:00. Its value expresses time in seconds. This means that in 2014-01-01 00:00:01 time_t will be equal to 1388516401.

This leads us for sure to another interesting fact... In 2038-01-19 03:14:07 time_t will reach 2147485547, the maximum value for a 32-bit number. Ever heard about John Titor and the Year 2038 problem? :D

Read Numeric Data from a Text File in C++

It can depend, especially on whether your file will have the same number of items on each row or not. If it will, then you probably want a 2D matrix class of some sort, usually something like this:

class array2D { 
    std::vector<double> data;
    size_t columns;
public:
    array2D(size_t x, size_t y) : columns(x), data(x*y) {}

    double &operator(size_t x, size_t y) {
       return data[y*columns+x];
    }
};

Note that as it's written, this assumes you know the size you'll need up-front. That can be avoided, but the code gets a little larger and more complex.

In any case, to read the numbers and maintain the original structure, you'd typically read a line at a time into a string, then use a stringstream to read numbers from the line. This lets you store the data from each line into a separate row in your array.

If you don't know the size ahead of time or (especially) if different rows might not all contain the same number of numbers:

11 12 13
23 34 56 78

You might want to use a std::vector<std::vector<double> > instead. This does impose some overhead, but if different rows may have different sizes, it's an easy way to do the job.

std::vector<std::vector<double> > numbers;

std::string temp;

while (std::getline(infile, temp)) {
    std::istringstream buffer(temp);
    std::vector<double> line((std::istream_iterator<double>(buffer)),
                             std::istream_iterator<double>());

    numbers.push_back(line);
}

...or, with a modern (C++11) compiler, you can use brackets for line's initialization:

    std::vector<double> line{std::istream_iterator<double>(buffer),
                             std::istream_iterator<double>()};

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I don't know whether this has appeared obvious here. I would like to point out that as far as client-side (browser) JavaScript is concerned, you can add type="module" to both external as well as internal js scripts.

Say, you have a file 'module.js':

var a = 10;
export {a};

You can use it in an external script, in which you do the import, eg.:

<!DOCTYPE html><html><body>
<script type="module" src="test.js"></script><!-- Here use type="module" rather than type="text/javascript" -->
</body></html>

test.js:

import {a} from "./module.js";
alert(a);

You can also use it in an internal script, eg.:

<!DOCTYPE html><html><body>
<script type="module">
    import {a} from "./module.js";
    alert(a);
</script>
</body></html>

It is worthwhile mentioning that for relative paths, you must not omit the "./" characters, ie.:

import {a} from "module.js";     // this won't work

ThreeJS: Remove object from scene

When you use : scene.remove(object); The object is removed from the scene, but the collision with it is still enabled !

To remove also the collsion with the object, you can use that (for an array) : objectsArray.splice(i, 1);

Example :

for (var i = 0; i < objectsArray.length; i++) {
//::: each object ::://
var object = objectsArray[i]; 
//::: remove all objects from the scene ::://
scene.remove(object); 
//::: remove all objects from the array ::://
objectsArray.splice(i, 1); 

}

SFTP file transfer using Java JSch

Below code works for me

   public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
  Session session = jsch.getSession(user, host);
  session.setPassword(password);
  session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

OR using StrictHostKeyChecking as "NO" (security consequences)

public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
   Session session = jsch.getSession(user, host, 22);
   Properties config = new Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);;
   session.setPassword(password);
   System.out.println("user=="+user+"\n host=="+host);
   session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

Disposing WPF User Controls

My scenario is little different, but the intent is same i would like to know when the parent window hosting my user control is closing/closed as The view(i.e my usercontrol) should invoke the presenters oncloseView to execute some functionality and perform clean up. ( well we are implementing a MVP pattern on a WPF PRISM application).

I just figured that in the Loaded event of the usercontrol, i can hook up my ParentWindowClosing method to the Parent windows Closing event. This way my Usercontrol can be aware when the Parent window is being closed and act accordingly!

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

Just do one thing

open skype > tools > advance or advance settings Change port 80 to something else 7395

Restart your system then start Apache

Is there Unicode glyph Symbol to represent "Search"

I'd recommend using http://shapecatcher.com/ to help search for unicode characters. It allows you to draw the shape you're after, and then lists the closest matches to that shape.

Is it possible to set an object to null?

"an object" of what type?

You can certainly assign NULL (and nullptr) to objects of pointer types, and it is implementation defined if you can assign NULL to objects of arithmetic types.

If you mean objects of some class type, the answer is NO (excepting classes that have operator= accepting pointer or arithmetic types)

"empty" is more plausible, as many types have both copy assignment and default construction (often implicitly). To see if an existing object is like a default constructed one, you will also need an appropriate bool operator==

How to add header data in XMLHttpRequest when using formdata?

Your error

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

appears because you must call setRequestHeader after calling open. Simply move your setRequestHeader line below your open line (but before send):

xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);

System.IO.IOException: file used by another process

Sounds like an external process (AV?) is locking it, but can't you avoid the problem in the first place?

private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
{
    try
    {
        string contents = File.ReadAllText(file.FullName);
        Console.WriteLine("input : {0}", contents);
        contents = contents.Replace(extractedMethod, modifiedMethod);
        Console.WriteLine("replaced String {0}", contents);
        File.WriteAllText(file.FullName, contents);
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        return false;
    }
}

How to install beautiful soup 4 with python 2.7 on windows

Install pip

Download get-pip. Remember to save it as "get-pip.py"

Now go to the download folder. Right click on get-pip.py then open with python.exe.

You can add system variable by

(by doing this you can use pip and easy_install without specifying path)

1 Clicking on Properties of My Computer

2 Then chose Advanced System Settings

3 Click on Advanced Tab

4 Click on Environment Variables

5 From System Variables >>> select variable path.

6 Click edit then add the following lines at the end of it

 ;c:\Python27;c:\Python27\Scripts

(please dont copy this, just go to your python directory and copy the paths similar to this)

NB:- you have to do this once only.

Install beautifulsoup4

Open cmd and type

pip install beautifulsoup4

Bootstrap 3: Offset isn't working?

If I get you right, you want something that seems to be the opposite of what is desired normally: you want a horizontal layout for small screens and vertically stacked elements on large screens. You may achieve this in a way like this:

<div class="container">
    <div class="row">
        <div class="hidden-md hidden-lg col-xs-3 col-xs-offset-6">a</div>
        <div class="hidden-md hidden-lg col-xs-3">b</div>
    </div>
    <div class="row">
        <div class="hidden-xs hidden-sm">c</div>

    </div>
</div>

On small screens, i.e. xs and sm, this generates one row with two columns with an offset of 6. On larger screens, i.e. md and lg, it generates two vertically stacked elements in full width (12 columns).

What is the difference between concurrency and parallelism?

I'm going to offer an answer that conflicts a bit with some of the popular answers here. In my opinion, concurrency is a general term that includes parallelism. Concurrency applies to any situation where distinct tasks or units of work overlap in time. Parallelism applies more specifically to situations where distinct units of work are evaluated/executed at the same physical time. The raison d'etre of parallelism is speeding up software that can benefit from multiple physical compute resources. The other major concept that fits under concurrency is interactivity. Interactivity applies when the overlapping of tasks is observable from the outside world. The raison d'etre of interactivity is making software that is responsive to real-world entities like users, network peers, hardware peripherals, etc.

Parallelism and interactivity are almost entirely independent dimension of concurrency. For a particular project developers might care about either, both or neither. They tend to get conflated, not least because the abomination that is threads gives a reasonably convenient primitive to do both.

A little more detail about parallelism:

Parallelism exists at very small scales (e.g. instruction-level parallelism in processors), medium scales (e.g. multicore processors) and large scales (e.g. high-performance computing clusters). Pressure on software developers to expose more thread-level parallelism has increased in recent years, because of the growth of multicore processors. Parallelism is intimately connected to the notion of dependence. Dependences limit the extent to which parallelism can be achieved; two tasks cannot be executed in parallel if one depends on the other (Ignoring speculation).

There are lots of patterns and frameworks that programmers use to express parallelism: pipelines, task pools, aggregate operations on data structures ("parallel arrays").

A little more detail about interactivity:

The most basic and common way to do interactivity is with events (i.e. an event loop and handlers/callbacks). For simple tasks events are great. Trying to do more complex tasks with events gets into stack ripping (a.k.a. callback hell; a.k.a. control inversion). When you get fed up with events you can try more exotic things like generators, coroutines (a.k.a. Async/Await), or cooperative threads.

For the love of reliable software, please don't use threads if what you're going for is interactivity.

Curmudgeonliness

I dislike Rob Pike's "concurrency is not parallelism; it's better" slogan. Concurrency is neither better nor worse than parallelism. Concurrency includes interactivity which cannot be compared in a better/worse sort of way with parallelism. It's like saying "control flow is better than data".

Output PowerShell variables to a text file

Use this:

"$computer, $Speed, $Regcheck" | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200

Arraylist swap elements

Use like this. Here is the online compilation of the code. Take a look http://ideone.com/MJJwtc

public static void swap(List list,
                        int i,
                        int j)

Swaps the elements at the specified positions in the specified list. (If the specified positions are equal, invoking this method leaves the list unchanged.)

Parameters: list - The list in which to swap elements. i - the index of one element to be swapped. j - the index of the other element to be swapped.

Read The official Docs of collection

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int%29

import java.util.*;
import java.lang.*;

class Main {
    public static void main(String[] args) throws java.lang.Exception       
    {    
        //create an ArrayList object
        ArrayList words = new ArrayList();

        //Add elements to Arraylist
        words.add("A");
        words.add("B");
        words.add("C");
        words.add("D");
        words.add("E");

        System.out.println("Before swaping, ArrayList contains : " + words);

        /*
      To swap elements of Java ArrayList use,
      static void swap(List list, int firstElement, int secondElement)
      method of Collections class. Where firstElement is the index of first
      element to be swapped and secondElement is the index of the second element
      to be swapped.

      If the specified positions are equal, list remains unchanged.

      Please note that, this method can throw IndexOutOfBoundsException if
      any of the index values is not in range.        */

        Collections.swap(words, 0, words.size() - 1);

        System.out.println("After swaping, ArrayList contains : " + words);    

    }
}

Oneline compilation example http://ideone.com/MJJwtc

How to implement a property in an interface

You should use abstract class to initialize a property. You can't inititalize in Inteface .

Convert seconds to HH-MM-SS with JavaScript?

You can also use below code:

int ss = nDur%60;
nDur   = nDur/60;
int mm = nDur%60;
int hh = nDur/60;

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

For generating icons for your Xcode projects, I'd suggest you consider using SquareIcon. I believe that it makes creating app icon sets for Apple platforms very easy. Just to let you know, this is my own app.

You can drop in a generic image file of your icon (like a PNG or JPG) and generate a .appiconset file which you can put in your Xcode project's asset catalog. This removes the requirement of manually resizing a bunch of images.

How to change font size in html?

Or add styles inline:

<p style="font-size:18px">Paragraph 1</p>
<p style="font-size:16px">Paragraph 2</p>

How to get an element's top position relative to the browser's viewport?

jQuery implements this quite elegantly. If you look at the source for jQuery's offset, you'll find this is basically how it's implemented:

var rect = elem.getBoundingClientRect();
var win = elem.ownerDocument.defaultView;

return {
    top: rect.top + win.pageYOffset,
    left: rect.left + win.pageXOffset
};

position fixed is not working

We'll never convince people to leave IE6 if we keep striving to deliver quality websites to those users.

Only IE7+ understood "position: fixed".

https://developer.mozilla.org/en-US/docs/Web/CSS/position

So you're out of luck for IE6. To get the footer semi-sticky try this:

.main {
  min-height: 100%;
  margin-bottom: -60px;
}
.footer {
  height: 60px;
}

You could also use an iFrame maybe.

This will keep the footer from 'lifting off' from the bottom of the page. If you have more than one page of content then it will push down out of site.

On a philosophical note, I'd rather point IE6 users to http://browsehappy.com/ and spend the time I save hacking for IE6 on something else.

The simplest way to comma-delimit a list?

if (array.length>0)          // edited in response Joachim's comment
  sb.append(array[i]);
for (int i=1; i<array.length; i++)
  sb.append(",").append(array[i]);

Based on Clearest way to comma-delimit a list (Java)?

Using this idea: Does the last element in a loop deserve a separate treatment?

Understanding timedelta

why do I have to pass seconds = uptime to timedelta

Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int is superfluous as they could also accept floats.

and why does the string casting works so nicely that I get HH:MM:SS ?

It's not the typecasting that formats, is the internal __str__ method of the object. In fact you will achieve the same result if you write:

print datetime.timedelta(seconds=int(uptime))

How to fill color in a cell in VBA?

  1. Use conditional formatting instead of VBA to highlight errors.

  2. Using a VBA loop like the one you posted will take a long time to process

  3. the statement If cell.Value = "#N/A" Then will never work. If you insist on using VBA to highlight errors, try this instead.

    Sub ColorCells()

    Dim Data As Range
    Dim cell As Range
    Set currentsheet = ActiveWorkbook.Sheets("Comparison")
    Set Data = currentsheet.Range("A2:AW1048576")
    
    For Each cell In Data
    
    If IsError(cell.Value) Then
       cell.Interior.ColorIndex = 3
    End If
    Next
    
    End Sub
    
  4. Be prepared for a long wait, since the procedure loops through 51 million cells

  5. There are more efficient ways to achieve what you want to do. Update your question if you have a change of mind.

How to get the name of a class without the package?

If using a StackTraceElement, use:

String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);

System.out.println(simpleClassName);

Count number of matches of a regex in Javascript

tl;dr: Generic Pattern Counter

// THIS IS WHAT YOU NEED
const count = (str) => {
  const re = /YOUR_PATTERN_HERE/g
  return ((str || '').match(re) || []).length
}

For those that arrived here looking for a generic way to count the number of occurrences of a regex pattern in a string, and don't want it to fail if there are zero occurrences, this code is what you need. Here's a demonstration:

_x000D_
_x000D_
/*_x000D_
 *  Example_x000D_
 */_x000D_
_x000D_
const count = (str) => {_x000D_
  const re = /[a-z]{3}/g_x000D_
  return ((str || '').match(re) || []).length_x000D_
}_x000D_
_x000D_
const str1 = 'abc, def, ghi'_x000D_
const str2 = 'ABC, DEF, GHI'_x000D_
_x000D_
console.log(`'${str1}' has ${count(str1)} occurrences of pattern '/[a-z]{3}/g'`)_x000D_
console.log(`'${str2}' has ${count(str2)} occurrences of pattern '/[a-z]{3}/g'`)
_x000D_
_x000D_
_x000D_

Original Answer

The problem with your initial code is that you are missing the global identifier:

>>> 'hi there how are you'.match(/\s/g).length;
4

Without the g part of the regex it will only match the first occurrence and stop there.

Also note that your regex will count successive spaces twice:

>>> 'hi  there'.match(/\s/g).length;
2

If that is not desirable, you could do this:

>>> 'hi  there'.match(/\s+/g).length;
1

Pass a reference to DOM object with ng-click

The angular way is shown in the angular docs :)

https://docs.angularjs.org/api/ng/directive/ngReadonly

Here is the example they use:

<body>
    Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
    <input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>

Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).

So basically in your case you would want to do something like below or check out this working example.

<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>

CALL command vs. START with /WAIT option

This is what I found while running batch files in parallel (multiple instances of the same bat file at the same time with different input parameters) :

Lets say that you have an exe file that performs a long task called LongRunningTask.exe

If you call the exe directly from the bat file, only the first call to the LongRunningTask will succed, while the rest will get an OS error "File is already in use by the process"

If you use this command:

start /B /WAIT "" "LongRunningTask.exe" "parameters"

You will be able to run multiple instances of the bat and exe, while still waiting for the task to finish before the bat continues executing the remaining commands. The /B option is to avoid creating another window, the empty quotes are needed in order to the command to work, see the reference below.

Note that if you don´t use the /WAIT in the start, the LongRunningTask will be executed at the same time than the remaining commands in the batch file, so it might create problems if one of these commands requires the output of the LongRunningTask

Resuming :

This can´t run in parallel :

  • call LongRunningTask.exe

This will run in parallel and will be ok as far as there are no data dependencies between the output of the command and the rest of the bat file :

  • start /B "" "LongRunningTask.exe" "parameters"

This will run in parallel and wait for the task to finish, so you can use the output :

  • start /B /WAIT "" "LongRunningTask.exe" "parameters"

Reference for the start command : How can I run a program from a batch file without leaving the console open after the program start?

How to create a regex for accepting only alphanumeric characters?

Try below Alphanumeric regex

"^[a-zA-Z0-9]*$"

^ - Start of string

[a-zA-Z0-9]* - multiple characters to include

$ - End of string

See more: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

How to run composer from anywhere?

Some of this may be due to the OS your server is running. I recently did a migration to a new hosting environment running Ubuntu. Adding this alias alias composer="/path/to/your/composer" to .bashrc or .bash_aliases didn't work at first because of two reasons:

The server was running csh, not bash, by default. To check if this is an issue in your case, run echo $0. If the what is returned is -csh you will want to change it to bash, since some processes run by Composer will fail using csh/tcsh.

To change it, first check if bash is available on your server by running cat /etc/shells. If, in the list returned, you see bin/bash, you can change the default to bash by running chsh -s /bin/csh.

Now, at this point, you should be able to run Composer, but normally, on Ubuntu, you will have to load the script at every session by sourcing your Bash scripts by running source ~/.bashrc or source ~/.bash_profile. This is because, in most cases, Ubuntu won't load your Bash script, since it loads .profile as the default script.

To load your Bash scripts when you open a session, try adding this to your .profile (this is if your Bash script is .bashrc—modify accordingly if .bash_profile or other):

if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
        . "$HOME/.bashrc"
    fi
fi

To test, close your session and reload. If it's working properly, running composer -v or which composer should behave as expected.

Installation of SQL Server Business Intelligence Development Studio

http://msdn.microsoft.com/en-us/library/ms173767.aspx

Business Intelligence Development Studio is Microsoft Visual Studio 2008 with additional project types that are specific to SQL Server business intelligence. Business Intelligence Development Studio is the primary environment that you will use to develop business solutions that include Analysis Services, Integration Services, and Reporting Services projects. Each project type supplies templates for creating the objects required for business intelligence solutions, and provides a variety of designers, tools, and wizards to work with the objects.

If you already have Visual Studio installed, the new project types will be installed along with SQL Server.

More Information

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

Storing an object in state of a React component?

You can use ES6 spread on previous values in the object to avoid overwrite

this.setState({
     abc: {
            ...this.state.abc,
            xyz: 'new value'
           }
});

No value accessor for form control

If you get this issue, then either

  • the formControlName is not located on the value accessor element.
  • or you're not importing the module for that element.

How do I replace text inside a div element?

Here's an easy jQuery way:

var el = $('#yourid .yourclass');

el.html(el.html().replace(/Old Text/ig, "New Text"));

HashMap allows duplicates?

HashMap don't allow duplicate keys,but since it's not thread safe,it might occur duplicate keys. eg:

 while (true) {
            final HashMap<Object, Object> map = new HashMap<Object, Object>(2);
            map.put("runTimeType", 1);
            map.put("title", 2);
            map.put("params", 3);
            final AtomicInteger invokeCounter = new AtomicInteger();

            for (int i = 0; i < 100; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        map.put("formType", invokeCounter.incrementAndGet());
                    }
                }).start();
            }
            while (invokeCounter.intValue() != 100) {
                Thread.sleep(10);
            }
            if (map.size() > 4) {
// this means you insert two or more formType key to the map
               System.out.println( JSONObject.fromObject(map));
            }
        }