Programs & Examples On #Windows mobile

Windows Mobile is a mobile operating system developed by Microsoft that was used in smartphones and mobile devices, but is being currently phased out to specialized markets. It is superseded by Windows Phone (starting with Windows Phone 7 in 2010).

How to connect a Windows Mobile PDA to Windows 10

Unfortunately the Windows Mobile Device Center stopped working out of the box after the Creators Update for Windows 10. The application won't open and therefore it's impossible to get the sync working. In order to get it running now we need to modify the ActiveSync registry settings. Create a BAT file with the following contents and run it as administrator:

REG ADD HKLM\SYSTEM\CurrentControlSet\Services\RapiMgr /v SvcHostSplitDisable /t REG_DWORD /d 1 /f
REG ADD HKLM\SYSTEM\CurrentControlSet\Services\WcesComm /v SvcHostSplitDisable /t REG_DWORD /d 1 /f

Restart the computer and everything should work.

Auto detect mobile browser (via user-agent?)

I put this demo with scripts and examples included together:

http://www.mlynn.org/2010/06/mobile-device-detection-and-redirection-with-php/

This example utilizes php functions for user agent detection and offers the additional benefit of permitting users to state a preference for a version of the site which would not typically be the default based on their browser or device type. This is done with cookies (maintained using php on the server-side as opposed to javascript.)

Be sure to check out the download link in the article for the examples.

Hope you enjoy!

How to insert   in XSLT

&#160; works really well. However, it will display one of those strange characters in ANSI encoding. <xsl:text> worked best for me.

<xsl:text> </xsl:text>

Javascript to set hidden form value on drop down change

$(function() {
$('#myselect').change(function() {
   $('#myhidden').val =$("#myselect option:selected").text();
    });
});

how to use Blob datatype in Postgres

I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB

Read the part with the title 'What is the best way to store the files in the Database?'

How to add certificate chain to keystore?

I solved the problem by cat'ing all the pems together:

cat cert.pem chain.pem fullchain.pem >all.pem
openssl pkcs12 -export -in all.pem -inkey privkey.pem -out cert_and_key.p12 -name tomcat -CAfile chain.pem -caname root -password MYPASSWORD
keytool -importkeystore -deststorepass MYPASSWORD -destkeypass MYPASSWORD -destkeystore MyDSKeyStore.jks -srckeystore cert_and_key.p12 -srcstoretype PKCS12 -srcstorepass MYPASSWORD -alias tomcat
keytool -import -trustcacerts -alias root -file chain.pem -keystore MyDSKeyStore.jks -storepass MYPASSWORD

(keytool didn't know what to do with a PKCS7 formatted key)

I got all the pems from letsencrypt

Python Selenium Chrome Webdriver

You need to specify the path where your chromedriver is located.

  1. Download chromedriver for your desired platform from here.

  2. Place chromedriver on your system path, or where your code is.

  3. If not using a system path, link your chromedriver.exe (For non-Windows users, it's just called chromedriver):

    browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
    

    (Set executable_path to the location where your chromedriver is located.)

    If you've placed chromedriver on your System Path, you can shortcut by just doing the following:

    browser = webdriver.Chrome()

  4. If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:

    chmod +x chromedriver

  5. That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

How to fix request failed on channel 0

I solved a similar problem with one of our users who was used only for ssh port forwarding so he don't need to have access to PTY and it was prohibited in .ssh/authorized_keys file:

no-pty ssh-rsa AAA...nUB9 someuser

So when you tried to log in to this user, only message

PTY allocation request failed on channel 0

was returned. So check your user's authorized_keys file.

How to add a new object (key-value pair) to an array in javascript?

.push() will add elements to the end of an array.

Use .unshift() if need to add some element to the beginning of array i.e:

items.unshift({'id':5});

Demo:

_x000D_
_x000D_
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.unshift({'id': 0});_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

And use .splice() in case you want to add object at a particular index i.e:

items.splice(2, 0, {'id':5});
           // ^ Given object will be placed at index 2...

Demo:

_x000D_
_x000D_
items = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];_x000D_
items.splice(2, 0, {'id': 2.5});_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

If you are just going to substitute it into a URL I suppose one field would do - so you can form a URL like

http://maps.google.co.uk/maps?q=12.345678,12.345678&z=6

but as it is two pieces of data I would store them in separate fields

Java, List only subdirectories from a directory, not files

In case you're interested in a solution using Java 7 and NIO.2, it could go like this:

private static class DirectoriesFilter implements Filter<Path> {
    @Override
    public boolean accept(Path entry) throws IOException {
        return Files.isDirectory(entry);
    }
}

try (DirectoryStream<Path> ds = Files.newDirectoryStream(FileSystems.getDefault().getPath(root), new DirectoriesFilter())) {
        for (Path p : ds) {
            System.out.println(p.getFileName());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

How can I use delay() with show() and hide() in Jquery

Why don't you try the fadeIn() instead of using a show() with delay(). I think what you are trying to do can be done with this. Here is the jQuery code for fadeIn and FadeOut() which also has inbuilt method for delaying the process.

$(document).ready(function(){
   $('element').click(function(){
      //effects take place in 3000ms
      $('element_to_hide').fadeOut(3000);
      $('element_to_show').fadeIn(3000);
   });
}

Is it possible to append to innerHTML without destroying descendants' event listeners?

I'm a lazy programmer. I don't use DOM because it seems like extra typing. To me, the less code the better. Here's how I would add "bar" without replacing "foo":

function start(){
var innermyspan = document.getElementById("myspan").innerHTML;
document.getElementById("myspan").innerHTML=innermyspan+"bar";
}

Google Maps v3 - limit viewable area and zoom level

Here's my variant to solve the problem of viewable area's limitation.

        google.maps.event.addListener(this.map, 'idle', function() {
            var minLat = strictBounds.getSouthWest().lat();
            var minLon = strictBounds.getSouthWest().lng();
            var maxLat = strictBounds.getNorthEast().lat();
            var maxLon = strictBounds.getNorthEast().lng();
            var cBounds  = self.map.getBounds();
            var cMinLat = cBounds.getSouthWest().lat();
            var cMinLon = cBounds.getSouthWest().lng();
            var cMaxLat = cBounds.getNorthEast().lat();
            var cMaxLon = cBounds.getNorthEast().lng();
            var centerLat = self.map.getCenter().lat();
            var centerLon = self.map.getCenter().lng();

            if((cMaxLat - cMinLat > maxLat - minLat) || (cMaxLon - cMinLon > maxLon - minLon))
            {   //We can't position the canvas to strict borders with a current zoom level
                self.map.setZoomLevel(self.map.getZoomLevel()+1);
                return;
            }
            if(cMinLat < minLat)
                var newCenterLat = minLat + ((cMaxLat-cMinLat) / 2);
            else if(cMaxLat > maxLat)
                var newCenterLat = maxLat - ((cMaxLat-cMinLat) / 2);
            else
                var newCenterLat = centerLat;
            if(cMinLon < minLon)
                var newCenterLon = minLon + ((cMaxLon-cMinLon) / 2);
            else if(cMaxLon > maxLon)
                var newCenterLon = maxLon - ((cMaxLon-cMinLon) / 2);
            else
                var newCenterLon = centerLon;

            if(newCenterLat != centerLat || newCenterLon != centerLon)
                self.map.setCenter(new google.maps.LatLng(newCenterLat, newCenterLon));
        });

strictBounds is an object of new google.maps.LatLngBounds() type. self.gmap stores a Google Map object (new google.maps.Map()).

It really works but don't only forget to take into account the haemorrhoids with crossing 0th meridians and parallels if your bounds cover them.

Using sed and grep/egrep to search and replace

try something using a for loop

 for i in `egrep -lR "YOURSEARCH" .` ; do echo  $i; sed 's/f/k/' <$i >/tmp/`basename $i`; mv /tmp/`basename $i` $i; done

not pretty, but should do.

What does it mean: The serializable class does not declare a static final serialVersionUID field?

Any class that can be serialized (i.e. implements Serializable) should declare that UID and it must be changed whenever anything changes that affects the serialization (additional fields, removed fields, change of field order, ...). The field's value is checked during deserialization and if the value of the serialized object does not equal the value of the class in the current VM, an exception is thrown.

Note that this value is special in that it is serialized with the object even though it is static, for the reasons described above.

Sort a list of lists with a custom compare function

You need to slightly modify your compare function and use functools.cmp_to_key to pass it to sorted. Example code:

import functools

lst = [list(range(i, i+5)) for i in range(5, 1, -1)]

def fitness(item):
    return item[0]+item[1]+item[2]+item[3]+item[4]
def compare(item1, item2):
    return fitness(item1) - fitness(item2)

sorted(lst, key=functools.cmp_to_key(compare))

Output:

[[2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9]]

Works :)

C++ floating point to integer type conversions

Normal way is to:

float f = 3.4;
int n = static_cast<int>(f);

PostgreSQL error 'Could not connect to server: No such file or directory'

for what it's worth, I experienced this same error when I had a typo (md4 instead of md5) in my pg_hba.conf file (/etc/postgresql/9.5/main/pg_hba.conf)

If you got here as I did, double-check that file once to make sure there isn't anything ridiculous in there.

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

No module named pkg_resources

ImportError: No module named pkg_resources: the solution is to reinstall python pip using the following Command are under.

Step: 1 Login in root user.

sudo su root

Step: 2 Uninstall python-pip package if existing.

apt-get purge -y python-pip

Step: 3 Download files using wget command(File download in pwd )

wget https://bootstrap.pypa.io/get-pip.py

Step: 4 Run python file.

python ./get-pip.py

Step: 5 Finaly exicute installation command.

apt-get install python-pip

Note: User must be root.

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

Install package : Microsoft.AspNet.WebApi.Cors

go to : App_Start --> WebApiConfig

Add :

var cors = new EnableCorsAttribute("http://localhost:4200", "", ""); config.EnableCors(cors);

Note : If you add '/' as end of the particular url not worked for me.

How to get a value from a cell of a dataframe?

I needed the value of one cell, selected by column and index names. This solution worked for me:

original_conversion_frequency.loc[1,:].values[0]

Task<> does not contain a definition for 'GetAwaiter'

In my case just add using System; solve the issue.

How to retrieve Jenkins build parameters using the Groovy API?

thanks patrice-n! this code worked to get both queued and running jobs and their parameters:

import hudson.model.Job
import hudson.model.ParametersAction
import hudson.model.Queue
import jenkins.model.Jenkins

println("================================================")
for (Job job : Jenkins.instanceOrNull.getAllItems(Job.class)) {
    if (job.isInQueue()) {
        println("------------------------------------------------")
        println("InQueue " + job.name)

        Queue.Item queue = job.getQueueItem()
        if (queue != null) {
            println(queue.params)
        }
    }
    if (job.isBuilding()) {
        println("------------------------------------------------")
        println("Building " + job.name)

        def build = job.getBuilds().getLastBuild()
        def parameters = build?.getAllActions().find{ it instanceof ParametersAction }?.parameters
        parameters.each {
            def dump = it.dump()
            println "parameter ${it.name}: ${dump}"
        }
    }
}
println("================================================")

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

Flatten List in LINQ

If you have a List<List<int>> k you can do

List<int> flatList= k.SelectMany( v => v).ToList();

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

My solution on Windows was to either run console window as Administrator or change the environment variable MAVEN_OPTS to use a hardcoded path to trust.jks (e.g. 'C:\Users\oddros') instead of '%USERPROFILE%'. My MAVEN_OPTS now looks like this:

-Djavax.net.ssl.trustStore=C:\Users\oddros\trust.jks -Djavax.net.ssl.trustStorePassword=changeit

How to convert unsigned long to string

char buffer [50];

unsigned long a = 5;

int n=sprintf (buffer, "%lu", a);

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

Creating a site wrapper div inside the <body> and applying the overflow-x:hidden to the wrapper instead of the <body> or <html> fixed the issue.

It appears that browsers that parse the <meta name="viewport"> tag simply ignore overflow attributes on the html and body tags.

Note: You may also need to add position: relative to the wrapper div.

Python: Tuples/dictionaries as keys, select, sort

Personally, one of the things I love about python is the tuple-dict combination. What you have here is effectively a 2d array (where x = fruit name and y = color), and I am generally a supporter of the dict of tuples for implementing 2d arrays, at least when something like numpy or a database isn't more appropriate. So in short, I think you've got a good approach.

Note that you can't use dicts as keys in a dict without doing some extra work, so that's not a very good solution.

That said, you should also consider namedtuple(). That way you could do this:

>>> from collections import namedtuple
>>> Fruit = namedtuple("Fruit", ["name", "color"])
>>> f = Fruit(name="banana", color="red")
>>> print f
Fruit(name='banana', color='red')
>>> f.name
'banana'
>>> f.color
'red'

Now you can use your fruitcount dict:

>>> fruitcount = {Fruit("banana", "red"):5}
>>> fruitcount[f]
5

Other tricks:

>>> fruits = fruitcount.keys()
>>> fruits.sort()
>>> print fruits
[Fruit(name='apple', color='green'), 
 Fruit(name='apple', color='red'), 
 Fruit(name='banana', color='blue'), 
 Fruit(name='strawberry', color='blue')]
>>> fruits.sort(key=lambda x:x.color)
>>> print fruits
[Fruit(name='banana', color='blue'), 
 Fruit(name='strawberry', color='blue'), 
 Fruit(name='apple', color='green'), 
 Fruit(name='apple', color='red')]

Echoing chmullig, to get a list of all colors of one fruit, you would have to filter the keys, i.e.

bananas = [fruit for fruit in fruits if fruit.name=='banana']

You are trying to add a non-nullable field 'new_field' to userprofile without a default

In case anyone is setting a ForeignKey, you can just allow nullable fields without setting a default:

new_field = models.ForeignKey(model, null=True)

If you already have data stored within the database, you can also set a default value:

new_field = models.ForeignKey(model, default=<existing model id here>)

Merge two json/javascript arrays in to one array

You can do this using Es 6 new feature :

var json1 = [{id:1, name: 'xxx' , ocupation : 'Doctor' }];

var json2 = [{id:2, name: 'xyz' ,ocupation : 'SE'}];

var combineJsonArray = [...json1 , ...json2];

//output should like this [ { id: 1, name: 'xxx', ocupation: 'Doctor' },
  { id: 2, name: 'xyz', ocupation: 'SE' } ]

Or You can put extra string or anything between two json array :

var json3 = [...json1 ,"test", ...json2];

// output should like this : [ { id: 1, name: 'xxx', ocupation: 'Doctor' },
  'test',
  { id: 2, name: 'xyz', ocupation: 'SE' } ]

How does EL empty operator work in JSF?

Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable using not empty operator on my dataModel that extends javax.faces.model.ListDataModel

Code sample:

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;

public class EntityDataModel extends ListDataModel<Entity> implements
        Collection<Entity>, SelectableDataModel<Entity>, Serializable {

    public EntityDataModel(List<Entity> data) { super(data); }

    @Override
    public Entity getRowData(String rowKey) {
        // In a real app, a more efficient way like a query by rowKey should be
        // implemented to deal with huge data
        List<Entity> entitys = (List<Entity>) getWrappedData();
        for (Entity entity : entitys) {
            if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
        }
        return null;
    }

    @Override
    public Object getRowKey(Entity entity) {
        return entity.getId();
    }

    @Override
    public boolean isEmpty() {
        List<Entity> entity = (List<Entity>) getWrappedData();
        return (entity == null) || entity.isEmpty();
    }
    // ... other not implemented methods of Collection...
}

Browser detection in JavaScript?

Below code snippet will show how how you can show UI elemnts depends on IE version and browser

$(document).ready(function () {

var msiVersion = GetMSIieversion();
if ((msiVersion <= 8) && (msiVersion != false)) {

    //Show UI elements specific to IE version 8 or low

    } else {
    //Show UI elements specific to IE version greater than 8 and for other browser other than IE,,ie..Chrome,Mozila..etc
    }
}
);

Below code will give how we can get IE version

function GetMSIieversion() {

var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
    // IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}

var trident = ua.indexOf('Trident/');
if (trident > 0) {
    // IE 11 => return version number
    var rv = ua.indexOf('rv:');
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}

var edge = ua.indexOf('Edge/');
if (edge > 0) {
    // Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}

// other browser like Chrome,Mozila..etc
return false;

}

How to set size for local image using knitr for markdown?

Here's some options that keep the file self-contained without retastering the image:

Wrap the image in div tags

<div style="width:300px; height:200px">
![Image](path/to/image)
</div>

Use a stylesheet

test.Rmd

---
title: test
output: html_document
css: test.css
---

## Page with an image {#myImagePage}

![Image](path/to/image)

test.css

#myImagePage img {
  width: 400px;
  height: 200px;
}

If you have more than one image you might need to use the nth-child pseudo-selector for this second option.

What is the difference between Bootstrap .container and .container-fluid classes?

Updated 2019

The basic difference is that container is scales responsively, while container-fluid is always width:100%. Therefore in the root CSS definitions, they appear the same, but if you look further you'll see that .container is bound to media queries.

Bootstrap 4

The container has 5 widths...

.container {
  width: 100%;
}

@media (min-width: 576px) {
  .container {
    max-width: 540px;
  }
}

@media (min-width: 768px) {
  .container {
    max-width: 720px;
  }
}

@media (min-width: 992px) {
  .container {
    max-width: 960px;
  }
}

@media (min-width: 1200px) {
  .container {
    max-width: 1140px;
  }
}

Bootstrap 3

The container has 4 sizes. Full width on xs screens, and then it's width varies based on the following media queries..

    @media (min-width: 1200px) {
        .container {
            width: 1170px;
        }
    }
    @media (min-width: 992px) {
        .container {
            width: 970px;
        }
    }
    @media (min-width: 768px) {
        .container {
            width: 750px;
        }
    }

container vs. container-fluid demo

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

Had this error with [email protected]

Try to reinstall mysql

brew reinstall [email protected]

This will fix

How can I link a photo in a Facebook album to a URL

You can only do this to you own photos. Due to recent upgrades, Facebook has made this more difficult. To do this, go to the album page where the photo is that you want to link to. You should see thumbnail images of the photos in the album. Hold down the "Control" or "Command" key while clicking the photo that you wish to link to. A new browser tab will open with the picture you clicked. Under the picture there is a URL that you can send to others to share the photo. You might have to have the privacy settings for that album set so that anyone can see the photos in that album. If you don't the person who clicks the link may have to be signed in and also be your "friend."

Here is an example of one of my photos: http://www.facebook.com/photo.php?pid=43764341&l=0d8a526a64&id=25502298 -it's my cat.

Update:

The link below the photo no longer appears. Once you open the photo in a new tab you can right click the photo (Control+click for Mac users) and click "Copy Image URL" or similar and then share this link. Based on my tests the person who clicks the link doesn't need to use Facebook. The photo will load without the Facebook interface. Like this - http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/189088_867367406856_25502298_43764341_1304758_n.jpg

How can I format decimal property to currency?

Your returned format will be limited by the return type you declare. So yes, you can declare the property as a string and return the formatted value of something. In the "get" you can put whatever data retrieval code you need. So if you need to access some numeric value, simply put your return statement as:

    private decimal _myDecimalValue = 15.78m;
    public string MyFormattedValue
    {
        get { return _myDecimalValue.ToString("c"); }
        private set;  //makes this a 'read only' property.
    }

How to call a stored procedure from Java and JPA

persistence.xml

 <persistence-unit name="PU2" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>jndi_ws2</non-jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>

codigo java

  String PERSISTENCE_UNIT_NAME = "PU2";
    EntityManagerFactory factory2;
    factory2 = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

    EntityManager em2 = factory2.createEntityManager();
    boolean committed = false;
    try {

        try {
            StoredProcedureQuery storedProcedure = em2.createStoredProcedureQuery("PKCREATURNO.INSERTATURNO");
            // set parameters
            storedProcedure.registerStoredProcedureParameter("inuPKEMPRESA", BigDecimal.class, ParameterMode.IN);
            storedProcedure.registerStoredProcedureParameter("inuPKSERVICIO", BigDecimal.class, ParameterMode.IN);
            storedProcedure.registerStoredProcedureParameter("inuPKAREA", BigDecimal.class, ParameterMode.IN);
            storedProcedure.registerStoredProcedureParameter("isbCHSIGLA", String.class, ParameterMode.IN);
            storedProcedure.registerStoredProcedureParameter("INUSINCALIFICACION", BigInteger.class, ParameterMode.IN);
            storedProcedure.registerStoredProcedureParameter("INUTIMBRAR", BigInteger.class, ParameterMode.IN);
            storedProcedure.registerStoredProcedureParameter("INUTRANSFERIDO", BigInteger.class, ParameterMode.IN);
            storedProcedure.registerStoredProcedureParameter("INTESTADO", BigInteger.class, ParameterMode.IN);
            storedProcedure.registerStoredProcedureParameter("inuContador", BigInteger.class, ParameterMode.OUT);

            BigDecimal inuPKEMPRESA = BigDecimal.valueOf(1);
            BigDecimal inuPKSERVICIO = BigDecimal.valueOf(5);
            BigDecimal inuPKAREA = BigDecimal.valueOf(23);
            String isbCHSIGLA = "";
            BigInteger INUSINCALIFICACION = BigInteger.ZERO;
            BigInteger INUTIMBRAR = BigInteger.ZERO;
            BigInteger INUTRANSFERIDO = BigInteger.ZERO;
            BigInteger INTESTADO = BigInteger.ZERO;
            BigInteger inuContador = BigInteger.ZERO;

            storedProcedure.setParameter("inuPKEMPRESA", inuPKEMPRESA);
            storedProcedure.setParameter("inuPKSERVICIO", inuPKSERVICIO);
            storedProcedure.setParameter("inuPKAREA", inuPKAREA);
            storedProcedure.setParameter("isbCHSIGLA", isbCHSIGLA);
            storedProcedure.setParameter("INUSINCALIFICACION", INUSINCALIFICACION);
            storedProcedure.setParameter("INUTIMBRAR", INUTIMBRAR);
            storedProcedure.setParameter("INUTRANSFERIDO", INUTRANSFERIDO);
            storedProcedure.setParameter("INTESTADO", INTESTADO);
            storedProcedure.setParameter("inuContador", inuContador);

            // execute SP
            storedProcedure.execute();
            // get result

            try {
                long _inuContador = (long) storedProcedure.getOutputParameterValue("inuContador");
                varCon = _inuContador + "";
            } catch (Exception e) {
            } 
        } finally {

        }
    } finally {
        em2.close();
    }

Call Jquery function

To call the function on click of some html element (control).

$('#controlID').click(myFunction);

You will need to ensure you bind the event when your html element is ready on which you binding the event. You can put the code in document.ready

$(document).ready(function(){
    $('#controlID').click(myFunction);
});

You can use anonymous function to bind the event to the html element.

$(document).ready(function(){
    $('#controlID').click(function(){
         $.messager.show({  
            title:'My Title',  
            msg:'The message content',  
            showType:'fade',  
            style:{  
                right:'',  
                bottom:''  
            }  
        });  
    });
});

If you want to bind click with many elements you can use class selector

$('.someclass').click(myFunction);

Edit based on comments by OP, If you want to call function under some condition

You can use if for conditional execution, for example,

if(a == 3)
     myFunction();

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

I programmatically provide required input files to GNUPlot executable and invoke it using system() function. It is suitable to my situation since I only want to visualize my data during research. But if you want the plotting functionality integrated into your executable file, maybe this is not for you :)

eslint: error Parsing error: The keyword 'const' is reserved

If using Visual Code one option is to add this to the settings.json file:

"eslint.options": {
    "useEslintrc": false,
    "parserOptions": {
        "ecmaVersion": 2017
    },
    "env": {
        "es6": true
    }
}

How to start a Process as administrator mode in C#

You probably need to set your application as an x64 app.

The IIS Snap In only works in 64 bit and doesn't work in 32 bit, and a process spawned from a 32 bit app seems to work to be a 32 bit process and the same goes for 64 bit apps.

Look at: Start process as 64 bit

How to Find App Pool Recycles in Event Log

IIS version 8.5 +

To enable Event Tracing for Windows for your website/application

  1. Go to Logging and ensure either ETW event only or Both log file and ETW event ...is selected.

enter image description here

  1. Enable the desired Recycle logs in the Advanced Settings for the Application Pool:

enter image description here

  1. Go to the default Custom View: WebServer filters IIS logs:

Custom Views > ServerRoles > Web Server

enter image description here

  1. ... or System logs:

Windows Logs > System

How to stop/cancel 'git log' command in terminal?

You can hit the key q (for quit) and it should take you to the prompt.

Please see this link.

How can I change the font-size of a select option?

try this

http://jsfiddle.net/VggvD/2/

CSS add your code

.select_join option{
    font-size:13px;
}

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

No alternative method is provided in the method's description because the preferred approach (as of API level 11) is to instantiate PreferenceFragment objects to load your preferences from a resource file. See the sample code here: PreferenceActivity

How to part DATE and TIME from DATETIME in MySQL

For only date use
date("Y-m-d");

and for only time use
date("H:i:s");

Sys is undefined

Try one of this solutions:

1. The browser fails to load the compressed script

This is usually the case if you get the error on IE6, but not on other browsers.

The Script Resource Handler – ScriptResource.axd compresses the scripts before returning them to the browser. In pre-RTM releases, the handler did it all the time for all browsers, and it wasn’t configurable. There is an issue in one of the components of IE6 that prevents it from loading compressed scripts correctly. See KB article here. In RTM builds, we’ve made two fixes for this. One, we don’t compress if IE6 is the browser client. Two, we’ve now made compression configurable. Here’s how you can toggle the web.config.

How do you fix it? First, make sure you are using the AJAX Extensions 1.0 RTM release. That alone should be enough. You can also try turning off compression by editing your web.config to have the following:

<system.web.extensions>
<scripting>
<scriptResourceHandler enableCompression="false" enableCaching="true" />
</scripting>
</system.web.extensions>

2. The required configuration for ScriptResourceHandler doesn’t exist for the web.config for your application

Make sure your web.config contains the entries from the default web.config file provided with the extensions install. (default location: C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025)

3. The virtual directory you are using for your web, isn’t correctly marked as an application (thus the configuration isn’t getting loaded) - This would happen for IIS webs.

Make sure that you are using a Web Application, and not just a Virtual Directory

4. ScriptResource.axd requests return 404

This usually points to a mis-configuration of ASP.NET as a whole. On a default installation of ASP.NET, any web request to a resource ending in .axd is passed from IIS to ASP.NET via an isapi mapping. Additionally the mapping is configured to not check if the file exists. If that mapping does not exist, or the check if file exists isn't disabled, then IIS will attempt to find the physical file ScriptResource.axd, won't find it, and return 404.

You can check to see if this is the problem by coipy/pasting the full url to ScriptResource.axd from here, and seeing what it returns

<script src="/MyWebApp/ScriptResource.axd?[snip - long query string]" type="text/javascript"></script>

How do you fix this? If ASP.NET isn't properly installed at all, you can run the "aspnet_regiis.exe" command line tool to fix it up. It's located in C:\WINDOWS\Microsoft.Net\Framework\v2.0.50727. You can run "aspnet_regiis -i -enable", which does the full registration of ASP.NET with IIS and makes sure the ISAPI is enabled in IIS6. You can also run "aspnet_regiis -s w3svc/1/root/MyWebApp" to only fix up the registration for your web application.

5. Resolving the "Sys is undefined" error in ASP.NET AJAX RTM under IIS 7

Put this entry under <system.webServer/><handlers/>:

<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

and remove the one under <system.web/><httpHandlers/>.

References: http://weblogs.asp.net/chrisri/demystifying-sys-is-undefined http://geekswithblogs.net/lorint/archive/2007/03/28/110161.aspx

CSS list item width/height does not work

Inline items cannot have a width. You have to use display: block or display:inline-block, but the latter is not supported everywhere.

How to find the day, month and year with moment.js

I am getting day, month and year using dedicated functions moment().date(), moment().month() and moment().year() of momentjs.

_x000D_
_x000D_
let day = moment('2014-07-28', 'YYYY/MM/DD').date();_x000D_
let month = 1 + moment('2014-07-28', 'YYYY/MM/DD').month();_x000D_
let year = moment('2014-07-28', 'YYYY/MM/DD').year();_x000D_
_x000D_
console.log(day);_x000D_
console.log(month);_x000D_
console.log(year);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

I don't know why there are 48 upvotes for @Chris Schmitz answer which is not 100% correct.

Month is in form of array and starts from 0 so to get exact value we should use 1 + moment().month()

How to use *ngIf else?

ngif expression resulting value won’t just be the boolean true or false

if the expression is just a object, it still evaluate it as truthiness.

if the object is undefined, or non-exist, then ngif will evaluate it as falseness.

common use is if an object loaded, exist, then display the content of this object, otherwise display "loading.......".

 <div *ngIf="!object">
     Still loading...........
 </div>

<div *ngIf="object">
     <!-- the content of this object -->

           object.info, object.id, object.name ... etc.
 </div>

another example:

  things = {
 car: 'Honda',
 shoes: 'Nike',
 shirt: 'Tom Ford',
 watch: 'Timex'
 };

 <div *ngIf="things.car; else noCar">
  Nice car!
 </div>

<ng-template #noCar>
   Call a Uber.
</ng-template>

 <!-- Nice car ! -->

anthoer example:

<div *ngIf="things.car; let car">
   Nice {{ car }}!
 </div>
<!-- Nice Honda! -->

ngif template

ngif angular 4

While loop to test if a file exists in bash

do it like this

while true
do
  [ -f /tmp/list.txt ] && break
  sleep 2
done
ls -l /tmp/list.txt

Convert date to YYYYMM format

SELECT CONVERT(nvarchar(6), GETDATE(), 112)

Command line: search and replace in all filenames matched by grep

If your sed(1) has a -i option, then use it like this:

for i in *; do
  sed -i 's/foo/bar/' $i
done

If not, there are several ways variations on the following depending on which language you want to play with:

ruby -i.bak -pe 'sub(%r{foo}, 'bar')' *
perl -pi.bak -e 's/foo/bar/' *

Can I write into the console in a unit test? If yes, why doesn't the console window open?

IMHO, output messages are relevant only for failed test cases in most cases. I made up the below format, and you can make your own too. This is displayed in the Visual Studio Test Explorer Window itself.

How can we throw this message in the Visual Studio Test Explorer Window?

Sample code like this should work:

if(test_condition_fails)
    Assert.Fail(@"Test Type: Positive/Negative.
                Mock Properties: someclass.propertyOne: True
                someclass.propertyTwo: True
                Test Properties: someclass.testPropertyOne: True
                someclass.testPropertyOne: False
                Reason for Failure: The Mail was not sent on Success Task completion.");

You can have a separate class dedicated to this for you.

PostgreSQL "DESCRIBE TABLE"

Use the following SQL statement

SELECT DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE table_name = 'tbl_name' 
AND COLUMN_NAME = 'col_name'

If you replace tbl_name and col_name, it displays data type of the particular coloumn that you looking for.

How do I access properties of a javascript object if I don't know the names?

var attr, object_information='';

for(attr in object){

      //Get names and values of propertys with style (name : value)
      object_information += attr + ' : ' + object[attr] + '\n'; 

   }


alert(object_information); //Show all Object

Video streaming over websockets using JavaScript

It's definitely conceivable but I am not sure we're there yet. In the meantime, I'd recommend using something like Silverlight with IIS Smooth Streaming. Silverlight is plugin-based, but it works on Windows/OSX/Linux. Some day the HTML5 <video> element will be the way to go, but that will lack support for a little while.

How to grep with a list of words

You need to use the option -f:

$ grep -f A B

The option -F does a fixed string search where as -f is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.

$ grep -Ff A B

You may also want the -w option for matching whole words only:

$ grep -wFf A B

Read man grep for a description of all the possible arguments and what they do.

Throwing exceptions from constructors

Although I have not worked C++ at a professional level, in my opinion, it is OK to throw exceptions from the constructors. I do that(if needed) in .Net. Check out this and this link. It might be of your interest.

Convert a number to 2 decimal places in Java

try this new DecimalFormat("#.00");

update:

    double angle = 20.3034;

    DecimalFormat df = new DecimalFormat("#.00");
    String angleFormated = df.format(angle);
    System.out.println(angleFormated); //output 20.30

Your code wasn't using the decimalformat correctly

The 0 in the pattern means an obligatory digit, the # means optional digit.

update 2: check bellow answer

If you want 0.2677 formatted as 0.27 you should use new DecimalFormat("0.00"); otherwise it will be .27

Best Practices for mapping one object to another

I would opt for AutoMapper, an open source and free mapping library which allows to map one type into another, based on conventions (i.e. map public properties with the same names and same/derived/convertible types, along with many other smart ones). Very easy to use, will let you achieve something like this:

Model model = Mapper.Map<Model>(dto);

Not sure about your specific requirements, but AutoMapper also supports custom value resolvers, which should help you writing a single, generic implementation of your particular mapper.

Position buttons next to each other in the center of page

.wrapper{
  float: left;
  width: 100%;
  text-align: center;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.button{
  display:inline-block;
}
<div class="wrapper">
  <button class="button">Button1</button>
  <button class="button">Button2</button>
</div>

Can I use git diff on untracked files?

Changes work when staged and non-staged with this command. New files work when staged:

$ git diff HEAD

If they are not staged, you will only see file differences.

invalid new-expression of abstract class type

invalid new-expression of abstract class type 'box'

There is nothing unclear about the error message. Your class box has at least one member that is not implemented, which means it is abstract. You cannot instantiate an abstract class.

If this is a bug, fix your box class by implementing the missing member(s).

If it's by design, derive from box, implement the missing member(s) and use the derived class.

SQL query with avg and group by

If I understand what you need, try this:

SELECT id, pass, AVG(val) AS val_1 
FROM data_r1 
GROUP BY id, pass;

Or, if you want just one row for every id, this:

SELECT d1.id,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 1) as val_1,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 2) as val_2,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 3) as val_3,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 4) as val_4,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 5) as val_5,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 6) as val_6,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id

set background color: Android

Color.parseColor("#rrggbb")

instead of #rrggbb you should be using hex values 0 to F for rr, gg and bb:

e.g. Color.parseColor("#000000") or Color.parseColor("#FFFFFF")

Source

From documentation:

public static int parseColor (String colorString):

Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuschia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'

So I believe that if you are using #rrggbb you are getting IllegalArgumentException in your logcat

Source

Alternative:

Color mColor = new Color();
mColor.red(redvalue);
mColor.green(greenvalue);
mColor.blue(bluevalue);
li.setBackgroundColor(mColor);

Source

WPF: ItemsControl with scrollbar (ScrollViewer)

To get a scrollbar for an ItemsControl, you can host it in a ScrollViewer like this:

<ScrollViewer VerticalScrollBarVisibility="Auto">
  <ItemsControl>
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
  </ItemsControl>
</ScrollViewer>

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

You probably need to change your mount command from:

[root@localhost Desktop]# sudo mount -t vboxsf D:\share_folder_vm \share_folder

to:

[root@localhost Desktop]# sudo mount -t vboxsf share_name \share_folder

where share_name is the "Name" of the share in the VirtualBox -> Shared Folders -> Folder List list box. The argument you have ("D:\share_folder_vm") is the "Path" of the share on the host, not the "Name".

Making a div vertically scrollable using CSS

Try like this.

_x000D_
_x000D_
<div style="overflow-y: scroll; height:400px;">
_x000D_
_x000D_
_x000D_

HTTP GET with request body

You can either send a GET with a body or send a POST and give up RESTish religiosity (it's not so bad, 5 years ago there was only one member of that faith -- his comments linked above).

Neither are great decisions, but sending a GET body may prevent problems for some clients -- and some servers.

Doing a POST might have obstacles with some RESTish frameworks.

Julian Reschke suggested above using a non-standard HTTP header like "SEARCH" which could be an elegant solution, except that it's even less likely to be supported.

It might be most productive to list clients that can and cannot do each of the above.

Clients that cannot send a GET with body (that I know of):

  • XmlHTTPRequest Fiddler

Clients that can send a GET with body:

  • most browsers

Servers & libraries that can retrieve a body from GET:

  • Apache
  • PHP

Servers (and proxies) that strip a body from GET:

  • ?

wkhtmltopdf: cannot connect to X server

It is recommended to use at least 0.12.2.1.

Starting from wkhtmltopdf >= 0.12.2 it doesn't require X server or emulation anymore. You can download new version from http://wkhtmltopdf.org/downloads.html

Default value in Doctrine

Be careful when setting default values on property definition! Do it in constructor instead, to keep it problem-free. If you define it on property definition, then persist the object to the database, then make a partial load, then not loaded properties will again have the default value. That is dangerous if you want to persist the object again.

vba pass a group of cells as range to function

There is another way to pass multiple ranges to a function, which I think feels much cleaner for the user. When you call your function in the spreadsheet you wrap each set of ranges in brackets, for example: calculateIt( (A1,A3), (B6,B9) )

The above call assumes your two Sessions are in A1 and A3, and your two Customers are in B6 and B9.

To make this work, your function needs to loop through each of the Areas in the input ranges. For example:

Function calculateIt(Sessions As Range, Customers As Range) As Single

    ' check we passed the same number of areas
    If (Sessions.Areas.Count <> Customers.Areas.Count) Then
        calculateIt = CVErr(xlErrNA)
        Exit Function
    End If

    Dim mySession, myCustomers As Range

    ' run through each area and calculate
    For a = 1 To Sessions.Areas.Count

        Set mySession = Sessions.Areas(a)
        Set myCustomers = Customers.Areas(a)

        ' calculate them...
    Next a

End Function

The nice thing is, if you have both your inputs as a contiguous range, you can call this function just as you would a normal one, e.g. calculateIt(A1:A3, B6:B9).

Hope that helps :)

Try reinstalling `node-sass` on node 0.12?

If you use Gulp then try:

npm install gulp-sass

I had the same problem and the gulp-sass package was the problem.

Cordova : Requirements check failed for JDK 1.8 or greater

In Linux (Debian/Ubuntu) this can be solved by selecting a Java 1.8 SDK in

sudo update-alternatives --config javac

Changing JAVA_HOME env variable directly does not seem to have any effect.

EDIT: responding to the comments: This probably has something to do with the fact that new Debian (and apparently Ubuntu) Java installations through the package manager do not use the JAVA_HOME enviroment variable to determine the location of the JRE. See this and this post for more info.

How to declare an array in Python?

A couple of contributions suggested that arrays in python are represented by lists. This is incorrect. Python has an independent implementation of array() in the standard library module array "array.array()" hence it is incorrect to confuse the two. Lists are lists in python so be careful with the nomenclature used.

list_01 = [4, 6.2, 7-2j, 'flo', 'cro']

list_01
Out[85]: [4, 6.2, (7-2j), 'flo', 'cro']

There is one very important difference between list and array.array(). While both of these objects are ordered sequences, array.array() is an ordered homogeneous sequences whereas a list is a non-homogeneous sequence.

PostgreSQL psql terminal command

psql --pset=format=FORMAT

Great for executing queries from command line, e.g.

psql --pset=format=unaligned -c "select bandanavalue from bandana where bandanakey = 'atlassian.confluence.settings';"

Async/Await Class Constructor

You may immediately invoke an anonymous async function that returns message and set it to the message variable. You might want to take a look at immediately invoked function expressions (IEFES), in case you are unfamiliar with this pattern. This will work like a charm.

var message = (async function() { return await grabUID(uid) })()

How to disable input conditionally in vue.js

Bear in mind that ES6 Sets/Maps don't appear to be reactive as far as i can tell, at time of writing.

How do you configure HttpOnly cookies in tomcat / java webapps?

also it should be noted that turning on HttpOnly will break applets that require stateful access back to the jvm.

the Applet http requests will not use the jsessionid cookie and may get assigned to a different tomcat.

What is the difference between git pull and git fetch + git rebase?

It should be pretty obvious from your question that you're actually just asking about the difference between git merge and git rebase.

So let's suppose you're in the common case - you've done some work on your master branch, and you pull from origin's, which also has done some work. After the fetch, things look like this:

- o - o - o - H - A - B - C (master)
               \
                P - Q - R (origin/master)

If you merge at this point (the default behavior of git pull), assuming there aren't any conflicts, you end up with this:

- o - o - o - H - A - B - C - X (master)
               \             /
                P - Q - R --- (origin/master)

If on the other hand you did the appropriate rebase, you'd end up with this:

- o - o - o - H - P - Q - R - A' - B' - C' (master)
                          |
                          (origin/master)

The content of your work tree should end up the same in both cases; you've just created a different history leading up to it. The rebase rewrites your history, making it look as if you had committed on top of origin's new master branch (R), instead of where you originally committed (H). You should never use the rebase approach if someone else has already pulled from your master branch.

Finally, note that you can actually set up git pull for a given branch to use rebase instead of merge by setting the config parameter branch.<name>.rebase to true. You can also do this for a single pull using git pull --rebase.

How can I switch my signed in user in Visual Studio 2013?

There is a comment about this under this answer, but I think it's important to list it here. If you want to preserve your settings, export them first because they will be lost.

From MSDN forums - since I had to hunt around far too much to find the solution to this:

  1. Close Visual Studio
  2. Start the Developer Command prompt installed with Visual Studio as an administrator.
  3. type 'devenv /resetuserdata' ('wdexpress /resetuserdata' for Express SKUs)
  4. Start Visual Studio Normally.

Worked for me.

What is "not assignable to parameter of type never" error in typescript?

Remove "strictNullChecks": true from "compilerOptions" or set it to false in the tsconfig.json file of your Ng app. These errors will go away like anything and your app would compile successfully.

Disclaimer: This is just a workaround. This error appears only when the null checks are not handled properly which in any case is not a good way to get things done.

Sending HTTP Post request with SOAP action using org.apache.http

The simplest way to identify what needs to be set on the soap action when invoking WCF service through a java client would to load the wsdl, go to the operation name matching the service. From there pick up the action URI and set it in the soap action header. You are done.

eg: from wsdl

<wsdl:operation name="MyOperation">
  <wsdl:input wsaw:Action="http://tempuri.org/IMyService/MyOperation" message="tns:IMyService_MyOperation_InputMessage" />
  <wsdl:output wsaw:Action="http://tempuri.org/IMyService/MyServiceResponse" message="tns:IMyService_MyOperation_OutputMessage" />

Now in the java code we should set the soap action as the Action URI.

//The rest of the httpPost object properties have not been shown for brevity
string actionURI='http://tempuri.org/IMyService/MyOperation';
httpPost.setHeader( "SOAPAction", actionURI);

How to Create a circular progressbar in Android which rotates on it?

Change

android:useLevel="false"

to

android:useLevel="true"

for second sahpe with id="@android:id/progress

hope it works

Which version of C# am I using

The language version is chosen based on the project's target framework by default.

Each project may use a different version of .Net framework, the best suitable C# compiler will be chosen by default by looking at the target framework. From visual studio, UI will not allow the users to changes the language version, however, we can change the language version by editing the project file with addition of new property group. But this may cause compile/run time issues in existing code.

<PropertyGroup>  
<LangVersion>8.0</LangVersion>  
</PropertyGroup>

I could see the following from Microsoft docs.

The compiler determines a default based on these rules:

Target framework  version     C# language version default
.NET Core           3.x         C# 8.0
.NET Core           2.x         C# 7.3
.NET Standard       2.1         C# 8.0
.NET Standard       2.0         C# 7.3
.NET Standard       1.x         C# 7.3
.NET Framework      all         C# 7.3

Change placeholder text

Using jquery you can do this by following code:

<input type="text" id="tbxEmail" name="Email" placeholder="Some Text"/>

$('#tbxEmail').attr('placeholder','Some New Text');

Join/Where with LINQ and Lambda

This linq query Should work for you. It will get all the posts that have post meta.

var query = database.Posts.Join(database.Post_Metas,
                                post => post.postId, // Primary Key
                                meta => meat.postId, // Foreign Key
                                (post, meta) => new { Post = post, Meta = meta });

Equivalent SQL Query

Select * FROM Posts P
INNER JOIN Post_Metas pm ON pm.postId=p.postId

remote rejected master -> master (pre-receive hook declined)

You might need to update the heroku version heroku update. I recently had that issue then I updated from version 7.42.2 to 7.47.5

my engine version is "engines": {"node":"14.8.0","npm":"6.14.7"}

jQuery Mobile how to check if button is disabled?

To see which options have been set on a jQuery UI button use:

$("#deliveryNext").button('option')

To check if it's disabled you can use:

$("#deliveryNext").button('option', 'disabled')

Unfortunately, if the button hasn't been explicitly enabled or disabled before, the above call will just return the button object itself so you'll need to first check to see if the options object contains the 'disabled' property.

So to determine if a button is disabled you can do it like this:

$("#deliveryNext").button('option').disabled != undefined && $("#deliveryNext").button('option', 'disabled')

Can you append strings to variables in PHP?

PHP syntax is little different in case of concatenation from JavaScript. Instead of (+) plus a (.) period is used for string concatenation.

<?php

$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
    $selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;

?>

List all the files and folders in a Directory with PHP recursive function

@A-312's solution may cause memory problems as it may create a huge array if /xampp/htdocs/WORK contains a lot of files and folders.

If you have PHP 7 then you can use Generators and optimize PHP's memory like this:

function getDirContents($dir) {
    $files = scandir($dir);
    foreach($files as $key => $value){

        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            yield $path;

        } else if($value != "." && $value != "..") {
           yield from getDirContents($path);
           yield $path;
        }
    }
}

foreach(getDirContents('/xampp/htdocs/WORK') as $value) {
    echo $value."\n";
}

yield from

How to replace all occurrences of a character in string?

I thought I'd toss in the boost solution as well:

#include <boost/algorithm/string/replace.hpp>

// in place
std::string in_place = "blah#blah";
boost::replace_all(in_place, "#", "@");

// copy
const std::string input = "blah#blah";
std::string output = boost::replace_all_copy(input, "#", "@");

How to remove empty cells in UITableView?

In the Storyboard, select the UITableView, and modify the property Style from Plain to Grouped.

Associative arrays in Shell scripts

I think that you need to step back and think about what a map, or associative array, really is. All it is is a way to store a value for a given key, and get that value back quickly and efficiently. You may also want to be able to iterate over the keys to retrieve every key value pair, or delete keys and their associated values.

Now, think about a data structure you use all the time in shell scripting, and even just in the shell without writing a script, that has these properties. Stumped? It's the filesystem.

Really, all you need to have an associative array in shell programming is a temp directory. mktemp -d is your associative array constructor:

prefix=$(basename -- "$0")
map=$(mktemp -dt ${prefix})
echo >${map}/key somevalue
value=$(cat ${map}/key)

If you don't feel like using echo and cat, you can always write some little wrappers; these ones are modelled off of Irfan's, though they just output the value rather than setting arbitrary variables like $value:

#!/bin/sh

prefix=$(basename -- "$0")
mapdir=$(mktemp -dt ${prefix})
trap 'rm -r ${mapdir}' EXIT

put() {
  [ "$#" != 3 ] && exit 1
  mapname=$1; key=$2; value=$3
  [ -d "${mapdir}/${mapname}" ] || mkdir "${mapdir}/${mapname}"
  echo $value >"${mapdir}/${mapname}/${key}"
}

get() {
  [ "$#" != 2 ] && exit 1
  mapname=$1; key=$2
  cat "${mapdir}/${mapname}/${key}"
}

put "newMap" "name" "Irfan Zulfiqar"
put "newMap" "designation" "SSE"
put "newMap" "company" "My Own Company"

value=$(get "newMap" "company")
echo $value

value=$(get "newMap" "name")
echo $value

edit: This approach is actually quite a bit faster than the linear search using sed suggested by the questioner, as well as more robust (it allows keys and values to contain -, =, space, qnd ":SP:"). The fact that it uses the filesystem does not make it slow; these files are actually never guaranteed to be written to the disk unless you call sync; for temporary files like this with a short lifetime, it's not unlikely that many of them will never be written to disk.

I did a few benchmarks of Irfan's code, Jerry's modification of Irfan's code, and my code, using the following driver program:

#!/bin/sh

mapimpl=$1
numkeys=$2
numvals=$3

. ./${mapimpl}.sh    #/ <- fix broken stack overflow syntax highlighting

for (( i = 0 ; $i < $numkeys ; i += 1 ))
do
    for (( j = 0 ; $j < $numvals ; j += 1 ))
    do
        put "newMap" "key$i" "value$j"
        get "newMap" "key$i"
    done
done

The results:

    $ time ./driver.sh irfan 10 5

    real    0m0.975s
    user    0m0.280s
    sys     0m0.691s

    $ time ./driver.sh brian 10 5

    real    0m0.226s
    user    0m0.057s
    sys     0m0.123s

    $ time ./driver.sh jerry 10 5

    real    0m0.706s
    user    0m0.228s
    sys     0m0.530s

    $ time ./driver.sh irfan 100 5

    real    0m10.633s
    user    0m4.366s
    sys     0m7.127s

    $ time ./driver.sh brian 100 5

    real    0m1.682s
    user    0m0.546s
    sys     0m1.082s

    $ time ./driver.sh jerry 100 5

    real    0m9.315s
    user    0m4.565s
    sys     0m5.446s

    $ time ./driver.sh irfan 10 500

    real    1m46.197s
    user    0m44.869s
    sys     1m12.282s

    $ time ./driver.sh brian 10 500

    real    0m16.003s
    user    0m5.135s
    sys     0m10.396s

    $ time ./driver.sh jerry 10 500

    real    1m24.414s
    user    0m39.696s
    sys     0m54.834s

    $ time ./driver.sh irfan 1000 5

    real    4m25.145s
    user    3m17.286s
    sys     1m21.490s

    $ time ./driver.sh brian 1000 5

    real    0m19.442s
    user    0m5.287s
    sys     0m10.751s

    $ time ./driver.sh jerry 1000 5

    real    5m29.136s
    user    4m48.926s
    sys     0m59.336s

Truncate all tables in a MySQL database in one command?

TB=$( mysql -Bse "show tables from DATABASE" );
for i in ${TB};
    do echo "Truncating table ${i}";
    mysql -e "set foreign_key_checks=0; set unique_checks=0;truncate table DATABASE.${i}; set foreign_key_checks=1; set unique_checks=1";
    sleep 1;
done

--

David,

Thank you for taking the time to format the code, but this is how it is supposed to be applied.

-Kurt

On a UNIX or Linux box:

Make sure you are in a bash shell. These commands are to be run, from the command line as follows.

Note:

I store my credentials in my ~/.my.cnf file, so I don't need to supply them on the command line.

Note:

cpm is the database name

I am only showing a small sample of the results, from each command.

Find your foreign key constraints:

klarsen@Chaos:~$ mysql -Bse "select concat(table_name, ' depends on ', referenced_table_name)
             from information_schema.referential_constraints
             where constraint_schema = 'cpm'
             order by referenced_table_name"
  1. approval_external_system depends on approval_request
  2. address depends on customer
  3. customer_identification depends on customer
  4. external_id depends on customer
  5. credential depends on customer
  6. email_address depends on customer
  7. approval_request depends on customer
  8. customer_status depends on customer
  9. customer_image depends on customer

List the tables and row counts:

klarsen@Chaos:~$ mysql -Bse "SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'cpm'" | cat -n

 1  address 297
 2  approval_external_system    0
 3  approval_request    0
 4  country 189
 5  credential  468
 6  customer    6776
 7  customer_identification 5631
 8  customer_image  2
 9  customer_status 13639

Truncate your tables:

klarsen@Chaos:~$ TB=$( mysql -Bse "show tables from cpm" ); for i in ${TB}; do echo "Truncating table ${i}"; mysql -e "set foreign_key_checks=0; set unique_checks=0;truncate table cpm.${i}; set foreign_key_checks=1; set unique_checks=1"; sleep 1; done
  1. Truncating table address
  2. Truncating table approval_external_system
  3. Truncating table approval_request
  4. Truncating table country
  5. Truncating table credential
  6. Truncating table customer
  7. Truncating table customer_identification
  8. Truncating table customer_image
  9. Truncating table customer_status

Verify that it worked:

klarsen@Chaos:~$ mysql -Bse "SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'cpm'" | cat -n

 1  address 0
 2  approval_external_system    0
 3  approval_request    0
 4  country 0
 5  credential  0
 6  customer    0
 7  customer_identification 0
 8  customer_image  0
 9  customer_status 0
10  email_address   0

On a Windows box:

NOTE:

cpm is the database name

C:\>for /F "tokens=*" %a IN ('mysql -Bse "show tables" cpm') do mysql -e "set foreign_key_checks=0; set unique_checks=0; truncate table %a; foreign_key_checks=1; set unique_checks=1" cpm

How to import large sql file in phpmyadmin

I have made a PHP script which is designed to import large database dumps which have been generated by phpmyadmin. It's called PETMI and you can download it here [project page] [gitlab page]. It has been tested with a 1GB database.

How do I read the file content from the Internal storage - Android App

Take a look this how to use storages in android http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

To read data from internal storage you need your app files folder and read content from here

String yourFilePath = context.getFilesDir() + "/" + "hello.txt";
File yourFile = new File( yourFilePath );

Also you can use this approach

FileInputStream fis = context.openFileInput("hello.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
    sb.append(line);
}

Integrating MySQL with Python in Windows

I found a location were one person had successfully built mysql for python2.6, sharing the link, http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe

...you might see a warning while import MySQLdb which is fine and that won’t hurt anything,

C:\Python26\lib\site-packages\MySQLdb__init__.py:34: DeprecationWarning: the sets module is deprecated from sets import ImmutableSet

Laravel where on relationship object

The correct syntax to do this on your relations is:

Event::whereHas('participants', function ($query) {
    return $query->where('IDUser', '=', 1);
})->get();

Read more at https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

Passing a variable from node.js to html

With Node and HTML alone you won't be able to achieve what you intend to; it's not like using PHP, where you could do something like <title> <?php echo $custom_title; ?>, without any other stuff installed.

To do what you want using Node, you can either use something that's called a 'templating' engine (like Jade, check this out) or use some HTTP requests in Javascript to get your data from the server and use it to replace parts of the HTML with it.

Both require some extra work; it's not as plug'n'play as PHP when it comes to doing stuff like you want.

Maven build debug in Eclipse

The Run/Debug configuration you're using is meant to let you run Maven on your workspace as if from the command line without leaving Eclipse.

Assuming your tests are JUnit based you should be able to debug them by choosing a source folder containing tests with the right button and choose Debug as... -> JUnit tests.

Git reset --hard and push to remote repository

Instead of fixing your "master" branch, it's way easier to swap it with your "desired-master" by renaming the branches. See https://stackoverflow.com/a/2862606/2321594. This way you wouldn't even leave any trace of multiple revert logs.

Pass Array Parameter in SqlCommand

I wanted to expand on the answer that Brian contributed to make this easily usable in other places.

/// <summary>
/// This will add an array of parameters to a SqlCommand. This is used for an IN statement.
/// Use the returned value for the IN part of your SQL call. (i.e. SELECT * FROM table WHERE field IN (returnValue))
/// </summary>
/// <param name="sqlCommand">The SqlCommand object to add parameters to.</param>
/// <param name="array">The array of strings that need to be added as parameters.</param>
/// <param name="paramName">What the parameter should be named.</param>
protected string AddArrayParameters(SqlCommand sqlCommand, string[] array, string paramName)
{
    /* An array cannot be simply added as a parameter to a SqlCommand so we need to loop through things and add it manually. 
     * Each item in the array will end up being it's own SqlParameter so the return value for this must be used as part of the
     * IN statement in the CommandText.
     */
    var parameters = new string[array.Length];
    for (int i = 0; i < array.Length; i++)
    {
        parameters[i] = string.Format("@{0}{1}", paramName, i);
        sqlCommand.Parameters.AddWithValue(parameters[i], array[i]);
    }

    return string.Join(", ", parameters);
}

You can use this new function as follows:

SqlCommand cmd = new SqlCommand();

string ageParameters = AddArrayParameters(cmd, agesArray, "Age");
sql = string.Format("SELECT * FROM TableA WHERE Age IN ({0})", ageParameters);

cmd.CommandText = sql;


Edit: Here is a generic variation that works with an array of values of any type and is usable as an extension method:

public static class Extensions
{
    public static void AddArrayParameters<T>(this SqlCommand cmd, string name, IEnumerable<T> values) 
    { 
        name = name.StartsWith("@") ? name : "@" + name;
        var names = string.Join(", ", values.Select((value, i) => { 
            var paramName = name + i; 
            cmd.Parameters.AddWithValue(paramName, value); 
            return paramName; 
        })); 
        cmd.CommandText = cmd.CommandText.Replace(name, names); 
    }
}

You can then use this extension method as follows:

var ageList = new List<int> { 1, 3, 5, 7, 9, 11 };
var cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM MyTable WHERE Age IN (@Age)";    
cmd.AddArrayParameters("Age", ageList);

Make sure you set the CommandText before calling AddArrayParameters.

Also make sure your parameter name won't partially match anything else in your statement (i.e. @AgeOfChild)

How to store an array into mysql?

you should have three tables: users, comments and comment_users.

comment_users has just two fields: fk_user_id and fk_comment_id

That way you can keep your performance up to a maximum :)

What is a Question Mark "?" and Colon ":" Operator Used for?

a=1;
b=2;

x=3;
y=4;

answer = a > b ? x : y;

answer=4 since the condition is false it takes y value.

A question mark (?)
. The value to use if the condition is true

A colon (:)
. The value to use if the condition is false

__init__ and arguments in Python

The current object is explicitly passed to the method as the first parameter. self is the conventional name. You can call it anything you want but it is strongly advised that you stick with this convention to avoid confusion.

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

java.net.MalformedURLException: no protocol

The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html

The method DocumentBuilder.parse(String) takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream or Reader, for example a StringReader. ... Welcome to the Java standard levels of indirections !

Basically :

DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));

Note that if you read your XML from a file, you can directly give the File object to DocumentBuilder.parse() .

As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !

Internet Explorer 11 detection

Using this RegExp seems works for IE 10 and IE 11:

function isIE(){
    return /Trident\/|MSIE/.test(window.navigator.userAgent);
}

I do not have a IE older than IE 10 to test this.

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

How do I add a delay in a JavaScript loop?

To my knowledge the setTimeout function is called asynchronously. What you can do is wrap the entire loop within an async function and await a Promise that contains the setTimeout as shown:

var looper = async function () {
  for (var start = 1; start < 10; start++) {
    await new Promise(function (resolve, reject) {
      setTimeout(function () {
        console.log("iteration: " + start.toString());
        resolve(true);
      }, 1000);
    });
  }
  return true;
}

And then you call run it like so:

looper().then(function(){
  console.log("DONE!")
});

Please take some time to get a good understanding of asynchronous programming.

Set iframe content height to auto resize dynamically

Simple solution:

<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>

This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.

Android, How can I Convert String to Date?

It could be a good idea to be careful with the Locale upon which c.getTime().toString(); depends.

One idea is to store the time in seconds (e.g. UNIX time). As an int you can easily compare it, and then you just convert it to string when displaying it to the user.

How to display PDF file in HTML?

I use Google Docs embeddable PDF viewer. The docs don't have to be uploaded to Google Docs, but they do have to be available online.

<iframe src="https://docs.google.com/gview?url=https://path.com/to/your/pdf.pdf&embedded=true" style="width:600px; height:500px;" frameborder="0"></iframe>

Two constructors

To call one constructor from another you need to use this() and you need to put it first. In your case the default constructor needs to call the one which takes an argument, not the other ways around.

json_decode() expects parameter 1 to be string, array given

Set decoding to true

Your decoding is not set to true. If you don't have access to set the source to true. The code below will fix it for you.

$WorkingArray = json_decode(json_encode($data),true);

Django templates: If false?

Look at the yesno helper

Eg:

{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}

Load a Bootstrap popover content with AJAX. Is this possible?

Display ajax popover on static element with hover trigger:

$('.hover-ajax').popover({
    "html": true,
    trigger: 'hover',
    "content": function(){
        var div_id =  "tmp-id-" + $.now();
        return details_in_popup($(this).attr('href'), div_id);
    }
});

function details_in_popup(link, div_id){
    $.ajax({
        url: link,
        success: function(response){
            $('#'+div_id).html(response);
        }
    });
    return '<div id="'+ div_id +'">Loading...</div>';
}

Html :

<span class="hover-ajax" href="http://domain.tld/file.php"> Hey , hoover me ! </span>

Hive External Table Skip First Row

skip.header.line.count will skip the header line.

However, if you have some external tool accessing accessing the table, it will still see that actual data without skipping those lines

Convert Current date to integer

Do you need something like this(without time)?

public static Integer toJulianDate(Date pDate) {
if (pDate == null) {
  return null;
}
Calendar lCal = Calendar.getInstance();
lCal.setTime(pDate);
int lYear = lCal.get(Calendar.YEAR);
int lMonth = lCal.get(Calendar.MONTH) + 1;
int lDay = lCal.get(Calendar.DATE);
int a = (14 - lMonth) / 12;
int y = lYear + 4800 - a;
int m = lMonth + 12 * a - 3;
return lDay + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045;
}

React.createElement: type is invalid -- expected a string

In my case, I have added the same custom component as a prop instead of actual prob

   import AddAddress from '../../components/Manager/AddAddress';
    
    class Add extends React.PureComponent {
      render() {
        const {
          history,
          addressFormData,
          formErrors,
          addressChange,
          addAddress,
          isDefault,
          defaultChange
        } = this.props;
    

Error:

    return (
        <AddAddress
          addressFormData={addressFormData}
          formErrors={formErrors}
          addressChange={addressChange}
          addAddress={AddAddress} // here i have used the Component name as probs in same component itself instead of prob
          isDefault={isDefault}
          defaultChange={defaultChange}
        />
      </SubPage>

Solution:

return (
    <AddAddress
      addressFormData={addressFormData}
      formErrors={formErrors}
      addressChange={addressChange}
      addAddress={addAddress} // removed the component name and give prob name
      isDefault={isDefault}
      defaultChange={defaultChange}
    />
  </SubPage>

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

Not unique table/alias

Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.

Try

    SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
      FROM Project_Assigned pa
INNER JOIN Account a
        ON pa.AccountID = a.Account_ID
INNER JOIN Project p
        ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
        ON a.Account_ID = c.Account_ID
     WHERE a.Access_Type = 'Client';

Create instance of generic type in Java?

If you mean new E() then it is impossible. And I would add that it is not always correct - how do you know if E has public no-args constructor? But you can always delegate creation to some other class that knows how to create an instance - it can be Class<E> or your custom code like this

interface Factory<E>{
    E create();
}    

class IntegerFactory implements Factory<Integer>{    
  private static int i = 0; 
  Integer create() {        
    return i++;    
  }
}

Convert all strings in a list to int

Use a list comprehension:

results = [int(i) for i in results]

e.g.

>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]

jQuery AutoComplete Trigger Change Event

Here you go. It's a little messy but it works.

$(function () {  
  var companyList = $("#CompanyList").autocomplete({ 
      change: function() {
          alert('changed');
      }
   });
   companyList.autocomplete('option','change').call(companyList);
});

I want to show all tables that have specified column name

You can use the information schema views:

SELECT DISTINCT TABLE_SCHEMA, TABLE_NAME
FROM Information_Schema.Columns
WHERE COLUMN_NAME = 'ID'

Here's the MSDN reference for the "Columns" view: http://msdn.microsoft.com/en-us/library/ms188348.aspx

Undefined reference to pthread_create in Linux

check man page and you will get.

Compile and link with -pthread.

SYNOPSIS
       #include <pthread.h>

       int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);


       Compile and link with -pthread.
       ....

Apply global variable to Vuejs

In your main.js file, you have to import Vue like this :

import Vue from 'vue'

Then you have to declare your global variable in the main.js file like this :

Vue.prototype.$actionButton = 'Not Approved'

If you want to change the value of the global variable from another component, you can do it like this :

Vue.prototype.$actionButton = 'approved'

https://vuejs.org/v2/cookbook/adding-instance-properties.html#Base-Example

How to prevent default event handling in an onclick method?

Let your callback return false and pass that on to the onclick handler:

<a href="#" onclick="return callmymethod(24)">Call</a>

function callmymethod(myVal){
    //doing custom things with myVal
    //here I want to prevent default
    return false;
}

To create maintainable code, however, you should abstain from using "inline Javascript" (i.e.: code that's directly within an element's tag) and modify an element's behavior via an included Javascript source file (it's called unobtrusive Javascript).

The mark-up:

<a href="#" id="myAnchor">Call</a>

The code (separate file):

// Code example using Prototype JS API
$('myAnchor').observe('click', function(event) {
    Event.stop(event); // suppress default click behavior, cancel the event
    /* your onclick code goes here */
});

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Fitting polynomial model to data in R

Regarding the question 'can R help me find the best fitting model', there is probably a function to do this, assuming you can state the set of models to test, but this would be a good first approach for the set of n-1 degree polynomials:

polyfit <- function(i) x <- AIC(lm(y~poly(x,i)))
as.integer(optimize(polyfit,interval = c(1,length(x)-1))$minimum)

Notes

  • The validity of this approach will depend on your objectives, the assumptions of optimize() and AIC() and if AIC is the criterion that you want to use,

  • polyfit() may not have a single minimum. check this with something like:

    for (i in 2:length(x)-1) print(polyfit(i))
    
  • I used the as.integer() function because it is not clear to me how I would interpret a non-integer polynomial.

  • for testing an arbitrary set of mathematical equations, consider the 'Eureqa' program reviewed by Andrew Gelman here

Update

Also see the stepAIC function (in the MASS package) to automate model selection.

How do I find an element position in std::vector?

If a vector has N elements, there are N+1 possible answers for find. std::find and std::find_if return an iterator to the found element OR end() if no element is found. To change the code as little as possible, your find function should return the equivalent position:

size_t find( const vector<type>& where, int searchParameter )
{
   for( size_t i = 0; i < where.size(); i++ ) {
       if( conditionMet( where[i], searchParameter ) ) {
           return i;
       }
    }
    return where.size();
}
// caller:
const int position = find( firstVector, parameter );
if( position != secondVector.size() ) {
    doAction( secondVector[position] );
}

I would still use std::find_if, though.

Ansible: How to delete files and folders inside a directory?

Below code will delete the entire contents of artifact_path

- name: Clean artifact path
  file:
    state: absent
    path: "{{ artifact_path }}/"

Note: this will delete the directory too.

Java Runtime.getRuntime(): getting output from executing a command line program

Adapted from the previous answer:

public static String execCmdSync(String cmd, CmdExecResult callback) throws java.io.IOException, InterruptedException {
    RLog.i(TAG, "Running command:", cmd);

    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd);

    //String[] commands = {"system.exe", "-get t"};

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    StringBuffer stdOut = new StringBuffer();
    StringBuffer errOut = new StringBuffer();

    // Read the output from the command:
    System.out.println("Here is the standard output of the command:\n");
    String s = null;
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
        stdOut.append(s);
    }

    // Read any errors from the attempted command:
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
        errOut.append(s);
    }

    if (callback == null) {
        return stdInput.toString();
    }

    int exitVal = proc.waitFor();
    callback.onComplete(exitVal == 0, exitVal, errOut.toString(), stdOut.toString(), cmd);

    return stdInput.toString();
}

public interface CmdExecResult{
    void onComplete(boolean success, int exitVal, String error, String output, String originalCmd);
}

How to copy text programmatically in my Android app?

Android support library update

As of Android Oreo, the support library only goes down to API 14. Most newer apps probably also have a min API of 14, and thus don't need to worry about the issues with API 11 mentioned in some of the other answers. A lot of the code can be cleaned up. (But see my edit history if you are still supporting lower versions.)

Copy

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", selectedText);
if (clipboard == null || clip == null) return;
clipboard.setPrimaryClip(clip);

Paste

I'm adding this code as a bonus, because copy/paste is usually done in pairs.

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
try {
    CharSequence text = clipboard.getPrimaryClip().getItemAt(0).getText();
} catch (Exception e) {
    return;
}

Notes

  • Be sure to import the android.content.ClipboardManager version rather than the old android.text.ClipboardManager. Same for ClipData.
  • If you aren't in an activity you can get the service with context.getSystemService().
  • I used a try/catch block for getting the paste text because multiple things can be null. You can check each one if you find that way more readable.

jQuery get textarea text

Why would you want to convert key strokes to text? Add a button that sends the text inside the textarea to the server when clicked. You can get the text using the value attribute as the poster before has pointed out, or using jQuery's API:

$('input#mybutton').click(function() {
    var text = $('textarea#mytextarea').val();
    //send to server and process response
});

Running a CMD or BAT in silent mode

Try SilentCMD. This is a small freeware program that executes a batch file without displaying the command prompt window.

Python - Extracting and Saving Video Frames

From here download this video so we have the same video file for the test. Make sure to have that mp4 file in the same directory of your python code. Then also make sure to run the python interpreter from the same directory.

Then modify the code, ditch waitKey that's wasting time also without a window it cannot capture the keyboard events. Also we print the success value to make sure it's reading the frames successfully.

import cv2
vidcap = cv2.VideoCapture('big_buck_bunny_720p_5mb.mp4')
success,image = vidcap.read()
count = 0
while success:
  cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file      
  success,image = vidcap.read()
  print('Read a new frame: ', success)
  count += 1

How does that go?

Oracle SQL Developer: Unable to find a JVM

Probably this is you are looking for (from this post):

Oracle SQL developer is NOT support on 64 bits JDK. To solve it, install a 32 bits / x86 JDK and update your SQL developer config file, so that it points to the 32 bits JDK.

Fix it! Edit the “sqldeveloper.conf“, which can be found under “{ORACLE_HOME}\sqldeveloper\sqldeveloper\bin\sqldeveloper.conf“, make sure “SetJavaHome” is point to your 32 bits JDK.

Update: Based on @FGreg answer below, in the Sql Developer version 4.XXX you can do it in user-specific config file:

  • Go to Properties -> Help -> About
  • Add / Change SetJavaHome to your path (for example - C:\Program Files (x86)\Java\jdk1.7.0_03) - this will override the setting in sqldeveloper.conf

Update 2: Based on @krm answer below, if your SQL Developer and JDK "bits" versions are not same, you can try to set the value of SetJavaHome property in product.conf

SetJavaHome C:\Program Files\Java\jdk1.7.0_80

The product.conf file is in my case located in the following directory:

C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0

How to link to a <div> on another page?

You simply combine the ideas of a link to another page, as with href=foo.html, and a link to an element on the same page, as with href=#bar, so that the fragment like #bar is written immediately after the URL that refers to another page:

<a href="foo.html#bar">Some nice link text</a>

The target is specified the same was as when linking inside one page, e.g.

<div id="bar">
<h2>Some heading</h2>
Some content
</div>

or (if you really want to link specifically to a heading only)

<h2 id="bar">Some heading</h2>

String.Format for Hex

More generally.

byte[] buf = new byte[] { 123, 2, 233 };

string s = String.Concat(buf.Select(b => b.ToString("X2")));

MySQL: Quick breakdown of the types of joins

I have 2 tables like this:

> SELECT * FROM table_a;
+------+------+
| id   | name |
+------+------+
|    1 | row1 |
|    2 | row2 |
+------+------+

> SELECT * FROM table_b;
+------+------+------+
| id   | name | aid  |
+------+------+------+
|    3 | row3 |    1 |
|    4 | row4 |    1 |
|    5 | row5 | NULL |
+------+------+------+

INNER JOIN cares about both tables

INNER JOIN cares about both tables, so you only get a row if both tables have one. If there is more than one matching pair, you get multiple rows.

> SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
+------+------+------+------+------+

It makes no difference to INNER JOIN if you reverse the order, because it cares about both tables:

> SELECT * FROM table_b b INNER JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
+------+------+------+------+------+

You get the same rows, but the columns are in a different order because we mentioned the tables in a different order.

LEFT JOIN only cares about the first table

LEFT JOIN cares about the first table you give it, and doesn't care much about the second, so you always get the rows from the first table, even if there is no corresponding row in the second:

> SELECT * FROM table_a a LEFT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
|    2 | row2 | NULL | NULL | NULL |
+------+------+------+------+------+

Above you can see all rows of table_a even though some of them do not match with anything in table b, but not all rows of table_b - only ones that match something in table_a.

If we reverse the order of the tables, LEFT JOIN behaves differently:

> SELECT * FROM table_b b LEFT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
|    5 | row5 | NULL | NULL | NULL |
+------+------+------+------+------+

Now we get all rows of table_b, but only matching rows of table_a.

RIGHT JOIN only cares about the second table

a RIGHT JOIN b gets you exactly the same rows as b LEFT JOIN a. The only difference is the default order of the columns.

> SELECT * FROM table_a a RIGHT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
| NULL | NULL |    5 | row5 | NULL |
+------+------+------+------+------+

This is the same rows as table_b LEFT JOIN table_a, which we saw in the LEFT JOIN section.

Similarly:

> SELECT * FROM table_b b RIGHT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
| NULL | NULL | NULL |    2 | row2 |
+------+------+------+------+------+

Is the same rows as table_a LEFT JOIN table_b.

No join at all gives you copies of everything

If you write your tables with no JOIN clause at all, just separated by commas, you get every row of the first table written next to every row of the second table, in every possible combination:

> SELECT * FROM table_b b, table_a;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    3 | row3 | 1    |    2 | row2 |
|    4 | row4 | 1    |    1 | row1 |
|    4 | row4 | 1    |    2 | row2 |
|    5 | row5 | NULL |    1 | row1 |
|    5 | row5 | NULL |    2 | row2 |
+------+------+------+------+------+

(This is from my blog post Examples of SQL join types)

How can you create pop up messages in a batch script?

msg * "Enter Your Message"

Does this help ?

Disable sorting on last column when using jQuery DataTables

This would be useful for v1.10+ of datatables. Set column number for which you want to remove sorting for e.g 1st column would be like:

columnDefs: [
   { orderable: false, targets: 0 }
]

For multiple columns(1st,second and third):

columnDefs: [
   { orderable: false, targets: [0,1,2] }
]

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

SO So So simple solution , go to c:/Users/user_name/.ssh/ and delete all pub / private key pairs , this way heroku will generate keys for you.

Force div element to stay in same place, when page is scrolled

There is something wrong with your code.

position : absolute makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll

This can be solved with position : fixed This property will make the element position fixed and still relative to the scroll.

Or

You can check it out Here

ASP.NET MVC: Html.EditorFor and multi-line text boxes

in your view, instead of:

@Html.EditorFor(model => model.Comments[0].Comment)

just use:

@Html.TextAreaFor(model => model.Comments[0].Comment, 5, 1, null)

what is the difference between ajax and jquery and which one is better?

AJAX is a way of sending information between browser and server without refreshing page. It can be done with or without library like jQuery.

It is easier with the library.

Here is a list of JavaScript libraries/frameworks commonly used in AJAX development.

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

Yes you can use CASE

UPDATE table 
SET columnB = CASE fieldA 
        WHEN columnA=1 THEN 'x' 
        WHEN columnA=2 THEN 'y' 
        ELSE 'z' 
      END 
WHERE columnC = 1

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

You have two options for displaying the Map

  1. Use Maps Library for Android to render the Map
  2. Use Maps API V3 inside a web view

For showing local POIs around a Lat, Long use Places APIs

Can Powershell Run Commands in Parallel?

You can execute parallel jobs in Powershell 2 using Background Jobs. Check out Start-Job and the other job cmdlets.

# Loop through the server list
Get-Content "ServerList.txt" | %{

  # Define what each job does
  $ScriptBlock = {
    param($pipelinePassIn) 
    Test-Path "\\$pipelinePassIn\c`$\Something"
    Start-Sleep 60
  }

  # Execute the jobs in parallel
  Start-Job $ScriptBlock -ArgumentList $_
}

Get-Job

# Wait for it all to complete
While (Get-Job -State "Running")
{
  Start-Sleep 10
}

# Getting the information back from the jobs
Get-Job | Receive-Job

How do I create a self-signed certificate for code signing on Windows?

As of PowerShell 4.0 (Windows 8.1/Server 2012 R2) it is possible to make a certificate in Windows without makecert.exe.

The commands you need are New-SelfSignedCertificate and Export-PfxCertificate.

Instructions are in Creating Self Signed Certificates with PowerShell.

Java get month string from integer

DateFormatSymbols class provides methods for our ease use.

To get short month strings. For example: "Jan", "Feb", etc.

getShortMonths()

To get month strings. For example: "January", "February", etc.

getMonths()

Sample code to return month string in mmm format,

private static String getShortMonthFromNumber(int month){
    if(month<0 || month>11){
        return "";
    }
    return new DateFormatSymbols().getShortMonths()[month];
}

What is the difference between UTF-8 and ISO-8859-1?

Wikipedia explains both reasonably well: UTF-8 vs Latin-1 (ISO-8859-1). Former is a variable-length encoding, latter single-byte fixed length encoding. Latin-1 encodes just the first 256 code points of the Unicode character set, whereas UTF-8 can be used to encode all code points. At physical encoding level, only codepoints 0 - 127 get encoded identically; code points 128 - 255 differ by becoming 2-byte sequence with UTF-8 whereas they are single bytes with Latin-1.

Eclipse and Windows newlines

You could give it a try. The problem is that Windows inserts a carriage return as well as a line feed when given a new line. Unix-systems just insert a line feed. So the extra carriage return character could be the reason why your eclipse messes up with the newlines.

Grab one or two files from your project and convert them. You could use Notepad++ to do so. Just open the file, go to Format->Convert to Unix (when you are using windows).

In Linux just try this on a command line:

sed 's/$'"/`echo \\\r`/" yourfile.java > output.java

Open two instances of a file in a single Visual Studio session

You can use the Windows ? New Window option to duplicate the current window. See more at: Why I like Visual Studio 2010? Undock Windows

Change background color on mouseover and remove it after mouseout

Try this , its working and simple

HTML

?????????????????????<html>
<head></head>
<body>
    <div class="forum">
        test
    </div>
</body>
</html>?????????????????????????????????????????????

Javascript

$(document).ready(function() {
    var colorOrig=$(".forum").css('background-color');
    $(".forum").hover(
    function() {
        //mouse over
        $(this).css('background', '#ff0')
    }, function() {
        //mouse out
        $(this).css('background', colorOrig)
    });
});?

css ?

.forum{
    background:#f0f;
}?

live demo

http://jsfiddle.net/caBzg/

Set Icon Image in Java

Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.

e.g.,

// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);

// use icon here
game.frame.setIconImage(myImg);

Why do I get a SyntaxError for a Unicode escape in my file path?

You need to use a raw string, double your slashes or use forward slashes instead:

r'C:\Users\expoperialed\Desktop\Python'
'C:\\Users\\expoperialed\\Desktop\\Python'
'C:/Users/expoperialed/Desktop/Python'

In regular python strings, the \U character combination signals a extended Unicode codepoint escape.

You can hit any number of other issues, for any of the recognised escape sequences, such as \a or \t or \x, etc.

How do I make a transparent canvas in html5?

Paint your two canvases onto a third canvas.

I had this same problem and none of the solutions here solved my problem. I had one opaque canvas with another transparent canvas above it. The opaque canvas was completely invisible but the background of the page body was visible. The drawings from the transparent canvas on top were visible while the opaque canvas below it was not.

@synthesize vs @dynamic, what are the differences?

As per the Apple documentation.

You use the @synthesize statement in a class’s implementation block to tell the compiler to create implementations that match the specification you gave in the @property declaration.

You use the @dynamic statement to tell the compiler to suppress a warning if it can’t find an implementation of accessor methods specified by an @property declaration.

More info:-

https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/DeclaredProperty.html

Center a 'div' in the middle of the screen, even when the page is scrolled up or down?

Correct Method is

.PopupPanel
{
    border: solid 1px black;
    position: fixed;
    left: 50%;
    top: 50%;
    background-color: white;
    z-index: 100;
    height: 400px;
    margin-top: -200px;

    width: 600px;
    margin-left: -300px;
}

How to Export-CSV of Active Directory Objects?

the first command is correct but change from convert to export to csv, as below,

Get-ADUser -Filter * -Properties * `
    | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization `
    | Sort-Object -Property Name `
    | Export-Csv -path  C:\Users\*\Desktop\file1.csv

Implement Validation for WPF TextBoxes

I have implemented this validation. But you would be used code behind. It is too much easy and simplest way.

XAML: For name Validtion only enter character from A-Z and a-z.

<TextBox x:Name="first_name_texbox" PreviewTextInput="first_name_texbox_PreviewTextInput" >  </TextBox>

Code Behind.

private void first_name_texbox_PreviewTextInput ( object sender, TextCompositionEventArgs e )
{
    Regex regex = new Regex ( "[^a-zA-Z]+" );
    if ( regex.IsMatch ( first_name_texbox.Text ) )
    {
        MessageBox.Show("Invalid Input !");
    }
}

For Salary and ID validation, replace regex constructor passed value with [0-9]+. It means you can only enter number from 1 to infinite.

You can also define length with [0-9]{1,4}. It means you can only enter less then or equal to 4 digit number. This baracket means {at least,How many number}. By doing this you can define range of numbers in textbox.

May it help to others.

XAML:

Code Behind.

private void salary_texbox_PreviewTextInput ( object sender, TextCompositionEventArgs e )
{
    Regex regex = new Regex ( "[^0-9]+" );
    if ( regex.IsMatch ( salary_texbox.Text ) )
    {
        MessageBox.Show("Invalid Input !");
    }
}

How to make Unicode charset in cmd.exe by default?

Open an elevated Command Prompt (run cmd as administrator). query your registry for available TT fonts to the console by:

    REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"

You'll see an output like :

    0    REG_SZ    Lucida Console
    00    REG_SZ    Consolas
    936    REG_SZ    *???
    932    REG_SZ    *MS ????

Now we need to add a TT font that supports the characters you need like Courier New, we do this by adding zeros to the string name, so in this case the next one would be "000" :

    REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"

Now we implement UTF-8 support:

    REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f

Set default font to "Courier New":

    REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f

Set font size to 20 :

    REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f

Enable quick edit if you like :

    REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f

How can I print the contents of an array horizontally?

If you need to pretty print an array of arrays, something like this could work: Pretty Print Array of Arrays in .NET C#

public string PrettyPrintArrayOfArrays(int[][] arrayOfArrays)
{
  if (arrayOfArrays == null)
    return "";

  var prettyArrays = new string[arrayOfArrays.Length];

  for (int i = 0; i < arrayOfArrays.Length; i++)
  {
    prettyArrays[i] = "[" + String.Join(",", arrayOfArrays[i]) + "]";
  }

  return "[" + String.Join(",", prettyArrays) + "]";
}

Example Output:

[[2,3]]

[[2,3],[5,4,3]]

[[2,3],[5,4,3],[8,9]]

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

I want to add something on @Michael Laffargue's post:

jqXHR.done() is faster!

jqXHR.success() have some load time in callback and sometimes can overkill script. I find that on hard way before.

UPDATE:

Using jqXHR.done(), jqXHR.fail() and jqXHR.always() you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:

/* Initialize some your AJAX function */
function call_ajax(attr){
    var settings=$.extend({
        call            : 'users',
        option          : 'list'
    }, attr );

    return $.ajax({
        type: "POST",
        url: "//exapmple.com//ajax.php",
        data: settings,
        cache : false
    });
}

/* .... Somewhere in your code ..... */

call_ajax({
    /* ... */
    id : 10,
    option : 'edit_user'
    change : {
          name : 'John Doe'
    }
    /* ... */
}).done(function(data){

    /* DO SOMETHING AWESOME */

});

How to detect when an @Input() value changes in Angular?

Here ngOnChanges will trigger always when your input property changes:

ngOnChanges(changes: SimpleChanges): void {
 console.log(changes.categoryId.currentValue)
}

Cannot open local file - Chrome: Not allowed to load local resource

If you could do this, it will represent a big security problem, as you can access your filesystem, and potentially act on the data available there... Luckily it's not possible to do what you're trying to do.

If you need local resources to be accessed, you can try to start a web server on your machine, and in this case your method will work. Other workarounds are possible, such as acting on Chrome settings, but I always prefer the clean way, installing a local web server, maybe on a different port (no, it's not so difficult!).

See also:

How to convert number to words in java

Find this code for Indian rupees and in lakhs & crores than Million and Billion. You can pass String or Bigdecimal to the method. This will give the correct output for paisa as well.

package yourpackage;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class Currency {
    
    public static String convertToWords(BigDecimal num) {
        return convertToWords(num.toString());
    }

    public static String convertToWords(String num) {
        BigDecimal bd = new BigDecimal(num);
        long number = bd.longValue();
        long no = bd.longValue();
        int decimal = (int) (bd.remainder(BigDecimal.ONE).doubleValue() * 100);
        int digits_length = String.valueOf(no).length();
        int i = 0;
        ArrayList<String> str = new ArrayList<>();
        HashMap<Integer, String> words = new HashMap<>();
        words.put(0, "");
        words.put(1, "One");
        words.put(2, "Two");
        words.put(3, "Three");
        words.put(4, "Four");
        words.put(5, "Five");
        words.put(6, "Six");
        words.put(7, "Seven");
        words.put(8, "Eight");
        words.put(9, "Nine");
        words.put(10, "Ten");
        words.put(11, "Eleven");
        words.put(12, "Twelve");
        words.put(13, "Thirteen");
        words.put(14, "Fourteen");
        words.put(15, "Fifteen");
        words.put(16, "Sixteen");
        words.put(17, "Seventeen");
        words.put(18, "Eighteen");
        words.put(19, "Nineteen");
        words.put(20, "Twenty");
        words.put(30, "Thirty");
        words.put(40, "Forty");
        words.put(50, "Fifty");
        words.put(60, "Sixty");
        words.put(70, "Seventy");
        words.put(80, "Eighty");
        words.put(90, "Ninety");
        String digits[] = { "", "Hundred", "Thousand", "Lakh", "Crore" };
        while (i < digits_length) {
            int divider = (i == 2) ? 10 : 100;
            number = no % divider;
            no = no / divider;
            i += divider == 10 ? 1 : 2;
            if (number > 0) {
                int counter = str.size();
                String plural = (counter > 0 && number > 9) ? "s" : "";
                String tmp = (number < 21) ? words.get(Integer.valueOf((int) number)) + " " + digits[counter] + plural
                        : words.get(Integer.valueOf((int) Math.floor(number / 10) * 10)) + " "
                                + words.get(Integer.valueOf((int) (number % 10))) + " " + digits[counter] + plural;
                str.add(tmp);
            } else {
                str.add("");
            }
        }

        Collections.reverse(str);
        String Rupees = String.join(" ", str).trim();

        String paise = (decimal) > 0
                ? " And " + words.get(Integer.valueOf((int) (decimal - decimal % 10))) + " "
                        + words.get(Integer.valueOf((int) (decimal % 10))) + " Paise "
                : "";
        return "Rupees " + Rupees + paise + " Only";
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("56721351 = " + Currency.convertToWords(new BigDecimal(56721351)));
        System.out.println("76521351.61 = " + Currency.convertToWords("76521351.61"));
    }

}

When you run this program for 56721351(as Bigdecimal) and 76521351.61(as String) the output is

56721351 = Rupees Five Crore Sixty Seven Lakhs Twenty One Thousands Three Hundred Fifty One Only
76521351.61 = Rupees Seven Crore Sixty Five Lakhs Twenty One Thousands Three Hundred Fifty One And Sixty One Paise  Only

How to use WHERE IN with Doctrine 2

->where($qb->expr()->in('foo.bar', ':data'))
            ->setParameter('participants', $data);

Also works with:

 ->andWhere($qb->expr()->in('foo.bar', ':users'))
                ->setParameter('data', $data);

How to add Class in <li> using wp_nav_menu() in Wordpress?

The correct one for me is the Zuan solution. Be aware to add isset to $args->add_li_class , however you got Notice: Undefined property: stdClass::$add_li_class if you haven't set the property in all yours wp_nav_menu() functions.

This is the function that worked for me:

function add_additional_class_on_li($classes, $item, $args) {
    if(isset($args->add_li_class)) {
      $classes[] = $args->add_li_class;
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_additional_class_on_li', 1, 3);

How do I convert a decimal to an int in C#?

You can't.

Well, of course you could, however an int (System.Int32) is not big enough to hold every possible decimal value.

That means if you cast a decimal that's larger than int.MaxValue you will overflow, and if the decimal is smaller than int.MinValue, it will underflow.

What happens when you under/overflow? One of two things. If your build is unchecked (i.e., the CLR doesn't care if you do), your application will continue after the value over/underflows, but the value in the int will not be what you expected. This can lead to intermittent bugs and may be hard to fix. You'll end up your application in an unknown state which may result in your application corrupting whatever important data its working on. Not good.

If your assembly is checked (properties->build->advanced->check for arithmetic overflow/underflow or the /checked compiler option), your code will throw an exception when an under/overflow occurs. This is probably better than not; however the default for assemblies is not to check for over/underflow.

The real question is "what are you trying to do?" Without knowing your requirements, nobody can tell you what you should do in this case, other than the obvious: DON'T DO IT.

If you specifically do NOT care, the answers here are valid. However, you should communicate your understanding that an overflow may occur and that it doesn't matter by wrapping your cast code in an unchecked block

unchecked
{
  // do your conversions that may underflow/overflow here
}

That way people coming behind you understand you don't care, and if in the future someone changes your builds to /checked, your code won't break unexpectedly.

If all you want to do is drop the fractional portion of the number, leaving the integral part, you can use Math.Truncate.

decimal actual = 10.5M;
decimal expected = 10M;
Assert.AreEqual(expected, Math.Truncate(actual));

VarBinary vs Image SQL Server Data Type to Store Binary Data?

There is also the rather spiffy FileStream, introduced in SQL Server 2008.

Why does using an Underscore character in a LIKE filter give me all the results?

You can write the query as below:

SELECT * FROM Manager
WHERE managerid LIKE '\_%' escape '\'
AND managername LIKE '%\_%' escape '\';

it will solve your problem.

In the shell, what does " 2>&1 " mean?

From a programmer's point of view, it means precisely this:

dup2(1, 2);

See the man page.

Understanding that 2>&1 is a copy also explains why ...

command >file 2>&1

... is not the same as ...

command 2>&1 >file

The first will send both streams to file, whereas the second will send errors to stdout, and ordinary output into file.

What is Mocking?

Mocking is generating pseudo-objects that simulate real objects behaviour for tests

Failed to load c++ bson extension

The only thing which helps me on Windows 7 (x64): https://stackoverflow.com/a/29714359/2670121

Reinstall node and python with x32 versions.
I spent a lot of time with this error:

Failed to load c++ bson extension

and finally, when I installed module node-gyp (for building native addons) and even installed windows SDK with visual studio - nodejs didn't recognize assembled module bson.node as a module. After reinstalling the problem is gone.

Again, What does this error mean?

Actually, it's even not error. You still can use mongoose. But in this case, instead of fast native realization of bson module, you got js-realization, which is slower.

I saw many tips like: "edit path deep inside node_modules..." - which is totally useless, because it does not solve the problem, but just turned off the error messages.

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

This is nice but doesn't answer the question:

"A VARCHAR should always be used instead of TINYTEXT." Tinytext is useful if you have wide rows - since the data is stored off the record. There is a performance overhead, but it does have a use.

iOS 7.0 No code signing identities found

With fastlane installed, you can create and install an Development Certificate by

cert --development
sigh --development

How can I print out C++ map values?

Since C++17 you can use range-based for loops together with structured bindings for iterating over your map. This improves readability, as you reduce the amount of needed first and second members in your code:

std::map<std::string, std::pair<std::string, std::string>> myMap;
myMap["x"] = { "a", "b" };
myMap["y"] = { "c", "d" };

for (const auto &[k, v] : myMap)
    std::cout << "m[" << k << "] = (" << v.first << ", " << v.second << ") " << std::endl;

Output:

m[x] = (a, b)
m[y] = (c, d)

Code on Coliru

How to change the data type of a column without dropping the column with query?

alter table [table name] remove [present column name] to [new column name.

How to make a vertical SeekBar in Android?

Working example

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;

public class VerticalSeekBar extends SeekBar {

    public VerticalSeekBar(Context context) {
        super(context);
    }

    public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public VerticalSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(h, w, oldh, oldw);
    }

   @Override
   public synchronized void setProgress(int progress)  // it is necessary for calling setProgress on click of a button
   {
    super.setProgress(progress);
    onSizeChanged(getWidth(), getHeight(), 0, 0); 
   }
    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    protected void onDraw(Canvas c) {
        c.rotate(-90);
        c.translate(-getHeight(), 0);

        super.onDraw(c);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                setProgress(getMax() - (int) (getMax() * event.getY() / getHeight()));
                onSizeChanged(getWidth(), getHeight(), 0, 0);
                break;

            case MotionEvent.ACTION_CANCEL:
                break;
        }
        return true;
    }
}

There, paste the code and save it. Now use it in your XML layout:

<android.widget.VerticalSeekBar
  android:id="@+id/seekBar1"
  android:layout_width="wrap_content"
  android:layout_height="200dp"
  />

Make sure to create a package android.widget and create VerticalSeekBar.java under this package

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

There is not much I can add to the what and why of the P=?NP part of the question, but in regards to the proof. Not only would a proof be worth some extra credit, but it would solve one of the Millennium Problems. An interesting poll was recently conducted and the published results (PDF) are definitely worth reading in regards to the subject of a proof.

How to Compare two Arrays are Equal using Javascript?

Use lodash. In ES6 syntax:

import isEqual from 'lodash/isEqual';
let equal = isEqual([1,2], [1,2]);  // true

Or previous js versions:

var isEqual = require('lodash/isEqual');
var equal = isEqual([1,2], [1,2]);  // true

Check string for nil & empty

var str: String? = nil

if str?.isEmpty ?? true {
    print("str is nil or empty")
}

str = ""

if str?.isEmpty ?? true {
    print("str is nil or empty")
}

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Commit empty folder structure (with git)

According to their FAQ, GIT doesn't track empty directories.

Git FAQ

However, there are workarounds based on your needs and your project requirements.

Basically if you want to track an empty directory you can place a .gitkeep file in there. The file can be blank and it will just work. This is Gits way of tracking an empty directory.

Another option is to provide documentation for the directory. You can just add a readme file in it describing its expected usage. Git will track the folder because it has a file in it and you have now provided documentation to you and/or whoever else might be using the source code.

If you are building a web app you may find it useful to just add an index.html file which may contain a permission denied message if the folder is only accessible through the app. Codeigniter does this with all their directories.

How to display loading message when an iFrame is loading?

$('iframe').load(function(){
      $(".loading").remove();
    alert("iframe is done loading")
}).show();


<iframe src="http://www.google.com" style="display:none;" width="600" height="300"/>
<div class="loading" style="width:600px;height:300px;">iframe loading</div>