Programs & Examples On #Nt4

Error: Cannot match any routes. URL Segment: - Angular 2

please modify your router.module.ts as:

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [
        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree',
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        },
        {
           path: '',
           redirectTo: 'two',
           pathMatch: 'full'
        }
    ]
},];

and in your component1.html

<h3>In One</h3>

<nav>
    <a routerLink="/two" class="dash-item">...Go to Two...</a>
    <a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
    <a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>

<router-outlet></router-outlet>                   // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet>  // Error: Cannot match any routes. URL Segment: 'three'

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

I just got the same error, when I didn't use the correct case. I could checkout out 'integration'. Git told me to perform a git pull to update my branch. I did that, but received the mentioned error. The correct branch name is 'Integration' with a capital 'I'. When I checked out that branch and pulled, it worked without problem.

Find elements inside forms and iframe using Java and Selenium WebDriver

Before you try searching for the elements within the iframe you will have to switch Selenium focus to the iframe.

Try this before searching for the elements within the iframe:

driver.switchTo().frame(driver.findElement(By.name("iFrameTitle")));

Concatenate multiple node values in xpath

If you need to join xpath-selected text nodes but can not use string-join (when you are stuck with XSL 1.0) this might help:

<xsl:variable name="x">
    <xsl:apply-templates select="..." mode="string-join-mode"/>
</xsl:variable>
joined and normalized: <xsl:value-of select="normalize-space($x)"/>

<xsl:template match="*" mode="string-join-mode">
    <xsl:apply-templates mode="string-join-mode"/>
</xsl:template>    

<xsl:template match="text()" mode="string-join-mode">
    <xsl:value-of select="."/>
</xsl:template>    

Python : Trying to POST form using requests

You can use the Session object

import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}

session = requests.Session()
session.post('https://admin.example.com/login.php',headers=headers,data=payload)
# the session instance holds the cookie. So use it to get/post later.
# e.g. session.get('https://example.com/profile')

how to add new <li> to <ul> onclick with javascript

There is nothing much to add to your code except appending the li tag to the ul

ul.appendChild(li)

and there you go just add this to your function and then it should work.

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

Powershell script does not run via Scheduled Tasks

I was having almost the same problem as this but slightly different on Server 2012 R2. I have a powershell script in Task Scheduler that copies 3 files from one location to another. If I run the script manually from powershell, it works like a charm. But when run from Task Scheduler, it only copies the first 2 small files, then hang on the 3rd (large file). And I was also getting a result of "The operator or administrator has refused the request". And I have done almost everything in this forum.

Here is the scenario and how I fixed it for me. May not work for others, but just in case it will:

Scenario: 1. Powershell script in Task Scheduler 2. Ran using a domain account which is a local admin on the server 3. Selected 'Run whether user is logged on or not" 4. Run with highest priviledges

Fix: 1. I had to login to the server using the domain account so that it created a local profile in C:\Users. 2. Checked and made user that the user has access to all the drives I referred to on my script

I believe #1 is the main fix for me. I hope this works for others out there.

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

I know this is an old post, but the suggested answers didn't work on my end. I want to leave this here just in case someone will find it useful.

What i did is:

@Override
public void onResume() {
    super.onResume();
    // add all fragments
    FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
    for(Fragment fragment : fragmentPages){
        String tag = fragment.getClass().getSimpleName();
        fragmentTransaction.add(R.id.contentPanel, fragment, tag);
        if(fragmentPages.indexOf(fragment) != currentPosition){
            fragmentTransaction.hide(fragment);
        } else {
            lastTag = tag;
        }
    }
    fragmentTransaction.commit();
}

Then in:

@Override
public void onPause() {
    super.onPause();
    // remove all attached fragments
    for(Fragment fragment: fragmentPages){
        getChildFragmentManager().beginTransaction().remove(fragment).commit();
    }
}

Printing out all the objects in array list

Whenever you print any instance of your class, the default toString implementation of Object class is called, which returns the representation that you are getting. It contains two parts: - Type and Hashcode

So, in student.Student@82701e that you get as output ->

  • student.Student is the Type, and
  • 82701e is the HashCode

So, you need to override a toString method in your Student class to get required String representation: -

@Override
public String toString() {
    return "Student No: " + this.getStudentNo() + 
           ", Student Name: " + this.getStudentName();
}

So, when from your main class, you print your ArrayList, it will invoke the toString method for each instance, that you overrided rather than the one in Object class: -

List<Student> students = new ArrayList();

// You can directly print your ArrayList
System.out.println(students); 

// Or, iterate through it to print each instance
for(Student student: students) {
    System.out.println(student);  // Will invoke overrided `toString()` method
}

In both the above cases, the toString method overrided in Student class will be invoked and appropriate representation of each instance will be printed.

Add JsonArray to JsonObject

here is simple code

List <String> list = new ArrayList <String>();
list.add("a");
list.add("b");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
        array.put(list.get(i));
}
JSONObject obj = new JSONObject();
try {
    obj.put("result", array);
} catch (JSONException e) {
 // TODO Auto-generated catch block
e.printStackTrace();
}
pw.write(obj.toString());

How to convert image into byte array and byte array to base64 String in android?

Try this:

// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    return stream.toByteArray();
}

// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg), 
                       Base64.NO_WRAP);

javascript - pass selected value from popup window to parent window input box

From your code

<input type=button value="Select" onClick="sendValue(this.form.details);"

Im not sure that your this.form.details valid or not.

IF it's valid, have a look in window.opener.document.getElementById('details').value = selvalue;

I can't found an input's id contain details I'm just found only id=sku1 (recommend you to add " like id="sku1").

And from your id it's hardcode. Let's see how to do with dynamic when a child has callback to update some textbox on the parent Take a look at here.

First page.

<html>
<head>
<script>
    function callFromDialog(id,data){ //for callback from the dialog
        document.getElementById(id).value = data;
        // do some thing other if you want
    }

    function choose(id){
        var URL = "secondPage.html?id=" + id + "&dummy=avoid#";
        window.open(URL,"mywindow","menubar=1,resizable=1,width=350,height=250")
    }
</script>
</head>
<body>
<input id="tbFirst" type="text" /> <button onclick="choose('tbFirst')">choose</button>
<input id="tbSecond" type="text" /> <button onclick="choose('tbSecond')">choose</button>
</body>
</html>

Look in function choose I'm sent an id of textbox to the popup window (don't forget to add dummy data at last of URL param like &dummy=avoid#)

Popup Page

<html>
<head>
<script>
    function goSelect(data){
        var idFromCallPage = getUrlVars()["id"];
        window.opener.callFromDialog(idFromCallPage,data); //or use //window.opener.document.getElementById(idFromCallPage).value = data;
        window.close();
    }


    function getUrlVars(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
</script>
</head>
<body>
<a href="#" onclick="goSelect('Car')">Car</a> <br />
<a href="#" onclick="goSelect('Food')">Food</a> <br />
</body>
</html>

I have add function getUrlVars for get URL param that the parent has pass to child.

Okay, when select data in the popup, for this case it's will call function goSelect

In that function will get URL param to sent back.

And when you need to sent back to the parent just use window.opener and the name of function like window.opener.callFromDialog

By fully is window.opener.callFromDialog(idFromCallPage,data);

Or if you want to use window.opener.document.getElementById(idFromCallPage).value = data; It's ok too.

How can I transition height: 0; to height: auto; using CSS?

Expanding on @jake's answer, the transition will go all the way to the max height value, causing an extremely fast animation - if you set the transitions for both :hover and off you can then control the crazy speed a little bit more.

So the li:hover is when the mouse enters the state and then the transition on the non-hovered property will be the mouse leave.

Hopefully this will be of some help.

e.g:

.sidemenu li ul {
   max-height: 0px;
   -webkit-transition: all .3s ease;
   -moz-transition: all .3s ease;
   -o-transition: all .3s ease;
   -ms-transition: all .3s ease;
   transition: all .3s ease;
}
.sidemenu li:hover ul {
    max-height: 500px;
    -webkit-transition: all 1s ease;
   -moz-transition: all 1s ease;
   -o-transition: all 1s ease;
   -ms-transition: all 1s ease;
   transition: all 1s ease;
}
/* Adjust speeds to the possible height of the list */

Here's a fiddle: http://jsfiddle.net/BukwJ/

SPAN vs DIV (inline-block)

According to the HTML spec, <span> is an inline element and <div> is a block element. Now that can be changed using the display CSS property but there is one issue: in terms of HTML validation, you can't put block elements inside inline elements so:

<p>...<div>foo</div>...</p>

is not strictly valid even if you change the <div> to inline or inline-block.

So, if your element is inline or inline-block use a <span>. If it's a block level element, use a <div>.

How to compile Go program consisting of multiple files?

When you separate code from main.go into for example more.go, you simply pass that file to go build/go run/go install as well.

So if you previously ran

go build main.go

you now simply

go build main.go more.go

As further information:

go build --help

states:

If the arguments are a list of .go files, build treats them as a list of source files specifying a single package.


Notice that go build and go install differ from go run in that the first two state to expect package names as arguments, while the latter expects go files. However, the first two will also accept go files as go install does.

If you are wondering: build will just build the packages/files, install will produce object and binary files in your GOPATH, and run will compile and run your program.

How do I connect to a Websphere Datasource with a given JNDI name?

DNS for Services

JNDI needs to be approached with the understanding that it is a service locator. When the desired service is hosted on the same server/node as the application, then your use of InitialContext may work.

What makes it more complicated is that defining a Data Source in Web Sphere (at least back in 4.0) allowed you to define the visibility to various degrees. Basically it adds namespaces to the environment and clients have to know where the resource is hosted.

Simple example.

javax.naming.InitialContext ctx = new javax.naming.InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/DataSourceAlias");

Here is IBM's reference page.

If you are trying to reference a data source from an app that is NOT in the J2EE container, you'll need a slightly different approach starting with needing some J2EE client jars in your classpath. http://www.coderanch.com/t/75386/Websphere/lookup-datasources-JNDI-outside-EE

scp from remote host to local host

You need the ip of the other pc and do:

scp user@ip_of_remote_pc:/home/user/stuff.php /Users/djorge/Desktop

it will ask you for 'user's password on the other pc.

Implements vs extends: When to use? What's the difference?

extends

  • class extends only one class
  • interface extends one or more interfaces

implements

  • class implements one or more interfaces
  • interfaces 'can not' implements anything

abstract classes also act like class, with extends and implements

Log4j: How to configure simplest possible file logging?

I have one generic log4j.xml file for you:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">

    <appender name="default.console" class="org.apache.log4j.ConsoleAppender">
        <param name="target" value="System.out" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <appender name="default.file" class="org.apache.log4j.FileAppender">
        <param name="file" value="/log/mylogfile.log" />
        <param name="append" value="false" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <appender name="another.file" class="org.apache.log4j.FileAppender">
        <param name="file" value="/log/anotherlogfile.log" />
        <param name="append" value="false" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <logger name="com.yourcompany.SomeClass" additivity="false">
        <level value="debug" />
        <appender-ref ref="another.file" />
    </logger>

    <root>
        <priority value="info" />
        <appender-ref ref="default.console" />
        <appender-ref ref="default.file" />
    </root>
</log4j:configuration>

with one console, two file appender and one logger poiting to the second file appender instead of the first.

EDIT

In one of the older projects I have found a simple log4j.properties file:

# For the general syntax of property based configuration files see
# the documentation of org.apache.log4j.PropertyConfigurator.

# The root category uses two appenders: default.out and default.file.
# The first one gathers all log output, the latter only starting with 
# the priority INFO.
# The root priority is DEBUG, so that all classes can be logged unless 
# defined otherwise in more specific properties.
log4j.rootLogger=DEBUG, default.out, default.file

# System.out.println appender for all classes
log4j.appender.default.out=org.apache.log4j.ConsoleAppender
log4j.appender.default.out.threshold=DEBUG
log4j.appender.default.out.layout=org.apache.log4j.PatternLayout
log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n

log4j.appender.default.file=org.apache.log4j.FileAppender
log4j.appender.default.file.append=true
log4j.appender.default.file.file=/log/mylogfile.log
log4j.appender.default.file.threshold=INFO
log4j.appender.default.file.layout=org.apache.log4j.PatternLayout
log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n

For the description of all the layout arguments look here: log4j PatternLayout arguments

Android replace the current fragment with another fragment

You can try below code. it’s very easy method for push new fragment from old fragment.

private int mContainerId;
private FragmentTransaction fragmentTransaction;
private FragmentManager fragmentManager;
private final static String TAG = "DashBoardActivity";

public void replaceFragment(Fragment fragment, String TAG) {

    try {
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(mContainerId, fragment, tag);
        fragmentTransaction.addToBackStack(tag);
        fragmentTransaction.commitAllowingStateLoss();

    } catch (Exception e) {
        // TODO: handle exception
    }

}

How can I specify the default JVM arguments for programs I run from eclipse?

Yes, right click the project. Click Run as then Run Configurations. You can change the parameters passed to the JVM in the Arguments tab in the VM Arguments box.

That configuration can then be used as the default when running the project.

Eclipse Build Path Nesting Errors

For Eclipse compiler to work properly you need to remove final/src from the source path and add final/src/main/java instead. This may also solve your problem as now the build directory won't be inside the Java source folder.

Displaying one div on top of another

Use CSS position: absolute; followed by top: 0px; left 0px; in the style attribute of each DIV. Replace the pixel values with whatever you want.

You can use z-index: x; to set the vertical "order" (which one is "on top"). Replace x with a number, higher numbers are on top of lower numbers.

Here is how your new code would look:

<div>
  <div id="backdrop" style="z-index: 1; position: absolute; top: 0px; left: 0px;"><img alt="" src='/backdrop.png' /></div>
  <div id="curtain" style="z-index: 2; position: absolute; top: 0px; left: 0px; background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;">&nbsp;</div>
</div>

how to set imageview src?

Each image has a resource-number, which is an integer. Pass this number to "setImageResource" and you should be ok.

Check this link for further information:
http://developer.android.com/guide/topics/resources/accessing-resources.html

e.g.:

imageView.setImageResource(R.drawable.myimage);

PostgreSQL IF statement

DO
$do$
BEGIN
   IF EXISTS (SELECT FROM orders) THEN
      DELETE FROM orders;
   ELSE
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

There are no procedural elements in standard SQL. The IF statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO command.

You need a semicolon (;) at the end of each statement in plpgsql (except for the final END).

You need END IF; at the end of the IF statement.

A sub-select must be surrounded by parentheses:

    IF (SELECT count(*) FROM orders) > 0 ...

Or:

    IF (SELECT count(*) > 0 FROM orders) ...

This is equivalent and much faster, though:

    IF EXISTS (SELECT FROM orders) ...

Alternative

The additional SELECT is not needed. This does the same, faster:

DO
$do$
BEGIN
   DELETE FROM orders;
   IF NOT FOUND THEN
      INSERT INTO orders VALUES (1,2,3);
   END IF;
END
$do$

Though unlikely, concurrent transactions writing to the same table may interfere. To be absolutely sure, write-lock the table in the same transaction before proceeding as demonstrated.

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

How do I 'git diff' on a certain directory?

Add Beyond Compare as your difftool in Git and add an alias for diffdir as:

git config --global alias.diffdir = "difftool --dir-diff --tool=bc3 --no-prompt"

Get the gitdiff as:

git diffdir 4bc7ba80edf6  7f566710c7

Reference: Compare entire directories w git difftool + Beyond Compare

Getting Access Denied when calling the PutObject operation with bucket-level permission

I was able to solve the issue by granting complete s3 access to Lambda from policies. Make a new role for Lambda and attach the policy with complete S3 Access to it.

Hope this will help.

How to remove border from specific PrimeFaces p:panelGrid?

I am using Primefaces 6.0 and in order to remove borders from my panel grid i use this style class "ui-noborder" as follow:

<p:panelGrid columns="3" styleClass="ui-noborder">
   <!--panel grid contents -->
</p:panelGrid>

It uses a css file named "components" in primefaces lib

Set variable in jinja

{{ }} tells the template to print the value, this won't work in expressions like you're trying to do. Instead, use the {% set %} template tag and then assign the value the same way you would in normal python code.

{% set testing = 'it worked' %}
{% set another = testing %}
{{ another }}

Result:

it worked

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Fastest way to convert string to integer in PHP

integer excract from any string

$in = 'tel.123-12-33';

preg_match_all('!\d+!', $in, $matches);
$out =  (int)implode('', $matches[0]);

//$out ='1231233';

Writing an Excel file in EPPlus

If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);

    package.Save();
}

Get access to parent control from user control - C#

If you want to get any parent by any child control you can use this code, and when you find the UserControl/Form/Panel or others you can call funnctions or set/get values:

Control myControl= this;
while (myControl.Parent != null)
{

    if (myControl.Parent!=null)
    {
        myControl = myControl.Parent;
        if  (myControl.Name== "MyCustomUserControl")
        {
            ((MyCustomUserControl)myControl).lblTitle.Text = "FOUND IT";
        }
    }

}

Automatically enter SSH password with script

You could use an expects script. I have not written one in quite some time but it should look like below. You will need to head the script with #!/usr/bin/expect

#!/usr/bin/expect -f
spawn ssh HOSTNAME
expect "login:" 
send "username\r"
expect "Password:"
send "password\r"
interact

How can I group data with an Angular filter?

In addition to the accepted answers above I created a generic 'groupBy' filter using the underscore.js library.

JSFiddle (updated): http://jsfiddle.net/TD7t3/

The filter

app.filter('groupBy', function() {
    return _.memoize(function(items, field) {
            return _.groupBy(items, field);
        }
    );
});

Note the 'memoize' call. This underscore method caches the result of the function and stops angular from evaluating the filter expression every time, thus preventing angular from reaching the digest iterations limit.

The html

<ul>
    <li ng-repeat="(team, players) in teamPlayers | groupBy:'team'">
        {{team}}
        <ul>
            <li ng-repeat="player in players">
                {{player.name}}
            </li>
        </ul>
    </li>
</ul>

We apply our 'groupBy' filter on the teamPlayers scope variable, on the 'team' property. Our ng-repeat receives a combination of (key, values[]) that we can use in our following iterations.

Update June 11th 2014 I expanded the group by filter to account for the use of expressions as the key (eg nested variables). The angular parse service comes in quite handy for this:

The filter (with expression support)

app.filter('groupBy', function($parse) {
    return _.memoize(function(items, field) {
        var getter = $parse(field);
        return _.groupBy(items, function(item) {
            return getter(item);
        });
    });
});

The controller (with nested objects)

app.controller('homeCtrl', function($scope) {
    var teamAlpha = {name: 'team alpha'};
    var teamBeta = {name: 'team beta'};
    var teamGamma = {name: 'team gamma'};

    $scope.teamPlayers = [{name: 'Gene', team: teamAlpha},
                      {name: 'George', team: teamBeta},
                      {name: 'Steve', team: teamGamma},
                      {name: 'Paula', team: teamBeta},
                      {name: 'Scruath of the 5th sector', team: teamGamma}];
});

The html (with sortBy expression)

<li ng-repeat="(team, players) in teamPlayers | groupBy:'team.name'">
    {{team}}
    <ul>
        <li ng-repeat="player in players">
            {{player.name}}
        </li>
    </ul>
</li>

JSFiddle: http://jsfiddle.net/k7fgB/2/

Extract the filename from a path

Get-ChildItem "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
|Select-Object -ExpandProperty Name

How can I get dictionary key as variable directly in Python (not by searching from value)?

if you just need to get a key-value from a simple dictionary like e.g:

os_type = {'ubuntu': '20.04'}

use popitem() method:

os, version = os_type.popitem()
print(os) # 'ubuntu'
print(version) # '20.04'

Escape quote in web.config connection string

Use &quot; instead of " to escape it.

web.config is an XML file so you should use XML escaping.

connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass&quot;word"

See this forum thread.

Update:

&quot; should work, but as it doesn't, have you tried some of the other string escape sequences for .NET? \" and ""?

Update 2:

Try single quotes for the connectionString:

connectionString='Server=dbsrv;User ID=myDbUser;Password=somepass"word'

Or:

connectionString='Server=dbsrv;User ID=myDbUser;Password=somepass&quot;word'

Update 3:

From MSDN (SqlConnection.ConnectionString Property):

To include values that contain a semicolon, single-quote character, or double-quote character, the value must be enclosed in double quotation marks. If the value contains both a semicolon and a double-quote character, the value can be enclosed in single quotation marks.

So:

connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass&quot;word'"

The issue is not with web.config, but the format of the connection string. In a connection string, if you have a " in a value (of the key-value pair), you need to enclose the value in '. So, while Password=somepass"word does not work, Password='somepass"word' does.

Javascript: Extend a Function

With a wider view of what you're actually trying to do and the context in which you're doing it, I'm sure we could give you a better answer than the literal answer to your question.

But here's a literal answer:

If you're assigning these functions to some property somewhere, you can wrap the original function and put your replacement on the property instead:

// Original code in main.js
var theProperty = init;

function init(){
     doSomething();
}

// Extending it by replacing and wrapping, in extended.js
theProperty = (function(old) {
    function extendsInit() {
        old();
        doSomething();
    }

    return extendsInit;
})(theProperty);

If your functions aren't already on an object, you'd probably want to put them there to facilitate the above. For instance:

// In main.js
var MyLibrary = {
    init: function init() {
    }
};

// In extended.js
(function() {
    var oldInit = MyLibrary.init;
    MyLibrary.init = extendedInit;
    function extendedInit() {
        oldInit.call(MyLibrary); // Use #call in case `init` uses `this`
        doSomething();
    }
})();

But there are better ways to do that. Like for instance, providing a means of registering init functions.

// In main.js
var MyLibrary = (function() {
    var initFunctions = [];
    return {
        init: function init() {
            var fns = initFunctions;
            initFunctions = undefined;
            for (var index = 0; index < fns.length; ++index) {
                try { fns[index](); } catch (e) { }
            }
        },
        addInitFunction: function addInitFunction(fn) {
            if (initFunctions) {
                // Init hasn't run yet, remember it
                initFunctions.push(fn);
            } else {
                // `init` has already run, call it almost immediately
                // but *asynchronously* (so the caller never sees the
                // call synchronously)
                setTimeout(fn, 0);
            }
        }
    };
})();

Here in 2020 (or really any time after ~2016), that can be written a bit more compactly:

// In main.js
const MyLibrary = (() => {
    let initFunctions = [];
    return {
        init() {
            const fns = initFunctions;
            initFunctions = undefined;
            for (const fn of fns) {
                try { fn(); } catch (e) { }
            }
        },
        addInitFunction(fn) {
            if (initFunctions) {
                // Init hasn't run yet, remember it
                initFunctions.push(fn);
            } else {
                // `init` has already run, call it almost immediately
                // but *asynchronously* (so the caller never sees the
                // call synchronously)
                setTimeout(fn, 0);
                // Or: `Promise.resolve().then(() => fn());`
                // (Not `.then(fn)` just to avoid passing it an argument)
            }
        }
    };
})();

How do I concatenate strings in Swift?

Several words about performance

UI Testing Bundle on iPhone 7(real device) with iOS 14

var result = ""
for i in 0...count {
    <concat_operation>
}

Count = 5_000

//Append
result.append(String(i))                         //0.007s 39.322kB

//Plus Equal
result += String(i)                              //0.006s 19.661kB

//Plus
result = result + String(i)                      //0.130s 36.045kB

//Interpolation
result = "\(result)\(i)"                         //0.164s 16.384kB

//NSString
result = NSString(format: "%@%i", result, i)     //0.354s 108.142kB

//NSMutableString
result.append(String(i))                         //0.008s 19.661kB

Disable next tests:

  • Plus up to 100_000 ~10s
  • interpolation up to 100_000 ~10s
  • NSString up to 10_000 -> memory issues

Count = 1_000_000

//Append
result.append(String(i))                         //0.566s 5894.979kB

//Plus Equal
result += String(i)                              //0.570s 5894.979kB

//NSMutableString
result.append(String(i))                         //0.751s 5891.694kB

*Note about Convert Int to String

Source code

import XCTest

class StringTests: XCTestCase {

    let count = 1_000_000
    
    let metrics: [XCTMetric] = [
        XCTClockMetric(),
        XCTMemoryMetric()
    ]
    
    let measureOptions = XCTMeasureOptions.default

    
    override func setUp() {
        measureOptions.iterationCount = 5
    }
    
    func testAppend() {
        var result = ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result.append(String(i))
            }
        }

    }
    
    func testPlusEqual() {
        var result = ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result += String(i)
            }
        }
    }
    
    func testPlus() {
        var result = ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result = result + String(i)
            }
        }
    }
    
    func testInterpolation() {
        var result = ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result = "\(result)\(i)"
            }
        }
    }
    
    //Up to 10_000
    func testNSString() {
        var result: NSString =  ""
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result = NSString(format: "%@%i", result, i)
            }
        }
    }
    
    func testNSMutableString() {
        let result = NSMutableString()
        measure(metrics: metrics, options: measureOptions) {
            for i in 0...count {
                result.append(String(i))
            }
        }
    }

}

how to bind img src in angular 2 in ngFor?

I hope i am understanding your question correctly, as the above comment says you need to provide more information.

In order to bind it to your view you would use property binding which is using [property]="value". Hope this helps.

<div *ngFor="let student of students">  
 {{student.id}}
 {{student.name}}

 <img [src]="student.image">

</div>  

Running Node.js in apache?

No. NodeJS is not available as an Apache module in the way mod-perl and mod-php are, so it's not possible to run node "on top of" Apache. As hexist pointed out, it's possible to run node as a separate process and arrange communication between the two, but this is quite different to the LAMP stack you're already using.

As a replacement for Apache, node offers performance advantages if you have many simultaneous connections. There's also a huge ecosystem of modules for almost anything you can think of.

From your question, it's not clear if you need to dynamically generate pages on every request, or just generate new content periodically for caching and serving. If its the latter, you could use separate node task to generate content to a directory that Apache would serve, but again, that's quite different to PHP or Perl.

Node isn't the best way to serve static content. Nginx and Varnish are more effective at that. They can serve static content while Node handles the dynamic data.

If you're considering using node for a web application at all, Express should be high on your list. You could implement a web application purely in Node, but Express (and similar frameworks like Flatiron, Derby and Meteor) are designed to take a lot of the pain and tedium away. Although the Express documentation can seem a bit sparse at first, check out the screen casts which are still available here: http://expressjs.com/2x/screencasts.html They'll give you a good sense of what express offers and why it is useful. The github repository for ExpressJS also contains many good examples for everything from authentication to organizing your app.

Automatically create an Enum based on values in a database lookup table?

Aren't we coming to this from the wrong direction?

If the data is likely to change at all during the lifetime of the deployed release then an enum is just not appropriate, and you need to use a dictionary, hash or other dynamic collection.

If you know the set of possible values is fixed for the life of the deployed release, then an enum is preferable.

If you must have something in your database that replicates the enumerated set, then why not add a deployment step to clear and repopulate the database table with the definitive set of enum values?

textarea character limit

I have written my method for this, have fun testing it on your browsers, and give me feedback.

cheers.

function TextareaControl(textarea,charlimit,charCounter){
    if(
            textarea.tagName.toLowerCase() === "textarea" && 
            typeof(charlimit)==="number" &&
            typeof(charCounter) === "object" && 
            charCounter.innerHTML !== null
    ){
        var oldValue = textarea.value;
        textarea.addEventListener("keyup",function(){
            var charsLeft = charlimit-parseInt(textarea.value.length,10);
            if(charsLeft<0){
                textarea.value = oldValue;
                charsLeft = charlimit-parseInt(textarea.value.length,10);
            }else{
                oldValue = textarea.value;
            }
            charCounter.innerHTML = charsLeft;
        },false);
    }
}

Convert integer value to matching Java Enum

As @MeBigFatGuy says, except you can make your static {...} block use a loop over the values() collection:

static {
    for (PcapLinkType type : PcapLinkType.values()) {
        intToTypeMap.put(type.getValue(), type);
    }
}

Second line in li starts under the bullet after CSS-reset

I second Dipaks' answer, but often just the text-indent is enough as you may/maynot be positioning the ul for better layout control.

ul li{
text-indent: -1em;
}

Best C/C++ Network Library

Aggregated List of Libraries

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

Core jQuery doesn't have anything special for touch events, but you can easily build your own using the following events

  • touchstart
  • touchmove
  • touchend
  • touchcancel

For example, the touchmove

document.addEventListener('touchmove', function(e) {
    e.preventDefault();
    var touch = e.touches[0];
    alert(touch.pageX + " - " + touch.pageY);
}, false);

This works in most WebKit based browsers (incl. Android).

Here is some good documentation.

Best way to convert IList or IEnumerable to Array

Which version of .NET are you using? If it's .NET 3.5, I'd just call ToArray() and be done with it.

If you only have a non-generic IEnumerable, do something like this:

IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();

If you don't know the type within that method but the method's callers do know it, make the method generic and try this:

public static void T[] PerformQuery<T>()
{
    IEnumerable query = ...;
    T[] array = query.Cast<T>().ToArray();
    return array;
}

Creating and appending text to txt file in VB.NET

This should work for you without changing program logic (by not outputting "Start error" on the top of each file) like the other answers do :) Remember to add exception handling code.

Dim filePath As String = String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))

Dim fileExists As Boolean = File.Exists(filePath)

Using writer As New StreamWriter(filePath, True)
    If Not fileExists Then
        writer.WriteLine("Start Error Log for today")
    End If
    writer.WriteLine("Error Message in  Occured at-- " & DateTime.Now)
End Using

What is the difference between ng-if and ng-show/ng-hide

@Gajus Kuizinas and @CodeHater are correct. Here i am just giving an example. While we are working with ng-if, if the assigned value is false then the whole html elements will be removed from DOM. and if assigned value is true, then the html elements will be visible on the DOM. And the scope will be different compared to the parent scope. But in case of ng-show, it wil just show and hide the elements based on the assigned value. But it always stays in the DOM. Only the visibility changes as per the assigned value.

http://plnkr.co/edit/3G0V9ivUzzc8kpLb1OQn?p=preview

Hope this example will help you in understanding the scopes. Try giving false values to ng-show and ng-if and check the DOM in console. Try entering the values in the input boxes and observe the difference.

<!DOCTYPE html>

Hello Plunker!

<input type="text" ng-model="data">
<div ng-show="true">
    <br/>ng-show=true :: <br/><input type="text" ng-model="data">
</div>
<div ng-if="true">
    <br/>ng-if=true :: <br/><input type="text" ng-model="data">
</div> 
{{data}}

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

Jonny 5 beat me to it. I was going to suggest using the \W+ without the \s as in text.replace(/\W+/g, " "). This covers white space as well.

Deserializing JSON Object Array with Json.net

Slight modification to what was stated above. My Json format, which validates was

{
    mycollection:{[
           {   
               property0:value,
               property1:value,
             },
             {   
               property0:value,
               property1:value,
             }
           ]

         }
       }

Using AlexDev's response, I did this Looping each child, creating reader from it

 public partial class myModel
{
    public static List<myModel> FromJson(string json) => JsonConvert.DeserializeObject<myModelList>(json, Converter.Settings).model;
}

 public class myModelList {
    [JsonConverter(typeof(myModelConverter))]
    public List<myModel> model { get; set; }

}

class myModelConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        var list = Activator.CreateInstance(objectType) as System.Collections.IList;
        var itemType = objectType.GenericTypeArguments[0];
        foreach (var child in token.Children())  //mod here
        {
            var newObject = Activator.CreateInstance(itemType);
            serializer.Populate(child.CreateReader(), newObject); //mod here
            list.Add(newObject);
        }
        return list;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
    }
    public override bool CanWrite => false;
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();

}

SQLite table constraint - unique on multiple columns

If you already have a table and can't/don't want to recreate it for whatever reason, use indexes:

CREATE UNIQUE INDEX my_index ON my_table(col_1, col_2);

How can I get log4j to delete old rotating log files?

You can achieve it using custom log4j appender.
MaxNumberOfDays - possibility to set amount of days of rotated log files.
CompressBackups - possibility to archive old logs with zip extension.

package com.example.package;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Optional;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CustomLog4jAppender extends FileAppender {

    private static final int TOP_OF_TROUBLE = -1;
    private static final int TOP_OF_MINUTE = 0;
    private static final int TOP_OF_HOUR = 1;
    private static final int HALF_DAY = 2;
    private static final int TOP_OF_DAY = 3;
    private static final int TOP_OF_WEEK = 4;
    private static final int TOP_OF_MONTH = 5;

    private String datePattern = "'.'yyyy-MM-dd";
    private String compressBackups = "false";
    private String maxNumberOfDays = "7";
    private String scheduledFilename;
    private long nextCheck = System.currentTimeMillis() - 1;
    private Date now = new Date();
    private SimpleDateFormat sdf;
    private RollingCalendar rc = new RollingCalendar();

    private static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");

    public CustomLog4jAppender() {
    }

    public CustomLog4jAppender(Layout layout, String filename, String datePattern) throws IOException {
        super(layout, filename, true);
        this.datePattern = datePattern;
        activateOptions();
    }

    public void setDatePattern(String pattern) {
        datePattern = pattern;
    }

    public String getDatePattern() {
        return datePattern;
    }

    @Override
    public void activateOptions() {
        super.activateOptions();
        if (datePattern != null && fileName != null) {
            now.setTime(System.currentTimeMillis());
            sdf = new SimpleDateFormat(datePattern);
            int type = computeCheckPeriod();
            printPeriodicity(type);
            rc.setType(type);
            File file = new File(fileName);
            scheduledFilename = fileName + sdf.format(new Date(file.lastModified()));
        } else {
            LogLog.error("Either File or DatePattern options are not set for appender [" + name + "].");
        }
    }

    private void printPeriodicity(int type) {
        String appender = "Log4J Appender: ";
        switch (type) {
            case TOP_OF_MINUTE:
                LogLog.debug(appender + name + " to be rolled every minute.");
                break;
            case TOP_OF_HOUR:
                LogLog.debug(appender + name + " to be rolled on top of every hour.");
                break;
            case HALF_DAY:
                LogLog.debug(appender + name + " to be rolled at midday and midnight.");
                break;
            case TOP_OF_DAY:
                LogLog.debug(appender + name + " to be rolled at midnight.");
                break;
            case TOP_OF_WEEK:
                LogLog.debug(appender + name + " to be rolled at start of week.");
                break;
            case TOP_OF_MONTH:
                LogLog.debug(appender + name + " to be rolled at start of every month.");
                break;
            default:
                LogLog.warn("Unknown periodicity for appender [" + name + "].");
        }
    }

    private int computeCheckPeriod() {
        RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, Locale.ENGLISH);
        Date epoch = new Date(0);
        if (datePattern != null) {
            for (int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
                simpleDateFormat.setTimeZone(gmtTimeZone);
                String r0 = simpleDateFormat.format(epoch);
                rollingCalendar.setType(i);
                Date next = new Date(rollingCalendar.getNextCheckMillis(epoch));
                String r1 = simpleDateFormat.format(next);
                if (!r0.equals(r1)) {
                    return i;
                }
            }
        }
        return TOP_OF_TROUBLE;
    }

    private void rollOver() throws IOException {
        if (datePattern == null) {
            errorHandler.error("Missing DatePattern option in rollOver().");
            return;
        }
        String datedFilename = fileName + sdf.format(now);
        if (scheduledFilename.equals(datedFilename)) {
            return;
        }
        this.closeFile();
        File target = new File(scheduledFilename);
        if (target.exists()) {
            Files.delete(target.toPath());
        }
        File file = new File(fileName);
        boolean result = file.renameTo(target);
        if (result) {
            LogLog.debug(fileName + " -> " + scheduledFilename);
        } else {
            LogLog.error("Failed to rename [" + fileName + "] to [" + scheduledFilename + "].");
        }
        try {
            this.setFile(fileName, false, this.bufferedIO, this.bufferSize);
        } catch (IOException e) {
            errorHandler.error("setFile(" + fileName + ", false) call failed.");
        }
        scheduledFilename = datedFilename;
    }

    @Override
    protected void subAppend(LoggingEvent event) {
        long n = System.currentTimeMillis();
        if (n >= nextCheck) {
            now.setTime(n);
            nextCheck = rc.getNextCheckMillis(now);
            try {
                cleanupAndRollOver();
            } catch (IOException ioe) {
                LogLog.error("cleanupAndRollover() failed.", ioe);
            }
        }
        super.subAppend(event);
    }

    public String getCompressBackups() {
        return compressBackups;
    }

    public void setCompressBackups(String compressBackups) {
        this.compressBackups = compressBackups;
    }

    public String getMaxNumberOfDays() {
        return maxNumberOfDays;
    }

    public void setMaxNumberOfDays(String maxNumberOfDays) {
        this.maxNumberOfDays = maxNumberOfDays;
    }

    protected void cleanupAndRollOver() throws IOException {
        File file = new File(fileName);
        Calendar cal = Calendar.getInstance();
        int maxDays = 7;
        try {
            maxDays = Integer.parseInt(getMaxNumberOfDays());
        } catch (Exception e) {
            // just leave it at 7.
        }
        cal.add(Calendar.DATE, -maxDays);
        Date cutoffDate = cal.getTime();
        if (file.getParentFile().exists()) {
            File[] files = file.getParentFile().listFiles(new StartsWithFileFilter(file.getName(), false));
            int nameLength = file.getName().length();
            for (File value : Optional.ofNullable(files).orElse(new File[0])) {
                String datePart;
                try {
                    datePart = value.getName().substring(nameLength);
                    Date date = sdf.parse(datePart);
                    if (date.before(cutoffDate)) {
                        Files.delete(value.toPath());
                    } else if (getCompressBackups().equalsIgnoreCase("YES") || getCompressBackups().equalsIgnoreCase("TRUE")) {
                        zipAndDelete(value);
                    }
                } catch (Exception pe) {
                    // This isn't a file we should touch (it isn't named correctly)
                }
            }
        }
        rollOver();
    }

    private void zipAndDelete(File file) throws IOException {
        if (!file.getName().endsWith(".zip")) {
            File zipFile = new File(file.getParent(), file.getName() + ".zip");
            try (FileInputStream fis = new FileInputStream(file);
                 FileOutputStream fos = new FileOutputStream(zipFile);
                 ZipOutputStream zos = new ZipOutputStream(fos)) {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zos.putNextEntry(zipEntry);
                byte[] buffer = new byte[4096];
                while (true) {
                    int bytesRead = fis.read(buffer);
                    if (bytesRead == -1) {
                        break;
                    } else {
                        zos.write(buffer, 0, bytesRead);
                    }
                }
                zos.closeEntry();
            }
            Files.delete(file.toPath());
        }
    }

    class StartsWithFileFilter implements FileFilter {
        private String startsWith;
        private boolean inclDirs;

        StartsWithFileFilter(String startsWith, boolean includeDirectories) {
            super();
            this.startsWith = startsWith.toUpperCase();
            inclDirs = includeDirectories;
        }

        public boolean accept(File pathname) {
            if (!inclDirs && pathname.isDirectory()) {
                return false;
            } else {
                return pathname.getName().toUpperCase().startsWith(startsWith);
            }
        }
    }

    class RollingCalendar extends GregorianCalendar {
        private static final long serialVersionUID = -3560331770601814177L;

        int type = CustomLog4jAppender.TOP_OF_TROUBLE;

        RollingCalendar() {
            super();
        }

        RollingCalendar(TimeZone tz, Locale locale) {
            super(tz, locale);
        }

        void setType(int type) {
            this.type = type;
        }

        long getNextCheckMillis(Date now) {
            return getNextCheckDate(now).getTime();
        }

        Date getNextCheckDate(Date now) {
            this.setTime(now);

            switch (type) {
                case CustomLog4jAppender.TOP_OF_MINUTE:
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.MINUTE, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_HOUR:
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.HOUR_OF_DAY, 1);
                    break;
                case CustomLog4jAppender.HALF_DAY:
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    int hour = get(Calendar.HOUR_OF_DAY);
                    if (hour < 12) {
                        this.set(Calendar.HOUR_OF_DAY, 12);
                    } else {
                        this.set(Calendar.HOUR_OF_DAY, 0);
                        this.add(Calendar.DAY_OF_MONTH, 1);
                    }
                    break;
                case CustomLog4jAppender.TOP_OF_DAY:
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.DATE, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_WEEK:
                    this.set(Calendar.DAY_OF_WEEK, getFirstDayOfWeek());
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.WEEK_OF_YEAR, 1);
                    break;
                case CustomLog4jAppender.TOP_OF_MONTH:
                    this.set(Calendar.DATE, 1);
                    this.set(Calendar.HOUR_OF_DAY, 0);
                    this.set(Calendar.MINUTE, 0);
                    this.set(Calendar.SECOND, 0);
                    this.set(Calendar.MILLISECOND, 0);
                    this.add(Calendar.MONTH, 1);
                    break;
                default:
                    throw new IllegalStateException("Unknown periodicity type.");
            }
            return getTime();
        }
    }    
}

And use this properties in your log4j config file:

log4j.appender.[appenderName]=com.example.package.CustomLog4jAppender
log4j.appender.[appenderName].File=/logs/app-daily.log
log4j.appender.[appenderName].Append=true
log4j.appender.[appenderName].encoding=UTF-8
log4j.appender.[appenderName].layout=org.apache.log4j.EnhancedPatternLayout
log4j.appender.[appenderName].layout.ConversionPattern=%-5.5p %d %C{1.} - %m%n
log4j.appender.[appenderName].DatePattern='.'yyyy-MM-dd
log4j.appender.[appenderName].MaxNumberOfDays=7
log4j.appender.[appenderName].CompressBackups=true

How to select rows from a DataFrame based on column values

More flexibility using .query with Pandas >= 0.25.0:

August 2019 updated answer

Since Pandas >= 0.25.0 we can use the query method to filter dataframes with Pandas methods and even column names which have spaces. Normally the spaces in column names would give an error, but now we can solve that using a backtick (`) - see GitHub:

# Example dataframe
df = pd.DataFrame({'Sender email':['[email protected]', "[email protected]", "[email protected]"]})

     Sender email
0  [email protected]
1  [email protected]
2    [email protected]

Using .query with method str.endswith:

df.query('`Sender email`.str.endswith("@shop.com")')

Output

     Sender email
1  [email protected]
2    [email protected]

Also we can use local variables by prefixing it with an @ in our query:

domain = 'shop.com'
df.query('`Sender email`.str.endswith(@domain)')

Output

     Sender email
1  [email protected]
2    [email protected]

Fastest method to replace all instances of a character in a string

The easiest would be to use a regular expression with g flag to replace all instances:

str.replace(/foo/g, "bar")

This will replace all occurrences of foo with bar in the string str. If you just have a string, you can convert it to a RegExp object like this:

var pattern = "foobar",
    re = new RegExp(pattern, "g");

How to find foreign key dependencies in SQL Server?

SELECT  obj.name AS FK_NAME,
    sch.name AS [schema_name],
    tab1.name AS [table],
    col1.name AS [column],
    tab2.name AS [referenced_table],
    col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
    ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
    ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
    ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
    ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
    ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
    ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id

It will give you:

The FK itself Schema that the FK belongs to

  • The "referencing table" or the table that has the FK
  • The "referencing column" or the column inside referencing table that points to the FK
  • The "referenced table" or the table that has the key column that your FK is pointing to
  • The "referenced column" or the column that is the key that your FK is pointing to

What's the best way to add a full screen background image in React Native

(This has been deprecated now you can use ImageBackground)

This is how I've done it. The main deal was getting rid of the static fixed sizes.

class ReactStrap extends React.Component {
  render() {
    return (
      <Image source={require('image!background')} style={styles.container}>
        ... Your Content ...
      </Image>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    // remove width and height to override fixed static size
    width: null,
    height: null,
  }
};

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

How to prevent a double-click using jQuery?

I found that most solutions didn't work with clicks on elements like Labels or DIV's (eg. when using Kendo controls). So I made this simple solution:

function isDoubleClicked(element) {
    //if already clicked return TRUE to indicate this click is not allowed
    if (element.data("isclicked")) return true;

    //mark as clicked for 1 second
    element.data("isclicked", true);
    setTimeout(function () {
        element.removeData("isclicked");
    }, 1000);

    //return FALSE to indicate this click was allowed
    return false;
}

Use it on the place where you have to decide to start an event or not:

$('#button').on("click", function () {
    if (isDoubleClicked($(this))) return;

    ..continue...
});

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

How do you use the "WITH" clause in MySQL?

In Sql the with statement specifies a temporary named result set, known as a common table expression (CTE). It can be used for recursive queries, but in this case, it specifies as subset. If mysql allows for subselectes i would try

select t1.* 
from  (
            SELECT  article.*, 
                    userinfo.*, 
                    category.* 
            FROM    question INNER JOIN 
                    userinfo ON userinfo.user_userid=article.article_ownerid INNER JOIN category ON article.article_categoryid=category.catid
            WHERE   article.article_isdeleted = 0
     ) t1
ORDER BY t1.article_date DESC Limit 1, 3

How to handle floats and decimal separators with html5 input type number

uses a text type but forces the appearance of the numeric keyboard

<input value="12,4" type="text" inputmode="numeric" pattern="[-+]?[0-9]*[.,]?[0-9]+">

the inputmode tag is the solution

How do I get the number of days between two dates in JavaScript?

This may not be the most elegant solution, but it seems to answer the question with a relatively simple bit of code, I think. Can't you use something like this:

function dayDiff(startdate, enddate) {
  var dayCount = 0;

  while(enddate >= startdate) {
    dayCount++;
    startdate.setDate(startdate.getDate() + 1);
  }

return dayCount; 
}

This is assuming you are passing date objects as parameters.

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

One of the reasons of this problem might be "Build Active Architecture Only". You need set to true.

Getting hold of the outer class object from the inner class object

if you don't have control to modify the inner class, the refection may help you (but not recommend). this$0 is reference in Inner class which tells which instance of Outer class was used to create current instance of Inner class.

Remove a symlink to a directory

I had this problem with MinGW (actually Git Bash) running on a Windows Server. None of the above suggestions seemed to work. In the end a made a copy of the directory in case then deleted the soft link in Windows Explorer then deleted the item in the Recycle Bin. It made noises like it was deleting the files but didn't. Do make a backup though!

How to handle static content in Spring MVC?

If I understand your issue correctly, I think I have found a solution to your problem:

I had the same issue where raw output was shown with no css styles, javascripts or jquery files found.

I just added mappings to the "default" servlet. The following was added to the web.xml file:

 <servlet-mapping>
  <servlet-name>default</servlet-name>
  <url-pattern>*.css</url-pattern>
 </servlet-mapping>

 <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
 </servlet-mapping>

This should filter out the javascript and css file requests from the DispatcherRequest object.

Again, not sure if this is what you are after, but it worked for me. I think "default" is the name of the default servlet within JBoss. Not too sure what it is for other servers.

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

I have python2.7 installed via brew and the following solved my problem

brew install numpy

It installs python3, but it still works and sets it up for 2.7 as well.

sqlalchemy IS NOT NULL select

Starting in version 0.7.9 you can use the filter operator .isnot instead of comparing constraints, like this:

query.filter(User.name.isnot(None))

This method is only necessary if pep8 is a concern.

source: sqlalchemy documentation

C++: what regex library should I use?

Boost.Regex is very good and is slated to become part of the C++0x standard (it's already in TR1).

Personally, I find Boost.Xpressive much nicer to work with. It is a header-only library and it has some nice features such as static regexes (regexes compiled at compile time).

Update: If you're using a C++11 compliant compiler (gcc 4.8 is NOT!), use std::regex unless you have good reason to use something else.

How to set placeholder value using CSS?

As @Sarfraz already mentioned CSS, I'll just add HTML5 to the mix.

You can use the HTML5 placeholder attribute:

<input type="text" placeholder="Placeholder text blah blah." />

Defining a `required` field in Bootstrap

Use 'needs-validation' apart from form-group, it will work.

What is the difference between C++ and Visual C++?

What is the difference between c++ and visaul c++?

Visual C++ is an IDE. There's also C++Builder from Embarcadero. (Used to be Borland.) There are also a few other C++ IDE's.

I know that c++ has the portability and all so if you know c++ how is it related to visual c++?

C++ is as portable as the libraries that you use in your C++ application. VC++ has some specialized libraries to use with Windows, so if you use those libraries in your C++ application, you're stuck with Windows. But a simple "Hello, World" application that just uses the console as output can be compiled on Windows, Linux, VMS, AS/400, Smartphones, FreeBSD, MS-DOS, CP80 and almost any other system for which you can find a C++ compiler. Injteresting fact: at http://nethack.org/ you can download the C sourcecode for an almost antique game, where you have to walk through a bunch of mazes, kick some monsters around, find treasures and steal some valuable amulet and bring that amulet back out. (It's also a game where you can encounter your characters from previous, failed attempts to get that amulet. :-) The sourcecode of NetHack is a fine example of how portable C (C++) code can be.

Is visual c++ mostly for online apps?

No. But it can be used for online apps. Actually, C# is used more often for server-side web applications while C++ (VC++) is used for all kinds of (server) components that your application will be depending upon.

Would visual basic be better for desktop applications?

Or Embarcadero Delphi. Delphi and Basic are languages that are easier to learn than C++ and both have very good IDE's to develop GUI applications with. Unfortunately, Visual Basic is now running on .NET only, while there are still many developers who need to create WIN32 applications. Those developers often have to choose between Delphi or C++ or else convince management to move to .NET development.

Matching a Forward Slash with a regex

You can also work around special JS handling of the forward slash by enclosing it in a character group, like so:

const start = /[/]/g;
"/dev/null".match(start)     // => ["/", "/"]

const word = /[/](\w+)/ig;
"/dev/null".match(word)      // => ["/dev", "/null"]

How to prepend a string to a column value in MySQL?

You can use the CONCAT function to do that:

UPDATE tbl SET col=CONCAT('test',col);

If you want to get cleverer and only update columns which don't already have test prepended, try

UPDATE tbl SET col=CONCAT('test',col)
WHERE col NOT LIKE 'test%';

How to get cumulative sum

You can use this simple query for progressive calculation :

select 
   id
  ,SomeNumt
  ,sum(SomeNumt) over(order by id ROWS between UNBOUNDED PRECEDING and CURRENT ROW) as CumSrome
from @t

How to use SVG markers in Google Maps API v3

As mentioned by others in this thread, don't forget to explicitly set the width and height attributes in the svg like so:

<svg id="some_id" data-name="some_name" xmlns="http://www.w3.org/2000/svg"
     viewBox="0 0 26 42"
     width="26px" height="42px">

if you don't do that no js manipulation can help you as gmaps will not have a frame of reference and always use a standard size.

(i know it has been mentioned in some comments, but they are easy to miss. This information helped me in various cases)

How to sum the values of a JavaScript object?

Now you can make use of reduce function and get the sum.

_x000D_
_x000D_
const object1 = { 'a': 1 , 'b': 2 , 'c':3 }_x000D_
_x000D_
console.log(Object.values(object1).reduce((a, b) => a + b, 0));
_x000D_
_x000D_
_x000D_

Good Free Alternative To MS Access

VistaDB has an express version which is free to use and is syntax and driver compatible with SQL Server. VistaDB is a single file and only requires their driver .dll to work in your asp.net or winforms project.

Since it is syntax and datasource compatible you can upgrade to SQL Server if needed.

from their site:

VistaDB is a fully managed and typesafe ASP.NET and WinForms applications using C#, VB.NET and other CLR-compliant languages.

VistaDB.net

How can I rename column in laravel using migration?

I know this is an old question, but I faced the same problem recently in Laravel 7 application. To make renaming columns work I used a tip from this answer where instead of composer require doctrine/dbal I have issued composer require doctrine/dbal:^2.12.1 because the latest version of doctrine/dbal still throws an error.

Just keep in mind that if you already use a higher version, this answer might not be appropriate for you.

Git commit -a "untracked files"?

As the name suggests 'untracked files' are the files which are not being tracked by git. They are not in your staging area, and were not part of any previous commits. If you want them to be versioned (or to be managed by git) you can do so by telling 'git' by using 'git add'. Check this chapter Recording Changes to the Repository in the Progit book which uses a nice visual to provide a good explanation about recording changes to git repo and also explaining the terms 'tracked' and 'untracked'.

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

I had this due to a simple ordering mistake on my end. I called

[WRONG] docker run <image> <arguments> <command>

When I should have used

docker run <arguments> <image> <command>

Same resolution on similar question: https://stackoverflow.com/a/50762266/6278

Creating a batch file, for simple javac and java command execution

@author MADMILK
@echo off
:getback1
set /p jump1=Do you want to compile? Write yes/no : 
if %jump1% = yes
goto loop
if %jump1% = no
goto getback2
:: Important part here
:getback2
set /p jump2=Do you want to run a java program? Write yes/no : 
if %jump2% = yes
goto loop2
if %jump2% = no
goto getback1
:: Make a folder anywhere what you want to use for scripts, for example i make one.
cd desktop
:: This is the folder where is gonna be your script(s)
mkdir My Scripts
cd My Scripts
title Java runner/compiler
echo REMEMBER! LOWER CASES AND UPPER CASES ARE IMPORTANT!
:loop
echo This is the java compiler program.
set /p jcVal=What java program do you want to compile? : 
javac %jcVal%
:loop2
echo This is the java code runner program.
set /p javaVal=What java program do you want to run? : 
java %javaVal%
pause >nul
echo Press NOTHING to leave

Encode/Decode URLs in C++

CGICC includes methods to do url encode and decode. form_urlencode and form_urldecode

How to write subquery inside the OUTER JOIN Statement

You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.

SELECT
       cs.CUSID
       ,dp.DEPID
FROM
    CUSTMR cs
        LEFT OUTER JOIN (
            SELECT
                    DEPID
                    ,DEPNAME
                FROM
                    DEPRMNT 
                WHERE
                    dp.DEPADDRESS = 'TOKYO'
        ) ss
            ON (
                ss.DEPID = cs.CUSID
                AND ss.DEPNAME = cs.CUSTNAME
            )
WHERE
    cs.CUSID != '' 

Compiler error: "class, interface, or enum expected"

You forgot your class declaration:

public class MyClass {
...

Does java have a int.tryparse that doesn't throw an exception for bad data?

Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.

Anyway, I'd just do this:

public Integer tryParse(Object obj) {
  Integer retVal;
  try {
    retVal = Integer.parseInt((String) obj);
  } catch (NumberFormatException nfe) {
    retVal = 0; // or null if that is your preference
  }
  return retVal;
}

Bootstrap $('#myModal').modal('show') is not working

jQuery lib has to be loaded first. In my case, i was loading bootstrap lib first, also tried tag with target and firing a click trigger. But the main issue was - jquery has to be loaded first.

How to get child element by index in Jquery?

Doesn't nth-child return siblings rather than children?

var $selFirst = $(".second:nth-child(1)");

will return the first element with the class '.second'.

var $selFirst = $(".selector:nth-child(1)");

should give you the first sibling of class '.selector'

How do I call the base class constructor?

In the header file define a base class:

class BaseClass {
public:
    BaseClass(params);
};

Then define a derived class as inheriting the BaseClass:

class DerivedClass : public BaseClass {
public:
    DerivedClass(params);
};

In the source file define the BaseClass constructor:

BaseClass::BaseClass(params)
{
     //Perform BaseClass initialization
}

By default the derived constructor only calls the default base constructor with no parameters; so in this example, the base class constructor is NOT called automatically when the derived constructor is called, but it can be achieved simply by adding the base class constructor syntax after a colon (:). Define a derived constructor that automatically calls its base constructor:

DerivedClass::DerivedClass(params) : BaseClass(params)
{
     //This occurs AFTER BaseClass(params) is called first and can
     //perform additional initialization for the derived class
}

The BaseClass constructor is called BEFORE the DerivedClass constructor, and the same/different parameters params may be forwarded to the base class if desired. This can be nested for deeper derived classes. The derived constructor must call EXACTLY ONE base constructor. The destructors are AUTOMATICALLY called in the REVERSE order that the constructors were called.

EDIT: There is an exception to this rule if you are inheriting from any virtual classes, typically to achieve multiple inheritance or diamond inheritance. Then you MUST explicitly call the base constructors of all virtual base classes and pass the parameters explicitly, otherwise it will only call their default constructors without any parameters. See: virtual inheritance - skipping constructors

How can I commit a single file using SVN over a network?

this should work:

svn commit -m "<Your message here>" path/to/your/file

you can also add multiple files like this:

svn commit -m "<Your message here>" path/to/your/file [path/to/your/file] [path/to/your/file]

Convert number to month name in PHP

this is trivially easy, why are so many people making such bad suggestions? @Bora was the closest, but this is the most robust

/***
 * returns the month in words for a given month number
 */
date("F", strtotime(date("Y")."-".$month."-01"));

this is the way to do it

change cursor from block or rectangle to line?

please Press fn +ins key together

importing a CSV into phpmyadmin

In phpMyAdmin, click the table, and then click the Import tab at the top of the page.

Browse and open the csv file. Leave the charset as-is. Uncheck partial import unless you have a HUGE dataset (or slow server). The format should already have selected “CSV” after selecting your file, if not then select it (not using LOAD DATA). If you want to clear the whole table before importing, check “Replace table data with file”. Optionally check “Ignore duplicate rows” if you think you have duplicates in the CSV file. Now the important part, set the next four fields to these values:

Fields terminated by: ,
Fields enclosed by: “
Fields escaped by: \
Lines terminated by: auto

Currently these match the defaults except for “Fields terminated by”, which defaults to a semicolon.

Now click the Go button, and it should run successfully.

What's the difference between next() and nextLine() methods from Scanner class?

From javadocs

next() Returns the next token if it matches the pattern constructed from the specified string. nextLine() Advances this scanner past the current line and returns the input that was skipped.

Which one you choose depends which suits your needs best. If it were me reading a whole file I would go for nextLine until I had all the file.

Initialize a byte array to a certain value, other than the default null?

var array = Encoding.ASCII.GetBytes(new string(' ', 100));

How to generate UL Li list from string array using jquery?

var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i)
{
    var li = $('<li/>')
        .addClass('ui-menu-item')
        .attr('role', 'menuitem')
        .appendTo(cList);
    var aaa = $('<a/>')
        .addClass('ui-all')
        .text(countries[i])
        .appendTo(li);
});

lexical or preprocessor issue file not found occurs while archiving?

I had this same issue now and found that my sub-projects 'Public Header Folder Path' was set to an incorrect path (when compared with what my main project was using as its 'Header Search Path' and 'User Header Search Path').

e.g.

My main project had the following:

  • Header Search Paths
    • Debug "build/Debug-iphoneos/../../Headers"
    • Release "build/Debug-iphoneos/../../Headers"

And the same for the User Header Search Paths


Whereas my sub-project (dependency) had the following:

  • Public Header Folder Path
    • Debug "include/BoxSDK"
    • Release "include/BoxSDK"

Changing the 'Public Header Folder Path' to "../../Headers/BoxSDK" fixed the problem since the main project was already searching that folder ('../../Headers').

PS: I took some good screenshots, but I am not allowed to post an answer with images until I hit reputation 10 :(

C: How to free nodes in the linked list?

One function can do the job,

void free_list(node *pHead)
{
    node *pNode = pHead, *pNext;

    while (NULL != pNode)
    {
        pNext = pNode->next;
        free(pNode);
        pNode = pNext;
    }

}

How to get the background color code of an element in hex?

This Solution utilizes part of what @Newred and @Radu Di?a said. But will work in less standard cases.

 $(this).attr('style').split(';').filter(item => item.startsWith('background-color'))[0].split(":")[1].replace(/\s/g, '');

The issue both of them have is that neither check for a space between background-color: and the color.

All of these will match with the above code.

 background-color: #ffffff
 background-color:      #fffff;
 background-color:#fffff;

How can I insert a line break into a <Text> component in React Native?

Another way to insert <br> between text lines that are defined in an array:

import react, { Fragment } from 'react';

const lines = [
  'One line',
  'Another line',
];

const textContent =
  lines.reduce(items, line, index) => {
    if (index > 0) {
      items.push(<br key={'br-'+index}/>);
    }
    items.push(<Fragment key={'item-'+index}>{line}</Fragment>);
    return items;
  }, []);

Then the text can be used as variable:

<Text>{textContent}</Text>

If not available, Fragment can be defined this way:

const Fragment = (props) => props.children;

Python: "Indentation Error: unindent does not match any outer indentation level"

I had this same problem and it had nothing to do with tabs. This was my problem code:

def genericFunction(variable):

    for line in variable:

       line = variable


   if variable != None:
      return variable

Note the above for is indented with more spaces than the line that starts with if. This is bad. All your indents must be consistent. So I guess you could say I had a stray space and not a stray tab.

Is there a way to get the XPath in Google Chrome?

You can try using Chrome Web Extension TruePath which dynamically generates the relative XPath on right click on the web page and display all the XPath as menu items.

How do I make Java register a string input with spaces?

Instead of

Scanner in = new Scanner(System.in);
String question;
question = in.next();

Type in

Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();

This should be able to take spaces as input.

Sorting a DropDownList? - C#, ASP.NET

You may not have access to the SQL, but if you have the DataSet or DataTable, you can certainly call the Sort() method.

How to check if one DateTime is greater than the other in C#

        if (new DateTime(5000) > new DateTime(1000))
        {
            Console.WriteLine("i win");
        }

error running apache after xampp install

After changing main port from 80 to 8080 you have to change the config in XAMPP control panel as I show in the images:

1) enter image description here

2) enter image description here

3) enter image description here

Then restart the service and that's it !

Invalid column count in CSV input on line 1 Error

When facing errors with input files of any type, encoding issues are common.

A simple solution might be to open a new file, copy pasting your CSV text in it, then saving it as a new file.

Login failed for user 'DOMAIN\MACHINENAME$'

For me the problem was resolved when I replaced the default Built-in account 'ApplicationPoolIdentity' with a network account which was allowed access to the database.

Settings can be made in Internet Information Server (IIS 7+) > Application Pools > Advanded Settings > Process Model > Identity

How to use onSavedInstanceState example please

Store information:

static final String PLAYER_SCORE = "playerScore";
static final String PLAYER_LEVEL = "playerLevel";

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(PLAYER_SCORE, mCurrentScore);
    savedInstanceState.putInt(PLAYER_LEVEL, mCurrentLevel);

// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}

If you don't want to restore information in your onCreate-Method:

Here are the examples: Recreating an Activity

Instead of restoring the state during onCreate() you may choose to implement onRestoreInstanceState(), which the system calls after the onStart() method. The system calls onRestoreInstanceState() only if there is a saved state to restore, so you do not need to check whether the Bundle is null

public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);

// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(PLAYER_SCORE);
mCurrentLevel = savedInstanceState.getInt(PLAYER_LEVEL);
}

Get JSON Data from URL Using Android?

private class GetProfileRequestAsyncTasks extends AsyncTask<String, Void, JSONObject> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected JSONObject doInBackground(String... urls) {
        if (urls.length > 0) {
            String url = urls[0];
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            httpget.setHeader("x-li-format", "json");
            try {
                HttpResponse response = httpClient.execute(httpget);
                if (response != null) {
                    //If status is OK 200
                    if (response.getStatusLine().getStatusCode() == 200) {
                        String result = EntityUtils.toString(response.getEntity());
                        //Convert the string result to a JSON Object
                        return new JSONObject(result);
                    }
                }
            } catch (IOException e) {

            } catch (JSONException e) {
            }
        }
        return null;
    }
    @Override
    protected void onPostExecute(JSONObject data) {
        if (data != null) {
            Log.d(TAG, String.valueOf(data));
        }
    }

}

How do I create an iCal-type .ics file that can be downloaded by other users?

There is also this tool you can use. It supports multi-events .ics file creation. It also supports timezone as well.

http://apps.marudot.com/ical/

Checking for multiple conditions using "when" on single task in ansible

Adding to https://stackoverflow.com/users/1638814/nvartolomei answer, which will probably fix your error.

Strictly answering your question, I just want to point out that the when: statement is probably correct, but would look easier to read in multiline and still fulfill your logic:

when: 
  - sshkey_result.rc == 1
  - github_username is undefined or 
    github_username |lower == 'none'

https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement

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

I found another way to export table in sql file.

Suppose my table is abs_item_variations

abs_item_variations ->structure -> propose table structure -> export -> Go

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

pattern="[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}"

This is pattern to enter the date for textbox in HTML5.
The first one[0-9]{1,2} will take only decimal number minimum 1 and maximum 2.
And other similarly.

Get the closest number out of an array

ES6 (ECMAScript 2015) Version:

_x000D_
_x000D_
const counts = [4, 9, 15, 6, 2];
const goal = 5;

const output = counts.reduce((prev, curr) => Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);

console.log(output);
_x000D_
_x000D_
_x000D_

For reusability you can wrap in a curry function that supports placeholders (http://ramdajs.com/0.19.1/docs/#curry or https://lodash.com/docs#curry). This gives lots of flexibility depending on what you need:

_x000D_
_x000D_
const getClosest = _.curry((counts, goal) => {
  return counts.reduce((prev, curr) => Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});

const closestToFive = getClosest(_, 5);
const output = closestToFive([4, 9, 15, 6, 2]);

console.log(output);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Error message "Linter pylint is not installed"

I had this issue as well and found the error's log regarding permissions or something.

So, I ran Visual Studio Code with administrator privileges and ran "pip install pylint" in the terminal. Then the error seemed to be fixed.

(I run Visual Studio Code on Windows 10.)

base 64 encode and decode a string in angular (2+)

For encoding to base64 in Angular2, you can use btoa() function.

Example:-

console.log(btoa("stringAngular2")); 
// Output:- c3RyaW5nQW5ndWxhcjI=

For decoding from base64 in Angular2, you can use atob() function.

Example:-

console.log(atob("c3RyaW5nQW5ndWxhcjI=")); 
// Output:- stringAngular2

The term "Add-Migration" is not recognized

Try the following steps:

1) Open project.json file and Remove all Microsoft.EntityFrameworkCore.Tools references from dependencies and tools sections.

2) Close Package Manager Console (PMC) and restart Visual Studio

3) Add under dependencies section:

 "Microsoft.EntityFrameworkCore.Tools": {
  "version": "1.0.0-preview2-final",
  "type": "build"
 }

4) Add under tools section

"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"

5) Restart again Visual Studio 2015

6) Open the PMC and type

Add-Migration $Your_First_Migration_Name$

This happen because the PMC recognize the tools when Visual Studio is starting.

How to resize superview to fit all subviews with autolayout?

The correct API to use is UIView systemLayoutSizeFittingSize:, passing either UILayoutFittingCompressedSize or UILayoutFittingExpandedSize.

For a normal UIView using autolayout this should just work as long as your constraints are correct. If you want to use it on a UITableViewCell (to determine row height for example) then you should call it against your cell contentView and grab the height.

Further considerations exist if you have one or more UILabel's in your view that are multiline. For these it is imperitive that the preferredMaxLayoutWidth property be set correctly such that the label provides a correct intrinsicContentSize, which will be used in systemLayoutSizeFittingSize's calculation.

EDIT: by request, adding example of height calculation for a table view cell

Using autolayout for table-cell height calculation isn't super efficient but it sure is convenient, especially if you have a cell that has a complex layout.

As I said above, if you're using a multiline UILabel it's imperative to sync the preferredMaxLayoutWidth to the label width. I use a custom UILabel subclass to do this:

@implementation TSLabel

- (void) layoutSubviews
{
    [super layoutSubviews];

    if ( self.numberOfLines == 0 )
    {
        if ( self.preferredMaxLayoutWidth != self.frame.size.width )
        {
            self.preferredMaxLayoutWidth = self.frame.size.width;
            [self setNeedsUpdateConstraints];
        }
    }
}

- (CGSize) intrinsicContentSize
{
    CGSize s = [super intrinsicContentSize];

    if ( self.numberOfLines == 0 )
    {
        // found out that sometimes intrinsicContentSize is 1pt too short!
        s.height += 1;
    }

    return s;
}

@end

Here's a contrived UITableViewController subclass demonstrating heightForRowAtIndexPath:

#import "TSTableViewController.h"
#import "TSTableViewCell.h"

@implementation TSTableViewController

- (NSString*) cellText
{
    return @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
}

#pragma mark - Table view data source

- (NSInteger) numberOfSectionsInTableView: (UITableView *) tableView
{
    return 1;
}

- (NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger) section
{
    return 1;
}

- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath
{
    static TSTableViewCell *sizingCell;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        sizingCell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell"];
    });

    // configure the cell
    sizingCell.text = self.cellText;

    // force layout
    [sizingCell setNeedsLayout];
    [sizingCell layoutIfNeeded];

    // get the fitting size
    CGSize s = [sizingCell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize];
    NSLog( @"fittingSize: %@", NSStringFromCGSize( s ));

    return s.height;
}

- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
    TSTableViewCell *cell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell" ];

    cell.text = self.cellText;

    return cell;
}

@end

A simple custom cell:

#import "TSTableViewCell.h"
#import "TSLabel.h"

@implementation TSTableViewCell
{
    IBOutlet TSLabel* _label;
}

- (void) setText: (NSString *) text
{
    _label.text = text;
}

@end

And, here's a picture of the constraints defined in the Storyboard. Note that there are no height/width constraints on the label - those are inferred from the label's intrinsicContentSize:

enter image description here

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

You're using port 3000 on the client-side. I'd hazard a guess that's the Angular port and not the server port? It should be connecting to the server port.

How to convert a Drawable to a Bitmap?

This piece of code helps.

Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
                                           R.drawable.icon_resource);

Here a version where the image gets downloaded.

String name = c.getString(str_url);
URL url_value = new URL(name);
ImageView profile = (ImageView)v.findViewById(R.id.vdo_icon);
if (profile != null) {
    Bitmap mIcon1 =
        BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
    profile.setImageBitmap(mIcon1);
}

Automatically set appsettings.json for dev and release environments in asp.net core?

.vscode/launch.json file is only used by Visual Studio as well as /Properties/launchSettings.json file. Don't use these files in production.

The launchSettings.json file:

  1. Is only used on the local development machine.
  2. Is not deployed.
  3. contains profile settings.

    • Environment values set in launchSettings.json override values set in the system environment

To use a file 'appSettings.QA.json' for example. You can use 'ASPNETCORE_ENVIRONMENT'. Follow the steps below.

  1. Add a new Environment Variable on the host machine and call it 'ASPNETCORE_ENVIRONMENT'. Set its value to 'QA'.
  2. Create a file 'appSettings.QA.json' in your project. Add your configuration here.
  3. Deploy to the machine in step 1. Confirm 'appSettings.QA.json' is deployed.
  4. Load your website. Expect appSettings.QA.json to be used in here.

Function to convert timestamp to human date in javascript

Moment.js can convert unix timestamps into any custom format

In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");

will print 18-10-2013 11:53:14;

Here's a plunker that demonstrates this.

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

upload_max_filesize = 8M;
post_max_size = 8M;

Imagine you already changed above values. But what happen when user try to upload large files greater than 8M ?

This is what happen, PHP shows this warning!

Warning: POST Content-Length of x bytes exceeds the limit of y bytes in Unknown on line 0

you can avoid it by adding

ob_get_contents();
ob_end_clean();

How to create a windows service from java app

I am currently requiring this to run an Eclipse-based application but I need to set some variables first that is local to that application. sc.exe will only allow executables but not scripts so I turned to autoexnt.exe which is part of the Windows 2003 resource kit. It restricts the service to a single batch file but I only need one batch script to be converted into a service.

ciao!

Export specific rows from a PostgreSQL table as INSERT SQL script

For a data-only export use COPY.
You get a file with one table row per line as plain text (not INSERT commands), it's smaller and faster:

COPY (SELECT * FROM nyummy.cimory WHERE city = 'tokio') TO '/path/to/file.csv';

Import the same to another table of the same structure anywhere with:

COPY other_tbl FROM '/path/to/file.csv';

COPY writes and read files local to the server, unlike client programs like pg_dump or psql which read and write files local to the client. If both run on the same machine, it doesn't matter much, but it does for remote connections.

There is also the \copy command of psql that:

Performs a frontend (client) copy. This is an operation that runs an SQL COPY command, but instead of the server reading or writing the specified file, psql reads or writes the file and routes the data between the server and the local file system. This means that file accessibility and privileges are those of the local user, not the server, and no SQL superuser privileges are required.

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

The idea of interfaces is generally to expose a sort of base line contract by which code that performs work on an object can be guaranteed of certain functionality provided by that object. In the case of IEnumerable<T>, that contract happens to be "you can access all of my elements one by one."

The kinds of methods that can be written based on this contract alone are many. See the Enumerable class for tons of examples.

But to zero in on just one concrete one: think about Sum. In order to sum up a bunch of items, what do you need? What contract would you require? The answer is quite simple: just a way to see every item, no more. Random access isn't necessary. Even a total count of all the items is not necessary.

To have added an indexer to the IEnumerable<T> interface would have been detrimental in two ways:

  1. Code that requires the contract described above (access to a sequence of elements), if it required the IEnumerable<T> interface, would be artificially restrictive as it could not deal with any type that did not implement an indexer, even though to deal with such a type should really be well within the capabilities of the code.
  2. Any type that wanted to expose a sequence of elements but was not appropriately equipped to provide random access by index (e.g., LinkedList<T>, Dictionary<TKey, TValue>) would now have to either provide some inefficient means of simulating indexing, or else abandon the IEnumerable<T> interface.

All this being said, considering that the purpose of an interface is to provide a guarantee of the minimum required functionality in a given scenario, I really think that the IList<T> interface is poorly designed. Or rather, the lack of an interface "between" IEnumerable<T> and IList<T> (random access, but no modification) is an unfortunate oversight in the BCL, in my opinion.

Where to install Android SDK on Mac OS X?

I ended up placing my at ~/sdks/android-sdk-mac_x86. I like to keep all of my SDKs in one place and for me an sdk folder under my home directory makes the most sense.

jQuery UI dialog box not positioned center screen

My Scenario: I had to scroll down on page to open dialog on a button click, due to window scroll the dialog was not opening vertically center to window, it was going out of view-port.

As Ken has mentioned above , after you have set your modal content execute below statement.

$("selector").dialog('option', 'position', 'center');

If content is pre-loaded before modal opens just execute this in open event, else manipulate DOM in open event and then execute statement.

$( ".selector" ).dialog({
open: function( event, ui ) {
//Do DOM manipulation if needed before executing below statement
$(this).dialog('option', 'position', 'center');
}
});

It worked well for me and the best thing is that you don't include any other plugin or library for it to work.

User Control - Custom Properties

Just add public properties to the user control.

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

Convert Java Date to UTC String

Why not just use java.text.SimpleDateFormat ?

Date someDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s = df.format(someDate);

Or see: http://www.tutorialspoint.com/java/java_date_time.htm

How to check if a string contains a substring in Bash

You should remember that shell scripting is less of a language and more of a collection of commands. Instinctively you think that this "language" requires you to follow an if with a [ or a [[. Both of those are just commands that return an exit status indicating success or failure (just like every other command). For that reason I'd use grep, and not the [ command.

Just do:

if grep -q foo <<<"$string"; then
    echo "It's there"
fi

Now that you are thinking of if as testing the exit status of the command that follows it (complete with semi-colon), why not reconsider the source of the string you are testing?

## Instead of this
filetype="$(file -b "$1")"
if grep -q "tar archive" <<<"$filetype"; then
#...

## Simply do this
if file -b "$1" | grep -q "tar archive"; then
#...

The -q option makes grep not output anything, as we only want the return code. <<< makes the shell expand the next word and use it as the input to the command, a one-line version of the << here document (I'm not sure whether this is standard or a Bashism).

Reading HTML content from a UIWebView

Note that the NSString stringWithContentsOfURL will report a totally different user-agent string than the UIWebView making the same request. So if your server is user-agent aware, and sending back different html depending on who is asking for it, you may not get correct results this way.

Also note that the @"document.body.innerHTML" mentioned above will only display what is in the body tag. If you use @"document.all[0].innerHTML" you will get both head and body. Which is still not the complete contents of the UIWebView, since it will not get back the !doctype or html tags, but it is a lot closer.

jquery's append not working with svg element?

Based on @chris-dolphin 's answer but using helper function:

// Creates svg element, returned as jQuery object
function $s(elem) {
  return $(document.createElementNS('http://www.w3.org/2000/svg', elem));
}

var $svg = $s("svg");
var $circle = $s("circle").attr({...});
$svg.append($circle);

How to encrypt String in Java

Here a simple solution with only java.* and javax.crypto.* dependencies for encryption of bytes providing confidentiality and integrity. It shall be indistinguishable under a choosen plaintext attack for short messages in the order of kilobytes.

It uses AES in the GCM mode with no padding, a 128bit key is derived by PBKDF2 with lots of iterations and a static salt from the provided password. This makes sure brute forcing passwords is hard and distributes the entropy over the entire key.

A random initialisation vector (IV) is generated and will be prepended to the ciphertext. Furthermore, the static byte 0x01 is prepended as the first byte as a 'version'.

The entire message goes into the message authentication code (MAC) generated by AES/GCM.

Here it goes, zero external dependencies encryption class providing confidentiality and integrity:

package ch.n1b.tcrypt.utils;

import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * This class implements AES-GCM symmetric key encryption with a PBKDF2 derived password.
 * It provides confidentiality and integrity of the plaintext.
 *
 * @author Thomas Richner
 * @created 2018-12-07
 */
public class AesGcmCryptor {

    // https://crypto.stackexchange.com/questions/26783/ciphertext-and-tag-size-and-iv-transmission-with-aes-in-gcm-mode
    private static final byte VERSION_BYTE = 0x01;
    private static final int VERSION_BYTE_LENGTH = 1;
    private static final int AES_KEY_BITS_LENGTH = 128;


    // fixed AES-GCM constants
    private static final String GCM_CRYPTO_NAME = "AES/GCM/NoPadding";
    private static final int GCM_IV_BYTES_LENGTH = 12;
    private static final int GCM_TAG_BYTES_LENGTH = 16;

    // can be tweaked, more iterations = more compute intensive to brute-force password
    private static final int PBKDF2_ITERATIONS = 1024;

    // protects against rainbow tables
    private static final byte[] PBKDF2_SALT = hexStringToByteArray("4d3fe0d71d2abd2828e7a3196ea450d4");

    public String encryptString(char[] password, String plaintext) throws CryptoException {

        byte[] encrypted = null;
        try {
            encrypted = encrypt(password, plaintext.getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException //
                | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException //
                | InvalidKeySpecException e) {
            throw new CryptoException(e);
        }
        return byteArrayToHexString(encrypted);
    }

    public String decryptString(char[] password, String ciphertext)
            throws CryptoException {

        byte[] ct = hexStringToByteArray(ciphertext);
        byte[] plaintext = null;
        try {
            plaintext = decrypt(password, ct);
        } catch (AEADBadTagException e) {
            throw new CryptoException(e);
        } catch ( //
                NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeySpecException //
                        | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException //
                        | BadPaddingException e) {
            throw new CryptoException(e);
        }
        return new String(plaintext, StandardCharsets.UTF_8);
    }

    /**
     * Decrypts an AES-GCM encrypted ciphertext and is
     * the reverse operation of {@link AesGcmCryptor#encrypt(char[], byte[])}
     *
     * @param password   passphrase for decryption
     * @param ciphertext encrypted bytes
     * @return plaintext bytes
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     * @throws InvalidKeySpecException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws IllegalArgumentException           if the length or format of the ciphertext is bad
     * @throws CryptoException
     */
    public byte[] decrypt(char[] password, byte[] ciphertext)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeySpecException,
            InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

        // input validation
        if (ciphertext == null) {
            throw new IllegalArgumentException("ciphertext cannot be null");
        }

        if (ciphertext.length <= VERSION_BYTE_LENGTH + GCM_IV_BYTES_LENGTH + GCM_TAG_BYTES_LENGTH) {
            throw new IllegalArgumentException("ciphertext too short");
        }

        // the version must match, we don't decrypt other versions
        if (ciphertext[0] != VERSION_BYTE) {
            throw new IllegalArgumentException("wrong version: " + ciphertext[0]);
        }

        // input seems legit, lets decrypt and check integrity

        // derive key from password
        SecretKey key = deriveAesKey(password, PBKDF2_SALT, AES_KEY_BITS_LENGTH);

        // init cipher
        Cipher cipher = Cipher.getInstance(GCM_CRYPTO_NAME);
        GCMParameterSpec params = new GCMParameterSpec(GCM_TAG_BYTES_LENGTH * 8,
                ciphertext,
                VERSION_BYTE_LENGTH,
                GCM_IV_BYTES_LENGTH
        );
        cipher.init(Cipher.DECRYPT_MODE, key, params);

        final int ciphertextOffset = VERSION_BYTE_LENGTH + GCM_IV_BYTES_LENGTH;

        // add version and IV to MAC
        cipher.updateAAD(ciphertext, 0, ciphertextOffset);

        // decipher and check MAC
        return cipher.doFinal(ciphertext, ciphertextOffset, ciphertext.length - ciphertextOffset);
    }

    /**
     * Encrypts a plaintext with a password.
     * <p>
     * The encryption provides the following security properties:
     * Confidentiality + Integrity
     * <p>
     * This is achieved my using the AES-GCM AEAD blockmode with a randomized IV.
     * <p>
     * The tag is calculated over the version byte, the IV as well as the ciphertext.
     * <p>
     * Finally the encrypted bytes have the following structure:
     * <pre>
     *          +-------------------------------------------------------------------+
     *          |         |               |                             |           |
     *          | version | IV bytes      | ciphertext bytes            |    tag    |
     *          |         |               |                             |           |
     *          +-------------------------------------------------------------------+
     * Length:     1B        12B            len(plaintext) bytes            16B
     * </pre>
     * Note: There is no padding required for AES-GCM, but this also implies that
     * the exact plaintext length is revealed.
     *
     * @param password  password to use for encryption
     * @param plaintext plaintext to encrypt
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws InvalidKeySpecException
     */
    public byte[] encrypt(char[] password, byte[] plaintext)
            throws NoSuchAlgorithmException, NoSuchPaddingException,
            InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException,
            InvalidKeySpecException {

        // initialise random and generate IV (initialisation vector)
        SecretKey key = deriveAesKey(password, PBKDF2_SALT, AES_KEY_BITS_LENGTH);
        final byte[] iv = new byte[GCM_IV_BYTES_LENGTH];
        SecureRandom random = SecureRandom.getInstanceStrong();
        random.nextBytes(iv);

        // encrypt
        Cipher cipher = Cipher.getInstance(GCM_CRYPTO_NAME);
        GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_BYTES_LENGTH * 8, iv);
        cipher.init(Cipher.ENCRYPT_MODE, key, spec);

        // add IV to MAC
        final byte[] versionBytes = new byte[]{VERSION_BYTE};
        cipher.updateAAD(versionBytes);
        cipher.updateAAD(iv);

        // encrypt and MAC plaintext
        byte[] ciphertext = cipher.doFinal(plaintext);

        // prepend VERSION and IV to ciphertext
        byte[] encrypted = new byte[1 + GCM_IV_BYTES_LENGTH + ciphertext.length];
        int pos = 0;
        System.arraycopy(versionBytes, 0, encrypted, 0, VERSION_BYTE_LENGTH);
        pos += VERSION_BYTE_LENGTH;
        System.arraycopy(iv, 0, encrypted, pos, iv.length);
        pos += iv.length;
        System.arraycopy(ciphertext, 0, encrypted, pos, ciphertext.length);

        return encrypted;
    }

    /**
     * We derive a fixed length AES key with uniform entropy from a provided
     * passphrase. This is done with PBKDF2/HMAC256 with a fixed count
     * of iterations and a provided salt.
     *
     * @param password passphrase to derive key from
     * @param salt     salt for PBKDF2 if possible use a per-key salt, alternatively
     *                 a random constant salt is better than no salt.
     * @param keyLen   number of key bits to output
     * @return a SecretKey for AES derived from a passphrase
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private SecretKey deriveAesKey(char[] password, byte[] salt, int keyLen)
            throws NoSuchAlgorithmException, InvalidKeySpecException {

        if (password == null || salt == null || keyLen <= 0) {
            throw new IllegalArgumentException();
        }
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(password, salt, PBKDF2_ITERATIONS, keyLen);
        SecretKey pbeKey = factory.generateSecret(spec);

        return new SecretKeySpec(pbeKey.getEncoded(), "AES");
    }

    /**
     * Helper to convert hex strings to bytes.
     * <p>
     * May be used to read bytes from constants.
     */
    private static byte[] hexStringToByteArray(String s) {

        if (s == null) {
            throw new IllegalArgumentException("Provided `null` string.");
        }

        int len = s.length();
        if (len % 2 != 0) {
            throw new IllegalArgumentException("Invalid length: " + len);
        }

        byte[] data = new byte[len / 2];
        for (int i = 0; i < len - 1; i += 2) {
            byte b = (byte) toHexDigit(s, i);
            b <<= 4;
            b |= toHexDigit(s, i + 1);
            data[i / 2] = b;
        }
        return data;
    }

    private static int toHexDigit(String s, int pos) {
        int d = Character.digit(s.charAt(pos), 16);
        if (d < 0) {
            throw new IllegalArgumentException("Cannot parse hex digit: " + s + " at " + pos);
        }
        return d;
    }

    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }

    public class CryptoException extends Exception {

        public CryptoException(Throwable cause) {
            super(cause);
        }
    }
}

Here the entire project with a nice CLI: https://github.com/trichner/tcrypt

Edit: now with appropriate encryptString and decryptString

Bootstrap modal appearing under background

I got it to work by giving a high z-index value to the modal window AFTER opening it. E.g.:

$("#myModal").modal("show");
$("#myModal").css("z-index", "1500");

How to get last key in an array?

Try using array_pop and array_keys function as follows:

<?php

$array = array(
    'one' => 1,
    'two' => 2,
    'three' => 3
);

echo array_pop(array_keys($array)); // prints three

?>

File upload from <input type="file">

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input name="file" type="file" (change)="onChange($event)"/>
    </div>
  `,
  providers: [ UploadService ]
})
export class AppComponent {
  file: File;
  onChange(event: EventTarget) {
        let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
        let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
        let files: FileList = target.files;
        this.file = files[0];
        console.log(this.file);
    }

   doAnythingWithFile() {
   }

}

How to check the Angular version?

Angular CLI ng v does output few more thing than just the version.

If you only want the version from it the you can add pipe grep and filter for angular like:

ng v | grep 'Angular:'

OUTPUT:

Angular: #.#.# <-- VERSION

For this, I have an alias which is

alias ngv='ng v | grep 'Angular:''

Then just use ngv

MySQL Data Source not appearing in Visual Studio

Stuzor and hexcodes solution worked for me as well. However, if you do want the latest connector you have to download another product. From the oracle website:

Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).

Vue component event after render

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

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

Is it possible to style a select box?

Update: As of 2013 the two I've seen that are worth checking are:

  • Chosen - loads of cool stuff, 7k+ watchers on github. (mentioned by 'a paid nerd' in the comments)
  • Select2 - inspired by Chosen, part of Angular-UI with a couple useful tweaks on Chosen.

Yeah!


As of 2012 one of the most lightweight, flexible solutions I've found is ddSlick. Relevant (edited) info from the site:

  • Adds images and text to select options
  • Can use JSON to populate options
  • Supports callback functions on selection

And here's a preview of the various modes:

enter image description here

How to set image on QPushButton?

This is old but it is still useful, Fully tested with QT5.3.

Be carreful, example concerning the ressources path :

In my case I created a ressources directory named "Ressources" in the source directory project.

The folder "ressources" contain pictures and icons.Then I added a prefix "Images" in Qt So the pixmap path become:

QPixmap pixmap(":/images/Ressources/icone_pdf.png");

JF

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

If you can select it, you can manipulate it.

Try this:

$(".head h3").html("your new header");

But as others mentioned, you probably want head div to have an id.

Why do you have to link the math library in C?

Because of ridiculous historical practice that nobody is willing to fix. Consolidating all of the functions required by C and POSIX into a single library file would not only avoid this question getting asked over and over, but would also save a significant amount of time and memory when dynamic linking, since each .so file linked requires the filesystem operations to locate and find it, and a few pages for its static variables, relocations, etc.

An implementation where all functions are in one library and the -lm, -lpthread, -lrt, etc. options are all no-ops (or link to empty .a files) is perfectly POSIX conformant and certainly preferable.

Note: I'm talking about POSIX because C itself does not specify anything about how the compiler is invoked. Thus you can just treat gcc -std=c99 -lm as the implementation-specific way the compiler must be invoked for conformant behavior.

How to set the text color of TextView in code?

There are many different ways to set color on text view.

  1. Add color value in studio res->values->colors.xml as

    <color name="color_purple">#800080</color>
    

    Now set the color in xml or actvity class as

    text.setTextColor(getResources().getColor(R.color.color_purple)
    
  2. If you want to give color code directly use below Color.parseColor code

    textView.setTextColor(Color.parseColor("#ffffff"));   
    
  3. You can also use RGB

    text.setTextColor(Color.rgb(200,0,0));
    
  4. Use can also use direct hexcode for textView. You can also insert plain HEX, like so:

    text.setTextColor(0xAARRGGBB);
    
  5. You can also use argb with alpha values.

       text.setTextColor(Color.argb(0,200,0,0));
    

    a for Alpha (Transparent) v.

  6. And if you're using the Compat library you can do something like this

       text.setTextColor(ContextCompat.getColor(context, R.color.color_purple));
    

append option to select menu?

HTML

<select id="mySelect">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
</select>

JavaScript

 var mySelect = document.getElementById('mySelect'),
    newOption = document.createElement('option');

newOption.value = 'bmw';

// Not all browsers support textContent (W3C-compliant)
// When available, textContent is faster (see http://stackoverflow.com/a/1359822/139010)
if (typeof newOption.textContent === 'undefined')
{
    newOption.innerText = 'BMW';
}
else
{
    newOption.textContent = 'BMW';
}

mySelect.appendChild(newOption);

Demo →

What is the difference between “int” and “uint” / “long” and “ulong”?

uint and ulong are the unsigned versions of int and long. That means they can't be negative. Instead they have a larger maximum value.

Type    Min                           Max                           CLS-compliant
int     -2,147,483,648                2,147,483,647                 Yes
uint    0                             4,294,967,295                 No
long    –9,223,372,036,854,775,808    9,223,372,036,854,775,807     Yes
ulong   0                             18,446,744,073,709,551,615    No

To write a literal unsigned int in your source code you can use the suffix u or U for example 123U.

You should not use uint and ulong in your public interface if you wish to be CLS-Compliant.

Read the documentation for more information:

By the way, there is also short and ushort and byte and sbyte.

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

How to detect page zoom level in all modern browsers?

Now it's an even bigger mess than it was when this question was first asked. From reading all the responses and blog posts I could find, here's a summary. I also set up this page to test all these methods of measuring the zoom level.

Edit (2011-12-12): I've added a project that can be cloned: https://github.com/tombigel/detect-zoom

  • IE8: screen.deviceXDPI / screen.logicalXDPI (or, for the zoom level relative to default zoom, screen.systemXDPI / screen.logicalXDPI)
  • IE7: var body = document.body,r = body.getBoundingClientRect(); return (r.left-r.right)/body.offsetWidth; (thanks to this example or this answer)
  • FF3.5 ONLY: screen.width / media query screen width (see below) (takes advantage of the fact that screen.width uses device pixels but MQ width uses CSS pixels--thanks to Quirksmode widths)
  • FF3.6: no known method
  • FF4+: media queries binary search (see below)
  • WebKit: https://www.chromestatus.com/feature/5737866978131968 (thanks to Teo in the comments)
  • WebKit: measure the preferred size of a div with -webkit-text-size-adjust:none.
  • WebKit: (broken since r72591) document.width / jQuery(document).width() (thanks to Dirk van Oosterbosch above). To get ratio in terms of device pixels (instead of relative to default zoom), multiply by window.devicePixelRatio.
  • Old WebKit? (unverified): parseInt(getComputedStyle(document.documentElement,null).width) / document.documentElement.clientWidth (from this answer)
  • Opera: document.documentElement.offsetWidth / width of a position:fixed; width:100% div. from here (Quirksmode's widths table says it's a bug; innerWidth should be CSS px). We use the position:fixed element to get the width of the viewport including the space where the scrollbars are; document.documentElement.clientWidth excludes this width. This is broken since sometime in 2011; I know no way to get the zoom level in Opera anymore.
  • Other: Flash solution from Sebastian
  • Unreliable: listen to mouse events and measure change in screenX / change in clientX

Here's a binary search for Firefox 4, since I don't know of any variable where it is exposed:

<style id=binarysearch></style>
<div id=dummyElement>Dummy element to test media queries.</div>
<script>
var mediaQueryMatches = function(property, r) {
  var style = document.getElementById('binarysearch');
  var dummyElement = document.getElementById('dummyElement');
  style.sheet.insertRule('@media (' + property + ':' + r +
                         ') {#dummyElement ' +
                         '{text-decoration: underline} }', 0);
  var matched = getComputedStyle(dummyElement, null).textDecoration
      == 'underline';
  style.sheet.deleteRule(0);
  return matched;
};
var mediaQueryBinarySearch = function(
    property, unit, a, b, maxIter, epsilon) {
  var mid = (a + b)/2;
  if (maxIter == 0 || b - a < epsilon) return mid;
  if (mediaQueryMatches(property, mid + unit)) {
    return mediaQueryBinarySearch(
        property, unit, mid, b, maxIter-1, epsilon);
  } else {
    return mediaQueryBinarySearch(
        property, unit, a, mid, maxIter-1, epsilon);
  }
};
var mozDevicePixelRatio = mediaQueryBinarySearch(
    'min--moz-device-pixel-ratio', '', a, b, maxIter, epsilon);
var ff35DevicePixelRatio = screen.width / mediaQueryBinarySearch(
    'min-device-width', 'px', 0, 6000, 25, .0001);
</script>

Call to undefined function oci_connect()

Alright, folks.

First, use

<?php 
phpinfo();
?> 

and determine your PHP Version (located at the very top, e.g. 7.0.xxx) and also, your PHP Version architecture: x64 or x86 and also, Thread Safe or Not THread Safe (located in the first table as "Thread Safety".) "Disabled" obviously means "Not Thread Safe".

It is absolutely critical that the following three pieces of software that you will need are:

  1. for the same major version of PHP (7.0 for 7.0.xxx)
  2. same version of Oracle as the version you are accessing (11g, 12g, etc)
  3. the same Not Thread Safe / Thread Safe version of PHP
  4. all for the same architecture.

If any of the following are for a different architecture, Not Thread Safe/Thread Safe version, PHP major version number, or database version, you'll get errors:

 1. PHP for Windows
 2. OCI8 PECL Drivers for PHP (https://pecl.php.net/package/oci8)
 3. Oracle Instant Client

Remember: If you are connecting to an 11g Oracle instance, you need an 11g driver.

Second, install the correct PHP, OCI8 PECL Driver, and instant client.

I chose:

d:\php\ for php
d:\oci\ for instant client
unzip the contents of the OCI8 PECL Driver into d:\php\ext\

Third, modify d:\php\php.ini according the instructions given by Oracle:

1. set the extension directory
2. set only one of the following:
  a. for 11g drivers, use extension=php_oci8_11g.dll
  b. for 12c drivers, use extension=php_oci8_12c.dll
  c. for other oracle DB drivers, use the correct oracle extension.

Fourth: Add d:\oci\ (or whatever your instant client install location is) to your system PATH.

Fifth: reboot your PC.

Sixth, on a command prompt, type "where oci*" and verify that your Instant Client install path version of oci.dll is present.

Seventh, go to d:\php\ and type "php -m" and you should see OCI8 in the list.

If you do not see OCI8 in the list of modules after typing "php -m", open up d:\php\errorlog.txt

If you see something like:

PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\php_oci8_11g.dll' - %1 is not a valid Win32 application.

then either instant client or your PECL driver download is not the same architecture as your PHP version.

If you see something like:

PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\php_oci8_12c.dll' - The specified procedure could not be found.

then you are using the wrong OCI8 PECL driver for your version of instant client.

Hope this helps.

Resize command prompt through commands

If you want to run a .bat file in full screen, right click on the "example.bat" and click create shortcut, then right click on the shortcut and click properties, then click layout, in layout you can adjust your file to the screen manually, however you can only run it this way if you use the shortcut. You can also change font size by clicking font instead of layout, select lucida and adjust the font size then click apply

How do I clone a range of array elements to a new array?

Code from the System.Private.CoreLib.dll:

public static T[] GetSubArray<T>(T[] array, Range range)
{
    if (array == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
    }
    (int Offset, int Length) offsetAndLength = range.GetOffsetAndLength(array.Length);
    int item = offsetAndLength.Offset;
    int item2 = offsetAndLength.Length;
    if (default(T) != null || typeof(T[]) == array.GetType())
    {
        if (item2 == 0)
        {
            return Array.Empty<T>();
        }
        T[] array2 = new T[item2];
        Buffer.Memmove(ref Unsafe.As<byte, T>(ref array2.GetRawSzArrayData()), ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), item), (uint)item2);
        return array2;
    }
    T[] array3 = (T[])Array.CreateInstance(array.GetType().GetElementType(), item2);
    Array.Copy(array, item, array3, 0, item2);
    return array3;
}


How do I format my oracle queries so the columns don't wrap?

I use a generic query I call "dump" (why? I don't know) that looks like this:

SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |

spool &1..txt

@@&1

spool off
exit

I then call SQL*Plus passing the actual SQL script I want to run as an argument:

sqlplus -S user/password@database @dump.sql my_real_query.sql

The result is written to a file

my_real_query.sql.txt

.

How to hide the Google Invisible reCAPTCHA badge

I saw next comment about this

It's also helpful to place the badge inline if you want to apply your own CSS to it. But do remember that you agreed to show Google's Terms and conditions when you registered for an API key - so don't hide it, please. And while it is possible to make the badge disappear completely with CSS, we wouldn't recommend it.

How to create a video from images with FFmpeg?

To create frames from video:

ffmpeg\ffmpeg -i %video% test\thumb%04d.jpg -hide_banner

Optional: remove frames you don't want in output video
(more accurate than trimming video with -ss & -t)

Then create video from image/frames eg.:

ffmpeg\ffmpeg -framerate 30 -start_number 56 -i test\thumb%04d.jpg -vf format=yuv420p test/output.mp4

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

Android 10 (Q) onwards wifi can not be enabled/disabled you need to open the setting intent,

// for android Q and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            Intent panelIntent = new 
Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY);
            startActivityForResult(panelIntent, 0);
        } else {
            // for previous android version
            WifiManager wifiManager = (WifiManager) 
this.getApplicationContext().getSystemService(WIFI_SERVICE);
            wifiManager.setWifiEnabled(true);
        }

In manifest,

 <uses-permission
    android:name="android.permission.CHANGE_WIFI_STATE"
    android:required="true" />

How can I change the user on Git Bash?

If you want to change the user at git Bash .You just need to configure particular user and email(globally) at the git bash.

$ git config --global user.name "abhi"
$ git config --global user.email "[email protected]"

Note: No need to delete the user from Keychain .

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.


The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.


Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.

Note:

  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.


Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.


Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

JavaScript to get rows count of a HTML table

Given a

<table id="tableId">
    <thead>
        <tr><th>Header</th></tr>
    </thead>
    <tbody>
        <tr><td>Row 1</td></tr>
        <tr><td>Row 2</td></tr>
        <tr><td>Row 3</td></tr>
    </tbody>
    <tfoot>
        <tr><td>Footer</td></tr>
    </tfoot>
</table>

and a

var table = document.getElementById("tableId");

there are two ways to count the rows:

var totalRowCount = table.rows.length; // 5
var tbodyRowCount = table.tBodies[0].rows.length; // 3

The table.rows.length returns the amount of ALL <tr> elements within the table. So for the above table it will return 5 while most people would really expect 3. The table.tBodies returns an array of all <tbody> elements of which we grab only the first one (our table has only one). When we count the rows on it, then we get the expected value of 3.

Add two numbers and display result in textbox with Javascript

<script>
function myFunction() {
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
document.getElementById("result").innerHTML = x;
}
</script>
<p>
<label>Enter First Number : </label><br>
<input type="number" id="txt1" name="text1"><br/>
<label>Enter Second Number : </label><br>
<input type="number" id="txt2" name="text2">
</p>
<p>
<button onclick="myFunction()">Calculate</button>
</p>
<br/>
<p id="result"></p>

How to implement class constructor in Visual Basic?

Suppose your class is called MyStudent. Here's how you define your class constructor:

Public Class MyStudent
    Public StudentId As Integer

    'Here's the class constructor:
    Public Sub New(newStudentId As Integer)
        StudentId = newStudentId
    End Sub
End Class

Here's how you call it:

Dim student As New MyStudent(studentId)

Of course, your class constructor can contain as many or as few arguments as you need--even none, in which case you leave the parentheses empty. You can also have several constructors for the same class, all with different combinations of arguments. These are known as different "signatures" for your class constructor.

Running ASP.Net on a Linux based server

I can speak from experience. Even if your ASP.net website only uses .NET libraries supported by Mono you are going to have a hard time getting it to run if its anything beyond Hello World.

You won't have to re-write much code but you will spend hours/days/weeks dealing with little issues with mod_mono/xsp/apache configuration and file permissions and error handling and all the little things that go into a large website. (Be prepared to spend a lot of time asking questions on serverfault :) )

The problem is that a lot of people don't use Mono for ASP.net websites and so there aren't as many people reporting bugs so a lot of things that are minor bugs go un-fixed for a long time.

Python dictionary: are keys() and values() always the same order?

Good references to the docs. Here's how you can guarantee the order regardless of the documentation / implementation:

k, v = zip(*d.iteritems())

Copy directory contents into a directory with python

from subprocess import call

def cp_dir(source, target):
    call(['cp', '-a', source, target]) # Linux

cp_dir('/a/b/c/', '/x/y/z/')

It works for me. Basically, it executes shell command cp.

PHP server on local machine?

If you are using Windows, then the WPN-XM Server Stack might be a suitable alternative.

Android Studio - mergeDebugResources exception

In my case none of above works, I have just renamed the project name, everything works well.

Example:

My project name Before - sticky-headers-recyclerview-master

My project name After - SHRV

Hope this will help you.

Remove duplicates from a list of objects based on property in Java 8

Try this code:

Collection<Employee> nonDuplicatedEmployees = employees.stream()
   .<Map<Integer, Employee>> collect(HashMap::new,(m,e)->m.put(e.getId(), e), Map::putAll)
   .values();

How to get index of an item in java.util.Set

After creating Set just convert it to List and get by index from List:

Set<String> stringsSet = new HashSet<>();
stringsSet.add("string1");
stringsSet.add("string2");

List<String> stringsList = new ArrayList<>(stringsSet);
stringsList.get(0); // "string1";
stringsList.get(1); // "string2";

Get checkbox list values with jQuery

Since nobody has mentioned this..

If all you want is an array of values, an easier alternative would be to use the .map() method. Just remember to call .get() to convert the jQuery object to an array:

Example Here

var names = $('.parent input:checked').map(function () {
    return this.name;
}).get();

console.log(names);

_x000D_
_x000D_
var names = $('.parent input:checked').map(function () {_x000D_
    return this.name;_x000D_
}).get();_x000D_
_x000D_
console.log(names);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="parent">_x000D_
    <input type="checkbox" name="name1" />_x000D_
    <input type="checkbox" name="name2" />_x000D_
    <input type="checkbox" name="name3" checked="checked" />_x000D_
    <input type="checkbox" name="name4" checked="checked" />_x000D_
    <input type="checkbox" name="name5" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Pure JavaScript:

Example Here

var elements = document.querySelectorAll('.parent input:checked');
var names = Array.prototype.map.call(elements, function(el, i) {
    return el.name;
});

console.log(names);

_x000D_
_x000D_
var elements = document.querySelectorAll('.parent input:checked');_x000D_
var names = Array.prototype.map.call(elements, function(el, i){_x000D_
    return el.name;_x000D_
});_x000D_
_x000D_
console.log(names);
_x000D_
<div class="parent">_x000D_
    <input type="checkbox" name="name1" />_x000D_
    <input type="checkbox" name="name2" />_x000D_
    <input type="checkbox" name="name3" checked="checked" />_x000D_
    <input type="checkbox" name="name4" checked="checked" />_x000D_
    <input type="checkbox" name="name5" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS submit button weird rendering on iPad/iPhone

The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)

-webkit-appearance:none;
opacity: 1

After setting the opacity, the button looked the same on all the different devices/emulator/desktop.

Jest spyOn function called

You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance before trying to spy on the method.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const instance = app.instance()
    const spy = jest.spyOn(instance, 'myClickFunc')

    instance.forceUpdate();    

    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html

Set TextView text from html-formatted string resource in XML

As the top answer here is suggesting something wrong (or at least too complicated), I feel this should be updated, although the question is quite old:

When using String resources in Android, you just have to call getString(...) from Java code or use android:text="@string/..." in your layout XML.

Even if you want to use HTML markup in your Strings, you don't have to change a lot:

The only characters that you need to escape in your String resources are:

  • double quotation mark: " becomes \"
  • single quotation mark: ' becomes \'
  • ampersand: & becomes &#38; or &amp;

That means you can add your HTML markup without escaping the tags:

<string name="my_string"><b>Hello World!</b> This is an example.</string>

However, to be sure, you should only use <b>, <i> and <u> as they are listed in the documentation.

If you want to use your HTML strings from XML, just keep on using android:text="@string/...", it will work fine.

The only difference is that, if you want to use your HTML strings from Java code, you have to use getText(...) instead of getString(...) now, as the former keeps the style and the latter will just strip it off.

It's as easy as that. No CDATA, no Html.fromHtml(...).

You will only need Html.fromHtml(...) if you did encode your special characters in HTML markup. Use it with getString(...) then. This can be necessary if you want to pass the String to String.format(...).

This is all described in the docs as well.

Edit:

There is no difference between getText(...) with unescaped HTML (as I've proposed) or CDATA sections and Html.fromHtml(...).

See the following graphic for a comparison:

enter image description here

Razor-based view doesn't see referenced assemblies

Try adding the namespace your MyClasses is in to the web.config under

<pages> <namespaces></namespaces> </pages>

Best practice for instantiating a new Android Fragment

I believe I have a much simpeler solution for this.

public class MyFragment extends Fragment{

   private String mTitle;
   private List<MyObject> mObjects;

   public static MyFragment newInstance(String title, List<MyObject> objects)
   MyFragment myFrag = new MyFragment();
   myFrag.mTitle = title;
   myFrag.mObjects = objects;
   return myFrag;
   }

How to reduce a huge excel file

If your file is just text, the best solution is to save each worksheet as .csv and then reimport it into excel - it takes a bit more work, but I reduced a 20MB file to 43KB.

How to insert text in a td with id, using JavaScript

Use jQuery

Look how easy it would be if you did.

Example:

$('#td1').html('hello world');

How to select the first, second, or third element with a given class name?

You probably finally realized this between posting this question and today, but the very nature of selectors makes it impossible to navigate through hierarchically unrelated HTML elements.

Or, to put it simply, since you said in your comment that

there are no uniform parent containers

... it's just not possible with selectors alone, without modifying the markup in some way as shown by the other answers.

You have to use the jQuery .eq() solution.

How to change the href for a hyperlink using jQuery

Stop using jQuery just for the sake of it! This is so simple with JavaScript only.

document.querySelector('#the-link').setAttribute('href', 'http://google.com');

https://jsfiddle.net/bo77f8mg/1/

How to set a header for a HTTP GET request, and trigger file download?

Try

html

<!-- placeholder , 
    `click` download , `.remove()` options ,
     at js callback , following js 
-->
<a>download</a>

js

        $(document).ready(function () {
            $.ajax({
                // `url` 
                url: '/echo/json/',
                type: "POST",
                dataType: 'json',
                // `file`, data-uri, base64
                data: {
                    json: JSON.stringify({
                        "file": "data:text/plain;base64,YWJj"
                    })
                },
                // `custom header`
                headers: {
                    "x-custom-header": 123
                },
                beforeSend: function (jqxhr) {
                    console.log(this.headers);
                    alert("custom headers" + JSON.stringify(this.headers));
                },
                success: function (data) {
                    // `file download`
                    $("a")
                        .attr({
                        "href": data.file,
                            "download": "file.txt"
                    })
                        .html($("a").attr("download"))
                        .get(0).click();
                    console.log(JSON.parse(JSON.stringify(data)));
                },
                error: function (jqxhr, textStatus, errorThrown) {
                  console.log(textStatus, errorThrown)
                }
            });
        });

jsfiddle http://jsfiddle.net/guest271314/SJYy3/

Import XXX cannot be resolved for Java SE standard classes

Right click on project - >BuildPath - >Configure BuildPath - >Libraries tab - >

Double click on JRE SYSTEM LIBRARY - >Then select alternate JRE

Can I use CASE statement in a JOIN condition?

Yes, you can. Here is an example.

SELECT a.*
FROM TableA a
LEFT OUTER JOIN TableB j1 ON  (CASE WHEN LEN(COALESCE(a.NoBatiment, '')) = 3 
                                THEN RTRIM(a.NoBatiment) + '0' 
                                ELSE a.NoBatiment END ) = j1.ColumnName 

How to manually set REFERER header in Javascript?

Above solution does not work for me , I have tried following and it is working in all browsers.

simply made a fake ajax call, it will make a entry into referer header.

var request;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    try {
        request = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e) {
        try {
            request = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {}
    }
}
request.open("GET", url, true);
request.send();

Creating a textarea with auto-resize

This code works for pasting and select delete also.

_x000D_
_x000D_
onKeyPressTextMessage = function(){_x000D_
   var textArea = event.currentTarget;_x000D_
     textArea.style.height = 'auto';_x000D_
     textArea.style.height = textArea.scrollHeight + 'px';_x000D_
};
_x000D_
<textarea onkeyup="onKeyPressTextMessage(event)" name="welcomeContentTmpl" id="welcomeContent" onblur="onblurWelcomeTitle(event)" rows="2" cols="40" maxlength="320"></textarea>
_x000D_
_x000D_
_x000D_

Here is the JSFiddle

mongoError: Topology was destroyed

In my case, this error was caused by an identical server instance already running background.

The weird thing is when I started my server without notice there's one running already, the console didn't show anything like 'something is using port xxx'. I could even upload something to the server. So, it took me quite long to locate this problem.

What's more, after closing all the applications I can imagine, I still could not find the process which is using this port in my Mac's activity monitor. I have to use lsof to trace. The culprit was not surprising - it's a node process. However, with the PID shown in the terminal, I found the port number in the monitor is different from the one used by my server.

All in all, kill all the node processes may solve this problem directly.

json_decode returns NULL after webservice call

Well, i had a similar issue and the problems was the PHP magic quotes in the server... here is my solution:

if(get_magic_quotes_gpc()){
  $param = stripslashes($_POST['param']);
}else{
  $param = $_POST['param'];
}
$param = json_decode($param,true);

How to get all privileges back to the root user in MySQL?

If you facing grant permission access denied problem, you can try mysql to fix the problem:

grant all privileges on . to root@'localhost' identified by 'Your password';

grant all privileges on . to root@'IP ADDRESS' identified by 'Your password?';

your can try this on any mysql user, its working.

Use below command to login mysql with iP address.

mysql -h 10.0.0.23 -u root -p

Changing website favicon dynamically

The favicon is declared in the head tag with something like:

<link rel="shortcut icon" type="image/ico" href="favicon.ico">

You should be able to just pass the name of the icon you want along in the view data and throw it into the head tag.

Fatal error: Call to a member function query() on null

First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:

global $db;

And I guess, when you wrote:

if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:

if ($result->num_rows==1) { return true; } else { return false; }

Getting the closest string match

You might find this library helpful! http://code.google.com/p/google-diff-match-patch/

It is currently available in Java, JavaScript, Dart, C++, C#, Objective C, Lua and Python

It works pretty well too. I use it in a couple of my Lua projects.

And I don't think it would be too difficult to port it to other languages!

Show or hide element in React

In some cases higher order component might be useful:

Create higher order component:

export var HidableComponent = (ComposedComponent) => class extends React.Component {
    render() {
        if ((this.props.shouldHide!=null && this.props.shouldHide()) || this.props.hidden)
            return null;
        return <ComposedComponent {...this.props}  />;
    }
};

Extend your own component:

export const MyComp= HidableComponent(MyCompBasic);

Then you can use it like this:

<MyComp hidden={true} ... />
<MyComp shouldHide={this.props.useSomeFunctionHere} ... />

This reduces a bit boilerplate and enforces sticking to naming conventions, however please be aware of that MyComp will still be instantiated - the way to omit is was mentioned earlier:

{ !hidden && <MyComp ... /> }

Creating a LINQ select from multiple tables

You can use anonymous types for this, i.e.:

var pageObject = (from op in db.ObjectPermissions
                  join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                  where pg.PageID == page.PageID
                  select new { pg, op }).SingleOrDefault();

This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:-

var pageObject = (from op in db.ObjectPermissions
                  join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                  where pg.PageID == page.PageID
                  select new
                  {
                      PermissionName = pg, 
                      ObjectPermission = op
                  }).SingleOrDefault();

This will enable you to say:-

if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit();

For example :-)

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

I created a nice Each extension that has the same behavior as jQuery's each function.

It allows something like below, where you can get the index of the current value and break out of the loop by returning false:

new[] { "first", "second", "third" }.Each((value, index) =>
{
    if (value.Contains("d"))
        return false;
    Console.Write(value);
    return true;
});

Here's the code

/// <summary>
/// Generic iterator function that is useful to replace a foreach loop with at your discretion.  A provided action is performed on each element.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action">Function that takes in the current value in the sequence. 
/// <returns></returns>
public static IEnumerable<T> Each<T>(this IEnumerable<T> source, Action<T> action)
{
    return source.Each((value, index) =>
    {
        action(value);
        return true;
    });
}


/// <summary>
/// Generic iterator function that is useful to replace a foreach loop with at your discretion.  A provided action is performed on each element.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action">Function that takes in the current value and its index in the sequence.  
/// <returns></returns>
public static IEnumerable<T> Each<T>(this IEnumerable<T> source, Action<T, int> action)
{
    return source.Each((value, index) =>
    {
        action(value, index);
        return true;
    });
}

/// <summary>
/// Generic iterator function that is useful to replace a foreach loop with at your discretion.  A provided action is performed on each element.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action">Function that takes in the current value in the sequence.  Returns a value indicating whether the iteration should continue.  So return false if you don't want to iterate anymore.</param>
/// <returns></returns>
public static IEnumerable<T> Each<T>(this IEnumerable<T> source, Func<T, bool> action)
{
    return source.Each((value, index) =>
    {
        return action(value);
    });
}

/// <summary>
/// Generic iterator function that is useful to replace a foreach loop with at your discretion.  A provided action is performed on each element.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="action">Function that takes in the current value and its index in the sequence.  Returns a value indicating whether the iteration should continue.  So return false if you don't want to iterate anymore.</param>
/// <returns></returns>
public static IEnumerable<T> Each<T>(this IEnumerable<T> source, Func<T, int, bool> action)
{
    if (source == null)
        return source;

    int index = 0;
    foreach (var sourceItem in source)
    {
        if (!action(sourceItem, index))
            break;
        index++;
    }
    return source;
}

Finding the indices of matching elements in list in Python

if you're doing a lot of this kind of thing you should consider using numpy.

In [56]: import random, numpy

In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list

In [58]: a, b = 1, 3

In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])

In response to Seanny123's question, I used this timing code:

import numpy, timeit, random

a, b = 1, 3

lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])

def numpy_way():
    numpy.flatnonzero((lst > 1) & (lst < 3))[:10]

def list_comprehension():
    [e for e in lst if 1 < e < 3][:10]

print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)

The numpy version is over 60 times faster.

ASP.NET MVC - Getting QueryString values

Query string parameters can be accepted simply by using an argument on the action - i.e.

public ActionResult Foo(string someValue, int someOtherValue) {...}

which will accept a query like .../someroute?someValue=abc&someOtherValue=123

Other than that, you can look at the request directly for more control.

How to unpublish an app in Google Play Developer Console

As per recent version. You need to go advanced settings. In this section you will find the un-publish button.

Slidedown and slideup layout with animation

This doesn't work for me, I want to to like jquery slideUp / slideDown function, I tried this code, but it only move the content wich stay at the same place after animation end, the view should have a 0dp height at start of slideDown and the view height (with wrap_content) after the end of the animation.

Uppercase first letter of variable

It is as simple as the following:

string = 'test';
newString = string[0].toUpperCase() + string.slice(1);
alert(newString);

Multi-statement Table Valued Function vs Inline Table Valued Function

I have not tested this, but a multi statement function caches the result set. There may be cases where there is too much going on for the optimizer to inline the function. For example suppose you have a function that returns a result from different databases depending on what you pass as a "Company Number". Normally, you could create a view with a union all then filter by company number but I found that sometimes sql server pulls back the entire union and is not smart enough to call the one select. A table function can have logic to choose the source.

Cocoa Autolayout: content hugging vs content compression resistance priority

If view.intrinsicContentSize.width != NSViewNoIntrinsicMetric, then auto layout creates a special constraint of type NSContentSizeLayoutConstraint. This constraint acts like two normal constraints:

  • a constraint requiring view.width <= view.intrinsicContentSize.width with the horizontal hugging priority, and
  • a constraint requiring view.width >= view.intrinsicContentSize.width with the horizontal compression resistance priority.

In Swift, with iOS 9's new layout anchors, you could set up equivalent constraints like this:

let horizontalHugging = view.widthAnchor.constraint(
    lessThanOrEqualToConstant: view.intrinsicContentSize.width)
horizontalHugging.priority = view.contentHuggingPriority(for: .horizontal)

let horizontalCompression = view.widthAnchor.constraint(
    greaterThanOrEqualToConstant: view.intrinsicContentSize.width)
horizontalCompression.priority = view.contentCompressionResistancePriority(for: .horizontal)

Similarly, if view.intrinsicContentSize.height != NSViewNoIntrinsicMetric, then auto layout creates an NSContentSizeLayoutConstraint that acts like two constraints on the view's height. In code, they would look like this:

let verticalHugging = view.heightAnchor.constraint(
    lessThanOrEqualToConstant: view.intrinsicContentSize.height)
verticalHugging.priority = view.contentHuggingPriority(for: .vertical)

let verticalCompression = view.heightAnchor.constraint(
    greaterThanOrEqualToConstant: view.intrinsicContentSize.height)
verticalCompression.priority = view.contentCompressionResistancePriority(for: .vertical)

You can see these special NSContentSizeLayoutConstraint instances (if they exist) by printing view.constraints after layout has run. Example:

label.constraints.forEach { print($0) }

// Output:
<NSContentSizeLayoutConstraint:0x7fd82982af90 H:[UILabel:0x7fd82980e5e0'Hello'(39)] Hug:250 CompressionResistance:750>
<NSContentSizeLayoutConstraint:0x7fd82982b4f0 V:[UILabel:0x7fd82980e5e0'Hello'(21)] Hug:250 CompressionResistance:750>

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

I came here with the same Error, though one with a different origin.

It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.

An int type is expected, not a np.float64

Solution: Try to install numpy 1.11.0

sudo pip install -U numpy==1.11.0.

stringstream, string, and char* conversion confusion

The std::string object returned by ss.str() is a temporary object that will have a life time limited to the expression. So you cannot assign a pointer to a temporary object without getting trash.

Now, there is one exception: if you use a const reference to get the temporary object, it is legal to use it for a wider life time. For example you should do:

#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main()
{
    stringstream ss("this is a string\n");

    string str(ss.str());

    const char* cstr1 = str.c_str();

    const std::string& resultstr = ss.str();
    const char* cstr2 = resultstr.c_str();

    cout << cstr1       // Prints correctly
        << cstr2;       // No more error : cstr2 points to resultstr memory that is still alive as we used the const reference to keep it for a time.

    system("PAUSE");

    return 0;
}

That way you get the string for a longer time.

Now, you have to know that there is a kind of optimisation called RVO that say that if the compiler see an initialization via a function call and that function return a temporary, it will not do the copy but just make the assigned value be the temporary. That way you don't need to actually use a reference, it's only if you want to be sure that it will not copy that it's necessary. So doing:

 std::string resultstr = ss.str();
 const char* cstr2 = resultstr.c_str();

would be better and simpler.

Socket.IO - how do I get a list of connected sockets/clients?

In Socket.IO 0.7 you have a clients method on the namespaces, this returns a array of all connected sockets.

API for no namespace:

var clients = io.sockets.clients();
var clients = io.sockets.clients('room'); // all users from room `room`

For a namespace

var clients = io.of('/chat').clients();
var clients = io.of('/chat').clients('room'); // all users from room `room`

Hopes this helps someone in the future

NOTE: This Solution ONLY works with version prior to 1.0


UPDATED 2020 Mar 06

From 1.x and above, please refer to this link: getting how many people are in a chat room in socket.io

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

I faced the same issue, I tried the below solution and it worked for me In Android SDK Manager Window, click on Tools->Options-> under "Others", check "Force https://... sources to be fetched using http://..."

Gradle build without tests

You can add the following lines to build.gradle, **/* excludes all the tests.

test {
    exclude '**/*'
}