Programs & Examples On #Temporal

Deserialize Java 8 LocalDateTime with JacksonMapper

This worked for me :

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;

@Column(name="end_date", nullable = false)
@DateTimeFormat(iso = ISO.DATE_TIME)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private LocalDateTime endDate;

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

Expanding on retrography's answer..: I had this same problem even when using LocalDate and not LocalDateTime. The issue was that I had created my DateTimeFormatter using .withResolverStyle(ResolverStyle.STRICT);, so I had to use date pattern uuuuMMdd instead of yyyyMMdd (i.e. "year" instead of "year-of-era")!

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
  .parseStrict()
  .appendPattern("uuuuMMdd")
  .toFormatter()
  .withResolverStyle(ResolverStyle.STRICT);
LocalDate dt = LocalDate.parse("20140218", formatter);

(This solution was originally a comment to retrography's answer, but I was encouraged to post it as a stand-alone answer because it apparently works really well for many people.)

Format LocalDateTime with Timezone in Java8

The prefix "Local" in JSR-310 (aka java.time-package in Java-8) does not indicate that there is a timezone information in internal state of that class (here: LocalDateTime). Despite the often misleading name such classes like LocalDateTime or LocalTime have NO timezone information or offset.

You tried to format such a temporal type (which does not contain any offset) with offset information (indicated by pattern symbol Z). So the formatter tries to access an unavailable information and has to throw the exception you observed.

Solution:

Use a type which has such an offset or timezone information. In JSR-310 this is either OffsetDateTime (which contains an offset but not a timezone including DST-rules) or ZonedDateTime. You can watch out all supported fields of such a type by look-up on the method isSupported(TemporalField).. The field OffsetSeconds is supported in OffsetDateTime and ZonedDateTime, but not in LocalDateTime.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
String s = ZonedDateTime.now().format(formatter);

What is the use of the @Temporal annotation in Hibernate?

If you're looking for short answer:

In the case of using java.util.Date, Java doesn't really know how to directly relate to SQL types. This is when @Temporal comes into play. It's used to specify the desired SQL type.

Source: Baeldung

Format Instant to String

Instants are already in UTC and already have a default date format of yyyy-MM-dd. If you're happy with that and don't want to mess with time zones or formatting, you could also toString() it:

Instant instant = Instant.now();
instant.toString()
output: 2020-02-06T18:01:55.648475Z


Don't want the T and Z? (Z indicates this date is UTC. Z stands for "Zulu" aka "Zero hour offset" aka UTC):

instant.toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.663763


Want milliseconds instead of nanoseconds? (So you can plop it into a sql query):

instant.truncatedTo(ChronoUnit.MILLIS).toString().replaceAll("[TZ]", " ")
output: 2020-02-06 18:01:55.664

etc.

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

Another Repeated column in mapping for entity error

use this, is work for me:

@Column(name = "candidate_id", nullable=false)
private Long candidate_id;
@ManyToOne(optional=false)
@JoinColumn(name = "candidate_id", insertable=false, updatable=false)
private Candidate candidate;

How to force Hibernate to return dates as java.util.Date instead of Timestamp?

A simple alternative to using a custom UserType is to construct a new java.util.Date in the setter for the date property in your persisted bean, eg:

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Column;

@Entity
public class Purchase {

    private Date date;

    @Column
    public Date getDate() {
        return this.date;
    }

    public void setDate(Date date) {
        // force java.sql.Timestamp to be set as a java.util.Date
        this.date = new Date(date.getTime());
    }

}

How to close TCP and UDP ports via windows command line

Yes there is possible to close TCP or UDP port there is a command in DOS

TASKKILL /f /pid 1234 

I hope this will work for You

What is the correct way to free memory in C#

Here's a quick overview:

  • Once references are gone, your object will likely be garbage collected.
  • You can only count on statistical collection that keeps your heap size normal provided all references to garbage are really gone. In other words, there is no guarantee a specific object will ever be garbage collected.
    • It follows that your finalizer will also never be guaranteed to be called. Avoid finalizers.
  • Two common sources of leaks:
    • Event handlers and delegates are references. If you subscribe to an event of an object, you are referencing to it. If you have a delegate to an object's method, you are referencing it.
    • Unmanaged resources, by definition, are not automatically collected. This is what the IDisposable pattern is for.
  • Finally, if you want a reference that does not prevent the object from getting collected, look into WeakReference.

One last thing: If you declare Foo foo; without assigning it you don't have to worry - nothing is leaked. If Foo is a reference type, nothing was created. If Foo is a value type, it is allocated on the stack and thus will automatically be cleaned up.

JPQL SELECT between date statement

Try this query (replace t.eventsDate with e.eventsDate):

SELECT e FROM Events e WHERE e.eventsDate BETWEEN :startDate AND :endDate

Infinite Recursion with Jackson JSON and Hibernate JPA issue

VERY IMPORTANT: If you are using LOMBOK, make shure to exclude attributes of collections like Set, List, etc...

Like this:

@EqualsAndHashCode(exclude = {"attributeOfTypeList", "attributeOfTypeSet"})

Setting a JPA timestamp column to be generated by the database?

I have this working well using JPA2.0 and MySQL 5.5.10, for cases where I only care about the last time the row was modified. MySQL will create a timestamp on first insertion, and every time UPDATE is called on the row. (NOTE: this will be problematic if I cared whether or not the UPDATE actually made a change).

The "timestamp" column in this example is like a "last-touched" column.x`

The code below uses a separate column "version" for optimistic locking.

private long version;
private Date timeStamp

@Version
public long getVersion() {
    return version;
}

public void setVersion(long version) {
    this.version = version;
}

// columnDefinition could simply be = "TIMESTAMP", as the other settings are the MySQL default
@Column(name="timeStamp", columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
@Temporal(TemporalType.TIMESTAMP)
public Date getTimeStamp() {
    return timeStamp;
}

public void setTimeStamp(Date timeStamp) {
    this.timeStamp = timeStamp;
}

(NOTE: @Version doesn't work on a MySQL "DATETIME" column, where the attribute type is "Date" in the Entity class. This was because Date was generating a value down to the millisecond, however MySQL was not storing the millisecond, so when it did a comparison between what was in the database, and the "attached" entity, it thought they had different version numbers)

From the MySQL manual regarding TIMESTAMP :

With neither DEFAULT nor ON UPDATE clauses, it is the same as DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP.

Firefox setting to enable cross domain Ajax request

To allow cross domain:

  1. enter about:config
  2. accept to be careful
  3. enter security.fileuri.strict_origin_policy in the search bar
  4. change to false

You can now close the tab. Normally you can now make cross domain request with this config.

See here for more details.

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

In your case (creating a list) there is no difference in practice. But generally it is better to use setUp(), because that will help Junit to report Exceptions correctly. If an exception occurs in constructor/initializer of a Test, that is a test failure. However, if an exception occurs during setup, it is natural to think of it as some issue in setting up the test, and junit reports it appropriately.

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

To the best of my knowledge, you need to put your entire Java app in UTC timezone (so that Hibernate will store dates in UTC), and you'll need to convert to whatever timezone desired when you display stuff (at least we do it this way).

At startup, we do:

TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));

And set the desired timezone to the DateFormat:

fmt.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"))

Creation timestamp and last update timestamp with Hibernate and MySQL

Taking the resources in this post along with information taken left and right from different sources, I came with this elegant solution, create the following abstract class

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@MappedSuperclass
public abstract class AbstractTimestampEntity {

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created", nullable = false)
    private Date created;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated", nullable = false)
    private Date updated;

    @PrePersist
    protected void onCreate() {
    updated = created = new Date();
    }

    @PreUpdate
    protected void onUpdate() {
    updated = new Date();
    }
}

and have all your entities extend it, for instance:

@Entity
@Table(name = "campaign")
public class Campaign extends AbstractTimestampEntity implements Serializable {
...
}

How to fill Dataset with multiple tables?

If you are issuing a single command with several select statements, you might use NextResult method to move to next resultset within the datareader: http://msdn.microsoft.com/en-us/library/system.data.idatareader.nextresult.aspx

I show how it could look bellow:

public DataSet SelectOne(int id)
{
    DataSet result = new DataSet();
    using (DbCommand command = Connection.CreateCommand())
    {
        command.CommandText = @"
select * from table1
select * from table2
        ";

        var param = ParametersBuilder.CreateByKey(command, "ID", id, null);
        command.Parameters.Add(param);

        Connection.Open();
        using (DbDataReader reader = command.ExecuteReader())
        {
            result.MainTable.Load(reader);
            reader.NextResult();
            result.SecondTable.Load(reader);
            // ...
        }
        Connection.Close();
    }
    return result;
}

How to select ALL children (in any level) from a parent in jQuery?

I think you could do:

$('#google_translate_element').find('*').each(function(){
    $(this).unbind('click');
});

but it would cause a lot of overhead

replace \n and \r\n with <br /> in java

It works for me. The Java code works exactly as you wrote it. In the tester, the input string should be:

This is a string.
This is a long string.

...with a real linefeed. You can't use:

This is a string.\nThis is a long string.

...because it treats \n as the literal sequence backslash 'n'.

How to access the local Django webserver from outside world

For AWS users.

I had to use the following steps to get there.

1) Ensure that pip and django are installed at the sudo level

  • sudo apt-get install python-pip
  • sudo pip install django

2) Ensure that security group in-bound rules includ http on port 80 for 0.0.0.0/0

  • configured through AWS console

3) Add Public IP and DNS to ALLOWED_HOSTS

  • ALLOWED_HOSTS is a list object that you can find in settings.py
  • ALLOWED_HOSTS = ["75.254.65.19","ec2-54-528-27-21.compute-1.amazonaws.com"]

4) Launch development server with sudo on port 80

  • sudo python manage.py runserver 0:80

Site now available at either of the following (no need for :80 as that is default for http):

  • [Public DNS] i.e. ec2-54-528-27-21.compute-1.amazonaws.com
  • [Public IP] i.e 75.254.65.19

Monad in plain English? (For the OOP programmer with no FP background)

A monad is a data type that encapsulates a value, and to which, essentially, two operations can be applied:

  • return x creates a value of the monad type that encapsulates x
  • m >>= f (read it as "the bind operator") applies the function f to the value in the monad m

That's what a monad is. There are a few more technicalities, but basically those two operations define a monad. The real question is, "What a monad does?", and that depends on the monad — lists are monads, Maybes are monads, IO operations are monads. All that it means when we say those things are monads is that they have the monad interface of return and >>=.

reactjs - how to set inline style of backgroundcolor?

Your quotes are in the wrong spot. Here's a simple example:

<div style={{backgroundColor: "#FF0000"}}>red</div>

Redirecting to URL in Flask

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect(url_for('foo'))

@app.route('/foo')
def foo():
    return 'Hello Foo!'

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

Take a look at the example in the documentation.

Command to delete all pods in all kubernetes namespaces

There is no command to do exactly what you asked.

Here are some close matches.

You can delete all the pods in a single namespace with this command:

kubectl delete --all pods --namespace=foo

You can also delete all deployments in namespace which will delete all pods attached with the deployments corresponding to the namespace

kubectl delete --all deployments --namespace=foo

You can delete all namespaces and every object in every namespace (but not un-namespaced objects, like nodes and some events) with this command:

kubectl delete --all namespaces

However, the latter command is probably not something you want to do, since it will delete things in the kube-system namespace, which will make your cluster not usable.

This command will delete all the namespaces except kube-system, which might be useful:

for each in $(kubectl get ns -o jsonpath="{.items[*].metadata.name}" | grep -v kube-system);
do
  kubectl delete ns $each
done

How can I get the values of data attributes in JavaScript code?

You could also grab the attributes with the getAttribute() method which will return the value of a specific HTML attribute.

_x000D_
_x000D_
var elem = document.getElementById('the-span');_x000D_
_x000D_
var typeId = elem.getAttribute('data-typeId');_x000D_
var type   = elem.getAttribute('data-type');_x000D_
var points = elem.getAttribute('data-points');_x000D_
var important = elem.getAttribute('data-important');_x000D_
_x000D_
console.log(`typeId: ${typeId} | type: ${type} | points: ${points} | important: ${important}`_x000D_
);
_x000D_
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>
_x000D_
_x000D_
_x000D_

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

mysql stored-procedure: out parameter

try changing OUT to INOUT for your out_number parameter definition.

CREATE PROCEDURE my_sqrt(input_number INT, INOUT out_number FLOAT)

INOUT means that the input variable for out_number (@out_value in your case.) will also serve as the output variable from which you can select the value from.

How to implode array with key and value without foreach in PHP

Here is a simple example, using class:

$input = array(
    'element1'  => 'value1',
    'element2'  => 'value2',
    'element3' =>  'value3'
);

echo FlatData::flatArray($input,', ', '=');

class FlatData
{

    public static function flatArray(array $input = array(), $separator_elements = ', ', $separator = ': ')
    {
        $output = implode($separator_elements, array_map(
            function ($v, $k, $s) {
                return sprintf("%s{$s}%s", $k, $v);
            },
            $input,
            array_keys($input),
            array_fill(0, count($input), $separator)
        ));
      return $output;
    }

}

How to use JQuery with ReactJS

You should try and avoid jQuery in ReactJS. But if you really want to use it, you'd put it in componentDidMount() lifecycle function of the component.

e.g.

class App extends React.Component {
  componentDidMount() {
    // Jquery here $(...)...
  }

  // ...
}

Ideally, you'd want to create a reusable Accordion component. For this you could use Jquery, or just use plain javascript + CSS.

class Accordion extends React.Component {
  constructor() {
    super();
    this._handleClick = this._handleClick.bind(this);
  }

  componentDidMount() {
    this._handleClick();
  }

  _handleClick() {
    const acc = this._acc.children;
    for (let i = 0; i < acc.length; i++) {
      let a = acc[i];
      a.onclick = () => a.classList.toggle("active");
    }
  }

  render() {
    return (
      <div 
        ref={a => this._acc = a} 
        onClick={this._handleClick}>
        {this.props.children}
      </div>
    )
  }
}

Then you can use it in any component like so:

class App extends React.Component {
  render() {
    return (
      <div>
        <Accordion>
          <div className="accor">
            <div className="head">Head 1</div>
            <div className="body"></div>
          </div>
        </Accordion>
      </div>
    );
  }
}

Codepen link here: https://codepen.io/jzmmm/pen/JKLwEA?editors=0110 (I changed this link to https ^)

codeigniter model error: Undefined property

You have to load the db library first. In autoload.php add :

$autoload['libraries'] = array('database');

Also, try renaming User model class for "User_model".

How to add items to array in nodejs

var array = [];

//length array now = 0
array[array.length] = 'hello';
//length array now = 1
//            0
//array = ['hello'];//length = 1

Positioning the colorbar

using padding pad

In order to move the colorbar relative to the subplot, one may use the pad argument to fig.colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, orientation="horizontal", pad=0.2)
plt.show()

enter image description here

using an axes divider

One can use an instance of make_axes_locatable to divide the axes and create a new axes which is perfectly aligned to the image plot. Again, the pad argument would allow to set the space between the two axes.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)

fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

using subplots

One can directly create two rows of subplots, one for the image and one for the colorbar. Then, setting the height_ratios as gridspec_kw={"height_ratios":[1, 0.05]} in the figure creation, makes one of the subplots much smaller in height than the other and this small subplot can host the colorbar.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

fig, (ax, cax) = plt.subplots(nrows=2,figsize=(4,4), 
                  gridspec_kw={"height_ratios":[1, 0.05]})
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")

fig.colorbar(im, cax=cax, orientation="horizontal")

plt.show()

enter image description here

Replacing H1 text with a logo image: best method for SEO and accessibility?

How W3C does?

Simply have a look a look at https://www.w3.org/. The image has a z-index:1, the text is here but behind because of the z-index:0 coupled to the position: absolute;

The original HTML:

<h1 class="logo">
    <a tabindex="2" accesskey="1" href="/">
        <img src="/2008/site/images/logo-w3c-mobile-lg" width="90" height="53" alt="W3C">
    </a>
    <span class="alt-logo">W3C</span>
</h1>

The original CSS:

#w3c_mast h1 a {
    display: block;
    float: left;
    background: url(../images/logo-w3c-screen-lg) no-repeat top left;
    width: 100%;
    height: 107px;
    position: relative;
    z-index: 1;
}
.alt-logo {
    display: block;
    position: absolute;
    left: 20px;
    z-index: 0;
    background-color: #fff;
}

Android Eclipse - Could not find *.apk

Delete the project from your workspace & import again.
This worked for me.

Can't believe similar issue has been there since 2008.
http://code.google.com/p/android/issues/detail?id=834.

Unable to ping vmware guest from another vmware guest

There are several related solutions available on the internet, but it all depends on the configuration of the machine and the firewall rules.

For me below solution is worked:

  • Disabled the VMware Network Adapter VMNet8
  • Removed the network from the VM
  • Enabled the VMware Network Adapter VMNet8
  • Re-added the Network to VM, and set it to NAT
  • Restarted the machine

Check this blog post for detailed solution.

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

I catch the next case about cors. Maybe it will be useful to somebody. If you add feature 'WebDav Redirector' to your server, PUT and DELETE requests are failed.

So, you will need to remove 'WebDAVModule' from your IIS server:

  • "In the IIS modules Configuration, loop up the WebDAVModule, if your web server has it, then remove it".

Or add to your config:

<system.webServer>
<modules>
  <remove name="WebDAVModule"/>
</modules>
<handlers>
  <remove name="WebDAV" />
  ...
</handlers>

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

Oracle: SQL select date with timestamp

Answer provided by Nicholas Krasnov

SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';

How to Pass data from child to parent component Angular

In order to send data from child component create property decorated with output() in child component and in the parent listen to the created event. Emit this event with new values in the payload when ever it needed.

@Output() public eventName:EventEmitter = new EventEmitter();

to emit this event:

this.eventName.emit(payloadDataObject);

Gridview get Checkbox.Checked value

You want an independent for loop for all the rows in grid view, then refer the below link

http://nikhilsreeni.wordpress.com/asp-net/checkbox/

Select all checkbox in Gridview

CheckBox cb = default(CheckBox);
for (int i = 0; i <= grdforumcomments.Rows.Count – 1; i++)
{
    cb = (CheckBox)grdforumcomments.Rows[i].Cells[0].FindControl(“cbSel”);

    cb.Checked = ((CheckBox)sender).Checked;
}

Select checked rows to a dataset; For gridview multiple edit

CheckBox cb = default(CheckBox);

foreach (GridViewRow row in grdforumcomments.Rows)
{
    cb = (CheckBox)row.FindControl("cbsel");
    if (cb.Checked)
    {
        drArticleCommentsUpdates = dtArticleCommentsUpdates.NewRow();
        drArticleCommentsUpdates["Id"] = dgItem.Cells[0].Text;
        drArticleCommentsUpdates["Date"] = System.DateTime.Now;dtArticleCommentsUpdates.Rows.Add(drArticleCommentsUpdates);
    }
}

Check if Cookie Exists

Sorry, not enough rep to add a comment, but from zmbq's answer:

Anyway, to see if a cookie exists, you can check Cookies.Get(string), this will not modify the cookie collection.

is maybe not fully correct, as Cookies.Get(string) will actually create a cookie with that name, if it does not already exist. However, as he said, you need to be looking at Request.Cookies, not Response.Cookies So, something like:

bool cookieExists = HttpContext.Current.Request.Cookies["cookie_name"] != null;

Encode URL in JavaScript?

Similar kind of thing I tried with normal javascript

function fixedEncodeURIComponent(str){
     return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}

An efficient compression algorithm for short text strings

You might want to take a look at Standard Compression Scheme for Unicode.

SQL Server 2008 R2 use it internally and can achieve up to 50% compression.

SQL Query Multiple Columns Using Distinct on One Column Only

select * from 
(select 
ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_FruitType DESC) as tt
,*
from tblFruit
) a
where a.tt=1

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

MySQL Where DateTime is greater than today

SELECT * 
FROM customer 
WHERE joiningdate >= NOW();

How to set seekbar min and max value

Another solution to handle this case is creating a customized Seekbar, to get ride of converting the real value and SeekBar progress every time:

import android.content.Context
import android.util.AttributeSet
import android.widget.SeekBar

//
// Require SeekBar with range [Min, Max] and INCREMENT value,
// However, Android Seekbar starts from 0 and increment is 1 by default, Android supports min attr on API 26,
// To make a increment & range Seekbar, we can do the following conversion:
//
//     seekbar.setMax((Max - Min) / Increment)
//     seekbar.setProgress((actualValue - Min) / Increment)
//     seekbar.getProgress = Min + (progress * Increment)
//
// The RangeSeekBar is responsible for handling all these logic inside the class.

data class Range(val min: Int, val max: Int, private val defaultIncrement: Int) {
    val increment = if ((max - min) < defaultIncrement) 1 else defaultIncrement
}


internal fun Range.toSeekbarMaximum(): Int = (max - min) / increment


class RangeSeekBar: SeekBar, SeekBar.OnSeekBarChangeListener {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    var range: Range = Range(0, 100, 1)
        set(value) {
            field = value
            max = value.toSeekbarMaximum()
        }

    var value: Int = 0
        get() = range.min + progress * range.increment
        set(value) {
            progress = (value - range.min) / range.increment
            field = value
        }

    var onSeekBarChangeListenerDelegate: OnSeekBarChangeListener? = this

    override fun setOnSeekBarChangeListener(l: OnSeekBarChangeListener?) {
        onSeekBarChangeListenerDelegate = l
        super.setOnSeekBarChangeListener(this)
    }

    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
        onSeekBarChangeListenerDelegate?.onProgressChanged(seekBar, value, fromUser)
    }

    override fun onStartTrackingTouch(seekBar: SeekBar?) {
        onSeekBarChangeListenerDelegate?.onStartTrackingTouch(seekBar)
    }

    override fun onStopTrackingTouch(seekBar: SeekBar?) {
        onSeekBarChangeListenerDelegate?.onStopTrackingTouch(seekBar)
    }
}

Then in your fragment,

    // init
    range_seekbar.range = Range(10, 110, 10)
    range_seekbar.value = 20

    // observe value changes
    range_seekbar.userChanges().skipInitialValue().subscribe {
        println("current value=$it")
    }

Keywords: Kotlin, range SeekBar, Rx

Using 'starts with' selector on individual class names

While the top answer here is a workaround for the asker's particular case, if you're looking for a solution to actually using 'starts with' on individual class names:

You can use this custom jQuery selector, which I call :acp() for "A Class Prefix." Code is at the bottom of this post.

var test = $('div:acp("starting_text")');

This will select any and all <div> elements that have at least one class name beginning with the given string ("starting_text" in this example), regardless of whether that class is at the beginning or elsewhere in the class attribute strings.

<div id="1" class="apple orange lemon" />
<div id="2" class="orange applelemon banana" />
<div id="3" class="orange lemon apple" />
<div id="4" class="lemon orangeapple" />
<div id="5" class="lemon orange" />

var startsWithapp = $('div:acp("app")');

This will return elements 1, 2, and 3, but not 4 or 5.

Here's the declaration for the :acp custom selector, which you can put anywhere:

$(function(){
    $.expr[":"].acp = function(elem, index, m){
          var regString = '\\b' + m[3];
          var reg = new RegExp(regString, "g");
          return elem.className.match(reg);
    }
});

I made this because I do a lot of GreaseMonkey hacking of websites on which I have no backend control, so I often need to find elements with class names that have dynamic suffixes. It's been very useful.

disable all form elements inside div

Only text type

$(".form-edit-account :input[type=text]").attr("disabled", "disabled");

Only Password type

$(".form-edit-account :input[type=password]").attr("disabled", "disabled");

Only Email Type

$(".form-edit-account :input[type=email]").attr("disabled", "disabled");

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

If using cocoapods, try reinstalling the pods by running the following command.

pod install

What Process is using all of my disk IO

atop also works well and installs easily even on older CentOS 5.x systems which can't run iotop. Hit d to show disk details, ? for help.

ATOP - mybox                           2014/09/08  15:26:00                           ------                            10s elapsed
PRC |  sys    0.33s |  user   1.08s |                | #proc    161  |  #zombie    0 |  clones    31 |                | #exit         16  |
CPU |  sys   4% |  user     11% |  irq       0%  | idle    306%  |  wait     79% |               |  steal     1%  | guest     0%  |
cpu |  sys   2% |  user      8% |  irq       0%  | idle     11%  |  cpu000 w 78% |               |  steal     0%  | guest     0%  |
cpu |  sys   1% |  user      1% |  irq       0%  | idle     98%  |  cpu001 w  0% |               |  steal     0%  | guest     0%  |
cpu |  sys   1% |  user      1% |  irq       0%  | idle     99%  |  cpu003 w  0% |               |  steal     0%  | guest     0%  |
cpu |  sys   0% |  user      1% |  irq       0%  | idle     99%  |  cpu002 w  0% |               |  steal     0%  | guest     0%  |
CPL |  avg1    2.09 |  avg5    2.09 |  avg15   2.09  |               |  csw    54184 |  intr   33581 |                | numcpu     4  |
MEM |  tot     8.0G |  free   81.9M |  cache   2.9G  | dirty   0.8M  |  buff  174.7M |  slab  305.0M |                |               |
SWP |  tot     2.0G |  free    2.0G |                |               |               |               |  vmcom   8.4G  | vmlim   6.0G  |
LVM |  Group00-root |  busy     85% |  read       0  | write  30658  |  KiB/w      4 |  MBr/s   0.00 |  MBw/s  11.98  | avio 0.28 ms  |
DSK |          xvdb |  busy     85% |  read       0  | write  23706  |  KiB/w      5 |  MBr/s   0.00 |  MBw/s  11.97  | avio 0.36 ms  |
NET |  transport    |  tcpi    2705 |  tcpo    2008  | udpi      36  |  udpo      43 |  tcpao     14 |  tcppo     45  | tcprs      1  |
NET |  network      |  ipi     2788 |  ipo     2072  | ipfrw      0  |  deliv   2768 |               |  icmpi      7  | icmpo     20  |
NET |  eth0    ---- |  pcki    2344 |  pcko    1623  | si 1455 Kbps  |  so  781 Kbps |  erri       0 |  erro       0  | drpo       0  |
NET |  lo      ---- |  pcki     423 |  pcko     423  | si   88 Kbps  |  so   88 Kbps |  erri           0 |  erro       0  | drpo       0  |
NET |  eth1    ---- |  pcki  22 |  pcko      26  | si    3 Kbps  |  so    5 Kbps |  erri       0 |  erro       0  | drpo       0  |

  PID                   RDDSK                    WRDSK                   WCANCL                    DSK                   CMD        1/1
 9862                      0K                   53124K                       0K                    98%                   java
  358                      0K                     636K                       0K                     1%                   jbd2/dm-0-8
13893                      0K                     192K                      72K                     0%                   java
 1699                      0K                      60K                       0K                     0%                   syslogd
 4668                      0K                      24K                       0K                     0%                   zabbix_agentd

This clearly shows java pid 9862 is the culprit.

How to get the second column from command output?

#!/usr/bin/python
import sys 

col = int(sys.argv[1]) - 1

for line in sys.stdin:
    columns = line.split()

    try:
        print(columns[col])
    except IndexError:
        # ignore
        pass

Then, supposing you name the script as co, say, do something like this to get the sizes of files (the example assumes you're using Linux, but the script itself is OS-independent) :-

ls -lh | co 5

How to convert ISO8859-15 to UTF8?

Could it be that your file is not ISO-8859-15 encoded? You should be able to check with the file command:

file YourFile.txt

Also, you can use iconv without providing the encoding of the original file:

iconv -t UTF-8 YourFile.txt

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

Use the DOM's getElementByid method:

document.getElementById("DATE").value = "your date";

A date can be made with the Date class:

d = new Date();

(Protip: install a javascript console such as in Chrome or Firefox' Firebug extension. It enables you to play with the DOM and Javascript)

How to create a HashMap with two keys (Key-Pair, Value)?

If they are two integers you can try a quick and dirty trick: Map<String, ?> using the key as i+"#"+j.

If the key i+"#"+j is the same as j+"#"+i try min(i,j)+"#"+max(i,j).

What's the difference between deadlock and livelock?

Maybe these two examples illustrate you the difference between a deadlock and a livelock:


Java-Example for a deadlock:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadlockSample {

    private static final Lock lock1 = new ReentrantLock(true);
    private static final Lock lock2 = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread threadA = new Thread(DeadlockSample::doA,"Thread A");
        Thread threadB = new Thread(DeadlockSample::doB,"Thread B");
        threadA.start();
        threadB.start();
    }

    public static void doA() {
        System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
        lock1.lock();
        System.out.println(Thread.currentThread().getName() + " : holds lock 1");

        try {
            System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
            lock2.lock();
            System.out.println(Thread.currentThread().getName() + " : holds lock 2");

            try {
                System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
            } finally {
                lock2.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
            }
        } finally {
            lock1.unlock();
            System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
        }
    }

    public static void doB() {
        System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
        lock2.lock();
        System.out.println(Thread.currentThread().getName() + " : holds lock 2");

        try {
            System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
            lock1.lock();
            System.out.println(Thread.currentThread().getName() + " : holds lock 1");

            try {
                System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
            } finally {
                lock1.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
            }
        } finally {
            lock2.unlock();
            System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
        }
    }
}

Sample output:

Thread A : waits for lock 1
Thread B : waits for lock 2
Thread A : holds lock 1
Thread B : holds lock 2
Thread B : waits for lock 1
Thread A : waits for lock 2

Java-Example for a livelock:


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LivelockSample {

    private static final Lock lock1 = new ReentrantLock(true);
    private static final Lock lock2 = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread threadA = new Thread(LivelockSample::doA, "Thread A");
        Thread threadB = new Thread(LivelockSample::doB, "Thread B");
        threadA.start();
        threadB.start();
    }

    public static void doA() {
        try {
            while (!lock1.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
                Thread.sleep(100);
            }
            System.out.println(Thread.currentThread().getName() + " : holds lock 1");

            try {
                while (!lock2.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
                    Thread.sleep(100);
                }
                System.out.println(Thread.currentThread().getName() + " : holds lock 2");

                try {
                    System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
                } finally {
                    lock2.unlock();
                    System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
                }
            } finally {
                lock1.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
            }
        } catch (InterruptedException e) {
            // can be ignored here for this sample
        }
    }

    public static void doB() {
        try {
            while (!lock2.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
                Thread.sleep(100);
            }
            System.out.println(Thread.currentThread().getName() + " : holds lock 2");

            try {
                while (!lock1.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
                    Thread.sleep(100);
                }
                System.out.println(Thread.currentThread().getName() + " : holds lock 1");

                try {
                    System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
                } finally {
                    lock1.unlock();
                    System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
                }
            } finally {
                lock2.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
            }
        } catch (InterruptedException e) {
            // can be ignored here for this sample
        }
    }
}

Sample output:

Thread B : holds lock 2
Thread A : holds lock 1
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
...

Both examples force the threads to aquire the locks in different orders. While the deadlock waits for the other lock, the livelock does not really wait - it desperately tries to acquire the lock without the chance of getting it. Every try consumes CPU cycles.

What is the total amount of public IPv4 addresses?

Public IP Addresses

https://github.com/stephenlb/geo-ip will generate a list of Valid IP Public Addresses including Localities.

'1.0.0.0/8' to '191.0.0.0/8' are the valid public IP Address range exclusive of the reserved Private IP Addresses as follows:

import iptools
## Private IP Addresses
private_ips = iptools.IpRangeList(
    '0.0.0.0/8',      '10.0.0.0/8',     '100.64.0.0/10', '127.0.0.0/8',
    '169.254.0.0/16', '172.16.0.0/12',  '192.0.0.0/24',  '192.0.2.0/24',
    '192.88.99.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24',
    '203.0.113.0/24', '224.0.0.0/4',    '240.0.0.0/4',   '255.255.255.255/32'
)

IP Generator

Generates a JSON dump of IP Addresses and associated Geo information. Note that the valid public IP Address range is from '1.0.0.0/8' to '191.0.0.0/8' excluding the reserved Private IP Address ranges shown lower down in this readme.

docker build -t geo-ip .
docker run -e IPRANGE='54.0.0.0/30' geo-ip               ## a few IPs
docker run -e IPRANGE='54.0.0.0/26' geo-ip               ## a few more IPs
docker run -e IPRANGE='54.0.0.0/16' geo-ip               ## a lot more IPs
docker run -e IPRANGE='0.0.0.0/0'   geo-ip               ## ALL IPs ( slooooowwwwww )
docker run -e IPRANGE='0.0.0.0/0'   geo-ip > geo-ip.json ## ALL IPs saved to JSON File
docker run geo-ip 

A little faster option for scanning all valid public addresses:

for i in $(seq 1 191); do \
    docker run -e IPRANGE="$i.0.0.0/8" geo-ip; \
    sleep 1; \ 
done

This prints less than 4,228,250,625 JSON lines to STDOUT. Here is an example of one of the lines:

{"city": "Palo Alto", "ip": "0.0.0.0", "longitude": -122.1274,
 "continent": "North America", "continent_code": "NA",
 "state": "California", "country": "United States", "latitude": 37.418,
 "iso_code": "US", "state_code": "CA", "aso": "PubNub",
 "asn": "11404", "zip_code": "94107"}

Private and Reserved IP Range

The dockerfile in the repo above will exclude non-usable IP addresses following the guide from the wikipedia article: https://en.wikipedia.org/wiki/Reserved_IP_addresses

MaxMind Geo IP

The dockerfile imports a free public Database provided by https://www.maxmind.com/en/home

Chrome:The website uses HSTS. Network errors...this page will probably work later

Encountered similar error. resetting chrome://net-internals/#hsts did not work for me. The issue was that my vm's clock was skewed by days. resetting the time did work out to resolve this issue. https://support.google.com/chrome/answer/4454607?hl=en

How do I create a datetime in Python from milliseconds?

import pandas as pd

Date_Time = pd.to_datetime(df.NameOfColumn, unit='ms')

How can I create objects while adding them into a vector?

You cannot insert a class into a vector, you can insert an object (provided that it is of the proper type or convertible) of a class though.

If the type Player has a default constructor, you can create a temporary object by doing Player(), and that should work for your case:

vectorOfGamers.push_back(Player());

How do I use Assert.Throws to assert the type of the exception?

Assert.Throws returns the exception that's thrown which lets you assert on the exception.

var ex = Assert.Throws<Exception>(() => user.MakeUserActive());
Assert.That(ex.Message, Is.EqualTo("Actual exception message"));

So if no exception is thrown, or an exception of the wrong type is thrown, the first Assert.Throws assertion will fail. However if an exception of the correct type is thrown then you can now assert on the actual exception that you've saved in the variable.

By using this pattern you can assert on other things than the exception message, e.g. in the case of ArgumentException and derivatives, you can assert that the parameter name is correct:

var ex = Assert.Throws<ArgumentNullException>(() => foo.Bar(null));
Assert.That(ex.ParamName, Is.EqualTo("bar"));

You can also use the fluent API for doing these asserts:

Assert.That(() => foo.Bar(null), 
Throws.Exception
  .TypeOf<ArgumentNullException>()
  .With.Property("ParamName")
  .EqualTo("bar"));

or alternatively

Assert.That(
    Assert.Throws<ArgumentNullException>(() =>
        foo.Bar(null)
    .ParamName,
Is.EqualTo("bar"));

A little tip when asserting on exception messages is to decorate the test method with the SetCultureAttribute to make sure that the thrown message is using the expected culture. This comes into play if you store your exception messages as resources to allow for localization.

Netbeans - class does not have a main method

This destroyed me for a while.... I knew that there HAD to be an easier way with a world class IDE like Netbeans.

The easiest method is to press Shift+F11 (Clean and Build Project), then hit F6 to run it.

It refreshes Netbeans appropriately and finds your main without all the manual labor; and if you have multiple mains, it will give you the option to select the correct one.

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

Anyone who is looking to do this in Ubuntu/linux using php -

Ubuntu comes with libre office installed default. Anyone can use the shell command to use the headless libre office for this.

shell_exec('/usr/bin/libreoffice --headless --convert-to pdf:writer_pdf_Export --outdir /var/www/html/demo/public_html/src/var/output /var/www/html/demo/public_html/src/var/source/sample.doc');

Hope it helps others like me.

Android: java.lang.SecurityException: Permission Denial: start Intent

You have to add android:exported="true" in the manifest file in the activity you are trying to start.

From the android:exported documentation:

android:exported
Whether or not the activity can be launched by components of other applications — "true" if it can be, and "false" if not. If "false", the activity can be launched only by components of the same application or applications with the same user ID.

The default value depends on whether the activity contains intent filters. The absence of any filters means that the activity can be invoked only by specifying its exact class name. This implies that the activity is intended only for application-internal use (since others would not know the class name). So in this case, the default value is "false". On the other hand, the presence of at least one filter implies that the activity is intended for external use, so the default value is "true".

This attribute is not the only way to limit an activity's exposure to other applications. You can also use a permission to limit the external entities that can invoke the activity (see the permission attribute).

How to draw rounded rectangle in Android UI?

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/white" />
    <corners android:radius="4dp" />
</shape>

How to iterate through a list of objects in C++

-> it works like pointer u don't have to use *

for( list<student>::iterator iter= data.begin(); iter != data.end(); iter++ )
cout<<iter->name; //'iter' not 'it'

error: the details of the application error from being viewed remotely

This can be the message you receive even when custom errors is turned off in web.config file. It can mean you have run out of free space on the drive that hosts the application. Clean your log files if you have no other space to gain on the drive.

Bootstrap: how do I change the width of the container?

You are tying one had behind your back saying that you won't use the LESS files. I built my first Twitter Bootstrap theme using 2.0, and I did everything in CSS -- creating an override.css file. It took days to get things to work correctly.

Now we have 3.0. Let me assure you that it takes less time to learn LESS, which is pretty straight forward if you're comfortable with CSS, than doing all of those crazy CSS overrides. Making changes like the one you want is a piece of cake.

In Bootstrap 3.0, the container class controls the width, and all of the contained styles adjust to fill the container. The container width variables are at the bottom of the variables.less file.

// Container sizes
// --------------------------------------------------

// Small screen / tablet
@container-tablet:            ((720px + @grid-gutter-width));

// Medium screen / desktop
@container-desktop:           ((940px + @grid-gutter-width));

// Large screen / wide desktop
@container-lg-desktop:        ((1020px + @grid-gutter-width));

Some sites either don't have enough content to fill the 1020 display or you want a narrower frame for aesthetic reasons. Because BS uses a 12-column grid I use a multiple like 960.

Deserialize a JSON array in C#

This code is working fine for me,

var a = serializer.Deserialize<List<Entity>>(json);

Minimum and maximum date

To augment T.J.'s answer, exceeding the min/max values generates an Invalid Date.

_x000D_
_x000D_
let maxDate = new Date(8640000000000000);_x000D_
let minDate = new Date(-8640000000000000);_x000D_
_x000D_
console.log(new Date(maxDate.getTime()).toString());_x000D_
console.log(new Date(maxDate.getTime() - 1).toString());_x000D_
console.log(new Date(maxDate.getTime() + 1).toString()); // Invalid Date_x000D_
_x000D_
console.log(new Date(minDate.getTime()).toString());_x000D_
console.log(new Date(minDate.getTime() + 1).toString());_x000D_
console.log(new Date(minDate.getTime() - 1).toString()); // Invalid Date
_x000D_
_x000D_
_x000D_

What does PHP keyword 'var' do?

I quote from http://www.php.net/manual/en/language.oop5.visibility.php

Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.

How to center links in HTML

Try doing a nav element with a ul element. Mine has a main above but I don't think you need it.

<main>
<nav>
<ul><li><a href="http//www.google.com">search</a>
<li><a href="http//www.google.com">search</a>
<li><a href="http//www.google.com">search</a>

The code is something like this.
When ever I put in the code it wouldn't work right so you need to fill in the blank,
then center it.

main
nav
ul> li> a>: href="link of choice":name of link:/a>

How to add dividers and spaces between items in RecyclerView?

RecyclerView doesn't provide straightforward interface for drawing dividers of lists. But actually it provides us a much more flexible way to draw dividers. We use RecyclerView.ItemDecoration to decorate RecyclerView's tiles with dividers or anything you want. That is also why it is called ItemDecoration.

As described in Meterial Design Guidelines:

The divider sits within the baseline of the tile.

So if you want to follow the Material Design Guidelines, you don't need extra space to draw the dividers. Just draw them on the tiles. However, you have the right to do whatever you want to do. So I implemented one which gives you the ability to set insets as well as draw on/underneath the tiles.

public class InsetDivider extends RecyclerView.ItemDecoration {

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    private Paint mPaint;
    // in pixel
    private int mDividerHeight;
    // left inset for vertical list, top inset for horizontal list
    private int mFirstInset;
    // right inset for vertical list, bottom inset for horizontal list
    private int mSecondInset;
    private int mColor;
    private int mOrientation;
    // set it to true to draw divider on the tile, or false to draw beside the tile.
    // if you set it to false and have inset at the same time, you may see the background of
    // the parent of RecyclerView.
    private boolean mOverlay;

    private InsetDivider() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.FILL);
    }

    public int getDividerHeight() {
        return mDividerHeight;
    }

    public void setDividerHeight(int dividerHeight) {
        this.mDividerHeight = dividerHeight;
    }

    public int getFirstInset() {
        return mFirstInset;
    }

    public void setFirstInset(int firstInset) {
        this.mFirstInset = firstInset;
    }

    public int getSecondInset() {
        return mSecondInset;
    }

    public void setSecondInset(int secondInset) {
        this.mSecondInset = secondInset;
    }

    public int getColor() {
        return mColor;
    }

    public void setColor(int color) {
        this.mColor = color;
        mPaint.setColor(color);
    }

    public int getOrientation() {
        return mOrientation;
    }

    public void setOrientation(int orientation) {
        this.mOrientation = orientation;
    }

    public boolean getOverlay() {
        return mOverlay;
    }

    public void setOverlay(boolean overlay) {
        this.mOverlay = overlay;
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }
    }

    protected void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft() + mFirstInset;
        final int right = parent.getWidth() - parent.getPaddingRight() - mSecondInset;
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            if (parent.getChildAdapterPosition(child) == (parent.getAdapter().getItemCount() - 1)) {
                continue;
            }
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int bottom;
            final int top;
            if (mOverlay) {
                bottom = child.getBottom() + params.bottomMargin + Math.round(ViewCompat.getTranslationY(child));
                top = bottom - mDividerHeight;
            } else {
                top = child.getBottom() + params.bottomMargin + Math.round(ViewCompat.getTranslationY(child));
                bottom = top + mDividerHeight;
            }
            c.drawRect(left, top, right, bottom, mPaint);
        }
    }

    protected void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop() + mFirstInset;
        final int bottom = parent.getHeight() - parent.getPaddingBottom() - mSecondInset;
        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            if (parent.getChildAdapterPosition(child) == (parent.getAdapter().getItemCount() - 1)) {
                continue;
            }
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                .getLayoutParams();
            final int right;
            final int left;
            if (mOverlay) {
                right = child.getRight() + params.rightMargin + Math.round(ViewCompat.getTranslationX(child));
                left = right - mDividerHeight;
            } else {
                left = child.getRight() + params.rightMargin + Math.round(ViewCompat.getTranslationX(child));
                right = left + mDividerHeight;
            }
            c.drawRect(left, top, right, bottom, mPaint);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        if (mOverlay) {
            super.getItemOffsets(outRect, view, parent, state);
            return;
        }

        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDividerHeight);
        } else {
            outRect.set(0, 0, mDividerHeight, 0);
        }
    }

    /**
     * Handy builder for creating {@link InsetDivider} instance.
     */
    public static class Builder {

        private Context mContext;
        private int mDividerHeight;
        private int mFirstInset;
        private int mSecondInset;
        private int mColor;
        private int mOrientation;
        private boolean mOverlay = true; // set default to true to follow Material Design Guidelines

        public Builder(Context context) {
            mContext = context;
        }

        public Builder dividerHeight(int dividerHeight) {
            mDividerHeight = dividerHeight;
            return this;
        }

        public Builder insets(int firstInset, int secondInset) {
            mFirstInset = firstInset;
            mSecondInset = secondInset;
            return this;
        }

        public Builder color(@ColorInt int color) {
            mColor = color;
            return this;
        }

        public Builder orientation(int orientation) {
            mOrientation = orientation;
            return this;
        }

        public Builder overlay(boolean overlay) {
            mOverlay = overlay;
            return this;
        }

        public InsetDivider build() {
            InsetDivider insetDivider = new InsetDivider();

            if (mDividerHeight == 0) {
                // Set default divider height to 1dp.
                 insetDivider.setDividerHeight(mContext.getResources().getDimensionPixelSize(R.dimen.divider_height));
            } else if (mDividerHeight > 0) {
                insetDivider.setDividerHeight(mDividerHeight);
            } else {
                throw new IllegalArgumentException("Divider's height can't be negative.");
            }

            insetDivider.setFirstInset(mFirstInset < 0 ? 0 : mFirstInset);
            insetDivider.setSecondInset(mSecondInset < 0 ? 0 : mSecondInset);

            if (mColor == 0) {
                throw new IllegalArgumentException("Don't forget to set color");
            } else {
                insetDivider.setColor(mColor);
            }

            if (mOrientation != InsetDivider.HORIZONTAL_LIST && mOrientation != InsetDivider.VERTICAL_LIST) {
                throw new IllegalArgumentException("Invalid orientation");
            } else {
                insetDivider.setOrientation(mOrientation);
            }

            insetDivider.setOverlay(mOverlay);

            return insetDivider;
        }
    }
}

And you can use it like this:

ItemDecoration divider = new InsetDivider.Builder(this)
                            .orientation(InsetDivider.VERTICAL_LIST) 
                            .dividerHeight(getResources().getDimensionPixelSize(R.dimen.divider_height))
                            .color(getResources().getColor(R.color.colorAccent))
                            .insets(getResources().getDimensionPixelSize(R.dimen.divider_inset), 0)
                            .overlay(true)
                            .build(); 

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(divider);

I also wrote a demo App about how to implement ItemDecoration and how to use them. You can check out my GitHub repo Dividers-For-RecyclerView. There are three implementations in it:

  • UnderneathDivider
  • OverlayDivider
  • InsetDivider

Switch statement for string matching in JavaScript

RegExp can be used on the input string not just technically but practically with the match method too.

Because the output of the match() is an array we need to retrieve the first array element of the result. When the match fails, the function returns null. To avoid an exception error we will add the || conditional operator before accessing the first array element and test against the input property that is a static property of regular expressions that contains the input string.

str = 'XYZ test';
switch (str) {
  case (str.match(/^xyz/) || {}).input:
    console.log("Matched a string that starts with 'xyz'");
    break;
  case (str.match(/test/) || {}).input:
    console.log("Matched the 'test' substring");        
    break;
  default:
    console.log("Didn't match");
    break;
}

Another approach is to use the String() constructor to convert the resulting array that must have only 1 element (no capturing groups) and whole string must be captured with quanitifiers (.*) to a string. In case of a failure the null object will become a "null" string. Not convenient.

str = 'haystack';
switch (str) {
  case String(str.match(/^hay.*/)):
    console.log("Matched a string that starts with 'hay'");
    break;
}

Anyway, a more elegant solution is to use the /^find-this-in/.test(str) with switch (true) method which simply returns a boolean value and it's easier to search without case sensitivity.

Removing u in list

[u'{email:[email protected],gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test1,gem:0}']

'u' denotes unicode characters. We can easily remove this with map function on the final list element

map(str, test)

Another way is when you are appending it to the list

test.append(str(a))

How can I concatenate a string and a number in Python?

Either something like this:

"abc" + str(9)

or

"abs{0}".format(9)

or

"abs%d" % (9,)

How to backup a local Git repository?

Both answers to this questions are correct, but I was still missing a complete, short solution to backup a Github repository into a local file. The gist is available here, feel free to fork or adapt to your needs.

backup.sh:

#!/bin/bash
# Backup the repositories indicated in the command line
# Example:
# bin/backup user1/repo1 user1/repo2
set -e
for i in $@; do
  FILENAME=$(echo $i | sed 's/\//-/g')
  echo "== Backing up $i to $FILENAME.bak"
  git clone [email protected]:$i $FILENAME.git --mirror
  cd "$FILENAME.git"
  git bundle create ../$FILENAME.bak --all
  cd ..
  rm -rf $i.git
  echo "== Repository saved as $FILENAME.bak"
done

restore.sh:

#!/bin/bash
# Restore the repository indicated in the command line
# Example:
# bin/restore filename.bak
set -e

FOLDER_NAME=$(echo $1 | sed 's/.bak//')
git clone --bare $1 $FOLDER_NAME.git

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

In Sql Server Management Studio:

just go to security->schema->dbo.

Double click dbo, then click on permission tab->(blue font)view database permission and feel free to scroll for required fields like "execute".Help yourself to choose usinggrantor deny controls. Hope this will help:)

Android Material and appcompat Manifest merger failed

in my case i am add in manifest file `

tools:replace="android:appComponentFactory"
android:appComponentFactory="whateverString"

application tag of course, It will work

Convert bytes to int?

Assuming you're on at least 3.2, there's a built in for this:

int.from_bytes( bytes, byteorder, *, signed=False )

...

The argument bytes must either be a bytes-like object or an iterable producing bytes.

The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.

The signed argument indicates whether two’s complement is used to represent the integer.


## Examples:
int.from_bytes(b'\x00\x01', "big")                         # 1
int.from_bytes(b'\x00\x01', "little")                      # 256

int.from_bytes(b'\x00\x10', byteorder='little')            # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)  #-1024

How can I update my ADT in Eclipse?

Reason to that is with the new update, they changed the URL for the Android Developer Tools update site to require HTTPS. If you are updating ADT, make sure you use HTTPS in the URL for the Android Developer Tools update site.

Java IOException "Too many open files"

You're obviously not closing your file descriptors before opening new ones. Are you on windows or linux?

Is a slash ("/") equivalent to an encoded slash ("%2F") in the path portion of an HTTP URL

What to do if :foo in its natural form contains slashes? You wouldn't want it to Isn't that the distinction the recommendation is attempting to preserve? It specifically notes,

The similarity to unix and other disk operating system filename conventions should be taken as purely coincidental, and should not be taken to indicate that URIs should be interpreted as file names.

If one was building an online interface to a backup program, and wished to express the path as a part of the URL path, it would make sense to encode the slashes in the file path, as that is not really part of the hierarchy of the resource - and more importantly, the route. /backups/2016-07-28content//home/dan/ loses the root of the filesystem in the double slash. Escaping the slashes is the appropriate way to distinguish, as I read it.

docker mounting volumes on host

Let me add my own answer, because I believe the others are missing the point of Docker.

Using VOLUME in the Dockerfile is the Right Way™, because you let Docker know that a certain directory contains permanent data. Docker will create a volume for that data and never delete it, even if you remove all the containers that use it.

It also bypasses the union file system, so that the volume is in fact an actual directory that gets mounted (read-write or readonly) in the right place in all the containers that share it.

Now, in order to access that data from the host, you only need to inspect your container:

# docker inspect myapp
[{
    .
    .
    .
    "Volumes": {
        "/var/www": "/var/lib/docker/vfs/dir/b3ef4bc28fb39034dd7a3aab00e086e6...",
        "/var/cache/nginx": "/var/lib/docker/vfs/dir/62499e6b31cb3f7f59bf00d8a16b48d2...",
        "/var/log/nginx": "/var/lib/docker/vfs/dir/71896ce364ef919592f4e99c6e22ce87..."
    },
    "VolumesRW": {
        "/var/www": false,
        "/var/cache/nginx": true,
        "/var/log/nginx": true
    }
}]

What I usually do is make symlinks in some standard place such as /srv, so that I can easily access the volumes and manage the data they contain (only for the volumes you care about):

ln -s /var/lib/docker/vfs/dir/b3ef4bc28fb39034dd7a3aab00e086e6... /srv/myapp-www
ln -s /var/lib/docker/vfs/dir/71896ce364ef919592f4e99c6e22ce87... /srv/myapp-log

Java TreeMap Comparator

you can swipe the key and the value. For example

        String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
        int[] v = {341, 273, 278, 329, 445};
        TreeMap<Integer,String>a=new TreeMap();
        for (int i = 0; i < k.length; i++) 
           a.put(v[i],k[i]);            
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
        a.remove(a.firstEntry().getKey());
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());

Open Form2 from Form1, close Form1 from Form2

private void button1_Click(object sender, EventArgs e)
{
      Form2 m = new Form2();
      m.Show();
      this.Visible = false;
}

Add items in array angular 4

Yes there is a way to do it.

First declare a class.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

Then in your component import the class

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html

Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2

How do I store the select column in a variable?

This is how to assign a value to a variable:

SELECT @EmpID = Id
  FROM dbo.Employee

However, the above query is returning more than one value. You'll need to add a WHERE clause in order to return a single Id value.

Open CSV file via VBA (performance)

Workbooks.Open does work too.

Workbooks.Open ActiveWorkbook.Path & "\Temp.csv", Local:=True

this works/is needed because i use Excel in germany and excel does use "," to separate .csv by default because i use an english installation of windows. even if you use the code below excel forces the "," separator.

Workbooks.Open ActiveWorkbook.Path & "\Test.csv", , , 6, , , , , ";"

and Workbooks.Open ActiveWorkbook.Path & "\Temp.csv", , , 4 +variants of this do not work(!)

why do they even have the delimiter parameter if it is blocked by the Local parameter ?! this makes no sense at all. but now it works.

How to position text over an image in css

How about something like this: http://jsfiddle.net/EgLKV/3/

Its done by using position:absolute and z-index to place the text over the image.

_x000D_
_x000D_
#container {_x000D_
  height: 400px;_x000D_
  width: 400px;_x000D_
  position: relative;_x000D_
}_x000D_
#image {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
}_x000D_
#text {_x000D_
  z-index: 100;_x000D_
  position: absolute;_x000D_
  color: white;_x000D_
  font-size: 24px;_x000D_
  font-weight: bold;_x000D_
  left: 150px;_x000D_
  top: 350px;_x000D_
}
_x000D_
<div id="container">_x000D_
  <img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />_x000D_
  <p id="text">_x000D_
    Hello World!_x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I detect if this dictionary key exists in C#?

Here is a little something I cooked up today. Seems to work for me. Basically you override the Add method in your base namespace to do a check and then call the base's Add method in order to actually add it. Hope this works for you

using System;
using System.Collections.Generic;
using System.Collections;

namespace Main
{
    internal partial class Dictionary<TKey, TValue> : System.Collections.Generic.Dictionary<TKey, TValue>
    {
        internal new virtual void Add(TKey key, TValue value)
        {   
            if (!base.ContainsKey(key))
            {
                base.Add(key, value);
            }
        }
    }

    internal partial class List<T> : System.Collections.Generic.List<T>
    {
        internal new virtual void Add(T item)
        {
            if (!base.Contains(item))
            {
                base.Add(item);
            }
        }
    }

    public class Program
    {
        public static void Main()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1,"b");
            dic.Add(1,"a");
            dic.Add(2,"c");
            dic.Add(1, "b");
            dic.Add(1, "a");
            dic.Add(2, "c");

            string val = "";
            dic.TryGetValue(1, out val);

            Console.WriteLine(val);
            Console.WriteLine(dic.Count.ToString());


            List<string> lst = new List<string>();
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");
            lst.Add("b");
            lst.Add("a");
            lst.Add("c");

            Console.WriteLine(lst[2]);
            Console.WriteLine(lst.Count.ToString());
        }
    }
}

Illegal mix of collations MySQL Error

My user account did not have the permissions to alter the database and table, as suggested in this solution.

If, like me, you don't care about the character collation (you are using the '=' operator), you can apply the reverse fix. Run this before your SELECT:

SET collation_connection = 'latin1_swedish_ci';

What's a simple way to get a text input popup dialog box on an iPhone

Just wanted to add an important piece of information that I believe was left out perhaps with the assumption that the ones seeking answers might already know. This problem happens a lot and I too found myself stuck when I tried to implement the viewAlert method for the buttons of the UIAlertView message. To do this you need to 1st add the delegate class which may look something like this:

@interface YourViewController : UIViewController <UIAlertViewDelegate>

Also you can find a very helpful tutorial here!

Hope this helps.

How can I copy a conditional formatting from one document to another?

You can also copy a cell which contains the conditional formatting and then select the range (of destination document -or page-) where you want the conditional format to be applied and select "paste special" > "paste only conditional formatting"

jQuery.active function

For anyone trying to use jQuery.active with JSONP requests (like I was) you'll need enable it with this:

jQuery.ajaxPrefilter(function( options ) {
    options.global = true;
});

Keep in mind that you'll need a timeout on your JSONP request to catch failures.

Change a branch name in a Git repo

If you're currently on the branch you want to rename:

git branch -m new_name 

Or else:

git branch -m old_name new_name 

You can check with:

git branch -a

As you can see, only the local name changed Now, to change the name also in the remote you must do:

git push origin :old_name

This removes the branch, then upload it with the new name:

git push origin new_name

Source: https://web.archive.org/web/20150929104013/http://blog.changecong.com:80/2012/10/rename-a-remote-branch-on-github

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays in JS have two types of properties:

Regular elements and associative properties (which are nothing but objects)

When you define a = new Array(), you are defining an empty array. Note that there are no associative objects yet

When you define b = new Array(2), you are defining an array with two undefined locations.

In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.

console.log (a) or console.log(b) prints the array elements i.e. [] and [undefined, undefined] respectively. But since a1/a2 and b1/b2 are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2) kind of syntax

How can I get argv[] as int?

/*

    Input from command line using atoi, and strtol 
*/

#include <stdio.h>//printf, scanf
#include <stdlib.h>//atoi, strtol 

//strtol - converts a string to a long int 
//atoi - converts string to an int 

int main(int argc, char *argv[]){

    char *p;//used in strtol 
    int i;//used in for loop

    long int longN = strtol( argv[1],&p, 10);
    printf("longN = %ld\n",longN);

    //cast (int) to strtol
    int N = (int) strtol( argv[1],&p, 10);
    printf("N = %d\n",N);

    int atoiN;
    for(i = 0; i < argc; i++)
    {
        //set atoiN equal to the users number in the command line 
        //The C library function int atoi(const char *str) converts the string argument str to an integer (type int).
        atoiN = atoi(argv[i]);
    }

    printf("atoiN = %d\n",atoiN);
    //-----------------------------------------------------//
    //Get string input from command line 
    char * charN;

    for(i = 0; i < argc; i++)
    {
        charN = argv[i];
    }

    printf("charN = %s\n", charN); 

}

Hope this helps. Good luck!

Writing Unicode text to a text file?

How to print unicode characters into a file:

Save this to file: foo.py:

#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import codecs
import sys 
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print(u'e with obfuscation: é')

Run it and pipe output to file:

python foo.py > tmp.txt

Open tmp.txt and look inside, you see this:

el@apollo:~$ cat tmp.txt 
e with obfuscation: é

Thus you have saved unicode e with a obfuscation mark on it to a file.

calculating the difference in months between two dates

There is no built in way to do this accurately in idiomatic-c#. There are some workarounds, such as this CodeProject example that people have coded though.

Image style height and width not taken in outlook mails

make the image the exact size needed in the email. Windows MSO has a hard time resizing images in different scenarios.

in the case of using a 1px by 1px transparent png or gif as a spacer, defining the dimensions via width, height, or style attributes will work as expected in the majority of clients, but not windows MSO (of course).

example use case - you are using a background image and need to position a with a link inside over some part of the background image. Using a 1px by 1px spacer gif/png will only expand so wide (about 30px). You need size the spacer to the exact dimensions.

Is it possible to specify condition in Count()?

Do you mean just this:

SELECT Count(*) FROM YourTable WHERE Position = 'Manager'

If so, then yup that works!

Example for boost shared_mutex (multiple reads/one write)?

It looks like you would do something like this:

boost::shared_mutex _access;
void reader()
{
  // get shared access
  boost::shared_lock<boost::shared_mutex> lock(_access);

  // now we have shared access
}

void writer()
{
  // get upgradable access
  boost::upgrade_lock<boost::shared_mutex> lock(_access);

  // get exclusive access
  boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
  // now we have exclusive access
}

Add button to navigationbar programmatically

How to add an add button to the navbar in swift:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "onAdd:")

onAdd:

func onAdd(sender: AnyObject) {
}

How to start MySQL server on windows xp

You need to run the server first. The command you use (in the question) starts a client to connect to the server but the server is not there so there the error.

Since I am not a Windows user (Linux comes equipped) so I might not be the best person to tell you how but I can point to you to a guide and another guide that show you how to get MySQL server up and running in Windows.

After you get that running, you can use the command (in the question) to connect it.

NOTE: You may also try http://www.apachefriends.org/en/xampp.html if you plan to use MySQL for web database development.

Hope this helps.

No String-argument constructor/factory method to deserialize from String value ('')

Had this when I accidentally was calling

mapper.convertValue(...)

instead of

mapper.readValue(...)

So, just make sure you call correct method, since argument are same and IDE can find many things

How do I concatenate two arrays in C#?

I know the OP was only mildly curious about performance. That larger arrays may get a different result (see @kurdishTree). And that it usually does not matter (@jordan.peoples). None the less, I was curious and therefore lost my mind ( as @TigerShark was explaining).... I mean that I wrote a simple test based on the original question.... and all the answers....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace concat
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] x = new int [] { 1, 2, 3};
            int[] y = new int [] { 4, 5 };


            int itter = 50000;
            Console.WriteLine("test iterations: {0}", itter);

            DateTime startTest = DateTime.Now;
            for(int  i = 0; i < itter; i++)
            {
                int[] z;
                z = x.Concat(y).ToArray();
            }
            Console.WriteLine ("Concat Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks );

            startTest = DateTime.Now;
            for(int  i = 0; i < itter; i++)
            {
                var vz = new int[x.Length + y.Length];
                x.CopyTo(vz, 0);
                y.CopyTo(vz, x.Length);
            }
            Console.WriteLine ("CopyTo Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks );

            startTest = DateTime.Now;
            for(int  i = 0; i < itter; i++)
            {
                List<int> list = new List<int>();
                list.AddRange(x);
                list.AddRange(y);
                int[] z = list.ToArray();
            }
            Console.WriteLine("list.AddRange Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                int[] z = Methods.Concat(x, y);
            }
            Console.WriteLine("Concat(x, y) Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                int[] z = Methods.ConcatArrays(x, y);
            }
            Console.WriteLine("ConcatArrays Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                int[] z = Methods.SSConcat(x, y);
            }
            Console.WriteLine("SSConcat Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int k = 0; k < itter; k++)
            {
                int[] three = new int[x.Length + y.Length];

                int idx = 0;

                for (int i = 0; i < x.Length; i++)
                    three[idx++] = x[i];
                for (int j = 0; j < y.Length; j++)
                    three[idx++] = y[j];
            }
            Console.WriteLine("Roll your own Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);


            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                int[] z = Methods.ConcatArraysLinq(x, y);
            }
            Console.WriteLine("ConcatArraysLinq Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                int[] z = Methods.ConcatArraysLambda(x, y);
            }
            Console.WriteLine("ConcatArraysLambda Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                List<int> targetList = new List<int>(x);
                targetList.Concat(y);
            }
            Console.WriteLine("targetList.Concat(y) Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);

            startTest = DateTime.Now;
            for (int i = 0; i < itter; i++)
            {
                int[] result = x.ToList().Concat(y.ToList()).ToArray();
            }
            Console.WriteLine("x.ToList().Concat(y.ToList()).ToArray() Test Time in ticks: {0}", (DateTime.Now - startTest).Ticks);
        }
    }
    static class Methods
    {
        public static T[] Concat<T>(this T[] x, T[] y)
        {
            if (x == null) throw new ArgumentNullException("x");
            if (y == null) throw new ArgumentNullException("y");
            int oldLen = x.Length;
            Array.Resize<T>(ref x, x.Length + y.Length);
            Array.Copy(y, 0, x, oldLen, y.Length);
            return x;
        }

        public static T[] ConcatArrays<T>(params T[][] list)
        {
            var result = new T[list.Sum(a => a.Length)];
            int offset = 0;
            for (int x = 0; x < list.Length; x++)
            {
                list[x].CopyTo(result, offset);
                offset += list[x].Length;
            }
            return result;
        }


        public static T[] SSConcat<T>(this T[] first, params T[][] arrays)
        {
            int length = first.Length;
            foreach (T[] array in arrays)
            {
                length += array.Length;
            }
            T[] result = new T[length];
            length = first.Length;
            Array.Copy(first, 0, result, 0, first.Length);
            foreach (T[] array in arrays)
            {
                Array.Copy(array, 0, result, length, array.Length);
                length += array.Length;
            }
            return result;
        }

        public static T[] ConcatArraysLinq<T>(params T[][] arrays)
        {
            return (from array in arrays
                    from arr in array
                    select arr).ToArray();
        }

        public static T[] ConcatArraysLambda<T>(params T[][] arrays)
        {
            return arrays.SelectMany(array => array.Select(arr => arr)).ToArray();
        }
    }

}

The result was:

enter image description here

Roll your own wins.

How to check if a windows form is already open, and close it if it is?

In addition, may be this will help


class Helper
    {
        public void disableMultiWindow(Form MdiParent, string formName)
        {
            FormCollection fc = Application.OpenForms;
            try
            {
                foreach (Form form in Application.OpenForms)
                {
                    if (form.Name == formName)
                    {
                        form.BringToFront();
                        return;
                    }
                }

                Assembly thisAssembly = Assembly.GetExecutingAssembly();
                Type typeToCreate = thisAssembly.GetTypes().Where(t => t.Name == formName).First();
                Form myProgram = (Form)Activator.CreateInstance(typeToCreate);
                myProgram.MdiParent = MdiParent;
                myProgram.Show();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }
    }

passing object by reference in C++

One thing that I have to add is that there is no reference in C.

Secondly, this is the language syntax convention. & - is an address operator but it also mean a reference - all depends on usa case

If there was some "reference" keyword instead of & you could write

int CDummy::isitme (reference CDummy param)

but this is C++ and we should accept it advantages and disadvantages...

Limit the size of a file upload (html input element)

_x000D_
_x000D_
const input = document.getElementById('input')_x000D_
_x000D_
input.addEventListener('change', (event) => {_x000D_
  const target = event.target_x000D_
   if (target.files && target.files[0]) {_x000D_
_x000D_
      /*Maximum allowed size in bytes_x000D_
        5MB Example_x000D_
        Change first operand(multiplier) for your needs*/_x000D_
      const maxAllowedSize = 5 * 1024 * 1024;_x000D_
      if (target.files[0].size > maxAllowedSize) {_x000D_
       // Here you can ask your users to load correct file_x000D_
        target.value = ''_x000D_
      }_x000D_
  }_x000D_
})
_x000D_
<input type="file" id="input" />
_x000D_
_x000D_
_x000D_

If you need to validate file type, write in comments below and I'll share my solution.

(Spoiler: accept attribute is not bulletproof solution)

How to set HTML5 required attribute in Javascript?

required is a reflected property (like id, name, type, and such), so:

element.required = true;

...where element is the actual input DOM element, e.g.:

document.getElementById("edName").required = true;

(Just for completeness.)

Re:

Then the attribute's value is not the empty string, nor the canonical name of the attribute:

edName.attributes.required = [object Attr]

That's because required in that code is an attribute object, not a string; attributes is a NamedNodeMap whose values are Attr objects. To get the value of one of them, you'd look at its value property. But for a boolean attribute, the value isn't relevant; the attribute is either present in the map (true) or not present (false).

So if required weren't reflected, you'd set it by adding the attribute:

element.setAttribute("required", "");

...which is the equivalent of element.required = true. You'd clear it by removing it entirely:

element.removeAttribute("required");

...which is the equivalent of element.required = false.

But we don't have to do that with required, since it's reflected.

How to revert the last migration?

I did this in 1.9.1 (to delete the last or latest migration created):

  1. rm <appname>/migrations/<migration #>*

    example: rm myapp/migrations/0011*

  2. logged into database and ran this SQL (postgres in this example)

    delete from django_migrations where name like '0011%';

I was then able to create new migrations that started with the migration number that I had just deleted (in this case, 11).

How to check if my string is equal to null?

Okay this is how datatypes work in Java. (You have to excuse my English, I am prob. not using the right vocab. You have to differentiate between two of them. The base datatypes and the normal datatypes. Base data types pretty much make up everything that exists. For example, there are all numbers, char, boolean etc. The normal data types or complex data types is everything else. A String is an array of chars, therefore a complex data type.

Every variable that you create is actually a pointer on the value in your memory. For example:

String s = new String("This is just a test");

the variable "s" does NOT contain a String. It is a pointer. This pointer points on the variable in your memory. When you call System.out.println(anyObject), the toString() method of that object is called. If it did not override toString from Object, it will print the pointer. For example:

public class Foo{
    public static void main(String[] args) {
        Foo f = new Foo();
        System.out.println(f);
    }
}

>>>>
>>>>
>>>>Foo@330bedb4

Everything behind the "@" is the pointer. This only works for complex data types. Primitive datatypes are DIRECTLY saved in their pointer. So actually there is no pointer and the values are stored directly.

For example:

int i = 123;

i does NOT store a pointer in this case. i will store the integer value 123 (in byte ofc).

Okay so lets come back to the == operator. It always compares the pointer and not the content saved at the pointer's position in the memory.

Example:

String s1 = new String("Hallo");
String s2 = new String("Hallo");

System.out.println(s1 == s2);

>>>>> false

This both String have a different pointer. String.equals(String other) however compares the content. You can compare primitive data types with the '==' operator because the pointer of two different objects with the same content is equal.

Null would mean that the pointer is empty. An empty primitive data type by default is 0 (for numbers). Null for any complex object however means, that object does not exist.

Greetings

Locate Git installation folder on Mac OS X

simply type in which git in your terminal window and it will show you exactly where it was installed.

How to decode a QR-code image in (preferably pure) Python?

There is a library called BoofCV which claims to better than ZBar and other libraries.
Here are the steps to use that (any OS).

Pre-requisites:

  • Ensure JDK 14+ is installed and set in $PATH
  • pip install pyboof

Class to decode:

import os
import numpy as np
import pyboof as pb

pb.init_memmap() #Optional

class QR_Extractor:
    # Src: github.com/lessthanoptimal/PyBoof/blob/master/examples/qrcode_detect.py
    def __init__(self):
        self.detector = pb.FactoryFiducial(np.uint8).qrcode()
    
    def extract(self, img_path):
        if not os.path.isfile(img_path):
            print('File not found:', img_path)
            return None
        image = pb.load_single_band(img_path, np.uint8)
        self.detector.detect(image)
        qr_codes = []
        for qr in self.detector.detections:
            qr_codes.append({
                'text': qr.message,
                'points': qr.bounds.convert_tuple()
            })
        return qr_codes

Usage:

qr_scanner = QR_Extractor()
output = qr_scanner.extract('Your-Image.jpg')
print(output)

Tested and works on Python 3.8 (Windows & Ubuntu)

Android ListView selected item stay highlighted

One way you can do this, is to Keep track of the current selected position in your activity:

@Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3) {
        currentPosition = position
        lv_cli.notifyDataSetChanged();
    }

Now, be sure you assign an ID to the parent layout (linearLayout, boxLayout, relativeLayout, .. Whatever you prefer) of your list item.

Then in your ListView you can do something Like this:

layoutBackground = (LinearLayout) convertView.findViewById(R.id.layout_background);

if (YourActivity.this.currentPosition == position) {
    layoutBackground.setBackgroundColor(YourActivity.this.getResources().getColor(R.color.hilight_color));
} else{
    layoutBackground.setBackgroundResource(R.drawable.list_item_drawable);
}

Basically, you just set the hilight color to the layout as a background when it equals your current selected position. Notice how I set a drawable background resource when the item is not selected. This could be in your case different (since you posted no code). In my case, this drawable is a selector which makes sure the item is hi-lighted when pressed.

NOTE: This simple code doesn't use a view-holder, but I really recommend using one.

Database, Table and Column Naming Conventions?

Take a look at ISO 11179-5: Naming and identification principles You can get it here: http://metadata-standards.org/11179/#11179-5

I blogged about it a while back here: ISO-11179 Naming Conventions

Laravel - Session store not set on request

I was getting this error with Laravel Sanctum. I fixed it by adding \Illuminate\Session\Middleware\StartSession::class, to the api middleware group in Kernel.php, but I later figured out this "worked" because my authentication routes were added in api.php instead of web.php, so Laravel was using the wrong auth guard.

I moved these routes here into web.php and then they started working properly with the AuthenticatesUsers.php trait:

Route::group(['middleware' => ['guest', 'throttle:10,5']], function () {
    Route::post('register', 'Auth\RegisterController@register')->name('register');
    Route::post('login', 'Auth\LoginController@login')->name('login');

    Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
    Route::post('password/reset', 'Auth\ResetPasswordController@reset');

    Route::post('email/verify/{user}', 'Auth\VerificationController@verify')->name('verification.verify');
    Route::post('email/resend', 'Auth\VerificationController@resend');

    Route::post('oauth/{driver}', 'Auth\OAuthController@redirectToProvider')->name('oauth.redirect');
    Route::get('oauth/{driver}/callback', 'Auth\OAuthController@handleProviderCallback')->name('oauth.callback');
});

Route::post('logout', 'Auth\LoginController@logout')->name('logout');

I figured out the problem after I got another weird error about RequestGuard::logout() does not exist.

It made me realize that my custom auth routes are calling methods from the AuthenticatesUsers trait, but I wasn't using Auth::routes() to accomplish it. Then I realized Laravel uses the web guard by default and that means routes should be in routes/web.php.

This is what my settings look like now with Sanctum and a decoupled Vue SPA app:

Kernel.php

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        EnsureFrontendRequestsAreStateful::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'throttle:60,1',
    ],
];

Note: With Laravel Sanctum and same-domain Vue SPA, you use httpOnly cookies for session cookie, and remember me cookie, and unsecure cookie for CSRF, so you use the web guard for auth, and every other protected, JSON-returning route should use auth:sanctum middleware.

config/auth.php

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

...

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],
],

Then you can have unit tests such as this, where critically, Auth::check(), Auth::user(), and Auth::logout() work as expected with minimal config and maximal usage of AuthenticatesUsers and RegistersUsers traits.

Here are a couple of my login unit tests:

TestCase.php

/**
 * Creates and/or returns the designated regular user for unit testing
 *
 * @return \App\User
 */
public function user() : User
{
    $user = User::query()->firstWhere('email', '[email protected]');

    if ($user) {
        return $user;
    }

    // User::generate() is just a wrapper around User::create()
    $user = User::generate('Test User', '[email protected]', self::AUTH_PASSWORD);

    return $user;
}

/**
 * Resets AuthManager state by logging out the user from all auth guards.
 * This is used between unit tests to wipe cached auth state.
 *
 * @param array $guards
 * @return void
 */
protected function resetAuth(array $guards = null) : void
{
    $guards = $guards ?: array_keys(config('auth.guards'));

    foreach ($guards as $guard) {
        $guard = $this->app['auth']->guard($guard);

        if ($guard instanceof SessionGuard) {
            $guard->logout();
        }
    }

    $protectedProperty = new \ReflectionProperty($this->app['auth'], 'guards');
    $protectedProperty->setAccessible(true);
    $protectedProperty->setValue($this->app['auth'], []);
}

LoginTest.php

protected $auth_guard = 'web';

/** @test */
public function it_can_login()
{
    $user = $this->user();

    $this->postJson(route('login'), ['email' => $user->email, 'password' => TestCase::AUTH_PASSWORD])
        ->assertStatus(200)
        ->assertJsonStructure([
            'user' => [
                ...expectedUserFields,
            ],
        ]);

    $this->assertEquals(Auth::check(), true);
    $this->assertEquals(Auth::user()->email, $user->email);
    $this->assertAuthenticated($this->auth_guard);
    $this->assertAuthenticatedAs($user, $this->auth_guard);

    $this->resetAuth();
}

/** @test */
public function it_can_logout()
{
    $this->actingAs($this->user())
        ->postJson(route('logout'))
        ->assertStatus(204);

    $this->assertGuest($this->auth_guard);

    $this->resetAuth();
}

I overrided the registered and authenticated methods in the Laravel auth traits so that they return the user object instead of just the 204 OPTIONS:

public function authenticated(Request $request, User $user)
{
    return response()->json([
        'user' => $user,
    ]);
}

protected function registered(Request $request, User $user)
{
    return response()->json([
        'user' => $user,
    ]);
}

Look at the vendor code for the auth traits. You can use them untouched, plus those two above methods.

  • vendor/laravel/ui/auth-backend/RegistersUsers.php
  • vendor/laravel/ui/auth-backend/AuthenticatesUsers.php

Here is my Vue SPA's Vuex actions for login:

async login({ commit }, credentials) {
    try {
        const { data } = await axios.post(route('login'), {
            ...credentials,
            remember: credentials.remember || undefined,
        });

        commit(FETCH_USER_SUCCESS, { user: data.user });
        commit(LOGIN);

        return commit(CLEAR_INTENDED_URL);
    } catch (err) {
        commit(LOGOUT);
        throw new Error(`auth/login# Problem logging user in: ${err}.`);
    }
},

async logout({ commit }) {
    try {
        await axios.post(route('logout'));

        return commit(LOGOUT);
    } catch (err) {
        commit(LOGOUT);

        throw new Error(`auth/logout# Problem logging user out: ${err}.`);
    }
},

It took me over a week to get Laravel Sanctum + same-domain Vue SPA + auth unit tests all working up to my standard, so hopefully my answer here can help save others time in the future.

Merging two CSV files using Python

When I'm working with csv files, I often use the pandas library. It makes things like this very easy. For example:

import pandas as pd

a = pd.read_csv("filea.csv")
b = pd.read_csv("fileb.csv")
b = b.dropna(axis=1)
merged = a.merge(b, on='title')
merged.to_csv("output.csv", index=False)

Some explanation follows. First, we read in the csv files:

>>> a = pd.read_csv("filea.csv")
>>> b = pd.read_csv("fileb.csv")
>>> a
   title  stage    jan    feb
0   darn  3.001  0.421  0.532
1     ok  2.829  1.036  0.751
2  three  1.115  1.146  2.921
>>> b
   title    mar    apr    may       jun  Unnamed: 5
0   darn  0.631  1.321  0.951    1.7510         NaN
1     ok  1.001  0.247  2.456    0.3216         NaN
2  three  0.285  1.283  0.924  956.0000         NaN

and we see there's an extra column of data (note that the first line of fileb.csv -- title,mar,apr,may,jun, -- has an extra comma at the end). We can get rid of that easily enough:

>>> b = b.dropna(axis=1)
>>> b
   title    mar    apr    may       jun
0   darn  0.631  1.321  0.951    1.7510
1     ok  1.001  0.247  2.456    0.3216
2  three  0.285  1.283  0.924  956.0000

Now we can merge a and b on the title column:

>>> merged = a.merge(b, on='title')
>>> merged
   title  stage    jan    feb    mar    apr    may       jun
0   darn  3.001  0.421  0.532  0.631  1.321  0.951    1.7510
1     ok  2.829  1.036  0.751  1.001  0.247  2.456    0.3216
2  three  1.115  1.146  2.921  0.285  1.283  0.924  956.0000

and finally write this out:

>>> merged.to_csv("output.csv", index=False)

producing:

title,stage,jan,feb,mar,apr,may,jun
darn,3.001,0.421,0.532,0.631,1.321,0.951,1.751
ok,2.829,1.036,0.751,1.001,0.247,2.456,0.3216
three,1.115,1.146,2.921,0.285,1.283,0.924,956.0

How to get all Errors from ASP.Net MVC modelState?

Useful for passing array of error messages to View, perhaps via Json:

messageArray = this.ViewData.ModelState.Values.SelectMany(modelState => modelState.Errors, (modelState, error) => error.ErrorMessage).ToArray();

Internal vs. Private Access Modifiers

Private members are accessible only within the body of the class or the struct in which they are declared.

Internal types or members are accessible only within files in the same assembly

How can I set the Secure flag on an ASP.NET Session Cookie?

Things get messy quickly if you are talking about checked-in code in an enterprise environment. We've found that the best approach is to have the web.Release.config contain the following:

<system.web>
  <compilation xdt:Transform="RemoveAttributes(debug)" />
  <authentication>
      <forms xdt:Transform="Replace" timeout="20" requireSSL="true" />
  </authentication>
</system.web>

That way, developers are not affected (running in Debug), and only servers that get Release builds are requiring cookies to be SSL.

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

A simple solution is to use Microsoft ASP.NET Web API 2.2 Client from NuGet.

Then you can simply do this and it'll serialize the object to JSON and set the Content-Type header to application/json; charset=utf-8:

var data = new
{
    name = "Foo",
    category = "article"
};

var client = new HttpClient();
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Add("token", token);
var response = await client.PostAsJsonAsync("", data);

JAX-WS client : what's the correct path to access the local WSDL?

Thanks a ton for Bhaskar Karambelkar's answer which explains in detail and fixed my issue. But also I would like to re phrase the answer in three simple steps for someone who is in a hurry to fix

  1. Make your wsdl local location reference as wsdlLocation= "http://localhost/wsdl/yourwsdlname.wsdl"
  2. Create a META-INF folder right under the src. Put your wsdl file/s in a folder under META-INF, say META-INF/wsdl
  3. Create an xml file jax-ws-catalog.xml under META-INF as below

    <catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog" prefer="system"> <system systemId="http://localhost/wsdl/yourwsdlname.wsdl" uri="wsdl/yourwsdlname.wsdl" /> </catalog>

Now package your jar. No more reference to the local directory, it's all packaged and referenced within

Decode JSON with unknown structure

The issue I had is that sometimes I will need to get at a value that is deeply nested. Normally you would need to do a type assertion at each level, so I went ahead and just made a method that takes a map[string]interface{} and a string key, and returns the resulting map[string]interface{}.

The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:

package main
type Slice []interface{}
type Map map[string]interface{}

func (m Map) M(s string) Map {
   return m[s].(map[string]interface{})
}

func (m Map) A(s string) Slice {
   return m[s].([]interface{})
}

func (a Slice) M(n int) Map {
   return a[n].(map[string]interface{})
}

and example code:

package main

import (
   "encoding/json"
   "fmt"
   "log"
   "os"
)

func main() {
   o, e := os.Open("a.json")
   if e != nil {
      log.Fatal(e)
   }
   in_m := Map{}
   json.NewDecoder(o).Decode(&in_m)
   out_m := in_m.
      M("contents").
      M("sectionListRenderer").
      A("contents").
      M(0).
      M("musicShelfRenderer").
      A("contents").
      M(0).
      M("musicResponsiveListItemRenderer").
      M("navigationEndpoint").
      M("browseEndpoint")
   fmt.Println(out_m)
}

Shortest distance between a point and a line segment

For anyone interested, here's a trivial conversion of Joshua's Javascript code to Objective-C:

- (double)distanceToPoint:(CGPoint)p fromLineSegmentBetween:(CGPoint)l1 and:(CGPoint)l2
{
    double A = p.x - l1.x;
    double B = p.y - l1.y;
    double C = l2.x - l1.x;
    double D = l2.y - l1.y;

    double dot = A * C + B * D;
    double len_sq = C * C + D * D;
    double param = dot / len_sq;

    double xx, yy;

    if (param < 0 || (l1.x == l2.x && l1.y == l2.y)) {
        xx = l1.x;
        yy = l1.y;
    }
    else if (param > 1) {
        xx = l2.x;
        yy = l2.y;
    }
    else {
        xx = l1.x + param * C;
        yy = l1.y + param * D;
    }

    double dx = p.x - xx;
    double dy = p.y - yy;

    return sqrtf(dx * dx + dy * dy);
}

I needed this solution to work with MKMapPoint so I will share it in case someone else needs it. Just some minor change and this will return the distance in meters :

- (double)distanceToPoint:(MKMapPoint)p fromLineSegmentBetween:(MKMapPoint)l1 and:(MKMapPoint)l2
{
    double A = p.x - l1.x;
    double B = p.y - l1.y;
    double C = l2.x - l1.x;
    double D = l2.y - l1.y;

    double dot = A * C + B * D;
    double len_sq = C * C + D * D;
    double param = dot / len_sq;

    double xx, yy;

    if (param < 0 || (l1.x == l2.x && l1.y == l2.y)) {
        xx = l1.x;
        yy = l1.y;
    }
    else if (param > 1) {
        xx = l2.x;
        yy = l2.y;
    }
    else {
        xx = l1.x + param * C;
        yy = l1.y + param * D;
    }

    return MKMetersBetweenMapPoints(p, MKMapPointMake(xx, yy));
}

removing table border

This will do it with border-collapse

table{
    border-collapse:collapse;
}

How to affect other elements when one element is hovered

Only this worked for me:

#container:hover .cube { background-color: yellow; }

Where .cube is CssClass of the #cube.

Tested in Firefox, Chrome and Edge.

Inline SVG in CSS

A little late, but if any of you have been going crazy trying to use inline SVG as a background, the escaping suggestions above do not quite work. For one, it does not work in IE, and depending on the content of your SVG the technique will cause trouble in other browsers, like FF.

If you base64 encode the svg (not the entire url, just the svg tag and its contents! ) it works in all browsers. Here is the same jsfiddle example in base64: http://jsfiddle.net/vPA9z/3/

The CSS now looks like this:

body { background-image: 
    url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHdpZHRoPScxMCcgaGVpZ2h0PScxMCc+PGxpbmVhckdyYWRpZW50IGlkPSdncmFkaWVudCc+PHN0b3Agb2Zmc2V0PScxMCUnIHN0b3AtY29sb3I9JyNGMDAnLz48c3RvcCBvZmZzZXQ9JzkwJScgc3RvcC1jb2xvcj0nI2ZjYycvPiA8L2xpbmVhckdyYWRpZW50PjxyZWN0IGZpbGw9J3VybCgjZ3JhZGllbnQpJyB4PScwJyB5PScwJyB3aWR0aD0nMTAwJScgaGVpZ2h0PScxMDAlJy8+PC9zdmc+");

Remember to remove any URL escaping before converting to base64. In other words, the above example showed color='#fcc' converted to color='%23fcc', you should go back to #.

The reason why base64 works better is that it eliminates all the issues with single and double quotes and url escaping

If you are using JS, you can use window.btoa() to produce your base64 svg; and if it doesn't work (it might complain about invalid characters in the string), you can simply use https://www.base64encode.org/.

Example to set a div background:

_x000D_
_x000D_
var mySVG = "<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><linearGradient id='gradient'><stop offset='10%' stop-color='#F00'/><stop offset='90%' stop-color='#fcc'/> </linearGradient><rect fill='url(#gradient)' x='0' y='0' width='100%' height='100%'/></svg>";_x000D_
var mySVG64 = window.btoa(mySVG);_x000D_
document.getElementById('myDiv').style.backgroundImage = "url('data:image/svg+xml;base64," + mySVG64 + "')";
_x000D_
html, body, #myDiv {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}
_x000D_
<div id="myDiv"></div>
_x000D_
_x000D_
_x000D_

With JS you can generate SVGs on the fly, even changing its parameters.

One of the better articles on using SVG is here : http://dbushell.com/2013/02/04/a-primer-to-front-end-svg-hacking/

Hope this helps

Mike

Excel formula to search if all cells in a range read "True", if not, then show "False"

=IF(COUNTIF(A1:D1,FALSE)>0,FALSE,TRUE)

(or you can specify any other range to look in)

using mailto to send email with an attachment

If you are using c# on the desktop, you can use SimpleMapi. That way it will be sent using the default mail client, and the user has the option of reviewing the message before sending, just like mailto:.

To use it you add the Simple-MAPI.NET package (it's 13Kb), and run:

var mapi = new SimpleMapi();
mapi.AddRecipient(null, address, false);
mapi.Attach(path);
//mapi.Logon(ParentForm.Handle);    //not really necessary
mapi.Send(subject, body, true);

Difference between $(this) and event.target?

There is a significant different in how jQuery handles the this variable with a "on" method

$("outer DOM element").on('click',"inner DOM element",function(){
  $(this) // refers to the "inner DOM element"
})

If you compare this with :-

$("outer DOM element").click(function(){
  $(this) // refers to the "outer DOM element"
})

What is jQuery Unobtrusive Validation?

For clarification, here is a more detailed example demonstrating Form Validation using jQuery Validation Unobtrusive.

Both use the following JavaScript with jQuery:

  $("#commentForm").validate({
    submitHandler: function(form) {
      // some other code
      // maybe disabling submit button
      // then:
      alert("This is a valid form!");
//      form.submit();
    }
  });

The main differences between the two plugins are the attributes used for each approach.

jQuery Validation

Simply use the following attributes:

  • Set required if required
  • Set type for proper formatting (email, etc.)
  • Set other attributes such as size (min length, etc.)

Here's the form...

<form id="commentForm">
  <label for="form-name">Name (required, at least 2 characters)</label>
  <input id="form-name" type="text" name="form-name" class="form-control" minlength="2" required>
  <input type="submit" value="Submit">
</form>

jQuery Validation Unobtrusive

The following data attributes are needed:

  • data-msg-required="This is required."
  • data-rule-required="true/false"

Here's the form...

<form id="commentForm">
  <label for="form-x-name">Name (required, at least 2 characters)</label>
  <input id="form-x-name" type="text" name="name" minlength="2" class="form-control" data-msg-required="Name is required." data-rule-required="true">
  <input type="submit" value="Submit">
</form>

Based on either of these examples, if the form fields that are required have been filled, and they meet the additional attribute criteria, then a message will pop up notifying that all form fields are validated. Otherwise, there will be text near the offending form fields that indicates the error.

References: - jQuery Validation: https://jqueryvalidation.org/documentation/

Smooth GPS data

Mapped to CoffeeScript if anyones interested. **edit -> sorry using backbone too, but you get the idea.

Modified slightly to accept a beacon with attribs

{latitude: item.lat,longitude: item.lng,date: new Date(item.effective_at),accuracy: item.gps_accuracy}

MIN_ACCURACY = 1

# mapped from http://stackoverflow.com/questions/1134579/smooth-gps-data

class v.Map.BeaconFilter

  constructor: ->
    _.extend(this, Backbone.Events)

  process: (decay,beacon) ->

    accuracy     = Math.max beacon.accuracy, MIN_ACCURACY

    unless @variance?
      # if variance nil, inititalise some values
      @variance     = accuracy * accuracy
      @timestamp_ms = beacon.date.getTime();
      @lat          = beacon.latitude
      @lng          = beacon.longitude

    else

      @timestamp_ms = beacon.date.getTime() - @timestamp_ms

      if @timestamp_ms > 0
        # time has moved on, so the uncertainty in the current position increases
        @variance += @timestamp_ms * decay * decay / 1000;
        @timestamp_ms = beacon.date.getTime();

      # Kalman gain matrix K = Covarariance * Inverse(Covariance + MeasurementVariance)
      # NB: because K is dimensionless, it doesn't matter that variance has different units to lat and lng
      _k  = @variance / (@variance + accuracy * accuracy)
      @lat = _k * (beacon.latitude  - @lat)
      @lng = _k * (beacon.longitude - @lng)

      @variance = (1 - _k) * @variance

    [@lat,@lng]

How to compare files from two different branches?

The best way to do it is by using git diff in the following way: git diff <source_branch> <target_branch> -- file_path

It will check the difference between files in those branches. Take a look at this article for more information about git commands and how they work.

UTF-8 problems while reading CSV file with fgetcsv

Try this:

<?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data); //added
        $num = count ($data);
        for ($c=0; $c < $num; $c++) {
            // output data
            echo "<td>$data[$c]</td>";
        }
        echo "</tr><tr>";
}
?>

Is null check needed before calling instanceof?

Just as a tidbit:

Even (((A)null)instanceof A) will return false.


(If typecasting null seems surprising, sometimes you have to do it, for example in situations like this:

public class Test
{
  public static void test(A a)
  {
    System.out.println("a instanceof A: " + (a instanceof A));
  }

  public static void test(B b) {
    // Overloaded version. Would cause reference ambiguity (compile error)
    // if Test.test(null) was called without casting.
    // So you need to call Test.test((A)null) or Test.test((B)null).
  }
}

So Test.test((A)null) will print a instanceof A: false.)


P.S.: If you are hiring, please don't use this as a job interview question. :D

Is there an equivalent to background-size: cover and contain for image elements?

With CSS you can simulate object-fit: [cover|contain];. It's use transform and [max|min]-[width|height]. It's not perfect. That not work in one case: if the image is wider and shorter than the container.

_x000D_
_x000D_
.img-ctr{_x000D_
  background: red;/*visible only in contain mode*/_x000D_
  border: 1px solid black;_x000D_
  height: 300px;_x000D_
  width: 600px;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  display: block;_x000D_
}_x000D_
.img{_x000D_
  display: block;_x000D_
_x000D_
  /*contain:*/_x000D_
  /*max-height: 100%;_x000D_
  max-width: 100%;*/_x000D_
  /*--*/_x000D_
_x000D_
  /*cover (not work for images wider and shorter than the container):*/_x000D_
  min-height: 100%;_x000D_
  width: 100%;_x000D_
  /*--*/_x000D_
_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
}
_x000D_
<p>Large square:_x000D_
<span class="img-ctr"><img class="img" src="http://placehold.it/1000x1000"></span>_x000D_
</p>_x000D_
<p>Small square:_x000D_
<span class="img-ctr"><img class="img" src="http://placehold.it/100x100"></span>_x000D_
</p>_x000D_
<p>Large landscape:_x000D_
<span class="img-ctr"><img class="img" src="http://placehold.it/2000x1000"></span>_x000D_
</p>_x000D_
<p>Small landscape:_x000D_
<span class="img-ctr"><img class="img" src="http://placehold.it/200x100"></span>_x000D_
</p>_x000D_
<p>Large portrait:_x000D_
<span class="img-ctr"><img class="img" src="http://placehold.it/1000x2000"></span>_x000D_
</p>_x000D_
<p>Small portrait:_x000D_
<span class="img-ctr"><img class="img" src="http://placehold.it/100x200"></span>_x000D_
</p>_x000D_
<p>Ultra thin portrait:_x000D_
<span class="img-ctr"><img class="img" src="http://placehold.it/200x1000"></span>_x000D_
</p>_x000D_
<p>Ultra wide landscape (images wider and shorter than the container):_x000D_
<span class="img-ctr"><img class="img" src="http://placehold.it/1000x200"></span>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Fatal error: Call to undefined function imap_open() in PHP

I had the same issue. After changing a semicolon in the php.ini file I solved my problem. Let's see how can you solve it?

First, open php.ini file. xampp/php/php.ini

Search extension=imap

remove semicolon before extension and save this file.

Code before remove semicolon ;extension=imap

Code after remove semicolon extension=imap

Finally, open the XAMPP Control panel and restart Apache.

Importing Excel into a DataTable Quickly

Caling .Value2 is an expensive operation because it's a COM-interop call. I would instead read the entire range into an array and then loop through the array:

object[,] data = Range.Value2;

// Create new Column in DataTable
for (int cCnt = 1; cCnt <= Range.Columns.Count; cCnt++)
{
    textBox3.Text = cCnt.ToString();

    var Column = new DataColumn();
    Column.DataType = System.Type.GetType("System.String");
    Column.ColumnName = cCnt.ToString();
    DT.Columns.Add(Column);

    // Create row for Data Table
    for (int rCnt = 1; rCnt <= Range.Rows.Count; rCnt++)
    {
        textBox2.Text = rCnt.ToString();

        string CellVal = String.Empty;
        try
        {
            cellVal = (string)(data[rCnt, cCnt]);
        }
        catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
        {
            ConvertVal = (double)(data[rCnt, cCnt]);
            cellVal = ConvertVal.ToString();
        }

        DataRow Row;

        // Add to the DataTable
        if (cCnt == 1)
        {

            Row = DT.NewRow();
            Row[cCnt.ToString()] = cellVal;
            DT.Rows.Add(Row);
        }
        else
        {

            Row = DT.Rows[rCnt + 1];
            Row[cCnt.ToString()] = cellVal;

        }
    }
} 

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

Try this:

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

How to add jQuery to an HTML page?

Include javascript using script tags just before your ending body tag. Preferably you will want to put it in a separate file and link to it to keep things a little more organized and easier to read. Theres a simple article here that will show you how http://www.selftaughtweb.com/how-to-include-javascript/

How to wait for async method to complete?

just put Wait() to wait until task completed

GetInputReportViaInterruptTransfer().Wait();

what is Promotional and Feature graphic in Android Market/Play Store?

In market client on phones at least featured apps with high ratings get to display the promotional graphic.

This is the one that shows up on top even before you start searching the market for a specific app.

See this answer from Android market forum.

Edited: One of the google employee gives some clarifications here

Update: Both links above are now broken but the detailed information can be found here

Selected applications have the ability to be featured atop their respective categories. This is not a guaranteed feature, but uploading promotional graphics is something that we recommend.

Bootstrap 3: How do you align column content to bottom of row

Vertical align bottom and remove the float seems to work. I then had a margin issue, but the -2px keeps them from getting pushed down (and they still don't overlap)

.profile-header > div {
  display: inline-block;
  vertical-align: bottom;
  float: none;
  margin: -2px;
}
.profile-header {
  margin-bottom:20px;
  border:2px solid green;
  display: table-cell;
}
.profile-pic {
  height:300px;
  border:2px solid red;
}
.profile-about {
  border:2px solid blue;
}
.profile-about2 {
  border:2px solid pink;
}

Example here: http://www.bootply.com/125740#

What is the JavaScript version of sleep()?

The problem with most solutions here is that they rewind the stack. This can be a big problem in some cases.In this example I show how to use iterators in different way to simulate real sleep

In this example the generator is calling it's own next() so once it's going, it's on his own.

var h=a();
h.next().value.r=h; //that's how U run it, best I came up with

//sleep without breaking stack !!!
function *a(){
    var obj= {};

    console.log("going to sleep....2s")

    setTimeout(function(){obj.r.next();},2000)  
     yield obj;

    console.log("woke up");
    console.log("going to sleep no 2....2s")
    setTimeout(function(){obj.r.next();},2000)  
     yield obj;

     console.log("woke up");
    console.log("going to sleep no 3....2s")

     setTimeout(function(){obj.r.next();},2000) 
     yield obj;

    console.log("done");

}

Using :: in C++

You're pretty much right about cout and cin. They are objects (not functions) defined inside the std namespace. Here are their declarations as defined by the C++ standard:

Header <iostream> synopsis

#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>

namespace std {
  extern istream cin;
  extern ostream cout;
  extern ostream cerr;
  extern ostream clog;

  extern wistream wcin;
  extern wostream wcout;
  extern wostream wcerr;
  extern wostream wclog;
}

:: is known as the scope resolution operator. The names cout and cin are defined within std, so we have to qualify their names with std::.

Classes behave a little like namespaces in that the names declared inside the class belong to the class. For example:

class foo
{
  public:
    foo();
    void bar();
};

The constructor named foo is a member of the class named foo. They have the same name because its the constructor. The function bar is also a member of foo.

Because they are members of foo, when referring to them from outside the class, we have to qualify their names. After all, they belong to that class. So if you're going to define the constructor and bar outside the class, you need to do it like so:

foo::foo()
{
  // Implement the constructor
}

void foo::bar()
{
  // Implement bar
}

This is because they are being defined outside the class. If you had not put the foo:: qualification on the names, you would be defining some new functions in the global scope, rather than as members of foo. For example, this is entirely different bar:

void bar()
{
  // Implement different bar
}

It's allowed to have the same name as the function in the foo class because it's in a different scope. This bar is in the global scope, whereas the other bar belonged to the foo class.

JavaScript Array splice vs slice

slice does not change original array it return new array but splice changes the original array.

example: var arr = [1,2,3,4,5,6,7,8];
         arr.slice(1,3); // output [2,3] and original array remain same.
         arr.splice(1,3); // output [2,3,4] and original array changed to [1,5,6,7,8].

splice method second argument is different from slice method. second argument in splice represent count of elements to remove and in slice it represent end index.

arr.splice(-3,-1); // output [] second argument value should be greater then 
0.
arr.splice(-3,-1); // output [6,7] index in minus represent start from last.

-1 represent last element so it start from -3 to -1. Above are major difference between splice and slice method.

Set up an HTTP proxy to insert a header

Rather than using a proxy, I'm using the Firefox plugin "Modify Headers" to insert headers (in my case, to fake a login using the Single Sign On so I can test as different people).

Two Radio Buttons ASP.NET C#

Set the GroupName property of both radio buttons to the same value. You could also try using a RadioButtonGroup, which does this for you automatically.

Pass correct "this" context to setTimeout callback?

NOTE: This won't work in IE

var ob = {
    p: "ob.p"
}

var p = "window.p";

setTimeout(function(){
    console.log(this.p); // will print "window.p"
},1000); 

setTimeout(function(){
    console.log(this.p); // will print "ob.p"
}.bind(ob),1000);

to remove first and last element in array

fruits.shift();  // Removes the first element from an array and returns only that element.
fruits.pop();    // Removes the last element from an array and returns only that element. 

See all methods for an Array.

Call fragment from fragment

Just do that: getTabAt(index of your tab)

        ActionBar actionBar = getSupportActionBar();
        actionBar.selectTab(actionBar.getTabAt(0));

Reason: no suitable image found

For me this issue was appearing due to the WWRD cert -- Mine was up to date but for some reason it was set to 'always trust' instead of 'use system default', which apparently makes a difference.

Cross-Domain Cookies

I've created an NPM module, which allows you to share locally-stored data across domains: https://www.npmjs.com/package/cookie-toss

By using an iframe hosted on Domain A, you can store all of your user data on Domain A, and reference that data by posting requests to the Domain A iframe.

Thus, Domains B, C, etc. can inject the iframe and post requests to it to store and access the desired data. Domain A becomes the hub for all shared data.

With a domain whitelist inside of Domain A, you can ensure only your dependent sites can access the data on Domain A.

The trick is to have the code inside of the iframe on Domain A which is able to recognize which data is being requested. The README in the above NPM module goes more in depth into the procedure.

Hope this helps!

Registry key for global proxy settings for Internet Explorer 10 on Windows 8

[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings] "ProxySettingsPerUser"=dword:00000000

Reading file using fscanf() in C

First of all, you're testing fp twice. so printf("Error Reading File\n"); never gets executed.

Then, the output of fscanf should be equal to 2 since you're reading two values.

TCPDF not render all CSS properties

TCPDF 5.9.010 (2010-10-27) - Support for CSS properties 'border-spacing' and 'padding' for tables were added.

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

Answer for BigDecimal throws ArithmeticException

public static void main(String[] args) {
        int age = 30;
        BigDecimal retireMentFund = new BigDecimal("10000.00");
        retireMentFund.setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal yearsInRetirement = new BigDecimal("20.00");
        String name = " Dennis";
        for ( int i = age; i <=65; i++){
            recalculate(retireMentFund,new BigDecimal("0.10"));
        }
        BigDecimal monthlyPension =   retireMentFund.divide(
                yearsInRetirement.divide(new BigDecimal("12"), new MathContext(2, RoundingMode.CEILING)), new MathContext(2, RoundingMode.CEILING));      
        System.out.println(name+ " will have £" + monthlyPension +" per month for retirement");
    }
public static void recalculate (BigDecimal fundAmount, BigDecimal rate){
        fundAmount.multiply(rate.add(new BigDecimal("1.00")));
    }

Add MathContext object in your divide method call and adjust precision and rounding mode. This should fix your problem

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

Output on Windows 10

Fonts: C:\Windows\Fonts
CommonStartMenu: C:\ProgramData\Microsoft\Windows\Start Menu
CommonPrograms: C:\ProgramData\Microsoft\Windows\Start Menu\Programs
CommonStartup: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
CommonDesktopDirectory: C:\Users\Public\Desktop
CommonApplicationData: C:\ProgramData
Windows: C:\Windows
System: C:\Windows\system32
ProgramFiles: C:\Program Files (x86)
SystemX86: C:\Windows\SysWOW64
ProgramFilesX86: C:\Program Files (x86)
CommonProgramFiles: C:\Program Files (x86)\Common Files
CommonProgramFilesX86: C:\Program Files (x86)\Common Files
CommonTemplates: C:\ProgramData\Microsoft\Windows\Templates
CommonDocuments: C:\Users\Public\Documents
CommonAdminTools: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools
CommonMusic: C:\Users\Public\Music
CommonPictures: C:\Users\Public\Pictures
CommonVideos: C:\Users\Public\Videos
Resources: C:\Windows\resources
LocalizedResources:
CommonOemLinks:

Code Snippet if you want to log your own

foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
    string commonAppData = Environment.GetFolderPath(f);
    Console.WriteLine("{0}: {1}", f, commonAppData);
}
Console.ReadLine();

Hunk #1 FAILED at 1. What's that mean?

In some cases, there is no difference in file versions, but only in indentation, spacing, line ending or line numbers.

To patch despite those differences, it's possible to use the following two arguments :

--ignore-whitespace : It ignores whitespace differences (indentation, etc).

--fuzz 3 : the "--fuzz X" option sets the maximum fuzz factor to lines. This option only applies to context and unified diffs; it ignores up to X lines while looking for the place to install a hunk. Note that a larger fuzz factor increases the odds of making a faulty patch. The default fuzz factor is 2; there is no point to setting it to more than the number of lines of context in the diff, ordinarily 3.

Don't forget to user "--dry-run" : It'll try the patch without applying it.

Example :

patch --verbose --dry-run --ignore-whitespace --fuzz 3 < /path/to/patch.patch

More informations about Fuzz :

https://www.gnu.org/software/diffutils/manual/html_node/Inexact.html

How do I call one constructor from another in Java?

Yes, it is possible:

public class Foo {
    private int x;

    public Foo() {
        this(1);
    }

    public Foo(int x) {
        this.x = x;
    }
}

To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.

See also this related question, which is about C# but where the same principles apply.

Ansible: filter a list by its attributes

Not necessarily better, but since it's nice to have options here's how to do it using Jinja statements:

- debug:
    msg: "{% for address in network.addresses.private_man %}\
        {% if address.type == 'fixed' %}\
          {{ address.addr }}\
        {% endif %}\
      {% endfor %}"

Or if you prefer to put it all on one line:

- debug:
    msg: "{% for address in network.addresses.private_man if address.type == 'fixed' %}{{ address.addr }}{% endfor %}"

Which returns:

ok: [localhost] => {
    "msg": "172.16.1.100"
}

What is the current choice for doing RPC in Python?

We are developing Versile Python (VPy), an implementation for python 2.6+ and 3.x of a new ORB/RPC framework. Functional AGPL dev releases for review and testing are available. VPy has native python capabilities similar to PyRo and RPyC via a general native objects layer (code example). The product is designed for platform-independent remote object interaction for implementations of Versile Platform.

Full disclosure: I work for the company developing VPy.

Can you have if-then-else logic in SQL?

Please check whether this helps:

select TOP 1
    product, 
    price 
from 
    table1 
where 
    (project=1 OR Customer=2 OR company=3) AND
    price IS NOT NULL
ORDER BY company 

What is the difference between Left, Right, Outer and Inner Joins?

Making it more visible might help. One example:

Table 1:

ID_STUDENT STUDENT_NAME

1               Raony
2               Diogo
3               Eduardo
4               Luiz

Table 2:

ID_STUDENT LOCKER

3               l1
4               l2
5               l3

What I get when I do:

-Inner join of Table 1 and Table 2: 

    - Inner join returns both tables merged only when the key 
      (ID_STUDENT) exists in both tables

    ID_STUDENT       STUDENT_NAME      LOCKER   

        3               Eduardo          l1
        4               Luiz             l2

-Left join of Table 1 and Table 2:

    - Left join merges both tables with all records form table 1, in 
      other words, there might be non-populated fields from table 2

    ID_ESTUDANTE    NOME_ESTUDANTE     LOCKER   

        1               Raony            -
        2               Diogo            -
        3               Eduardo          l1
        4               Luiz             l2

-Right join of table 1 and table 2:

    - Right join merges both tables with all records from table 2, in 
      other words, there might be non-populated fields from table 1

    ID_STUDENT        STUDENT_NAME     LOCKER   

        3               Eduardo          l1
        4               Luiz             l2
        5               -                l3

-Outter join of table 1 and table 2:

    - Returns all records from both tables, in other words, there
      might be non-populated fields either from table 1 or 2.

    ID_STUDENT        STUDENT_NAME     LOCKER   
        1               Raony            -
        2               Diogo            -
        3               Eduardo          l1
        4               Luiz             l2
        5               -                l3

How to create a static library with g++?

You can create a .a file using the ar utility, like so:

ar crf lib/libHeader.a header.o

lib is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a in the directory lib. So, in your current directory, do:

mkdir lib

Then run the above ar command.

When linking all libraries, you can do it like so:

g++ test.o -L./lib -lHeader -o test  

The -L flag will get g++ to add the lib/ directory to the path. This way, g++ knows what directory to search when looking for libHeader. -llibHeader flags the specific library to link.

where test.o is created like so:

g++ -c test.cpp -o test.o 

How to run mysql command on bash?

I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.

#!/bin/bash
    PROPERTY_FILE=filename.properties

    function getProperty {
       PROP_KEY=$1
       PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
       echo $PROP_VALUE
    }

    echo "# Reading property from $PROPERTY_FILE"
    DB_USER=$(getProperty "db.username")
    DB_PASS=$(getProperty "db.password")
    ROOT_LOC=$(getProperty "root.location")
    echo $DB_USER
    echo $DB_PASS
    echo $ROOT_LOC
    echo "Writing on DB ... "
    mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL

    update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
    EOFMYSQL
    echo "Writing root location($ROOT_LOC) is done ... "
    counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;

    if [ "$counter" = "1" ]
    then
    echo "ROOT location updated"
    fi

What's the key difference between HTML 4 and HTML 5?

You might be interested in this list of HTML5 elements and attributes.

Also, please note that it's "HTML 4", not "HTML4". Indeed, for HTML 5, both variants are used, but there is an important difference in meaning. HTML 5 refers to the name of the W3C specification, whereas "HTML5" is the document type of those HTML files with a text/html MIME type that follow this spec. The same goes for XHTML 5 vs. XHTML5.

Plotting a list of (x, y) coordinates in python matplotlib

If you have a numpy array you can do this:

import numpy as np
from matplotlib import pyplot as plt

data = np.array([
    [1, 2],
    [2, 3],
    [3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()

Get 2 Digit Number For The Month

SELECT REPLACE(CONVERT(varchar, MONTH(GetDate()) * 0.01), '0.', '')

How to replace negative numbers in Pandas Data Frame by zero

With lambda function

df['column'] = df['column'].apply(lambda x : x if x > 0 else 0)

Keyboard shortcut to change font size in Eclipse?

Oddly, working on a .js file and Ctrl, Shift, += works to zoom in (and Ctrl - works to zoom out but you have to select 1 or 2 after Ctrl -). This only works when I'm in the js file but the zoom applies to all my open tabs. Using Eclipse Juno on Ubuntu.

python - find index position in list based of partial string

Your idea to use enumerate() was correct.

indices = []
for i, elem in enumerate(mylist):
    if 'aa' in elem:
        indices.append(i)

Alternatively, as a list comprehension:

indices = [i for i, elem in enumerate(mylist) if 'aa' in elem]

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

One more method is to Define the Layout inside the View:

   @{
    Layout = "~/Views/Shared/_MyAdminLayout.cshtml";
    }

More Ways to do, can be found here, hope this helps someone.

Detach (move) subdirectory into separate Git repository

The original question wants XYZ/ABC/(*files) to become ABC/ABC/(*files). After implementing the accepted answer for my own code, I noticed that it actually changes XYZ/ABC/(*files) into ABC/(*files). The filter-branch man page even says,

The result will contain that directory (and only that) as its project root."

In other words, it promotes the top-level folder "up" one level. That's an important distinction because, for example, in my history I had renamed a top-level folder. By promoting folders "up" one level, git loses continuity at the commit where I did the rename.

I lost contiuity after filter-branch

My answer to the question then is to make 2 copies of the repository and manually delete the folder(s) you want to keep in each. The man page backs me up with this:

[...] avoid using [this command] if a simple single commit would suffice to fix your problem

Automatically create requirements.txt

I blindly followed the accepted answer of using pip3 freeze > requirements.txt

It generated a huge file that listed all the dependencies of the entire solution, which is not what I wanted.

So you need to figure out what sort of requirements.txt you are trying to generate.

If you need a requirements.txt file that has ALL the dependencies, then use the pip3

pip3 freeze > requirements.txt

However, if you want to generate a minimal requirements.txt that only lists the dependencies you need, then use the pipreqs package. Especially helpful if you have numerous requirements.txt files in per component level in the project and not a single file on the solution wide level.

pip install pipreqs
pipreqs [path to folder]
e.g. pipreqs .

How do you overcome the svn 'out of date' error?

Are you moving it using svn mv, or just mv? I think using just mv may cause this issue.

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

Try to disable SELinux by this command /usr/sbin/setenforce 0. In my case it solved the problem.

PHP, get file name without file extension

Another approach is by using regular expressions.

$fileName = basename($filePath);
$fileNameNoExtension = preg_replace("/\.[^.]+$/", "", $fileName);

This removes from the last period . up until the end of the string.

Python convert object to float

I eventually used:

weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)

It worked just fine, except that I got the following message.

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.

How to add image for button in android?

The new MaterialButton from the Material Components can include an icon:

<com.google.android.material.button.MaterialButton
    android:id="@+id/material_icon_button"
    style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/icon_button_label_enabled"
    app:icon="@drawable/icon_24px"/>

You can also customize some icon properties like iconSize and iconGravity.

Reference here.

jQuery - getting custom attribute from selected option

Here is the entire script with an AJAX call to target a single list within a page with multiple lists. None of the other stuff above worked for me until I used the "id" attribute even though my attribute name is "ItemKey". By using the debugger

Chrome Debug

I was able to see that the selected option had attributes: with a map to the JQuery "id" and the value.

<html>
<head>
<script type="text/JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<select id="List1"></select>
<select id="List2">
<option id="40000">List item #1</option>
<option id="27888">List item #2</option>
</select>

<div></div>
</body>
<script type="text/JavaScript">
//get a reference to the select element
$select = $('#List1');

//request the JSON data and parse into the select element
$.ajax({
url: 'list.json',
dataType:'JSON',
success:function(data){

//clear the current content of the select
$select.html('');

//iterate over the data and append a select option
$.each(data.List, function(key, val){
$select.append('<option id="' + val.ItemKey + '">' + val.ItemText + '</option>');
})
},

error:function(){

//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});

$( "#List1" ).change(function () {
var optionSelected = $('#List1 option:selected').attr('id');
$( "div" ).text( optionSelected );
});
</script>
</html>

Here is the JSON File to create...

{  
"List":[  
{  
"Sort":1,
"parentID":0,
"ItemKey":100,
"ItemText":"ListItem-#1"
},
{  
"Sort":2,
"parentID":0,
"ItemKey":200,
"ItemText":"ListItem-#2"
},
{  
"Sort":3,
"parentID":0,
"ItemKey":300,
"ItemText":"ListItem-#3"
},
{  
"Sort":4,
"parentID":0,
"ItemKey":400,
"ItemText":"ListItem-#4"
}
]
}

Hope this helps, thank you all above for getting me this far.

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation.

Then try the following:

@RequestMapping(value = "/{email}/authenticate", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, 
        produces = {MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody  Representation authenticate(@PathVariable("email") String anEmailAddress, MultiValueMap paramMap) throws Exception {
   if(paramMap == null && paramMap.get("password") == null) {
        throw new IllegalArgumentException("Password not provided");
    }
    return null;
}

Note that removed the annotation @RequestBody

answer: Http Post request with content type application/x-www-form-urlencoded not working in Spring

How can I make Jenkins CI with Git trigger on pushes to master?

As already noted by gezzed in his comment, meanwhile there is a good solution (described in Polling must die: triggering Jenkins builds from a Git hook):

  • Set the Jenkins job's build trigger to Poll SCM, but do not specify a schedule.

  • Create a GitHub post-receive trigger to notify the URL

    http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>?token=<get token from git to build remotely>
    
  • This will trigger all builds that poll the specified Git repository.

  • However, polling actually checks whether anything has been pushed to the used branch.

It works perfectly.

How to get a json string from url?

AFAIK JSON.Net does not provide functionality for reading from a URL. So you need to do this in two steps:

using (var webClient = new System.Net.WebClient()) {
    var json = webClient.DownloadString(URL);
    // Now parse with JSON.Net
}

How to insert data into elasticsearch

To test and try curl requests from Windows, you can make use of Postman client Chrome extension. It is very simple to use and quite powerful.

Or as suggested you can install the cURL util.

A sample curl request is as follows.

curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
"user" : "Arun Thundyill Saseendran",
"post_date" : "2009-03-23T12:30:00",
"message" : "trying out Elasticsearch"
}' "http://10.103.102.56:9200/sampleindex/sampletype/"

I am also getting started with and exploring ES in vast. So please let me know if you have any other doubts.

EDIT: Updated the index name and type name to be fully lowercase to avoid errors and follow convention.

Display html text in uitextview

Use a UIWebView on iOS 5-.

On iOS 6+ you can use UITextView.attributedString, see https://stackoverflow.com/a/20996085 for how.


There's also an undocumented -[UITextView setContentToHTMLString:] method. Do not use this if you want to submit to AppStore.

A terminal command for a rooted Android to remount /System as read/write

Try

mount -o remount,rw /system

If no error message is printed, it works.

Or, you should do the following.

First, make sure the fs type.

mount

Issue this command to find it out.

Then

mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system

Note that the fs(yaffs2) and device(/dev/block/mtdblock3) are depend on your system.

Malformed String ValueError ast.literal_eval() with String representation of Tuple

From the documentation for ast.literal_eval():

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Decimal isn't on the list of things allowed by ast.literal_eval().

How to track down access violation "at address 00000000"

Here is a real quick temporary fix, at least until you reboot again but it will get rid of a persistent access. I had installed a program that works fine but for some reason, there is a point that did not install correctly in the right file. So when it cannot access the file, it pops up the access denied but instead of just one, it keeps trying to start it up so even searching for the location to stop it permanently, it will continue to pop up more and more and more every 3 seconds. To stop that from happening at least temporarily, do the following...

  1. Ctl+Alt+Del
  2. Open your Task Manager
  3. Note down the name of the program that's requesting access (you may see it in your application's tab)
  4. Click on your Processes tab
  5. Scroll through until you find the Process matching the program name and click on it
  6. Click End Process

That will prevent the window from persistently popping up, at least until you reboot. I know that does not solve the problem but like anything, there is a process of elimination and this step here will at least make it a little less annoying.

curl Failed to connect to localhost port 80

In my case, the file ~/.curlrc had a wrong proxy configured.

How do I escape a string inside JavaScript code inside an onClick handler?

Declare separate functions in the <head> section and invoke those in your onClick method. If you have lots you could use a naming scheme that numbers them, or pass an integer in in your onClicks and have a big fat switch statement in the function.

Check if a Python list item contains a string inside another string

for item in my_list:
    if item.find("abc") != -1:
        print item

Perform debounce in React.js

You can use Lodash debounce https://lodash.com/docs/4.17.5#debounce method. It is simple and effective.

import * as lodash from lodash;

const update = (input) => {
    // Update the input here.
    console.log(`Input ${input}`);     
}

const debounceHandleUpdate = lodash.debounce((input) => update(input), 200, {maxWait: 200});

doHandleChange() {
   debounceHandleUpdate(input);
}

You can also cancel the debounce method by using the below method.

this.debounceHandleUpdate.cancel();

Hope it helps you. Cheers!!

Find size of an array in Perl

All three give the same result if we modify the second one a bit:

my @arr = (2, 4, 8, 10);

print "First result:\n";
print scalar @arr; 

print "\n\nSecond result:\n";
print $#arr + 1; # Shift numeration with +1 as it shows last index that starts with 0.

print "\n\nThird result:\n";
my $arrSize = @arr;
print $arrSize;

GCC: array type has incomplete element type

It's the array that's causing trouble in:

void print_graph(g_node graph_node[], double weight[][], int nodes);

The second and subsequent dimensions must be given:

void print_graph(g_node graph_node[], double weight[][32], int nodes);

Or you can just give a pointer to pointer:

void print_graph(g_node graph_node[], double **weight, int nodes);

However, although they look similar, those are very different internally.

If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):

void fvla(int m, int C[m][m]); // valid: VLA with prototype scope

void fvla(int m, int C[m][m])  // valid: adjusted to auto pointer to VLA
{
    typedef int VLA[m][m];     // valid: block scope typedef VLA
    struct tag {
        int (*y)[n];           // invalid: y not ordinary identifier
        int z[n];              // invalid: z not ordinary identifier
    };
    int D[m];                  // valid: auto VLA
    static int E[m];           // invalid: static block scope VLA
    extern int F[m];           // invalid: F has linkage and is VLA
    int (*s)[m];               // valid: auto pointer to VLA
    extern int (*r)[m];        // invalid: r has linkage and points to VLA
    static int (*q)[m] = &B;   // valid: q is a static block pointer to VLA
}

Question in comments

[...] In my main(), the variable I am trying to pass into the function is a double array[][], so how would I pass that into the function? Passing array[0][0] into it gives me incompatible argument type, as does &array and &array[0][0].

In your main(), the variable should be:

double array[10][20];

or something faintly similar; maybe

double array[][20] = { { 1.0, 0.0, ... }, ... };

You should be able to pass that with code like this:

typedef struct graph_node
{
    int X;
    int Y;
    int active;
} g_node;

void print_graph(g_node graph_node[], double weight[][20], int nodes);

int main(void)
{
    g_node g[10];
    double array[10][20];
    int n = 10;

    print_graph(g, array, n);
    return 0;
}

That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:

/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c

json_encode(): Invalid UTF-8 sequence in argument

The problem is that this character is UTF8, but json_encode does not handle it correctly. To say more, there is a list of other characters (see Unicode characters list), that will trigger the same error, so stripping off this one (Å) will not correct an issue to the end.

What we have used is to convert these chars to html entities like this:

htmlentities( (string) $value, ENT_QUOTES, 'utf-8', FALSE);

Best way to compare two complex objects

You can use extension method, recursion to resolve this problem:

public static bool DeepCompare(this object obj, object another)
{     
  if (ReferenceEquals(obj, another)) return true;
  if ((obj == null) || (another == null)) return false;
  //Compare two object's class, return false if they are difference
  if (obj.GetType() != another.GetType()) return false;

  var result = true;
  //Get all properties of obj
  //And compare each other
  foreach (var property in obj.GetType().GetProperties())
  {
      var objValue = property.GetValue(obj);
      var anotherValue = property.GetValue(another);
      if (!objValue.Equals(anotherValue)) result = false;
  }

  return result;
 }

public static bool CompareEx(this object obj, object another)
{
 if (ReferenceEquals(obj, another)) return true;
 if ((obj == null) || (another == null)) return false;
 if (obj.GetType() != another.GetType()) return false;

 //properties: int, double, DateTime, etc, not class
 if (!obj.GetType().IsClass) return obj.Equals(another);

 var result = true;
 foreach (var property in obj.GetType().GetProperties())
 {
    var objValue = property.GetValue(obj);
    var anotherValue = property.GetValue(another);
    //Recursion
    if (!objValue.DeepCompare(anotherValue))   result = false;
 }
 return result;
}

or compare by using Json (if object is very complex) You can use Newtonsoft.Json:

public static bool JsonCompare(this object obj, object another)
{
  if (ReferenceEquals(obj, another)) return true;
  if ((obj == null) || (another == null)) return false;
  if (obj.GetType() != another.GetType()) return false;

  var objJson = JsonConvert.SerializeObject(obj);
  var anotherJson = JsonConvert.SerializeObject(another);

  return objJson == anotherJson;
}

Core Data: Quickest way to delete all instances of an entity

In Swift 3.0

 func deleteAllRecords() {
        //delete all data
        let context = appDelegate.persistentContainer.viewContext

        let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "YourClassName")
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)

        do {
            try context.execute(deleteRequest)
            try context.save()
        } catch {
            print ("There was an error")
        }
    }

what happens when you type in a URL in browser

Look up the specification of HTTP. Or to get started, try http://www.jmarshall.com/easy/http/

How to view/delete local storage in Firefox?

Try this, it works for me:

var storage = null;
setLocalStorage();

function setLocalStorage() {
    storage = (localStorage ? localStorage : (window.content.localStorage ? window.content.localStorage : null));

    try {
        storage.setItem('test_key', 'test_value');//verify if posible saving in the current storage
    }
    catch (e) {
        if (e.name == "NS_ERROR_FILE_CORRUPTED") {
            storage = sessionStorage ? sessionStorage : null;//set the new storage if fails
        }
    }
}

How to start MySQL with --skip-grant-tables?

Edit my.ini file and add skip-grant-tables and restart your mysql server :

[mysqld]
port= 3306
socket = "C:/xampp/mysql/mysql.sock"
basedir = "C:/xampp/mysql" 
tmpdir = "C:/xampp/tmp" 
datadir = "C:/xampp/mysql/data"
pid_file = "mysql.pid"
# enable-named-pipe
key_buffer = 16M
max_allowed_packet = 1M
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
log_error = "mysql_error.log"
skip-grant-tables
# Change here for bind listening
# bind-address="127.0.0.1" 
# bind-address = ::1 

JQuery .each() backwards

I think u need

.parentsUntill()

SOAP request in PHP with CURL

Tested and working!

  • with https, user & password

     <?php 
     //Data, connection, auth
     $dataFromTheForm = $_POST['fieldName']; // request data from the form
     $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
     $soapUser = "username";  //  username
     $soapPassword = "password"; // password
    
     // xml post structure
    
     $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                         <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                           <soap:Body>
                             <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
                               <PRICE>'.$dataFromTheForm.'</PRICE> 
                             </GetItemPrice >
                           </soap:Body>
                         </soap:Envelope>';   // data from the form, e.g. some ID number
    
        $headers = array(
                     "Content-type: text/xml;charset=\"utf-8\"",
                     "Accept: text/xml",
                     "Cache-Control: no-cache",
                     "Pragma: no-cache",
                     "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", 
                     "Content-length: ".strlen($xml_post_string),
                 ); //SOAPAction: your op URL
    
         $url = $soapUrl;
    
         // PHP cURL  for https connection with auth
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
         // converting
         $response = curl_exec($ch); 
         curl_close($ch);
    
         // converting
         $response1 = str_replace("<soap:Body>","",$response);
         $response2 = str_replace("</soap:Body>","",$response1);
    
         // convertingc to XML
         $parser = simplexml_load_string($response2);
         // user $parser to get your data out of XML response and to display it. 
     ?>
    

npx command not found

if you are using Linux system, use sudo command

sudo npm i -g npx

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

Using a different font with twitter bootstrap

The easiest way I've seen is to use Google Fonts.

Go to Google Fonts and choose a font, then Google will give you a link to put in your HTML.

Google's link to your font

Then add this to your custom.css:

h1, h2, h3, h4, h5, h6 {
    font-family: 'Your Font' !important;
}
p, div {
    font-family: 'Your Font' !important;
}

or

body {
   font-family: 'Your Font' !important;
}

How to get all options of a select using jQuery?

Use:

$("#id option").each(function()
{
    // Add $(this).val() to your list
});

.each() | jQuery API Documentation

How do I get a value of a <span> using jQuery?

I think this should be a simple example:

$('#item1 span').text();

or

$('#item1 span').html();

Running javascript in Selenium using Python

Try browser.execute_script instead of selenium.GetEval.

See this answer for example.

Option to ignore case with .contains method?

I know I'm a little late to the party but in Kotlin you can easily use:

fun Collection<String>.containsIgnoreCase(item: String) = any {
    it.equals(item, ignoreCase = true)
}


val list = listOf("Banana")

println(list.contains("banana"))
println(list.containsIgnoreCase("BaNaNa"))

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

The most simple way is to use Record type Record<number, productDetails >

interface productDetails {
   productId : number , 
   price : number , 
   discount : number
};

const myVar : Record<number, productDetails> = {
   1: {
       productId : number , 
       price : number , 
       discount : number
   }
}

Regex Match all characters between two strings

Here is how I did it:
This was easier for me than trying to figure out the specific regex necessary.

int indexPictureData = result.IndexOf("-PictureData:");
int indexIdentity = result.IndexOf("-Identity:");
string returnValue = result.Remove(indexPictureData + 13);
returnValue = returnValue + " [bytecoderemoved] " + result.Remove(0, indexIdentity); `