Programs & Examples On #Input devices

Anything related to input devices, i.e. hardware devices (e.g. a mouse, a keyboard, a webcam, etc.) used to gather information from the outside world and converting them into a digital format suitable for processing by a machine.

JavaScript: Check if mouse button down?

Using the MouseEvent api, to check the pressed button, if any:

_x000D_
_x000D_
document.addEventListener('mousedown', (e) => console.log(e.buttons))
_x000D_
_x000D_
_x000D_

Return:

A number representing one or more buttons. For more than one button pressed simultaneously, the values are combined (e.g., 3 is primary + secondary).

0 : No button or un-initialized
1 : Primary button (usually the left button)
2 : Secondary button (usually the right button)
4 : Auxilary button (usually the mouse wheel button or middle button)
8 : 4th button (typically the "Browser Back" button)
16 : 5th button (typically the "Browser Forward" button)

Group by multiple field names in java 8

I needed to make report for a catering firm which serves lunches for various clients. In other words, catering may have on or more firms which take orders from catering, and it must know how many lunches it must produce every single day for all it's clients !

Just to notice, I didn't use sorting, in order not to over complicate this example.

This is my code :

@Test
public void test_2() throws Exception {
    Firm catering = DS.firm().get(1);
    LocalDateTime ldtFrom = LocalDateTime.of(2017, Month.JANUARY, 1, 0, 0);
    LocalDateTime ldtTo = LocalDateTime.of(2017, Month.MAY, 2, 0, 0);
    Date dFrom = Date.from(ldtFrom.atZone(ZoneId.systemDefault()).toInstant());
    Date dTo = Date.from(ldtTo.atZone(ZoneId.systemDefault()).toInstant());

    List<PersonOrders> LON = DS.firm().getAllOrders(catering, dFrom, dTo, false);
    Map<Object, Long> M = LON.stream().collect(
            Collectors.groupingBy(p
                    -> Arrays.asList(p.getDatum(), p.getPerson().getIdfirm(), p.getIdProduct()),
                    Collectors.counting()));

    for (Map.Entry<Object, Long> e : M.entrySet()) {
        Object key = e.getKey();
        Long value = e.getValue();
        System.err.println(String.format("Client firm :%s, total: %d", key, value));
    }
}

Selecting data frame rows based on partial string match in a column

Try str_detect() from the stringr package, which detects the presence or absence of a pattern in a string.

Here is an approach that also incorporates the %>% pipe and filter() from the dplyr package:

library(stringr)
library(dplyr)

CO2 %>%
  filter(str_detect(Treatment, "non"))

   Plant        Type  Treatment conc uptake
1    Qn1      Quebec nonchilled   95   16.0
2    Qn1      Quebec nonchilled  175   30.4
3    Qn1      Quebec nonchilled  250   34.8
4    Qn1      Quebec nonchilled  350   37.2
5    Qn1      Quebec nonchilled  500   35.3
...

This filters the sample CO2 data set (that comes with R) for rows where the Treatment variable contains the substring "non". You can adjust whether str_detect finds fixed matches or uses a regex - see the documentation for the stringr package.

ComboBox SelectedItem vs SelectedValue

If we want to bind to a dictionary ie

  <ComboBox SelectedValue="{Binding Pathology, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                              ItemsSource="{x:Static RnxGlobal:CLocalizedEnums.PathologiesValues}" DisplayMemberPath="Value" SelectedValuePath="Key"
                              Margin="{StaticResource SmallMarginLeftBottom}"/>

then SelectedItem will not work whilist SelectedValue will

How to round a number to significant figures in Python

Most of these answers involve the math, decimal and/or numpy imports or output values as strings. Here is a simple solution in base python that handles both large and small numbers and outputs a float:

def sig_fig_round(number, digits=3):
    power = "{:e}".format(number).split('e')[1]
    return round(number, -(int(power) - digits))

Reliable method to get machine's MAC address in C#

let's say I have a TcpConnection using my local ip of 192.168.0.182. Then if I will like to know the mac address of that NIC I will call the meothod as: GetMacAddressUsedByIp("192.168.0.182")

public static string GetMacAddressUsedByIp(string ipAddress)
    {
        var ips = new List<string>();
        string output;

        try
        {
            // Start the child process.
            Process p = new Process();
            // Redirect the output stream of the child process.
            p.StartInfo.UseShellExecute = false;

            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = "ipconfig";
            p.StartInfo.Arguments = "/all";
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

        }
        catch
        {
            return null;
        }

        // pattern to get all connections
        var pattern = @"(?xis) 
(?<Header>
     (\r|\n) [^\r]+ :  \r\n\r\n
)
(?<content>
    .+? (?= ( (\r\n\r\n)|($)) )
)";

        List<Match> matches = new List<Match>();

        foreach (Match m in Regex.Matches(output, pattern))
            matches.Add(m);

        var connection = matches.Select(m => new
        {
            containsIp = m.Value.Contains(ipAddress),
            containsPhysicalAddress = Regex.Match(m.Value, @"(?ix)Physical \s Address").Success,
            content = m.Value
        }).Where(x => x.containsIp && x.containsPhysicalAddress)
        .Select(m => Regex.Match(m.content, @"(?ix)  Physical \s address [^:]+ : \s* (?<Mac>[^\s]+)").Groups["Mac"].Value).FirstOrDefault();

        return connection;
    }

How do I install soap extension?

In Ubuntu with php7.3:

sudo apt install php7.3-soap 
sudo service apache2 restart

Jquery date picker z-index issue

simply in your css use '.ui-datepicker{ z-index: 9999 !important;}' Here 9999 can be replaced to whatever layer value you want your datepicker available. Neither any code is to be commented nor adding 'position:relative;' css on input elements. Because increasing the z-index of input elements will have effect on all input type buttons, which may not be needed for some cases.

Python: Assign Value if None Exists

IfLoop's answer (and MatToufoutu's comment) work great for standalone variables, but I wanted to provide an answer for anyone trying to do something similar for individual entries in lists, tuples, or dictionaries.

Dictionaries

existing_dict = {"spam": 1, "eggs": 2}
existing_dict["foo"] = existing_dict["foo"] if "foo" in existing_dict else 3

Returns {"spam": 1, "eggs": 2, "foo": 3}

Lists

existing_list = ["spam","eggs"]
existing_list = existing_list if len(existing_list)==3 else 
                existing_list + ["foo"]

Returns ["spam", "eggs", "foo"]

Tuples

existing_tuple = ("spam","eggs")
existing_tuple = existing_tuple if len(existing_tuple)==3 else 
                 existing_tuple + ("foo",)

Returns ("spam", "eggs", "foo")

(Don't forget the comma in ("foo",) to define a "single" tuple.)

The lists and tuples solution will be more complicated if you want to do more than just check for length and append to the end. Nonetheless, this gives a flavor of what you can do.

Change navbar text color Bootstrap

In fact, we can simply use the standard bootstrap text colors, instead of hacking the CSS formats.

Standard Color examples: text-primary, text-secondary, text-success, text-danger, text-warning, text-info

In the Navbar code sample bellow, the text Homepage would be in the orange color (text-warning).

<a class="navbar-brand text-warning" href="/" > Homepage </a>

In the Navbar menu item sample bellow, the text Menu Item would be in the blue color (text-primary).

<a class="dropdown-item text-primary" href="/my-link">Menu Item</a>

Get list of data-* attributes using javascript / jQuery

or convert gilly3's excellent answer to a jQuery method:

$.fn.info = function () {
    var data = {};
    [].forEach.call(this.get(0).attributes, function (attr) {
        if (/^data-/.test(attr.name)) {
            var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function ($0, $1) {
                return $1.toUpperCase();
            });
            data[camelCaseName] = attr.value;
        }
    });
    return data;
}

Using: $('.foo').info();

What is the App_Data folder used for in Visual Studio?

App_Data is essentially a storage point for file-based data stores (as opposed to a SQL server database store for example). Some simple sites make use of it for content stored as XML for example, typically where hosting charges for a DB are expensive.

Is there a way to perform "if" in python's lambda

I think this is what you were looking for

>>> f = lambda x : print(x) if x==2 else print("ERROR")
>>> f(23)
ERROR
>>> f(2)
2
>>> 

location.host vs location.hostname and cross-browser compatibility?

interactive link anatomy

As a little memo: the interactive link anatomy

--

In short (assuming a location of http://example.org:8888/foo/bar#bang):

  • hostname gives you example.org
  • host gives you example.org:8888

How to create streams from string in Node.Js?

Another solution is passing the read function to the constructor of Readable (cf doc stream readeable options)

var s = new Readable({read(size) {
    this.push("your string here")
    this.push(null)
  }});

you can after use s.pipe for exemple

How to read from a text file using VBScript?

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll

or line by line with the method ReadLine:

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

'Loop over it
For Each line in dict.Items
  WScript.Echo line
Next

Labeling file upload button

I could achieve a button using jQueryMobile with following code:

<label for="ppt" data-role="button" data-inline="true" data-mini="true" data-corners="false">Upload</label>
<input id="ppt" type="file" name="ppt" multiple data-role="button" data-inline="true" data-mini="true" data-corners="false" style="opacity: 0;"/>

Above code creates a "Upload" button (custom text). On click of upload button, file browse is launched. Tested with Chrome 25 & IE9.

Difference between int32, int, int32_t, int8 and int8_t

Between int32 and int32_t, (and likewise between int8 and int8_t) the difference is pretty simple: the C standard defines int8_t and int32_t, but does not define anything named int8 or int32 -- the latter (if they exist at all) is probably from some other header or library (most likely predates the addition of int8_t and int32_t in C99).

Plain int is quite a bit different from the others. Where int8_t and int32_t each have a specified size, int can be any size >= 16 bits. At different times, both 16 bits and 32 bits have been reasonably common (and for a 64-bit implementation, it should probably be 64 bits).

On the other hand, int is guaranteed to be present in every implementation of C, where int8_t and int32_t are not. It's probably open to question whether this matters to you though. If you use C on small embedded systems and/or older compilers, it may be a problem. If you use it primarily with a modern compiler on desktop/server machines, it probably won't be.

Oops -- missed the part about char. You'd use int8_t instead of char if (and only if) you want an integer type guaranteed to be exactly 8 bits in size. If you want to store characters, you probably want to use char instead. Its size can vary (in terms of number of bits) but it's guaranteed to be exactly one byte. One slight oddity though: there's no guarantee about whether a plain char is signed or unsigned (and many compilers can make it either one, depending on a compile-time flag). If you need to ensure its being either signed or unsigned, you need to specify that explicitly.

Custom style to jquery ui dialogs

The solution only solves part of the problem, it may let you style the container and contents but doesn't let you change the titlebar. I developed a workaround of sorts but adding an id to the dialog div, then using jQuery .prev to change the style of the div which is the previous sibling of the dialog's div. This works because when jQueryUI creates the dialog, your original div becomes a sibling of the new container, but the title div is a the immediately previous sibling to your original div but neither the container not the title div has an id to simplify selecting the div.

HTML

<button id="dialog1" class="btn btn-danger">Warning</button>
<div title="Nothing here, really" id="nonmodal1">
  Nothing here
</div>

You can use CSS to style the main section of the dialog but not the title

.custom-ui-widget-header-warning {
  background: #EBCCCC;
  font-size: 1em;
}

You need some JS to style the title

$(function() {
                   $("#nonmodal1").dialog({
                     minWidth: 400,
                     minHeight: 'auto',
                     autoOpen: false,
                     dialogClass: 'custom-ui-widget-header-warning',
                     position: {
                       my: 'center',
                       at: 'left'
                     }
                   });

                   $("#dialog1").click(function() {
                     if ($("#nonmodal1").dialog("isOpen") === true) {
                       $("#nonmodal1").dialog("close");
                     } else {
                       $("#nonmodal1").dialog("open").prev().css('background','#D9534F');

                     }
                   });
    });

The example only shows simple styling (background) but you can make it as complex as you wish.

You can see it in action here:

http://codepen.io/chris-hore/pen/OVMPay

'list' object has no attribute 'shape'

Use numpy.array to use shape attribute.

>>> import numpy as np
>>> X = np.array([
...     [[-9.035250067710876], [7.453250169754028], [33.34074878692627]],
...     [[-6.63700008392334], [5.132999956607819], [31.66075038909912]],
...     [[-5.1272499561309814], [8.251499891281128], [30.925999641418457]]
... ])
>>> X.shape
(3L, 3L, 1L)

NOTE X.shape returns 3-items tuple for the given array; [n, T] = X.shape raises ValueError.

How to convert a Hibernate proxy to a real entity object

Starting from Hiebrnate 5.2.10 you can use Hibernate.proxy method to convert a proxy to your real entity:

MyEntity myEntity = (MyEntity) Hibernate.unproxy( proxyMyEntity );

Remove header and footer from window.print()

avoiding the top and bottom margin will solve your problem

@media print {
     @page {
        margin-left: 0.5in;
        margin-right: 0.5in;
        margin-top: 0;
        margin-bottom: 0;
      }
}

round() doesn't seem to be rounding properly

If you use the Decimal module you can approximate without the use of the 'round' function. Here is what I've been using for rounding especially when writing monetary applications:

Decimal(str(16.2)).quantize(Decimal('.01'), rounding=ROUND_UP)

This will return a Decimal Number which is 16.20.

How to determine equality for two JavaScript objects?

Though there are so many answers to this question already. My attempt is just to provide one more way of implementing this:

_x000D_
_x000D_
const primitveDataTypes = ['number', 'boolean', 'string', 'undefined'];_x000D_
const isDateOrRegExp = (value) => value instanceof Date || value instanceof RegExp;_x000D_
const compare = (first, second) => {_x000D_
    let agg = true;_x000D_
    if(typeof first === typeof second && primitveDataTypes.indexOf(typeof first) !== -1 && first !== second){_x000D_
        agg =  false;_x000D_
    }_x000D_
    // adding support for Date and RegExp._x000D_
    else if(isDateOrRegExp(first) || isDateOrRegExp(second)){_x000D_
        if(first.toString() !== second.toString()){_x000D_
            agg = false;_x000D_
        }_x000D_
    }_x000D_
    else {_x000D_
        if(Array.isArray(first) && Array.isArray(second)){_x000D_
        if(first.length === second.length){_x000D_
             for(let i = 0; i < first.length; i++){_x000D_
                if(typeof first[i] === 'object' && typeof second[i] === 'object'){_x000D_
                    agg = compare(first[i], second[i]);_x000D_
                }_x000D_
                else if(first[i] !== second[i]){_x000D_
                    agg = false;_x000D_
                }_x000D_
            }_x000D_
        } else {_x000D_
            agg = false;_x000D_
        }_x000D_
    } else {_x000D_
        const firstKeys = Object.keys(first);_x000D_
        const secondKeys = Object.keys(second);_x000D_
        if(firstKeys.length !== secondKeys.length){_x000D_
            agg = false;_x000D_
        }_x000D_
        for(let j = 0 ; j < firstKeys.length; j++){_x000D_
            if(firstKeys[j] !== secondKeys[j]){_x000D_
                agg = false;_x000D_
            }_x000D_
            if(first[firstKeys[j]] && second[secondKeys[j]] && typeof first[firstKeys[j]] === 'object' && typeof second[secondKeys[j]] === 'object'){_x000D_
                agg = compare(first[firstKeys[j]], second[secondKeys[j]]);_x000D_
             } _x000D_
             else if(first[firstKeys[j]] !== second[secondKeys[j]]){_x000D_
                agg = false;_x000D_
             } _x000D_
        }_x000D_
    }_x000D_
    }_x000D_
    return agg;_x000D_
}_x000D_
_x000D_
_x000D_
console.log('result', compare({a: 1, b: { c: [4, {d:5}, {e:6}]}, r: null}, {a: 1, b: { c: [4, {d:5}, {e:6}]}, r: 'ffd'}));  //returns false.
_x000D_
_x000D_
_x000D_

How can I recover a lost commit in Git?

Try this, This will show all commits recorded in git for a period of time

git reflog

Find the commit you want with

git log HEAD@{3}

or

git log -p HEAD@{3}    

Then check it out if it's the right one:

git checkout HEAD@{3}

This will create a detached head for that commit. Add and commit any changes if needed

git status 
git add
git commit -m "temp_work" 

Now if want to restore commit back to a branch lets say master you will need to name this branch switch to master then merge to master.

git branch temp
git checkout master
git merge temp

Here's also a link specifically for reflog on a Git tutorial site: Atlassian Git Tutorial

TextView bold via xml file?

use textstyle property as bold

android:textStyle = "bold";

How to start nginx via different port(other than 80)

You will need to change the configure port of either Apache or Nginx. After you do this you will need to restart the reconfigured servers, using the 'service' command you used.


Apache

Edit

sudo subl /etc/apache2/ports.conf 

and change the 80 on the following line to something different :

Listen 80

If you just change the port or add more ports here, you will likely also have to change the VirtualHost statement in

sudo subl /etc/apache2/sites-enabled/000-default.conf

and change the 80 on the following line to something different :

<VirtualHost *:80>

then restart by :

sudo service apache2 restart

Nginx

Edit

/etc/nginx/sites-enabled/default

and change the 80 on the following line :

listen 80;

then restart by :

sudo service nginx restart

c - warning: implicit declaration of function ‘printf’

the warning or error of kind IMPLICIT DECLARATION is that the compiler is expecting a Function Declaration/Prototype..

It might either be a header file or your own function Declaration..

Why am I getting error CS0246: The type or namespace name could not be found?

I had a similar problem after first pulling and starting a new solution. It was fixed in visual studio by first cleaning the project. Then restoring the packages. When I built again, there were no more type or namespace errors.

Excel VBA: AutoFill Multiple Cells with Formulas

Based on my Comment here is one way to get what you want done:

Start byt selecting any cell in your range and Press Ctrl + T

This will give you this pop up:

enter image description here

make sure the Where is your table text is correct and click ok you will now have:

enter image description here

Now If you add a column header in D it will automatically be added to the table all the way to the last row:

enter image description here

Now If you enter a formula into this column:

enter image description here

After you enter it, the formula will be auto filled all the way to last row:

enter image description here

Now if you add a new row at the next row under your table:

enter image description here

Once entered it will be resized to the width of your table and all columns with formulas will be added also:

enter image description here

Hope this solves your problem!

Jackson how to transform JsonNode to ArrayNode without casting?

Is there a method equivalent to getJSONArray in org.json so that I have proper error handling in case it isn't an array?

It depends on your input; i.e. the stuff you fetch from the URL. If the value of the "datasets" attribute is an associative array rather than a plain array, you will get a ClassCastException.

But then again, the correctness of your old version also depends on the input. In the situation where your new version throws a ClassCastException, the old version will throw JSONException. Reference: http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)

How to match, but not capture, part of a regex?

Try:

123-(?:(apple|banana|)-|)456

That will match apple, banana, or a blank string, and following it there will be a 0 or 1 hyphens. I was wrong about not having a need for a capturing group. Silly me.

Remove a modified file from pull request

Removing a file from pull request but not from your local repository.

  1. Go to your branch from where you created the request use the following commands

git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin

Note : no single quote or double quotes for the filepath

How to make a <div> appear in front of regular text/tables

You may add a div with position:absolute within a table/div with position:relative. For example, if you want your overlay div to be shown at the bottom right of the main text div (width and height can be removed):

<div style="position:relative;width:300px;height:300px;background-color:#eef">
    <div style="position:absolute;bottom:0;right:0;width:100px;height:100px;background-color:#fee">
        I'm over you!
    </div>
    Your main text
</div>

See it here: http://jsfiddle.net/bptvt5kb/

How to increase timeout for a single test case in mocha

This worked for me! Couldn't find anything to make it work with before()

describe("When in a long running test", () => {
  it("Should not time out with 2000ms", async () => {
    let service = new SomeService();
    let result = await service.callToLongRunningProcess();
    expect(result).to.be.true;
  }).timeout(10000); // Custom Timeout 
});

Returning a promise in an async function in TypeScript

It's complicated.

First of all, in this code

const p = new Promise((resolve) => {
    resolve(4);
});

the type of p is inferred as Promise<{}>. There is open issue about this on typescript github, so arguably this is a bug, because obviously (for a human), p should be Promise<number>.

Then, Promise<{}> is compatible with Promise<number>, because basically the only property a promise has is then method, and then is compatible in these two promise types in accordance with typescript rules for function types compatibility. That's why there is no error in whatever1.

But the purpose of async is to pretend that you are dealing with actual values, not promises, and then you get the error in whatever2 because {} is obvioulsy not compatible with number.

So the async behavior is the same, but currently some workaround is necessary to make typescript compile it. You could simply provide explicit generic argument when creating a promise like this:

const whatever2 = async (): Promise<number> => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

C++ compiling on Windows and Linux: ifdef switch

No, these defines are compiler dependent. What you can do, use your own set of defines, and set them on the Makefile. See this thread for more info.

C compile error: Id returned 1 exit status

I may guess, the old instance of your program is still running. Windows does not allow to change the files which are currently "in use" and your linker cannot write the new .exe on the top of the running one. Try stopping/killing your program.

How to call a web service from jQuery

Incase people have a problem like myself following Marwan Aouida's answer ... the code has a small typo. Instead of "success" it says "sucess" change the spelling and the code works fine.

Is there a difference between `continue` and `pass` in a for loop in python?

In your example, there will be no difference, since both statements appear at the end of the loop. pass is simply a placeholder, in that it does nothing (it passes execution to the next statement). continue, on the other hand, has a definite purpose: it tells the loop to continue as if it had just restarted.

for element in some_list:
    if not element:
        pass
    print element  

is very different from

for element in some_list:
    if not element:
        continue
    print element

How to concatenate two strings in C++?

Since it's C++ why not to use std::string instead of char*? Concatenation will be trivial:

std::string str = "abc";
str += "another";

CURL and HTTPS, "Cannot resolve host"

There is a current bug in glibc on Ubuntu which can have this effect: https://bugs.launchpad.net/ubuntu/+source/glibc/+bug/1674733

To resolve it, update libc and all related (Packages that will be upgraded: libc-bin libc-dev-bin libc6 libc6-dev libfreetype6 libfreetype6-dev locales multiarch-support) and restart the server.

How do I get only directories using Get-ChildItem?

Use:

Get-ChildItem \\myserver\myshare\myshare\ -Directory | Select-Object -Property name |  convertto-csv -NoTypeInformation  | Out-File c:\temp\mydirectorylist.csv

Which does the following

  • Get a list of directories in the target location: Get-ChildItem \\myserver\myshare\myshare\ -Directory
  • Extract only the name of the directories: Select-Object -Property name
  • Convert the output to CSV format: convertto-csv -NoTypeInformation
  • Save the result to a file: Out-File c:\temp\mydirectorylist.csv

Changing text of UIButton programmatically swift

Swift 5:

    let controlStates: Array<UIControl.State> = [.normal, .highlighted, .disabled, .selected, .focused, .application, .reserved]
    for controlState in controlStates {
        button.setTitle(NSLocalizedString("Title", comment: ""), for: controlState)
    }

Which port(s) does XMPP use?

The ports required will be different for your XMPP Server and any XMPP Clients. Most "modern" XMPP Servers follow the defined IANA Ports for Server-to-Server 5269 and for Client-to-Server 5222. Any additional ports depends on what features you enable on the Server, i.e. if you offer BOSH then you may need to open port 80.

File Transfer is highly dependent on both the Clients you use and the Server as to what port it will use, but most of them also negotiate the connect via your existing XMPP Client-to-Server link so the required port opening will be client side (or proxied via port 80.)

Putting a password to a user in PhpMyAdmin in Wamp

i have some problems with it, and fixed it my using another config variable

$cfg['Servers'][$i]['AllowNoPassword'] = true;
instead
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;

may be it will helpfull ot someone

What are the differences between WCF and ASMX web services?

ASMX Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.

Second, ASMX web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.

We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc

What is Func, how and when is it used

Think of it as a placeholder. It can be quite useful when you have code that follows a certain pattern but need not be tied to any particular functionality.

For example, consider the Enumerable.Select extension method.

  • The pattern is: for every item in a sequence, select some value from that item (e.g., a property) and create a new sequence consisting of these values.
  • The placeholder is: some selector function that actually gets the values for the sequence described above.

This method takes a Func<T, TResult> instead of any concrete function. This allows it to be used in any context where the above pattern applies.

So for example, say I have a List<Person> and I want just the name of every person in the list. I can do this:

var names = people.Select(p => p.Name);

Or say I want the age of every person:

var ages = people.Select(p => p.Age);

Right away, you can see how I was able to leverage the same code representing a pattern (with Select) with two different functions (p => p.Name and p => p.Age).

The alternative would be to write a different version of Select every time you wanted to scan a sequence for a different kind of value. So to achieve the same effect as above, I would need:

// Presumably, the code inside these two methods would look almost identical;
// the only difference would be the part that actually selects a value
// based on a Person.
var names = GetPersonNames(people);
var ages = GetPersonAges(people);

With a delegate acting as placeholder, I free myself from having to write out the same pattern over and over in cases like this.

How should I read a file line-by-line in Python?

if you're turned off by the extra line, you can use a wrapper function like so:

def with_iter(iterable):
    with iterable as iter:
        for item in iter:
            yield item

for line in with_iter(open('...')):
    ...

in Python 3.3, the yield from statement would make this even shorter:

def with_iter(iterable):
    with iterable as iter:
        yield from iter

What does ENABLE_BITCODE do in xcode 7?

What is embedded bitcode?

According to docs:

Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.

Update: This phrase in "New Features in Xcode 7" made me to think for a long time that Bitcode is needed for Slicing to reduce app size:

When you archive for submission to the App Store, Xcode will compile your app into an intermediate representation. The App Store will then compile the bitcode down into the 64 or 32 bit executables as necessary.

However that's not true, Bitcode and Slicing work independently: Slicing is about reducing app size and generating app bundle variants, and Bitcode is about certain binary optimizations. I've verified this by checking included architectures in executables of non-bitcode apps and founding that they only include necessary ones.

Bitcode allows other App Thinning component called Slicing to generate app bundle variants with particular executables for particular architectures, e.g. iPhone 5S variant will include only arm64 executable, iPad Mini armv7 and so on.

When to enable ENABLE_BITCODE in new Xcode?

For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS and tvOS apps, bitcode is required.

What happens to the binary when ENABLE_BITCODE is enabled in the new Xcode?

From Xcode 7 reference:

Activating this setting indicates that the target or project should generate bitcode during compilation for platforms and architectures which support it. For Archive builds, bitcode will be generated in the linked binary for submission to the app store. For other builds, the compiler and linker will check whether the code complies with the requirements for bitcode generation, but will not generate actual bitcode.

Here's a couple of links that will help in deeper understanding of Bitcode:

Parse error: Syntax error, unexpected end of file in my PHP code

For me, the most frequent cause is an omitted } character, so that a function or if statement block is not terminated. I fix this by inserting a } character after my recent edits and moving it around from there. I use an editor that can locate opening brackets corresponding to a closing bracket, so that feature helps, too (it locates the function that was not terminated correctly).

We can hope that someday language interpreters and compilers will do some work to generate better error messages, since it is so easy to omit a closing bracket.

If this helps anyone, please vote the answer up.

PostgreSQL naming conventions

Regarding tables names, case, etc, the prevalent convention is:

  • SQL keywords: UPPER CASE
  • names (identifiers): lower_case_with_underscores

For example:

UPDATE my_table SET name = 5;

This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase or PascalCase (or UPPER_CASE), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).

I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq).

See also some discussion here, here and (for general SQL) here, all with several related links.

Note: Postgresql 10 introduced identity columns as an SQL-compliant replacement for serial.

Get ID of element that called a function

You can use 'this' in event handler:

document.getElementById("preview").onmouseover = function() {
    alert(this.id);
}

Or pass event object to handler as follows:

document.getElementById("preview").onmouseover = function(evt) {
    alert(evt.target.id);
}

It's recommended to use attachEvent(for IE < 9)/addEventListener(IE9 and other browsers) to attach events. Example above is for brevity.

function myHandler(evt) {
    alert(evt.target.id);
}

var el = document.getElementById("preview");
if (el.addEventListener){
    el.addEventListener('click', myHandler, false); 
} else if (el.attachEvent){
    el.attachEvent('onclick', myHandler);
}

jQuery .load() call doesn't execute JavaScript in loaded HTML file

I realize this is somewhat of an older post, but for anyone that comes to this page looking for a similar solution...

http://api.jquery.com/jQuery.getScript/

jQuery.getScript( url, [ success(data, textStatus) ] )
  • url - A string containing the URL to which the request is sent.

  • success(data, textStatus) - A callback function that is executed if the request succeeds.

$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});

Checking if a string can be converted to float in Python

'1.43'.replace('.','',1).isdigit()

which will return true only if there is one or no '.' in the string of digits.

'1.4.3'.replace('.','',1).isdigit()

will return false

'1.ww'.replace('.','',1).isdigit()

will return false

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

Sometimes it may happen that you run multiple applications on the same java VM. In Case you have tried all the other solutions described above and it didnt work. Try Running your process by running it on a newly created java VM by passing vmargs

-agentlib:jdwp=transport=dt_socket,server=y,address=10049,suspend=n . 

Here address is what the vm takes.

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Just putting an r in front works well.

eg:

  white = pd.read_csv(r"C:\Users\hydro\a.csv")

Select Top and Last rows in a table (SQL server)

You must sort your data according your needs (es. in reverse order) and use select top query

python to arduino serial read & write

I found it is better to use the command Serial.readString() to replace the Serial.read() to obtain the continuous I/O for Arduino.

Check/Uncheck a checkbox on datagridview

I use the CellMouseUp event. I check for the proper column

if (e.ColumnIndex == datagridview.Columns["columncheckbox"].Index)

I set the actual cell to a DataGridViewCheckBoxCell

dgvChkBxCell = datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;

Then check to see if it's checked using EditingCellFormattedValue

if ((bool)dgvChkBxCell.EditingCellFormattedValue) { }

You will have to check for keyboard entry using the KeyUp event and check the .value property and also check that the CurrentCell's column index matches the checkbox column. The method does not provide e.RowIndex or e.ColumnIndex.

How can I inspect element in an Android browser?

Had to debug a site for native Android browser and came here. So I tried weinre on an OS X 10.9 (as weinre server) with Firefox 30.0 (weinre client) and an Android 4.1.2 (target). I'm really, really surprised of the result.

  1. Download and install node runtime from http://nodejs.org/download/
  2. Install weinre: sudo npm -g install weinre
  3. Find out your current IP address at Settings > Network
  4. Setup a weinre server on your machine: weinre --boundHost YOUR.IP.ADDRESS.HERE
  5. In your browser call: http://YOUR.IP.ADRESS.HERE:8080
  6. You'll see a script snippet, place it into your site: <script src="http://YOUR.IP.ADDRESS.HERE:8080/target/target-script-min.js"></script>
  7. Open the debug client in your local browser: http://YOUR.IP.ADDRESS.HERE:8080/client
  8. Finally on your Android: call the site you want to inspect (the one with the script inside) and see how it appears as "Target" in your local browser. Now you can open "Elements" or whatever you want.

Maybe 8080 isn't your default port. Then in step 4 you have to call weinre --httpPort YOURPORT --boundHost YOUR.IP.ADRESS.HERE.

And I don't remember exactly when it was, maybe somewhere after step 5, I had to accept incoming connections prompt, of course.

Happy debugging

P.S. I'm still overwhelmed how good that works. Even elements-highlighting work

XAMPP permissions on Mac OS X?

For latest OSX versions,

  1. Right click on the folder
  2. Select Get Info
  3. Expand the Sharing & Permission section
  4. Unlock the folder by clicking lock icon on bottom right-corner
  5. Now, select the user list and enable Read & Write privilege for the users
  6. Click on the + icon to add username
  7. Finally click settings icon and select Apply to enclosed items...

    enter image description here

Sorting arrays in javascript by object key value

Use Array's sort() method, eg

myArray.sort(function(a, b) {
    return a.distance - b.distance;
});

Twitter Bootstrap onclick event on buttons-radio

Don't use data-toggle attribute so that you can control the toggle behavior by yourself. So it will avoid 'race-condition'

my codes:

button group template (written in .erb, embedded ruby for ruby on rails):

<div class="btn-group" id="featuresFilter">
     <% _.each(features, function(feature) { %> <button class="btn btn-primary" data="<%= feature %>"><%= feature %></button> <% }); %>
</div>

and javascript:

onChangeFeatures = function(e){
        var el=e.target;
        $(el).button('toggle');

        var features=el.parentElement;
        var activeFeatures=$(features).find(".active");
        console.log(activeFeatures);
}

onChangeFeatures function will be triggered once the button is clicked.

How can I run a PHP script in the background after a form is submitted?

The simpler way to run a PHP script in background is

php script.php >/dev/null &

The script will run in background and the page will also reach the action page faster.

How do I delete specific lines in Notepad++?

You can try doing a replace of #region with \n, turning extended search mode on.

NodeJS/express: Cache and 304 status code

I had the same problem in Safari and Chrome (the only ones I've tested) but I just did something that seems to work, at least I haven't been able to reproduce the problem since I added the solution. What I did was add a metatag to the header with a generated timstamp. Doesn't seem right but it's simple :)

<meta name="304workaround" content="2013-10-24 21:17:23">

Update P.S As far as I can tell, the problem disappears when I remove my node proxy (by proxy i mean both express.vhost and http-proxy module), which is weird...

Spring MVC: How to return image in @ResponseBody?

if you are using Spring version of 3.1 or newer you can specify "produces" in @RequestMapping annotation. Example below works for me out of box. No need of register converter or anything else if you have web mvc enabled (@EnableWebMvc).

@ResponseBody
@RequestMapping(value = "/photo2", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto() throws IOException {
    InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
    return IOUtils.toByteArray(in);
}

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

do-while loop in R

Pretty self explanatory.

repeat{
  statements...
  if(condition){
    break
  }
}

Or something like that I would think. To get the effect of the do while loop, simply check for your condition at the end of the group of statements.

What is the difference between vmalloc and kmalloc?

Linux Kernel Development by Robert Love (Chapter 12, page 244 in 3rd edition) answers this very clearly.

Yes, physically contiguous memory is not required in many of the cases. Main reason for kmalloc being used more than vmalloc in kernel is performance. The book explains, when big memory chunks are allocated using vmalloc, kernel has to map the physically non-contiguous chunks (pages) into a single contiguous virtual memory region. Since the memory is virtually contiguous and physically non-contiguous, several virtual-to-physical address mappings will have to be added to the page table. And in the worst case, there will be (size of buffer/page size) number of mappings added to the page table.

This also adds pressure on TLB (the cache entries storing recent virtual to physical address mappings) when accessing this buffer. This can lead to thrashing.

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

Yes, the first means "match all strings that start with a letter", the second means "match all strings that contain a non-letter". The caret ("^") is used in two different ways, one to signal the start of the text, one to negate a character match inside square brackets.

Defining custom attrs

Qberticus's answer is good, but one useful detail is missing. If you are implementing these in a library replace:

xmlns:whatever="http://schemas.android.com/apk/res/org.example.mypackage"

with:

xmlns:whatever="http://schemas.android.com/apk/res-auto"

Otherwise the application that uses the library will have runtime errors.

Grant all on a specific schema in the db to a group role in PostgreSQL

My answer is similar to this one on ServerFault.com.

To Be Conservative

If you want to be more conservative than granting "all privileges", you might want to try something more like these.

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO some_user_;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO some_user_;

The use of public there refers to the name of the default schema created for every new database/catalog. Replace with your own name if you created a schema.

Access to the Schema

To access a schema at all, for any action, the user must be granted "usage" rights. Before a user can select, insert, update, or delete, a user must first be granted "usage" to a schema.

You will not notice this requirement when first using Postgres. By default every database has a first schema named public. And every user by default has been automatically been granted "usage" rights to that particular schema. When adding additional schema, then you must explicitly grant usage rights.

GRANT USAGE ON SCHEMA some_schema_ TO some_user_ ;

Excerpt from the Postgres doc:

For schemas, allows access to objects contained in the specified schema (assuming that the objects' own privilege requirements are also met). Essentially this allows the grantee to "look up" objects within the schema. Without this permission, it is still possible to see the object names, e.g. by querying the system tables. Also, after revoking this permission, existing backends might have statements that have previously performed this lookup, so this is not a completely secure way to prevent object access.

For more discussion see the Question, What GRANT USAGE ON SCHEMA exactly do?. Pay special attention to the Answer by Postgres expert Craig Ringer.

Existing Objects Versus Future

These commands only affect existing objects. Tables and such you create in the future get default privileges until you re-execute those lines above. See the other answer by Erwin Brandstetter to change the defaults thereby affecting future objects.

Saving image from PHP URL

copy('http://example.com/image.php', 'local/folder/flower.jpg');

How do I quickly rename a MySQL database (change schema name)?

Really, the simplest answer is to export your old database then import it into the new one that you've created to replace the old one. Of course, you should use phpMyAdmin or command line to do this.

Renaming and Jerry-rigging the database is a BAD-IDEA! DO NOT DO IT. (Unless you are the "hacker-type" sitting in your mother's basement in the dark and eating pizza sleeping during the day.)

You will end up with more problems and work than you want.

So,

  1. Create a new_database and name it the correct way.
  2. Go to your phpMyAdmin and open the database you want to export.
  3. Export it (check the options, but you should be OK with the defaults.
  4. You will get a file like or similar to this.
  5. The extension on this file is .sql

    -- phpMyAdmin SQL Dump -- version 3.2.4

    -- http://www.phpmyadmin.net

    -- Host: localhost -- Generation Time: Jun 30, 2010 at 12:17 PM -- Server version: 5.0.90 -- PHP Version: 5.2.6

    SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

    /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT /; /!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS /; /!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION /; /!40101 SET NAMES utf8 */;

    --

    -- Database: mydatab_online


    --

    -- Table structure for table user

    CREATE TABLE IF NOT EXISTS user ( timestamp int(15) NOT NULL default '0', ip varchar(40) NOT NULL default '', file varchar(100) NOT NULL default '', PRIMARY KEY (timestamp), KEY ip (ip), KEY file (file) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    --

    -- Dumping data for table user

    INSERT INTO user (timestamp, ip, file) VALUES (1277911052, '999.236.177.116', ''), (1277911194, '999.236.177.116', '');

This will be your .sql file. The one that you've just exported.

Find it on your hard-drive; usually it is in /temp. Select the empty database that has the correct name (the reason why you are reading this). SAY: Import - GO

Connect your program to the correct database by entering it into what usually is a configuration.php file. Refresh the server (both. Why? Because I am a UNIX oldtimer, and I said so. Now, you should be in good shape. If you have any further questions visit me on the web.

How to delete selected text in the vi editor

If you want to delete using line numbers you can use:

:startingline, last line d

Example:

:7,20 d

This example will delete line 7 to 20.

Modify the legend of pandas bar plot

To change the labels for Pandas df.plot() use ax.legend([...]):

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
df.plot(kind='bar', ax=ax)
#ax = df.plot(kind='bar') # "same" as above
ax.legend(["AAA", "BBB"]);

enter image description here

Another approach is to do the same by plt.legend([...]):

import matplotlib.pyplot as plt
df.plot(kind='bar')
plt.legend(["AAA", "BBB"]);

enter image description here

Web Service vs WCF Service

This answer is based on an article that no longer exists:

Summary of article:

"Basically, WCF is a service layer that allows you to build applications that can communicate using a variety of communication mechanisms. With it, you can communicate using Peer to Peer, Named Pipes, Web Services and so on.

You can’t compare them because WCF is a framework for building interoperable applications. If you like, you can think of it as a SOA enabler. What does this mean?

Well, WCF conforms to something known as ABC, where A is the address of the service that you want to communicate with, B stands for the binding and C stands for the contract. This is important because it is possible to change the binding without necessarily changing the code. The contract is much more powerful because it forces the separation of the contract from the implementation. This means that the contract is defined in an interface, and there is a concrete implementation which is bound to by the consumer using the same idea of the contract. The datamodel is abstracted out."

... later ...

"should use WCF when we need to communicate with other communication technologies (e,.g. Peer to Peer, Named Pipes) rather than Web Service"

Angular ng-if not true

you are not using the $scope you must use $ctrl.area or $scope.area instead of area

python-pandas and databases like mysql

For recent readers of this question: pandas have the following warning in their docs for version 14.0:

Warning: Some of the existing functions or function aliases have been deprecated and will be removed in future versions. This includes: tquery, uquery, read_frame, frame_query, write_frame.

And:

Warning: The support for the ‘mysql’ flavor when using DBAPI connection objects has been deprecated. MySQL will be further supported with SQLAlchemy engines (GH6900).

This makes many of the answers here outdated. You should use sqlalchemy:

from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('dialect://user:pass@host:port/schema', echo=False)
f = pd.read_sql_query('SELECT * FROM mytable', engine, index_col = 'ID')

How do I get column names to print in this C# program?

You can access column name specifically like this too if you don't want to loop through all columns:

table.Columns[1].ColumnName

Regex Last occurrence?

One that worked for me was:

.+(\\.+)$

Try it online!

Explanation:

.+     - any character except newline
(      - create a group
 \\.+   - match a backslash, and any characters after it
)      - end group
$      - this all has to happen at the end of the string

Read file from line 2 or skip header row

To generalize the task of reading multiple header lines and to improve readability I'd use method extraction. Suppose you wanted to tokenize the first three lines of coordinates.txt to use as header information.

Example

coordinates.txt
---------------
Name,Longitude,Latitude,Elevation, Comments
String, Decimal Deg., Decimal Deg., Meters, String
Euler's Town,7.58857,47.559537,0, "Blah"
Faneuil Hall,-71.054773,42.360217,0
Yellowstone National Park,-110.588455,44.427963,0

Then method extraction allows you to specify what you want to do with the header information (in this example we simply tokenize the header lines based on the comma and return it as a list but there's room to do much more).

def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited 
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens

Output

['Name', 'Longitude', 'Latitude', 'Elevation', 'Comments']
['String', 'Decimal Deg.', 'Decimal Deg.', 'Meters', 'String']

If coordinates.txt contains another headerline, simply change numberheaderlines. Best of all, it's clear what __readheader(rh, numberheaderlines=2) is doing and we avoid the ambiguity of having to figure out or comment on why author of the the accepted answer uses next() in his code.

How to scroll to top of long ScrollView layout?

 final ScrollView scrollview = (ScrollView)findViewById(R.id.selected_place_layout_scrollview);

         scrollview.post(new Runnable() { 
                public void run() { 
                    scrollview.scrollTo(0, 0); 
                } 
            }); 

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

React component not re-rendering on state change

After looking into many answers (most of them are correct for their scenarios) and none of them fix my problem I realized that my case is a bit different:

In my weird scenario my component was being rendered inside the state and therefore couldn't be updated. Below is a simple example:

constructor() {
    this.myMethod = this.myMethod.bind(this);
    this.changeTitle = this.changeTitle.bind(this);

    this.myMethod();
}

changeTitle() {
    this.setState({title: 'I will never get updated!!'});
}

myMethod() {
    this.setState({body: <div>{this.state.title}</div>});
}

render() {
    return <>
        {this.state.body}
        <Button onclick={() => this.changeTitle()}>Change Title!</Button>
    </>
}

After refactoring the code to not render the body from state it worked fine :)

Find document with array that contains a specific value

I feel like $all would be more appropriate in this situation. If you are looking for person that is into sushi you do :

PersonModel.find({ favoriteFood : { $all : ["sushi"] }, ...})

As you might want to filter more your search, like so :

PersonModel.find({ favoriteFood : { $all : ["sushi", "bananas"] }, ...})

$in is like OR and $all like AND. Check this : https://docs.mongodb.com/manual/reference/operator/query/all/

Getting the document object of an iframe

In my case, it was due to Same Origin policies. To explain it further, MDN states the following:

If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.

Non-recursive depth first search algorithm

http://www.youtube.com/watch?v=zLZhSSXAwxI

Just watched this video and came out with implementation. It looks easy for me to understand. Please critique this.

visited_node={root}
stack.push(root)
while(!stack.empty){
  unvisited_node = get_unvisited_adj_nodes(stack.top());
  If (unvisited_node!=null){
     stack.push(unvisited_node);  
     visited_node+=unvisited_node;
  }
  else
     stack.pop()
}

Python Error: "ValueError: need more than 1 value to unpack"

You can't run this particular piece of code in the interactive interpreter. You'll need to save it into a file first so that you can pass the argument to it like this

$ python hello.py user338690

How to split string and push in array using jquery

var string = 'a,b,c,d',
    strx   = string.split(',');
    array  = [];

array = array.concat(strx);
// ["a","b","c","d"]

Merge 2 DataTables and store in a new one

This is what i did for merging two datatables and bind the final result to the gridview

        DataTable dtTemp=new DataTable();
        for (int k = 0; k < GridView2.Rows.Count; k++)
        {
            string roomno = GridView2.Rows[k].Cells[1].Text;
            DataTable dtx = GetRoomDetails(chk, roomno, out msg);
            if (dtx.Rows.Count > 0)
            {
                dtTemp.Merge(dtx);
                dtTemp.AcceptChanges();

            }
        }

HTML+CSS: How to force div contents to stay in one line?

Try this:

div {
    border: 1px solid black;
    width: 70px;
    overflow: hidden;
    white-space: nowrap;
}

How should I load files into my Java application?

I haven't had a problem just using Unix-style path separators, even on Windows (though it is good practice to check File.separatorChar).

The technique of using ClassLoader.getResource() is best for read-only resources that are going to be loaded from JAR files. Sometimes, you can programmatically determine the application directory, which is useful for admin-configurable files or server applications. (Of course, user-editable files should be stored somewhere in the System.getProperty("user.home") directory.)

Count number of 1's in binary representation

In python or any other convert to bin string then split it with '0' to get rid of 0's then combine and get the length.

len(''.join(str(bin(122011)).split('0')))-1

Java: Get month Integer from Date

If you can't use Joda time and you still live in the dark world :) ( Java 5 or lower ) you can enjoy this :

Note: Make sure your date is allready made by the format : dd/MM/YYYY

/**
Make an int Month from a date
*/
public static int getMonthInt(Date date) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
    return Integer.parseInt(dateFormat.format(date));
}

/**
Make an int Year from a date
*/
public static int getYearInt(Date date) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
    return Integer.parseInt(dateFormat.format(date));
}

When should I use cross apply over inner join?

Cross apply can be used to replace subquery's where you need a column of the subquery

subquery

select * from person p where
p.companyId in(select c.companyId from company c where c.companyname like '%yyy%')

here i won't be able to select the columns of company table so, using cross apply

select P.*,T.CompanyName
from Person p
cross apply (
    select *
    from Company C
    where p.companyid = c.companyId and c.CompanyName like '%yyy%'
) T

Calling a function in jQuery with click()

$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});

How to insert values into the database table using VBA in MS access

  1. Remove this line of code: For i = 1 To DatDiff. A For loop must have the word NEXT
  2. Also, remove this line of code: StrSQL = StrSQL & "SELECT 'Test'" because its making Access look at your final SQL statement like this; INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );SELECT 'Test' Notice the semicolon in the middle of the SQL statement (should always be at the end. its by the way not required. you can also omit it). also, there is no space between the semicolon and the key word SELECT

in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #

SOAP request in PHP with CURL

Tested and working!

  • with https, user & password

     <?php 
     //Data, connection, auth
     $dataFromTheForm = $_POST['fieldName']; // request data from the form
     $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
     $soapUser = "username";  //  username
     $soapPassword = "password"; // password
    
     // xml post structure
    
     $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                         <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                           <soap:Body>
                             <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
                               <PRICE>'.$dataFromTheForm.'</PRICE> 
                             </GetItemPrice >
                           </soap:Body>
                         </soap:Envelope>';   // data from the form, e.g. some ID number
    
        $headers = array(
                     "Content-type: text/xml;charset=\"utf-8\"",
                     "Accept: text/xml",
                     "Cache-Control: no-cache",
                     "Pragma: no-cache",
                     "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", 
                     "Content-length: ".strlen($xml_post_string),
                 ); //SOAPAction: your op URL
    
         $url = $soapUrl;
    
         // PHP cURL  for https connection with auth
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
         // converting
         $response = curl_exec($ch); 
         curl_close($ch);
    
         // converting
         $response1 = str_replace("<soap:Body>","",$response);
         $response2 = str_replace("</soap:Body>","",$response1);
    
         // convertingc to XML
         $parser = simplexml_load_string($response2);
         // user $parser to get your data out of XML response and to display it. 
     ?>
    

Create a new Ruby on Rails application using MySQL instead of SQLite

On new project, easy peasy:

rails new your_new_project_name -d mysql

On existing project, definitely trickier. This has given me a number of issues on existing rails projects. This kind of works with me:

# On Gemfile:
gem 'mysql2',  '>= 0.3.18', '< 0.5' # copied from a new project for rails 5.1 :)
gem 'activerecord-mysql-adapter' # needed for mysql..

# On Dockerfile or on CLI:
sudo apt-get install -y  mysql-client libmysqlclient-dev 

exception.getMessage() output with class name

I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:

public static void main(String[] args) {
    try {
        throw new RuntimeException("Cannot move file");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
    }
}

...you will see a popup that says exactly what you want.


However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause:

public static void main(String[] args) {
    try {
        throw new Exception(new RuntimeException("Cannot move file"));
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                                      "Error: " + getRootCause(ex).getMessage());
    }
}

public static Throwable getRootCause(Throwable throwable) {
    if (throwable.getCause() != null)
        return getRootCause(throwable.getCause());

    return throwable;
}

Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.

'node' is not recognized as an internal or external command

I set the NODEJS variable in the system control panel but the only thing that worked to set the path was to do it from command line as administrator.

SET PATH=%NODEJS%;%PATH%

Another trick is that once you set the path you must close the console and open a new one for the new path to be taken into account.

However for the regular user to be able to use node I had to run set path again not as admin and restart the computer

Get custom product attributes in Woocommerce

The answer to "Any idea for getting all attributes at once?" question is just to call function with only product id:

$array=get_post_meta($product->id);

key is optional, see http://codex.wordpress.org/Function_Reference/get_post_meta

How can I see an the output of my C programs using Dev-C++?

You can open a command prompt (Start -> Run -> cmd, use the cd command to change directories) and call your program from there, or add a getchar() call at the end of the program, which will wait until you press Enter. In Windows, you can also use system("pause"), which will display a "Press enter to continue..." (or something like that) message.

Flutter - The method was called on null

Because of your initialization wrong.

Don't do like this,

MethodName _methodName;

Do like this,

MethodName _methodName = MethodName();

Iterating through a range of dates in Python

import datetime

def daterange(start, stop, step=datetime.timedelta(days=1), inclusive=False):
  # inclusive=False to behave like range by default
  if step.days > 0:
    while start < stop:
      yield start
      start = start + step
      # not +=! don't modify object passed in if it's mutable
      # since this function is not restricted to
      # only types from datetime module
  elif step.days < 0:
    while start > stop:
      yield start
      start = start + step
  if inclusive and start == stop:
    yield start

# ...

for date in daterange(start_date, end_date, inclusive=True):
  print strftime("%Y-%m-%d", date.timetuple())

This function does more than you strictly require, by supporting negative step, etc. As long as you factor out your range logic, then you don't need the separate day_count and most importantly the code becomes easier to read as you call the function from multiple places.

How to capture Curl output to a file?

For a single file you can use -O instead of -o filename to use the last segment of the URL path as the filename. Example:

curl http://example.com/folder/big-file.iso -O

will save the results to a new file named big-file.iso in the current folder. In this way it works similar to wget but allows you to specify other curl options that are not available when using wget.

VLook-Up Match first 3 characters of one column with another column

=IF(ISNUMBER(SEARCH(LEFT(H2,3),I2)),"YES","NO")))

Embed Google Map code in HTML with marker

USE this , Don't forget to get a google api key from

https://console.developers.google.com/apis/credentials

and replace it

    <div id="map" style="width:100%;height:400px;"></div>

<script>
function myMap() {

var map = new google.maps.Map(document.getElementById("map"), mapOptions);
  var myCenter = new google.maps.LatLng(38.224905, 48.252143);
  var mapCanvas = document.getElementById("map");
  var mapOptions = {center: myCenter, zoom: 16};
  var map = new google.maps.Map(mapCanvas, mapOptions);
  var marker = new google.maps.Marker({position:myCenter});
  marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=myMap"></script>

How do I ALTER a PostgreSQL table and make a column unique?

it's also possible to create a unique constraint of more than 1 column:

ALTER TABLE the_table 
    ADD CONSTRAINT constraint_name UNIQUE (column1, column2);

Installed Java 7 on Mac OS X but Terminal is still using version 6

i resolved this issue by re installing Yosemite and then cross check java version on terminal (java -version) and (javac -version) .It work perfectly now.It is not changing to java 7 as version 6 still present on (command + n) libray>java>javavirtualmachine>your javac current version.you need to address to java home .

sqlite database default time value 'now'

according to dr. hipp in a recent list post:

CREATE TABLE whatever(
     ....
     timestamp DATE DEFAULT (datetime('now','localtime')),
     ...
);

How do I get a reference to the app delegate in Swift?

Swift 4.2

In Swift, easy to access in your VC's

extension UIViewController {
    var appDelegate: AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
   }
}

How do I get column datatype in Oracle with PL-SQL with low privileges?

select t.data_type 
  from user_tab_columns t 
 where t.TABLE_NAME = 'xxx' 
   and t.COLUMN_NAME='aaa'

Hashmap holding different data types as values for instance Integer, String and Object

Do simply like below....

HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put(yourKey+"message","message");
yourHash.put(yourKey+"timestamp",timestamp);
yourHash.put(yourKey+"count ",count);
yourHash.put(yourKey+"version ",version);

typecast the value while getting back. For ex:

    int count = Integer.parseInt(yourHash.get(yourKey+"count"));
//or
int count = Integer.valueOf(yourHash.get(yourKey+"count"));
//or
int count = (Integer)yourHash.get(yourKey+"count"); //or (int)

Static extension methods

In short, no, you can't.

Long answer, extension methods are just syntactic sugar. IE:

If you have an extension method on string let's say:

public static string SomeStringExtension(this string s)
{
   //whatever..
}

When you then call it:

myString.SomeStringExtension();

The compiler just turns it into:

ExtensionClass.SomeStringExtension(myString);

So as you can see, there's no way to do that for static methods.

And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:

Bool.Parse(..)

vs.

Helper.ParseBool(..);

Doesn't really bring much to the table...

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

It might be a conflict with the same port specified in docker-compose.yml and docker-compose.override.yml or the same port specified explicitly and using an environment variable.

I had a docker-compose.yml with ports on a container specified using environment variables, and a docker-compose.override.yml with one of the same ports specified explicitly. Apparently docker tried to open both on the same container. docker container ls -a listed neither because the container could not start and list the ports.

What is reflection and why is it useful?

Reflection is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.

For example, all objects in Java have the method getClass(), which lets you determine the object's class even if you don't know it at compile time (e.g. if you declared it as an Object) - this might seem trivial, but such reflection is not possible in less dynamic languages such as C++. More advanced uses lets you list and call methods, constructors, etc.

Reflection is important since it lets you write programs that do not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.

Lots of modern frameworks use reflection extensively for this very reason. Most other modern languages use reflection as well, and in scripting languages (such as Python) they are even more tightly integrated, since it feels more natural within the general programming model of those languages.

SVN: Folder already under version control but not comitting?

Check for a directory 'apps/autocomplete/.svn'. Move it somewhere safe (in case you need to restore it because this did not work) and see if that fixes the problem.

How does internationalization work in JavaScript?

You can also try another library - https://github.com/wikimedia/jquery.i18n .

In addition to parameter replacement and multiple plural forms, it has support for gender a rather unique feature of custom grammar rules that some languages need.

cannot load such file -- bundler/setup (LoadError)

I've fixed that problem by creating test rails project and install all gems then I've replaced my current Gemfile.lock with the test and all thing works fine.

I think that this problem from bundler versions with hosting, so please make sure that hosting bundler is the same version with your project.

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

In my case, it was Blend SDK missed out on TeamCity machine. This caused the error due incorrect way of assembly resolving then.

What are the differences among grep, awk & sed?

I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....

they are very handy but you have to learn their options etc.

A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)

AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.

a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.

What is lexical scope?

I love the fully featured, language-agnostic answers from folks like @Arak. Since this question was tagged JavaScript though, I'd like to chip in some notes very specific to this language.

In JavaScript our choices for scoping are:

  • as-is (no scope adjustment)
  • lexical var _this = this; function callback(){ console.log(_this); }
  • bound callback.bind(this)

It's worth noting, I think, that JavaScript doesn't really have dynamic scoping. .bind adjusts the this keyword, and that's close, but not technically the same.

Here is an example demonstrating both approaches. You do this every time you make a decision about how to scope callbacks so this applies to promises, event handlers, and more.

Lexical

Here is what you might term Lexical Scoping of callbacks in JavaScript:

var downloadManager = {
  initialize: function() {
    var _this = this; // Set up `_this` for lexical access
    $('.downloadLink').on('click', function () {
      _this.startDownload();
    });
  },
  startDownload: function(){
    this.thinking = true;
    // Request the file from the server and bind more callbacks for when it returns success or failure
  }
  //...
};

Bound

Another way to scope is to use Function.prototype.bind:

var downloadManager = {
  initialize: function() {
    $('.downloadLink').on('click', function () {
      this.startDownload();
    }.bind(this)); // Create a function object bound to `this`
  }
//...

These methods are, as far as I know, behaviorally equivalent.

Why use static_cast<int>(x) instead of (int)x?

  1. Allows casts to be found easily in your code using grep or similar tools.
  2. Makes it explicit what kind of cast you are doing, and engaging the compiler's help in enforcing it. If you only want to cast away const-ness, then you can use const_cast, which will not allow you to do other types of conversions.
  3. Casts are inherently ugly -- you as a programmer are overruling how the compiler would ordinarily treat your code. You are saying to the compiler, "I know better than you." That being the case, it makes sense that performing a cast should be a moderately painful thing to do, and that they should stick out in your code, since they are a likely source of problems.

See Effective C++ Introduction

Why can't non-default arguments follow default arguments?

All required parameters must be placed before any default arguments. Simply because they are mandatory, whereas default arguments are not. Syntactically, it would be impossible for the interpreter to decide which values match which arguments if mixed modes were allowed. A SyntaxError is raised if the arguments are not given in the correct order:

Let us take a look at keyword arguments, using your function.

def fun1(a="who is you", b="True", x, y):
...     print a,b,x,y

Suppose its allowed to declare function as above, Then with the above declarations, we can make the following (regular) positional or keyword argument calls:

func1("ok a", "ok b", 1)  # Is 1 assigned to x or ?
func1(1)                  # Is 1 assigned to a or ?
func1(1, 2)               # ?

How you will suggest the assignment of variables in the function call, how default arguments are going to be used along with keyword arguments.

>>> def fun1(x, y, a="who is you", b="True"):
...     print a,b,x,y
... 

Reference O'Reilly - Core-Python
Where as this function make use of the default arguments syntactically correct for above function calls. Keyword arguments calling prove useful for being able to provide for out-of-order positional arguments, but, coupled with default arguments, they can also be used to "skip over" missing arguments as well.

Update a column in MySQL

if you want to fill all the column:

update 'column' set 'info' where keyID!=0;

Find ALL tweets from a user (not just the first 3,200)

I can confirm that the maximum can be slightly over 3200. I'm getting up to 3231 right now.

How do I check if a property exists on a dynamic anonymous type in c#?

I'm not sure why these answer are so complex, try:

dynamic settings = new
            {
                Filename = "temp.txt",
                Size = 10
            };

string fileName = settings.Filename;

var fileNameExists = fileName != null;

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

Anaconda does not use the PYTHONPATH. One should however note that if the PYTHONPATH is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a

unset PYTHONPATH

For instance this PYTHONPATH points to an incorrect pandas lib:

export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
    from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8

unsetting the PYTHONPATH prevents the wrong pandas lib from being loaded:

unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>

How to get Selected Text from select2 when using <input>

Also you can have the selected value using following code:

alert("Selected option value is: "+$('#SelectelementId').select2("val"));

How to use Servlets and Ajax?

Indeed, the keyword is "ajax": Asynchronous JavaScript and XML. However, last years it's more than often Asynchronous JavaScript and JSON. Basically, you let JS execute an asynchronous HTTP request and update the HTML DOM tree based on the response data.

Since it's pretty a tedious work to make it to work across all browsers (especially Internet Explorer versus others), there are plenty of JavaScript libraries out which simplifies this in single functions and covers as many as possible browser-specific bugs/quirks under the hoods, such as jQuery, Prototype, Mootools. Since jQuery is most popular these days, I'll use it in the below examples.

Kickoff example returning String as plain text

Create a /some.jsp like below (note: the code snippets in this answer doesn't expect the JSP file being placed in a subfolder, if you do so, alter servlet URL accordingly from "someservlet" to "${pageContext.request.contextPath}/someservlet"; it's merely omitted from the code snippets for brevity):

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 4112686</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
                $.get("someservlet", function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                    $("#somediv").text(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                });
            });
        </script>
    </head>
    <body>
        <button id="somebutton">press here</button>
        <div id="somediv"></div>
    </body>
</html>

Create a servlet with a doGet() method which look like this:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String text = "some text";

    response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
    response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
    response.getWriter().write(text);       // Write response body.
}

Map this servlet on an URL pattern of /someservlet or /someservlet/* as below (obviously, the URL pattern is free to your choice, but you'd need to alter the someservlet URL in JS code examples over all place accordingly):

package com.example;

@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
    // ...
}

Or, when you're not on a Servlet 3.0 compatible container yet (Tomcat 7, Glassfish 3, JBoss AS 6, etc or newer), then map it in web.xml the old fashioned way (see also our Servlets wiki page):

<servlet>
    <servlet-name>someservlet</servlet-name>
    <servlet-class>com.example.SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>someservlet</servlet-name>
    <url-pattern>/someservlet/*</url-pattern>
</servlet-mapping>

Now open the http://localhost:8080/context/test.jsp in the browser and press the button. You'll see that the content of the div get updated with the servlet response.

Returning List<String> as JSON

With JSON instead of plaintext as response format you can even get some steps further. It allows for more dynamics. First, you'd like to have a tool to convert between Java objects and JSON strings. There are plenty of them as well (see the bottom of this page for an overview). My personal favourite is Google Gson. Download and put its JAR file in /WEB-INF/lib folder of your webapplication.

Here's an example which displays List<String> as <ul><li>. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<String> list = new ArrayList<>();
    list.add("item1");
    list.add("item2");
    list.add("item3");
    String json = new Gson().toJson(list);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

The JS code:

$(document).on("click", "#somebutton", function() {  // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {    // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $ul = $("<ul>").appendTo($("#somediv")); // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, item) { // Iterate over the JSON array.
            $("<li>").text(item).appendTo($ul);      // Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
        });
    });
});

Do note that jQuery automatically parses the response as JSON and gives you directly a JSON object (responseJson) as function argument when you set the response content type to application/json. If you forget to set it or rely on a default of text/plain or text/html, then the responseJson argument wouldn't give you a JSON object, but a plain vanilla string and you'd need to manually fiddle around with JSON.parse() afterwards, which is thus totally unnecessary if you set the content type right in first place.

Returning Map<String, String> as JSON

Here's another example which displays Map<String, String> as <option>:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Map<String, String> options = new LinkedHashMap<>();
    options.put("value1", "label1");
    options.put("value2", "label2");
    options.put("value3", "label3");
    String json = new Gson().toJson(options);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

And the JSP:

$(document).on("click", "#somebutton", function() {               // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {                 // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $select = $("#someselect");                           // Locate HTML DOM element with ID "someselect".
        $select.find("option").remove();                          // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
        $.each(responseJson, function(key, value) {               // Iterate over the JSON object.
            $("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
        });
    });
});

with

<select id="someselect"></select>

Returning List<Entity> as JSON

Here's an example which displays List<Product> in a <table> where the Product class has the properties Long id, String name and BigDecimal price. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = someProductService.list();
    String json = new Gson().toJson(products);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

The JS code:

$(document).on("click", "#somebutton", function() {        // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {          // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $table = $("<table>").appendTo($("#somediv")); // Create HTML <table> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, product) {    // Iterate over the JSON array.
            $("<tr>").appendTo($table)                     // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
                .append($("<td>").text(product.id))        // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.name))      // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.price));    // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
        });
    });
});

Returning List<Entity> as XML

Here's an example which does effectively the same as previous example, but then with XML instead of JSON. When using JSP as XML output generator you'll see that it's less tedious to code the table and all. JSTL is this way much more helpful as you can actually use it to iterate over the results and perform server side data formatting. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = someProductService.list();

    request.setAttribute("products", products);
    request.getRequestDispatcher("/WEB-INF/xml/products.jsp").forward(request, response);
}

The JSP code (note: if you put the <table> in a <jsp:include>, it may be reusable elsewhere in a non-ajax response):

<?xml version="1.0" encoding="UTF-8"?>
<%@page contentType="application/xml" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<data>
    <table>
        <c:forEach items="${products}" var="product">
            <tr>
                <td>${product.id}</td>
                <td><c:out value="${product.name}" /></td>
                <td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td>
            </tr>
        </c:forEach>
    </table>
</data>

The JS code:

$(document).on("click", "#somebutton", function() {             // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseXml) {                // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response XML...
        $("#somediv").html($(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "somediv".
    });
});

You'll by now probably realize why XML is so much more powerful than JSON for the particular purpose of updating a HTML document using Ajax. JSON is funny, but after all generally only useful for so-called "public web services". MVC frameworks like JSF use XML under the covers for their ajax magic.

Ajaxifying an existing form

You can use jQuery $.serialize() to easily ajaxify existing POST forms without fiddling around with collecting and passing the individual form input parameters. Assuming an existing form which works perfectly fine without JavaScript/jQuery (and thus degrades gracefully when enduser has JavaScript disabled):

<form id="someform" action="someservlet" method="post">
    <input type="text" name="foo" />
    <input type="text" name="bar" />
    <input type="text" name="baz" />
    <input type="submit" name="submit" value="Submit" />
</form>

You can progressively enhance it with ajax as below:

$(document).on("submit", "#someform", function(event) {
    var $form = $(this);

    $.post($form.attr("action"), $form.serialize(), function(response) {
        // ...
    });

    event.preventDefault(); // Important! Prevents submitting the form.
});

You can in the servlet distinguish between normal requests and ajax requests as below:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String foo = request.getParameter("foo");
    String bar = request.getParameter("bar");
    String baz = request.getParameter("baz");

    boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

    // ...

    if (ajax) {
        // Handle ajax (JSON or XML) response.
    } else {
        // Handle regular (JSP) response.
    }
}

The jQuery Form plugin does less or more the same as above jQuery example, but it has additional transparent support for multipart/form-data forms as required by file uploads.

Manually sending request parameters to servlet

If you don't have a form at all, but just wanted to interact with the servlet "in the background" whereby you'd like to POST some data, then you can use jQuery $.param() to easily convert a JSON object to an URL-encoded query string.

var params = {
    foo: "fooValue",
    bar: "barValue",
    baz: "bazValue"
};

$.post("someservlet", $.param(params), function(response) {
    // ...
});

The same doPost() method as shown here above can be reused. Do note that above syntax also works with $.get() in jQuery and doGet() in servlet.

Manually sending JSON object to servlet

If you however intend to send the JSON object as a whole instead of as individual request parameters for some reason, then you'd need to serialize it to a string using JSON.stringify() (not part of jQuery) and instruct jQuery to set request content type to application/json instead of (default) application/x-www-form-urlencoded. This can't be done via $.post() convenience function, but needs to be done via $.ajax() as below.

var data = {
    foo: "fooValue",
    bar: "barValue",
    baz: "bazValue"
};

$.ajax({
    type: "POST",
    url: "someservlet",
    contentType: "application/json", // NOT dataType!
    data: JSON.stringify(data),
    success: function(response) {
        // ...
    }
});

Do note that a lot of starters mix contentType with dataType. The contentType represents the type of the request body. The dataType represents the (expected) type of the response body, which is usually unnecessary as jQuery already autodetects it based on response's Content-Type header.

Then, in order to process the JSON object in the servlet which isn't being sent as individual request parameters but as a whole JSON string the above way, you only need to manually parse the request body using a JSON tool instead of using getParameter() the usual way. Namely, servlets don't support application/json formatted requests, but only application/x-www-form-urlencoded or multipart/form-data formatted requests. Gson also supports parsing a JSON string into a JSON object.

JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
String foo = data.get("foo").getAsString();
String bar = data.get("bar").getAsString();
String baz = data.get("baz").getAsString();
// ...

Do note that this all is more clumsy than just using $.param(). Normally, you want to use JSON.stringify() only if the target service is e.g. a JAX-RS (RESTful) service which is for some reason only capable of consuming JSON strings and not regular request parameters.

Sending a redirect from servlet

Important to realize and understand is that any sendRedirect() and forward() call by the servlet on an ajax request would only forward or redirect the ajax request itself and not the main document/window where the ajax request originated. JavaScript/jQuery would in such case only retrieve the redirected/forwarded response as responseText variable in the callback function. If it represents a whole HTML page and not an ajax-specific XML or JSON response, then all you could do is to replace the current document with it.

document.open();
document.write(responseText);
document.close();

Note that this doesn't change the URL as enduser sees in browser's address bar. So there are issues with bookmarkability. Therefore, it's much better to just return an "instruction" for JavaScript/jQuery to perform a redirect instead of returning the whole content of the redirected page. E.g. by returning a boolean, or an URL.

String redirectURL = "http://example.com";

Map<String, String> data = new HashMap<>();
data.put("redirect", redirectURL);
String json = new Gson().toJson(data);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
function(responseJson) {
    if (responseJson.redirect) {
        window.location = responseJson.redirect;
        return;
    }

    // ...
}

See also:

find all the name using mysql query which start with the letter 'a'

One can also use RLIKE as below

SELECT * FROM artists WHERE name RLIKE '^[abc]';

don't fail jenkins build if execute shell fails

You can use the Text-finder Plugin. It will allow you to check the output console for an expression of your choice then mark the build as Unstable.

How can I add some small utility functions to my AngularJS application?

You can also use the constant service as such. Defining the function outside of the constant call allows it to be recursive as well.

function doSomething( a, b ) {
    return a + b;
};

angular.module('moduleName',[])
    // Define
    .constant('$doSomething', doSomething)
    // Usage
    .controller( 'SomeController', function( $doSomething ) {
        $scope.added = $doSomething( 100, 200 );
    })
;

How to add many functions in ONE ng-click?

ng-click "$watch(edit($index), open())"

TortoiseGit-git did not exit cleanly (exit code 1)

For me it was due to insufficient disk space , and it was resolved after I freed up some disk space on my local drive.

android.content.Context.getPackageName()' on a null object reference

In my case the error occurred inside a Fragment on this line:

Intent intent = new Intent(getActivity(), SecondaryActivity.class);

It happened when I double clicked on an item which triggered the code above so two SecondaryActivity.class activities were launched at the same time, one on top of the other. I closed the top SecondaryActivity.class activity by pressing back button which triggered a call to getActivity() in the SecondaryActivity.class which came to foreground. The call to getActivity() returned null. It's some kind of weird Android bug so it usually should not happen. You can block the clicks after the user clicked once.

Conditional step/stage in Jenkins pipeline

According to other answers I am adding the parallel stages scenario:

pipeline {
    agent any
    stages {
        stage('some parallel stage') {
            parallel {
                stage('parallel stage 1') {
                    when {
                      expression { ENV == "something" }
                    }
                    steps {
                        echo 'something'
                    }
                }
                stage('parallel stage 2') {
                    steps {
                        echo 'something'
                    }
                }
            }
        }
    }
}

How to set python variables to true or false?

you have to use capital True and False not true and false

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Just change your line of code to

<a href="~/Required/[email protected]">Edit</a>

from where you are calling this function that will pass corect id

How to stop event bubbling on checkbox click

In angularjs this should works:

event.preventDefault(); 
event.stopPropagation();

How do I detect whether a Python variable is a function?

Here's a couple of other ways:

def isFunction1(f) :
    return type(f) == type(lambda x: x);

def isFunction2(f) :
    return 'function' in str(type(f));

Here's how I came up with the second:

>>> type(lambda x: x);
<type 'function'>
>>> str(type(lambda x: x));
"<type 'function'>"
# Look Maa, function! ... I ACTUALLY told my mom about this!

How to parse json string in Android?

Use JSON classes for parsing e.g

JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String  uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");

JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....

Check if input is number or letter javascript

A better(error-free) code would be like:

function isReallyNumber(data) {
    return typeof data === 'number' && !isNaN(data);
}

This will handle empty strings as well. Another reason, isNaN("12") equals to false but "12" is a string and not a number, so it should result to true. Lastly, a bonus link which might interest you.

How to see the actual Oracle SQL statement that is being executed

On the data dictionary side there are a lot of tools you can use to such as Schema Spy

To look at what queries are running look at views sys.v_$sql and sys.v_$sqltext. You will also need access to sys.all_users

One thing to note that queries that use parameters will show up once with entries like

and TABLETYPE=’:b16’

while others that dont will show up multiple times such as:

and TABLETYPE=’MT’

An example of these tables in action is the following SQL to find the top 20 diskread hogs. You could change this by removing the WHERE rownum <= 20 and maybe add ORDER BY module. You often find the module will give you a bog clue as to what software is running the query (eg: "TOAD 9.0.1.8", "JDBC Thin Client", "runcbl@somebox (TNS V1-V3)" etc)

SELECT 
 module, 
 sql_text, 
 username, 
 disk_reads_per_exec, 
 buffer_gets, 
 disk_reads, 
 parse_calls, 
 sorts, 
 executions, 
 rows_processed, 
 hit_ratio, 
 first_load_time, 
 sharable_mem, 
 persistent_mem, 
 runtime_mem, 
 cpu_time, 
 elapsed_time, 
 address, 
 hash_value 
FROM 
  (SELECT
   module, 
   sql_text , 
   u.username , 
   round((s.disk_reads/decode(s.executions,0,1, s.executions)),2)  disk_reads_per_exec, 
   s.disk_reads , 
   s.buffer_gets , 
   s.parse_calls , 
   s.sorts , 
   s.executions , 
   s.rows_processed , 
   100 - round(100 *  s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio, 
   s.first_load_time , 
   sharable_mem , 
   persistent_mem , 
   runtime_mem, 
   cpu_time, 
   elapsed_time, 
   address, 
   hash_value 
  FROM
   sys.v_$sql s, 
   sys.all_users u 
  WHERE
   s.parsing_user_id=u.user_id 
   and UPPER(u.username) not in ('SYS','SYSTEM') 
  ORDER BY
   4 desc) 
WHERE
 rownum <= 20;

Note that if the query is long .. you will have to query v_$sqltext. This stores the whole query. You will have to look up the ADDRESS and HASH_VALUE and pick up all the pieces. Eg:

SELECT
 *
FROM
 sys.v_$sqltext
WHERE
 address = 'C0000000372B3C28'
 and hash_value = '1272580459'
ORDER BY 
 address, hash_value, command_type, piece
;

Developing C# on Linux

Mono Develop is what you want, if you have used visual studio you should find it simple enough to get started.

If I recall correctly you should be able to install with sudo apt-get install monodevelop

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

Use the Take method:

var foo = (from t in MyTable
           select t.Foo).Take(10);

In VB LINQ has a take expression:

Dim foo = From t in MyTable _
          Take 10 _
          Select t.Foo

From the documentation:

Take<TSource> enumerates source and yields elements until count elements have been yielded or source contains no more elements. If count exceeds the number of elements in source, all elements of source are returned.

Returning Promises from Vuex actions

TL:DR; return promises from you actions only when necessary, but DRY chaining the same actions.

For a long time I also though that returning actions contradicts the Vuex cycle of uni-directional data flow.

But, there are EDGE CASES where returning a promise from your actions might be "necessary".

Imagine a situation where an action can be triggered from 2 different components, and each handles the failure case differently. In that case, one would need to pass the caller component as a parameter to set different flags in the store.

Dumb example

Page where the user can edit the username in navbar and in /profile page (which contains the navbar). Both trigger an action "change username", which is asynchronous. If the promise fails, the page should only display an error in the component the user was trying to change the username from.

Of course it is a dumb example, but I don't see a way to solve this issue without duplicating code and making the same call in 2 different actions.

How can I add a Google search box to my website?

Figured it out, folks! for the NAME of the text box, you have to use "q". I had "g" just for my own personal preferences. But apparently it has to be "q".

Anyone know why?

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

Just an addition to nicktea's answer. This code loads the content of a remote page (without redirecting there), and also cleans up when closing it.

<script type="text/javascript">
    function showDialog() {
        $('<div>').dialog({
            modal: true,
            open: function () {
                $(this).load('AccessRightsConfig.htm');
            },
            close: function(event, ui) {
                    $(this).remove();
                },
            height: 400,
            width: 600,
            title: 'Ajax Page'
        });

        return false;
    }
</script>

Alter user defined type in SQL Server

As devio says there is no way to simply edit a UDT if it's in use.

A work-round through SMS that worked for me was to generate a create script and make the appropriate changes; rename the existing UDT; run the create script; recompile the related sprocs and drop the renamed version.

Custom Listview Adapter with filter Android

please check below code it will help you

DrawerActivity.userListview
            .setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    int pos = position;
                    Intent intent = new Intent(getContext(),
                            UserDetail.class);
                    intent.putExtra("model", list.get(position));
                    context.startActivity(intent);
                }
            });
    return convertView;
}

@Override
public android.widget.Filter getFilter() {

    return new android.widget.Filter() {

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {

            ArrayList<UserListModel> updatelist = (ArrayList<UserListModel>) results.values;
            UserListCustomAdaptor newadaptor = new UserListCustomAdaptor(
                    getContext(), getCount(), updatelist);

            if (results.equals(constraint)) {
                updatelist.add(modelobj);
            }
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {

                notifyDataSetInvalidated();
            }
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults filterResults = new FilterResults();
            list = new ArrayList<UserListModel>();

            if (constraint != null && DrawerActivity.userlist != null) {

                constraint = constraint.toString().toLowerCase();
                int length = DrawerActivity.userlist.size();
                int i = 0;
                while (i < length) {

                    UserListModel modelobj = DrawerActivity.userlist.get(i);
                    String data = modelobj.getFirstName() + " "
                            + modelobj.getLastName();
                    if (data.toLowerCase().contains(constraint.toString())) {
                        list.add(modelobj);
                    }

                    i++;
                }
                filterResults.values = list;
                filterResults.count = list.size();
            }
            return filterResults;
        }
    };
}

@Override
public int getCount() {
    return list.size();
}

@Override
public UserListModel getItem(int position) {

    return list.get(position);
}

How can I specify my .keystore file with Spring Boot and Tomcat?

Starting with Spring Boot 1.2, you can configure SSL using application.properties or application.yml. Here's an example for application.properties:

server.port = 8443
server.ssl.key-store = classpath:keystore.jks
server.ssl.key-store-password = secret
server.ssl.key-password = another-secret

Same thing with application.yml:

server:
  port: 8443
  ssl:
    key-store: classpath:keystore.jks
    key-store-password: secret
    key-password: another-secret

Here's a link to the current reference documentation.

How to coerce a list object to type 'double'

In this case a loop will also do the job (and is usually sufficiently fast).

a <- array(0, dim=dim(X))
for (i in 1:ncol(X)) {a[,i] <- X[,i]}

Date / Timestamp to record when a record was added to the table?

You can create a non-nullable DATETIME column on your table, and create a DEFAULT constraint on it to auto populate when a row is added.

e.g.

CREATE TABLE Example
(
SomeField INTEGER,
DateCreated DATETIME NOT NULL DEFAULT(GETDATE())
)

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

Git:nothing added to commit but untracked files present

If you have already tried using the git add . command to add all your untracked files, make sure you're not under a subfolder of your root project.

git add . will stage all your files under the current subfolder.

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

The JAX-WS dependency library “jaxws-rt.jar” is missing.

Go here http://jax-ws.java.net/. Download JAX-WS RI distribution. Unzip it and copy “jaxws-rt.jar” to Tomcat library folder “{$TOMCAT}/lib“. Restart Tomcat.

MVC razor form with multiple different submit buttons?

This elegant solution works for number of submit buttons:

@Html.Begin()
{
  // Html code here
  <input type="submit" name="command" value="submit1" />
  <input type="submit" name="command" value="submit2" />

}

And in your controllers' action method accept it as a parameter.

public ActionResult Create(Employee model, string command)
{
    if(command.Equals("submit1"))
    {
      // Call action here...
    }
    else
    {
      // Call another action here...
    }
}

Passing data between different controller action methods

Have you tried using ASP.NET MVC TempData ?

ASP.NET MVC TempData dictionary is used to share data between controller actions. The value of TempData persists until it is read or until the current user’s session times out. Persisting data in TempData is useful in scenarios such as redirection, when values are needed beyond a single request.

The code would be something like this:

[HttpPost]
public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
{
    XDocument updatedResultsDocument = myService.UpdateApplicationPools();
    TempData["doc"] = updatedResultsDocument;
    return RedirectToAction("UpdateConfirmation");
}

And in the ApplicationPoolController:

public ActionResult UpdateConfirmation()
{
    if (TempData["doc"] != null)
    {
        XDocument updatedResultsDocument = (XDocument) TempData["doc"];
            ...
        return View();
    }
}

How to check if an element is in an array

Here is my little extension I just wrote to check if my delegate array contains a delegate object or not (Swift 2). :) It Also works with value types like a charm.

extension Array
{
    func containsObject(object: Any) -> Bool
    {
        if let anObject: AnyObject = object as? AnyObject
        {
            for obj in self
            {
                if let anObj: AnyObject = obj as? AnyObject
                {
                    if anObj === anObject { return true }
                }
            }
        }
        return false
    }
}

If you have an idea how to optimize this code, than just let me know.

Using android.support.v7.widget.CardView in my project (Eclipse)

From: https://developer.android.com/tools/support-library/setup.html#libs-with-res

Adding libraries with resources To add a Support Library with resources (such as v7 appcompat for action bar) to your application project:

Using Eclipse

Create a library project based on the support library code:

  • Make sure you have downloaded the Android Support Library using the SDK Manager.

  • Create a library project and ensure the required JAR files are included in the project's build path:

  • Select File > Import.

  • Select Existing Android Code Into Workspace and click Next.

  • Browse to the SDK installation directory and then to the Support Library folder. For example, if you are adding the appcompat project, browse to /extras/android/support/v7/appcompat/.

  • Click Finish to import the project. For the v7 appcompat project, you should now see a new project titled android-support-v7-appcompat.

  • In the new library project, expand the libs/ folder, right-click each .jar file and select Build

  • Path > Add to Build Path. For example, when creating the the v7 appcompat project, add both the android-support-v4.jar and android-support-v7-appcompat.jar files to the build path.

  • Right-click the library project folder and select Build Path > Configure Build Path.

  • In the Order and Export tab, check the .jar files you just added to the build path, so they are available to projects that depend on this library project. For example, the appcompat project requires you to export both the android-support-v4.jar and android-support-v7-appcompat.jar files.

  • Uncheck Android Dependencies.

  • Click OK to complete the changes.

  • You now have a library project for your selected Support Library that you can use with one or more application projects.

  • Add the library to your application project:

  • In the Project Explorer, right-click your project and select Properties.

  • In the category panel on the left side of the dialog, select Android.

  • In the Library pane, click the Add button.

  • Select the library project and click OK. For example, the appcompat project should be listed as android-support-v7-appcompat.

  • In the properties window, click OK.

When a 'blur' event occurs, how can I find out which element focus went *to*?

Use something like this:

var myVar = null;

And then inside your function:

myVar = fldID;

And then:

setTimeout(setFocus,1000)

And then:

function setFocus(){ document.getElementById(fldID).focus(); }

Final code:

<html>
<head>
    <script type="text/javascript">
        function somefunction(){
            var myVar = null;

            myVar = document.getElementById('myInput');

            if(myVar.value=='')
                setTimeout(setFocusOnJobTitle,1000);
            else
                myVar.value='Success';
        }
        function setFocusOnJobTitle(){
            document.getElementById('myInput').focus();
        }
    </script>
</head>
<body>
<label id="jobTitleId" for="myInput">Job Title</label>
<input id="myInput" onblur="somefunction();"></input>
</body>
</html>

How to embed fonts in CSS?

One of the best source of information on this topic is Paul Irish's Bulletproof @font-face syntax article.

Read it and you will end with something like:

/* definition */
@font-face {
  font-family: EntezareZohoor2;
  src: url('fonts/EntezareZohoor2.eot');
  src: url('fonts/EntezareZohoor2.eot?') format('?'),
       url('fonts/EntezareZohoor2.woff') format('woff'),
       url('fonts/EntezareZohoor2.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

/* use */
body {
    font-family: EntezareZohoor2, Tahoma, serif;
}

How to make <div> fill <td> height

CSS height: 100% only works if the element's parent has an explicitly defined height. For example, this would work as expected:

td {
    height: 200px;
}

td div {
    /* div will now take up full 200px of parent's height */
    height: 100%;
}

Since it seems like your <td> is going to be variable height, what if you added the bottom right icon with an absolutely positioned image like so:

.thatSetsABackgroundWithAnIcon {
    /* Makes the <div> a coordinate map for the icon */
    position: relative;

    /* Takes the full height of its parent <td>.  For this to work, the <td>
       must have an explicit height set. */
    height: 100%;
}

.thatSetsABackgroundWithAnIcon .theIcon {        
    position: absolute;
    bottom: 0;
    right: 0;
}

With the table cell markup like so:

<td class="thatSetsABackground">  
  <div class="thatSetsABackgroundWithAnIcon">    
    <dl>
      <dt>yada
      </dt>
      <dd>yada
      </dd>
    </dl>
    <img class="theIcon" src="foo-icon.png" alt="foo!"/>
  </div>
</td>

Edit: using jQuery to set div's height

If you keep the <div> as a child of the <td>, this snippet of jQuery will properly set its height:

// Loop through all the div.thatSetsABackgroundWithAnIcon on your page
$('div.thatSetsABackgroundWithAnIcon').each(function(){
    var $div = $(this);

    // Set the div's height to its parent td's height
    $div.height($div.closest('td').height());
});

The Import android.support.v7 cannot be resolved

I tried the answer described here but it doesn´t worked for me. I have the last Android SDK tools ver. 23.0.2 and Android SDK Platform-tools ver. 20

The support library android-support-v4.jar is causing this conflict, just delete the library under /libs folder of your project, don´t be scared, the library is already contained in the library appcompat_v7, clean and build your project, and your project will work like a charm!

enter image description here

Setting up a websocket on Apache?

I struggled to understand the proxy settings for websockets for https therefore let me put clarity here what i realized.

First you need to enable proxy and proxy_wstunnel apache modules and the apache configuration file will look like this.

<IfModule mod_ssl.c>
    <VirtualHost _default_:443>
      ServerName www.example.com
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/your_project_public_folder

      SSLEngine on
      SSLCertificateFile    /etc/ssl/certs/path_to_your_ssl_certificate
      SSLCertificateKeyFile /etc/ssl/private/path_to_your_ssl_key

      <Directory /var/www/your_project_public_folder>
              Options Indexes FollowSymLinks
              AllowOverride All
              Require all granted
              php_flag display_errors On
      </Directory>
      ProxyRequests Off 
      ProxyPass /wss/  ws://example.com:port_no

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
</IfModule>

in your frontend application use the url "wss://example.com/wss/" this is very important mostly if you are stuck with websockets you might be making mistake in the front end url. You probably putting url wrongly like below.

wss://example.com:8080/wss/ -> port no should not be mentioned
ws://example.com/wss/ -> url should start with wss only.
wss://example.com/wss -> url should end with / -> most important

also interesting part is the last /wss/ is same as proxypass value if you writing proxypass /ws/ then in the front end you should write /ws/ in the end of url.

Matlab: Running an m-file from command-line

I think that one important point that was not mentioned in the previous answers is that, if not explicitly indicated, the matlab interpreter will remain open. Therefore, to the answer of @hkBattousai I will add the exit command:

"C:\<a long path here>\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\<a long path here>\mfile.m');exit;"

ArrayBuffer to base64 encoded string

By my side, using Chrome navigator, I had to use DataView() to read an arrayBuffer

function _arrayBufferToBase64( tabU8A ) {
var binary = '';
let lecteur_de_donnees = new DataView(tabU8A);
var len = lecteur_de_donnees.byteLength;
var chaine = '';
var pos1;
for (var i = 0; i < len; i++) {
    binary += String.fromCharCode( lecteur_de_donnees.getUint8( i ) );
}
chaine = window.btoa( binary )
return chaine;}

git pull aborted with error filename too long

A few years late, but I'd like to add that if you need to do this in one fell swoop (like I did) you can set the config settings during the clone command. Try this:

git clone -c core.longpaths=true <your.url.here>

How to redirect siteA to siteB with A or CNAME records

I think several of the answers hit around the possible solution to your problem.

I agree the easiest (and best solution for SEO purposes) is the 301 redirect. In IIS this is fairly trivial, you'd create a site for subdomain.hostone.com, after creating the site, right-click on the site and go into properties. Click on the "Home Directory" tab of the site properties window that opens. Select the radio button "A redirection to a URL", enter the url for the new site (http://subdomain.hosttwo.com), and check the checkboxes for "The exact URL entered above", "A permanent redirection for this resource" (this second checkbox causes a 301 redirect, instead of a 302 redirect). Click OK, and you're done.

Or you could create a page on the site of http://subdomain.hostone.com, using one of the following methods (depending on what the hosting platform supports)

PHP Redirect:


<?
Header( "HTTP/1.1 301 Moved Permanently" ); 
Header( "Location: http://subdomain.hosttwo.com" ); 
?>

ASP Redirect:


<%@ Language=VBScript %>
<%
Response.Status="301 Moved Permanently"
Response.AddHeader "Location","http://subdomain.hosttwo.com"
%>

ASP .NET Redirect:


<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://subdomain.hosttwo.com");
}
</script>

Now assuming your CNAME record is correctly created, then the only problem you are experiencing is that the site created for http://subdomain.hosttwo.com is using a shared IP, and host headers to determine which site should be displayed. To resolve this issue under IIS, in IIS Manager on the web server, you'd right-click on the site for subdomain.hosttwo.com, and click "Properties". On the displayed "Web Site" tab, you should see an "Advanced" button next to the IP address that you'll need to click. On the "Advanced Web Site Identification" window that appears, click "Add". Select the same IP address that is already being used by subdomain.hosttwo.com, enter 80 as the TCP port, and then enter subdomain.hosttwo.com as the Host Header value. Click OK until you are back to the main IIS Manager window, and you should be good to go. Open a browser, and browse to http://subdomain.hostone.com, and you'll see the site at http://subdomain.hosttwo.com appear, even though your URL shows http://subdomain.hostone.com

Hope that helps...

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

In Java 8 we can solve it as:

String str = "xyz";
str.chars().forEachOrdered(i -> System.out.print((char)i));
str.codePoints().forEachOrdered(i -> System.out.print((char)i));

The method chars() returns an IntStream as mentioned in doc:

Returns a stream of int zero-extending the char values from this sequence. Any char which maps to a surrogate code point is passed through uninterpreted. If the sequence is mutated while the stream is being read, the result is undefined.

The method codePoints() also returns an IntStream as per doc:

Returns a stream of code point values from this sequence. Any surrogate pairs encountered in the sequence are combined as if by Character.toCodePoint and the result is passed to the stream. Any other code units, including ordinary BMP characters, unpaired surrogates, and undefined code units, are zero-extended to int values which are then passed to the stream.

How is char and code point different? As mentioned in this article:

Unicode 3.1 added supplementary characters, bringing the total number of characters to more than the 2^16 = 65536 characters that can be distinguished by a single 16-bit char. Therefore, a char value no longer has a one-to-one mapping to the fundamental semantic unit in Unicode. JDK 5 was updated to support the larger set of character values. Instead of changing the definition of the char type, some of the new supplementary characters are represented by a surrogate pair of two char values. To reduce naming confusion, a code point will be used to refer to the number that represents a particular Unicode character, including supplementary ones.

Finally why forEachOrdered and not forEach ?

The behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept. Also check this question for more.

For difference between a character, a code point, a glyph and a grapheme check this question.

PHP compare two arrays and get the matched values not the difference

I think the better answer for this questions is

array_diff() 

because it Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays.

Whereas

array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved.

How to enter newline character in Oracle?

begin   
   dbms_output.put_line( 'hello' ||chr(13) || chr(10) || 'world' );
end;

Iterating through struct fieldnames in MATLAB

You can use the for each toolbox from http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each.

>> signal
signal = 
sin: {{1x1x25 cell}  {1x1x25 cell}}
cos: {{1x1x25 cell}  {1x1x25 cell}}

>> each(fieldnames(signal))
ans = 
CellIterator with properties:

NumberOfIterations: 2.0000e+000

Usage:

for bridge = each(fieldnames(signal))
   signal.(bridge) = rand(10);
end

I like it very much. Credit of course go to Jeremy Hughes who developed the toolbox.

WHERE vs HAVING

The main difference is that WHERE cannot be used on grouped item (such as SUM(number)) whereas HAVING can.

The reason is the WHERE is done before the grouping and HAVING is done after the grouping is done.

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

The JD-eclipse plugin 0.1.3 can only decompile .class files that are visible from the classpath/Build Path.

If your class resides in a .jar, you may simply add this jar to the Build Path as another library. From the Package Explorer browse your new library and open the class in the Class File Editor.

If you want to decompile any class on the file system, it has to reside in the appropriate folder hierachy, and the root folder has to be included in the build path. Here is an example:

  1. Class is foo.bar.MyClass in .../someDir/foo/bar/MyClass.class
  2. In your Eclipse project, add a folder with arbitrary name aClassDir, which links to .../someDir.
  3. Add that linked folder to the Build Path of the project.
  4. Use the Navigator View to navigate and open the .class file in the Class File Editor. (Note: Plain .class files on the file system are hidden in the Package Explorer view.)

Note: If someDir is a subfolder of your project, you might be able to skip step 2 (link folder) and add it directly to the Build Path. But that does not work, if it is the compiler output folder of the Eclipse project.

P.S. I wish I could just double click any .class file in any project subfolder without the need to have it in the classpath...

How to set DOM element as the first child?

I think you're looking for the .prepend function in jQuery. Example code:

$("#E").prepend("<p>Code goes here, yo!</p>");

Temporary table in SQL server causing ' There is already an object named' error

You are dropping it, then creating it, then trying to create it again by using SELECT INTO. Change to:

DROP TABLE #TMPGUARDIAN
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))  

INSERT INTO #TMPGUARDIAN 
SELECT LAST_NAME,FRST_NAME  
FROM TBL_PEOPLE

In MS SQL Server you can create a table without a CREATE TABLE statement by using SELECT INTO

Converting Go struct to JSON

You can define your own custom MarshalJSON and UnmarshalJSON methods and intentionally control what should be included, ex:

package main

import (
    "fmt"
    "encoding/json"
)

type User struct {
    name string
}

func (u *User) MarshalJSON() ([]byte, error) {
    return json.Marshal(&struct {
        Name     string `json:"name"`
    }{
        Name:     "customized" + u.name,
    })
}

func main() {
    user := &User{name: "Frank"}
    b, err := json.Marshal(user)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

Who is listening on a given TCP port on Mac OS X?

This is a good way on macOS High Sierra:

netstat -an |grep -i listen

How do I sort a two-dimensional (rectangular) array in C#?

Can I check - do you mean a rectangular array ([,])or a jagged array ([][])?

It is quite easy to sort a jagged array; I have a discussion on that here. Obviously in this case the Comparison<T> would involve a column instead of sorting by ordinal - but very similar.

Sorting a rectangular array is trickier... I'd probably be tempted to copy the data out into either a rectangular array or a List<T[]>, and sort there, then copy back.

Here's an example using a jagged array:

static void Main()
{  // could just as easily be string...
    int[][] data = new int[][] { 
        new int[] {1,2,3}, 
        new int[] {2,3,4}, 
        new int[] {2,4,1} 
    }; 
    Sort<int>(data, 2); 
} 
private static void Sort<T>(T[][] data, int col) 
{ 
    Comparer<T> comparer = Comparer<T>.Default;
    Array.Sort<T[]>(data, (x,y) => comparer.Compare(x[col],y[col])); 
} 

For working with a rectangular array... well, here is some code to swap between the two on the fly...

static T[][] ToJagged<T>(this T[,] array) {
    int height = array.GetLength(0), width = array.GetLength(1);
    T[][] jagged = new T[height][];

    for (int i = 0; i < height; i++)
    {
        T[] row = new T[width];
        for (int j = 0; j < width; j++)
        {
            row[j] = array[i, j];
        }
        jagged[i] = row;
    }
    return jagged;
}
static T[,] ToRectangular<T>(this T[][] array)
{
    int height = array.Length, width = array[0].Length;
    T[,] rect = new T[height, width];
    for (int i = 0; i < height; i++)
    {
        T[] row = array[i];
        for (int j = 0; j < width; j++)
        {
            rect[i, j] = row[j];
        }
    }
    return rect;
}
// fill an existing rectangular array from a jagged array
static void WriteRows<T>(this T[,] array, params T[][] rows)
{
    for (int i = 0; i < rows.Length; i++)
    {
        T[] row = rows[i];
        for (int j = 0; j < row.Length; j++)
        {
            array[i, j] = row[j];
        }
    }
}

Detecting input change in jQuery?

// .blur is triggered when element loses focus

$('#target').blur(function() {
  alert($(this).val());
});

// To trigger manually use:

$('#target').blur();

SQL Query To Obtain Value that Occurs more than once

SELECT LASTNAME, COUNT(*)
FROM STUDENTS
GROUP BY LASTNAME
ORDER BY COUNT(*) DESC

How to read Excel cell having Date with Apache POI?

Yes, I understood your problem. If is difficult to identify cell has Numeric or Data value.

If you want data in format that shows in Excel, you just need to format cell using DataFormatter class.

DataFormatter dataFormatter = new DataFormatter();
String cellStringValue = dataFormatter.formatCellValue(row.getCell(0));
System.out.println ("Is shows data as show in Excel file" + cellStringValue);  // Here it automcatically format data based on that cell format.
// No need for extra efforts 

String or binary data would be truncated. The statement has been terminated

SQL Server 2016 SP2 CU6 and SQL Server 2017 CU12 introduced trace flag 460 in order to return the details of truncation warnings. You can enable it at the query level or at the server level.

Query level

INSERT INTO dbo.TEST (ColumnTest)
VALUES (‘Test truncation warnings’)
OPTION (QUERYTRACEON 460);
GO

Server Level

DBCC TRACEON(460, -1);
GO

From SQL Server 2019 you can enable it at database level:

ALTER DATABASE SCOPED CONFIGURATION 
SET VERBOSE_TRUNCATION_WARNINGS = ON;

The old output message is:

Msg 8152, Level 16, State 30, Line 13
String or binary data would be truncated.
The statement has been terminated.

The new output message is:

Msg 2628, Level 16, State 1, Line 30
String or binary data would be truncated in table 'DbTest.dbo.TEST', column 'ColumnTest'. Truncated value: ‘Test truncation warnings‘'.

In a future SQL Server 2019 release, message 2628 will replace message 8152 by default.

Validate phone number with JavaScript

Simple Regular expression: /\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g

Check out the format, hope it works :
444-555-1234
f:246.555.8888
m:1235554567

HTML5 input type range show range value

if you still looking for the answer you can use input type="number" in place of type="range" min max work if it set in that order:
1-name
2-maxlength
3-size
4-min
5-max
just copy it

<input  name="X" maxlength="3" size="2" min="1" max="100" type="number" />

How to make a function wait until a callback has been called using node.js

If you want it very simple and easy, no fancy libraries, to wait for callback functions to be executed in node, before executing some other code, is like this:

//initialize a global var to control the callback state
var callbackCount = 0;
//call the function that has a callback
someObj.executeCallback(function () {
    callbackCount++;
    runOtherCode();
});
someObj2.executeCallback(function () {
    callbackCount++;
    runOtherCode();
});

//call function that has to wait
continueExec();

function continueExec() {
    //here is the trick, wait until var callbackCount is set number of callback functions
    if (callbackCount < 2) {
        setTimeout(continueExec, 1000);
        return;
    }
    //Finally, do what you need
    doSomeThing();
}

TSQL How do you output PRINT in a user defined function?

Use extended procedure xp_cmdshell to run a shell command. I used it to print output to a file:

exec xp_cmdshell 'echo "mytextoutput" >> c:\debuginfo.txt'

This creates the file debuginfo.txt if it does not exist. Then it adds the text "mytextoutput" (without quotation marks) to the file. Any call to the function will write an additional line.

You may need to enable this db-server property first (default = disabled), which I realize may not be to the liking of dba's for production environments though.

How does origin/HEAD get set?

Remember there are two independent git repos we are talking about. Your local repo with your code and the remote running somewhere else.

Your are right, when you change a branch, HEAD points to your current branch. All of this is happening on your local git repo. Not the remote repo, which could be owned by another developer, or siting on a sever in your office, or github, or another directory on the filesystem, or etc...

Your computer (local repo) has no business changing the HEAD pointer on the remote git repo. It could be owned by a different developer for example.

One more thing, what your computer calls origin/XXX is your computer's understanding of the state of the remote at the time of the last fetch.

So what would "organically" update origin/HEAD? It would be activity on the remote git repo. Not your local repo.

People have mentioned

git symbolic-ref HEAD refs/head/my_other_branch

Normally, that is used when there is a shared central git repo on a server for use by the development team. It would be a command executed on the remote computer. You would see this as activity on the remote git repo.

Download a file with Android, and showing the progress in a ProgressDialog

Use Android Query library, very cool indeed.You can change it to use ProgressDialog as you see in other examples, this one will show progress view from your layout and hide it after completion.

File target = new File(new File(Environment.getExternalStorageDirectory(), "ApplicationName"), "tmp.pdf");
new AQuery(this).progress(R.id.progress_view).download(_competition.qualificationScoreCardsPdf(), target, new AjaxCallback<File>() {
    public void callback(String url, File file, AjaxStatus status) {
        if (file != null) {
            // do something with file  
        } 
    }
});

Installing Apple's Network Link Conditioner Tool

  1. Remove "Network Link Conditioner", open "System Preferences", press CTRL and click the "Network Link Conditioner" icon. Select "Remove".
  2. Restart your computer
  3. Download the dmg "Hardware IO tools" for your XCode version from https://developer.apple.com/download/, you need to be logged in to do this.
  4. Open it and install "Network Link Conditioner"
  5. Restart your computer one last time.

Python nonlocal statement

Quote from the Python 3 Reference:

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.

As said in the reference, in case of several nested functions only variable in the nearest enclosing function is modified:

def outer():
    def inner():
        def innermost():
            nonlocal x
            x = 3

        x = 2
        innermost()
        if x == 3: print('Inner x has been modified')

    x = 1
    inner()
    if x == 3: print('Outer x has been modified')

x = 0
outer()
if x == 3: print('Global x has been modified')

# Inner x has been modified

The "nearest" variable can be several levels away:

def outer():
    def inner():
        def innermost():
            nonlocal x
            x = 3

        innermost()

    x = 1
    inner()
    if x == 3: print('Outer x has been modified')

x = 0
outer()
if x == 3: print('Global x has been modified')

# Outer x has been modified

But it cannot be a global variable:

def outer():
    def inner():
        def innermost():
            nonlocal x
            x = 3

        innermost()

    inner()

x = 0
outer()
if x == 3: print('Global x has been modified')

# SyntaxError: no binding for nonlocal 'x' found

How to run a method every X seconds

You can please try this code to call the handler every 15 seconds via onResume() and stop it when the activity is not visible, via onPause().

Handler handler = new Handler();
Runnable runnable;
int delay = 15*1000; //Delay for 15 seconds.  One second = 1000 milliseconds.


@Override
protected void onResume() {
   //start handler as activity become visible

    handler.postDelayed( runnable = new Runnable() {
        public void run() {
            //do something

            handler.postDelayed(runnable, delay);
        }
    }, delay);

    super.onResume();
}

// If onPause() is not included the threads will double up when you 
// reload the activity 

@Override
protected void onPause() {
    handler.removeCallbacks(runnable); //stop handler when activity not visible
    super.onPause();
}