text:
Q: Failed to fetch security undetermined error [IP: 91.189.91.38 80] in Ubuntu 20.04 First I ran sudo apt update and sudo apt update worked fine, but after running sudo apt upgrade I got the below error.
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following NEW packages will be installed:
  linux-headers-5.4.0-59 linux-headers-5.4.0-59-generic linux-image-5.4.0-59-generic linux-modules-5.4.0-59-generic linux-modules-extra-5.4.0-59-generic
The following packages will be upgraded:
  libasound2 libasound2-data libatopology2 libproxy1-plugin-gsettings libproxy1-plugin-networkmanager libproxy1v5 linux-generic-hwe-20.04 linux-headers-generic-hwe-20.04
  linux-image-generic-hwe-20.04 linux-libc-dev nautilus-sendto python-apt-common python3-apt
13 upgraded, 5 newly installed, 0 to remove and 0 not upgraded.
Need to get 72.5 kB/76.0 MB of archives.
After this operation, 360 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://in.archive.ubuntu.com/ubuntu focal-updates/main amd64 libproxy1-plugin-networkmanager amd64 0.4.15-10ubuntu1.2 [5,284 B]
Ign:1 http://in.archive.ubuntu.com/ubuntu focal-updates/main amd64 libproxy1-plugin-networkmanager amd64 0.4.15-10ubuntu1.2
Get:2 http://in.archive.ubuntu.com/ubuntu focal-updates/main amd64 libproxy1-plugin-gsettings amd64 0.4.15-10ubuntu1.2 [18.1 kB]
Ign:2 http://in.archive.ubuntu.com/ubuntu focal-updates/main amd64 libproxy1-plugin-gsettings amd64 0.4.15-10ubuntu1.2
Get:3 http://in.archive.ubuntu.com/ubuntu focal-updates/main amd64 libproxy1v5 amd64 0.4.15-10ubuntu1.2 [49.1 kB]
Ign:3 http://in.archive.ubuntu.com/ubuntu focal-updates/main amd64 libproxy1v5 amd64 0.4.15-10ubuntu1.2
Get:1 http://security.ubuntu.com/ubuntu focal-updates/main amd64 libproxy1-plugin-networkmanager amd64 0.4.15-10ubuntu1.2 [5,284 B]
Err:1 http://security.ubuntu.com/ubuntu focal-updates/main amd64 libproxy1-plugin-networkmanager amd64 0.4.15-10ubuntu1.2
  Undetermined Error [IP: 91.189.88.152 80]
Get:2 http://security.ubuntu.com/ubuntu focal-updates/main amd64 libproxy1-plugin-gsettings amd64 0.4.15-10ubuntu1.2 [18.1 kB]
Err:2 http://security.ubuntu.com/ubuntu focal-updates/main amd64 libproxy1-plugin-gsettings amd64 0.4.15-10ubuntu1.2
  Undetermined Error [IP: 91.189.88.152 80]
Get:3 http://security.ubuntu.com/ubuntu focal-updates/main amd64 libproxy1v5 amd64 0.4.15-10ubuntu1.2 [49.1 kB]
Err:3 http://security.ubuntu.com/ubuntu focal-updates/main amd64 libproxy1v5 amd64 0.4.15-10ubuntu1.2
  Undetermined Error [IP: 91.189.88.152 80]
E: Failed to fetch http://security.ubuntu.com/ubuntu/pool/main/libp/libproxy/libproxy1-plugin-networkmanager_0.4.15-10ubuntu1.2_amd64.deb  Undetermined Error [IP: 91.189.88.152 80]
E: Failed to fetch http://security.ubuntu.com/ubuntu/pool/main/libp/libproxy/libproxy1-plugin-gsettings_0.4.15-10ubuntu1.2_amd64.deb  Undetermined Error [IP: 91.189.88.152 80]
E: Failed to fetch http://security.ubuntu.com/ubuntu/pool/main/libp/libproxy/libproxy1v5_0.4.15-10ubuntu1.2_amd64.deb  Undetermined Error [IP: 91.189.88.152 80]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

Results of cat /etc/apt/sources.list:
# deb cdrom:[Ubuntu 20.04.1 LTS _Focal Fossa_ - Release amd64 (20200731)]/ focal main restricted

# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
# newer versions of the distribution.
deb http://in.archive.ubuntu.com/ubuntu/ focal main restricted
# deb-src http://in.archive.ubuntu.com/ubuntu/ focal main restricted

## Major bug fix updates produced after the final release of the
## distribution.
deb http://in.archive.ubuntu.com/ubuntu/ focal-updates main restricted
# deb-src http://in.archive.ubuntu.com/ubuntu/ focal-updates main restricted

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team. Also, please note that software in universe WILL NOT receive any
## review or updates from the Ubuntu security team.
deb http://in.archive.ubuntu.com/ubuntu/ focal universe
# deb-src http://in.archive.ubuntu.com/ubuntu/ focal universe
deb http://in.archive.ubuntu.com/ubuntu/ focal-updates universe
# deb-src http://in.archive.ubuntu.com/ubuntu/ focal-updates universe

## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
## team, and may not be under a free licence. Please satisfy yourself as to
## your rights to use the software. Also, please note that software in
## multiverse WILL NOT receive any review or updates from the Ubuntu
## security team.
deb http://in.archive.ubuntu.com/ubuntu/ focal multiverse
# deb-src http://in.archive.ubuntu.com/ubuntu/ focal multiverse
deb http://in.archive.ubuntu.com/ubuntu/ focal-updates multiverse
# deb-src http://in.archive.ubuntu.com/ubuntu/ focal-updates multiverse

## N.B. software from this repository may not have been tested as
## extensively as that contained in the main release, although it includes
## newer versions of some applications which may provide useful features.
## Also, please note that software in backports WILL NOT receive any review
## or updates from the Ubuntu security team.
deb http://in.archive.ubuntu.com/ubuntu/ focal-backports main restricted universe multiverse
# deb-src http://in.archive.ubuntu.com/ubuntu/ focal-backports main restricted universe multiverse

## Uncomment the following two lines to add software from Canonical's
## 'partner' repository.
## This software is not part of Ubuntu, but is offered by Canonical and the
## respective vendors as a service to Ubuntu users.
# deb http://archive.canonical.com/ubuntu focal partner
# deb-src http://archive.canonical.com/ubuntu focal partner

deb http://security.ubuntu.com/ubuntu focal-security main restricted
# deb-src http://security.ubuntu.com/ubuntu focal-security main restricted
deb http://security.ubuntu.com/ubuntu focal-security universe
# deb-src http://security.ubuntu.com/ubuntu focal-security universe
deb http://security.ubuntu.com/ubuntu focal-security multiverse
# deb-src http://security.ubuntu.com/ubuntu focal-security multiverse

# This system was installed using small removable media
# (e.g. netinst, live or single CD). The matching "deb cdrom"
# entries were disabled at the end of the installation process.
# For information about how to configure apt package sources,
# see the sources.list(5) manual.

Results of sudo apt update --fix-missing:
Hit:1 http://archive.ubuntu.com/ubuntu focal InRelease
Hit:2 http://security.ubuntu.com/ubuntu focal-security InRelease
Hit:3 http://archive.ubuntu.com/ubuntu focal-updates InRelease
Reading package lists... Done
Building dependency tree
Reading state information... Done
13 packages can be upgraded. Run 'apt list --upgradable' to see them.

Results of sudo apt upgrade :
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following NEW packages will be installed:
  linux-headers-5.4.0-59 linux-headers-5.4.0-59-generic linux-image-5.4.0-59-generic linux-modules-5.4.0-59-generic linux-modules-extra-5.4.0-59-generic
The following packages will be upgraded:
  libasound2 libasound2-data libatopology2 libproxy1-plugin-gsettings libproxy1-plugin-networkmanager libproxy1v5 linux-generic-hwe-20.04 linux-headers-generic-hwe-20.04
  linux-image-generic-hwe-20.04 linux-libc-dev nautilus-sendto python-apt-common python3-apt
13 upgraded, 5 newly installed, 0 to remove and 0 not upgraded.
Need to get 72.5 kB/76.0 MB of archives.
After this operation, 360 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://security.ubuntu.com/ubuntu focal-security/main amd64 libproxy1-plugin-networkmanager amd64 0.4.15-10ubuntu1.2 [5,284 B]
Ign:1 http://security.ubuntu.com/ubuntu focal-security/main amd64 libproxy1-plugin-networkmanager amd64 0.4.15-10ubuntu1.2
Get:2 http://security.ubuntu.com/ubuntu focal-security/main amd64 libproxy1-plugin-gsettings amd64 0.4.15-10ubuntu1.2 [18.1 kB]
Ign:2 http://security.ubuntu.com/ubuntu focal-security/main amd64 libproxy1-plugin-gsettings amd64 0.4.15-10ubuntu1.2
Get:3 http://security.ubuntu.com/ubuntu focal-security/main amd64 libproxy1v5 amd64 0.4.15-10ubuntu1.2 [49.1 kB]
Ign:3 http://security.ubuntu.com/ubuntu focal-security/main amd64 libproxy1v5 amd64 0.4.15-10ubuntu1.2
Get:1 http://archive.ubuntu.com/ubuntu focal-security/main amd64 libproxy1-plugin-networkmanager amd64 0.4.15-10ubuntu1.2 [5,284 B]
Err:1 http://archive.ubuntu.com/ubuntu focal-security/main amd64 libproxy1-plugin-networkmanager amd64 0.4.15-10ubuntu1.2
  Undetermined Error [IP: 91.189.88.142 80]
Get:2 http://archive.ubuntu.com/ubuntu focal-security/main amd64 libproxy1-plugin-gsettings amd64 0.4.15-10ubuntu1.2 [18.1 kB]
Err:2 http://archive.ubuntu.com/ubuntu focal-security/main amd64 libproxy1-plugin-gsettings amd64 0.4.15-10ubuntu1.2
  Undetermined Error [IP: 91.189.88.142 80]
Get:3 http://archive.ubuntu.com/ubuntu focal-security/main amd64 libproxy1v5 amd64 0.4.15-10ubuntu1.2 [49.1 kB]
Err:3 http://archive.ubuntu.com/ubuntu focal-security/main amd64 libproxy1v5 amd64 0.4.15-10ubuntu1.2
  Undetermined Error [IP: 91.189.88.142 80]
E: Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/libp/libproxy/libproxy1-plugin-networkmanager_0.4.15-10ubuntu1.2_amd64.deb  Undetermined Error [IP: 91.189.88.142 80]
E: Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/libp/libproxy/libproxy1-plugin-gsettings_0.4.15-10ubuntu1.2_amd64.deb  Undetermined Error [IP: 91.189.88.142 80]
E: Failed to fetch http://archive.ubuntu.com/ubuntu/pool/main/libp/libproxy/libproxy1v5_0.4.15-10ubuntu1.2_amd64.deb  Undetermined Error [IP: 91.189.88.142 80]
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

A: Taken from the comment by @krisna-kakade.
The following worked for me with no further action required.
sudo apt update --fix-missing
sudo apt upgrade

A: Revert your repositories list to the original Ubuntu Focal list by running the following command in the terminal:
sudo nano /etc/apt/sources.list

A file editor will be opened. Delete all the lines in it and then copy and paste the following in the file editor:
deb http://archive.ubuntu.com/ubuntu focal main universe multiverse restricted
deb http://security.ubuntu.com/ubuntu/ focal-security main multiverse universe restricted
deb http://archive.ubuntu.com/ubuntu focal-updates main multiverse universe restricted

Then, save and close the file by pressing Ctrl + X then press Y then press Enter
To verify you saved the file correctly, please run the following command in the terminal:
cat /etc/apt/sources.list

The output should be exactly:
deb http://archive.ubuntu.com/ubuntu focal main universe multiverse restricted
deb http://security.ubuntu.com/ubuntu/ focal-security main multiverse universe restricted
deb http://archive.ubuntu.com/ubuntu focal-updates main multiverse universe restricted

Ubuntu repositories have a defined format. They should be for example
something like deb http://archive.ubuntu.com/ubuntu bionic main.
Explanation:
deb: These repositories contain binaries or precompiled packages. These repositories are required for most users.
http://archive.ubuntu.com/ubuntu: The URI (Uniform Resource Identifier), in this case a location on the internet.
focal: is the release name of your Ubuntu installation.
main & restricted ...etc: are the section names or components. There can be several section names, separated by spaces.

After that, please clear apt cache by running the following command in the terminal:
sudo apt clean && sudo apt autoclean

Then update your repositories list by running the following command in the terminal:
sudo apt update

You should now be able to install packages and update your system again.
If after that, you still get errors, please first back up /etc/apt/sources.list.d/ to your home directory by running the following command in the terminal:
mkdir ~/old_sources_list_d && sudo cp -r /etc/apt/sources.list.d/* ~/old_sources_list_d/

After that, please clear all existing PPAs and repository lists in /etc/apt/sources.list.d/ by running the following command in the terminal:
sudo rm -r /etc/apt/sources.list.d/*

After that, please clear apt cache by running the following command in the terminal:
sudo apt clean && sudo apt autoclean

Then, please update your repositories list by running the following command again in the terminal:
sudo apt update

Notice:

*

*Check if your connection to the Internet is behind a firewall, limited in any way or behind a proxy and configure your system and connection accordingly or change to a different connection if available. Firewalls can block access to certain URLs and proxies can keep old stale links in their cache system and this would result in broken or unresponsive targets. Proxies can also modify the headers of the HTTP requests and interfere with responses from web-servers and change them and your computer might end up getting faulty responses that APT can not handle correctly. This is common in networks that are used by large number of people and limited resources or Internet speed for availability and security reasons.

*Check if there is an APT proxy configuration file  by running the following command:
ls /etc/apt/apt.conf.d/*proxy*

If the command returns back any results, move these files out of the /etc/apt/apt.conf.d/ directory or delete them.


text:
Q: Adding the Apache Common Math 3.6.1 project from Maven Repository to a Maven project in NetBeans 12.x Summary: I wanted to use the prime number functions in the Apache Common Math project to solve a prime number problem.  The Apache NetBeans IDE 12.2 complains "cannot find symbol" isPrime()  and the programs fails to compile.
What's going on?
Detailed info:
Using Apache NetBeans IDE 12.2 running on Windows 10, I created a Maven Java app project.
Then I followed the instructions posted by Ojonugwa Jude Ochalifuon on Mar 24 '18  Adding external JAR to Maven project in NetBeans
Specifically,

*

*I copied the Maven dependency XML from the Apache Math 3.6.1

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-math3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.6.1</version>
</dependency>

*and pasted it into my project's pom.xml

*Next, in the NetBeans 12.2 IDE, I performed a Clean and Build Project.  The process downloaded all of the Apache Commons 3.6.1 files and compiled the project successfully.  In the Projects tab, under the Dependencies folder, I saw the commons.math3-3.6.1.jar. I navigated down to the Primes.class.

*Next, I added the following import command to my .java file:
    import org.apache.commons.math3.primes.Primes;

The NetBean 12.2 IDE displayed a yellow squiggle under the import reporting "unused Import."

*Then I added the following code snippet:

    if (isPrime(candidate)) { … }

The NetBean 12.2 IDE displayed a red squiggle under the isPrime() method (which is defined in the Apache Math 3.6.1 package).
When I press Shift+F6 to run the file, I get the following compile-time error:
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project ProjectEuler: Compilation failure
robcor/projecteuler/Problem0027.java:[20,16] error: cannot find symbol
What's going on?
Thanks in advance for your help. Much appreciated.

A: Maybe,
if (Primes.isPrime(candidate)) { … }
solves your problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: N(th) Highest Salary Query I found a solution for finding the n(th) highest salary from the web :
SELECT * FROM Employee Emp1
WHERE (N-1) = (
           SELECT COUNT(DISTINCT(Emp2.Salary))
           FROM Employee Emp2
           WHERE Emp2.Salary > Emp1.Salary
           )

But I am unable to understand how the query is actually being executed, i.e. how the query is processing at each step, especially in the subquery where multiple alias of same table occur ->
WHERE Emp2.Salary > Emp1.Salary

And what is the comparison operator doing with this-
WHERE (N-1) = <subquery>

Can someone please help me out with it?

A: The Nth Highest salary is the one where there are N-1 higher salaries
E.g. the highest salary has no higher salaries
Making the following change to the query should demonstrate how it works:
SELECT * FROM Employee Emp1
CROSS APPLY
           (
           SELECT COUNT(DISTINCT(Emp2.Salary)) AS NHigher
           FROM Employee Emp2
           WHERE Emp2.Salary > Emp1.Salary
           ) X;

Fiddle for Sql Server here
Note however that most RDBMS allow OFFSET and LIMIT type restrictions, which will allow you to do retrieve the Nth row more efficiently with a plain ORDER BY.
e.g. In SQL Server 2012, to fetch the 2nd highest salary:
SELECT *
FROM Employee Emp1
ORDER BY SALARY DESC
OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY;

A: edited : this question is asking how to get n(th) highest salary or get top n(th) salary ?
 the examples says how to get n(th) salary for get top n(th) just change the line 2
 WHERE emp.Salary = to WHERE emp.Salary >= :D
there is one solution for this :

*

*take Nth top salary

*get the employees that have that salary
now you can implement it in witch way u like :
first solution grouping salary's :
SELECT * FROM Employee as emp
WHERE emp.Salary =
(
    SELECT TOP 1 t.Salary FROM
    (
        SELECT TOP N(th) e.Salary FROM Employee as e
        Group by e.Salary
        Order By e.Salary
    ) as t
    ORDER BY t.Salary DESC
)

second solution DISTINCT salarys :
SELECT * FROM Employee as emp
WHERE emp.Salary =
(
    SELECT TOP 1 t.Salary FROM
    (
        SELECT DISTINCT TOP N(th) e.Salary FROM Employee as e
        Order By e.Salary
    ) as t
    ORDER BY t.Salary DESC
)


text:
Q: How to get desired height of ListBox so it doesn't have scrollbar and its content fits there I have a ListBox inside a DockPanel. I want to find out what should be the size of the ListBox so it doesn't have the scroll bar. I use ListBox.DesiredSize but actually DesiredSize is equal to ListBox.ActualWidth / Height and the ListBox has scrollbar because there are more items that can fit its height.
How to get real desired size ?

A: If you want to get rid of scrollbar in Listbox instead of creating static height in wpf application, you can disable scrollbar property.
In XAML:
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled" />
<ListBox ScrollViewer.VerticalScrollBarVisibility="Disabled" />

In C#:
myListBox.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
myListBox.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);

You can disable the scrollbar
Or else
VerticalScrollBarVisibility="Auto"

and set any height for Listbox scroll bar will be visible only content reaches its max Listbox height.
Or
Try this to achieve the desired height by binding the ListBox height property to the ActualHeight of the LayoutRoot Grid via the XAML below:
<Grid x:Name="LayoutRoot" Background="LightGray">
<Grid.ColumnDefinitions>
    <ColumnDefinition Width=".24*"/>
    <ColumnDefinition Width=".73*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height=".9*"/>
    <RowDefinition Height=".1*"/>
</Grid.RowDefinitions>
<ListBox Name="Subdivisions" SelectedItem="{Binding SelectedSubdivisionViewModel}" ItemsSource="{Binding Path=Subdivisions}" Grid.IsSharedSizeScope="True" Height="{Binding ElementName=LayoutRoot, Path=ActualHeight}" >

The important bit being:
 Height="{Binding ElementName=LayoutRoot, Path=ActualHeight}"

Also achievable via ancestor type:
 Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}"

Its my working code you can change it from grid to Dockpanel.

A:
How to get real desired size ?

The desired size of the ListBox is calculated automatically if you don't explicitly set its Height or VerticalAlignment property and avoid putting it in a Panel that measures its children with an infinite space such as a StackPanel.
The desired size of the ListBox itself is however not the same as the aggregated size of all ListBoxItem containers. In fact, there is no easy way to calculate this height exactly since not all containers are generated up front provided that you haven't disabled the UI virtualization of the ListBox.
The easiest workaround/solution would probably be to get the height of the first container once the ListBox has been loaded and then multiply this value with the actual number of items, e.g.:
<ListBox x:Name="lb" Loaded="lb_Loaded">
    <ListBoxItem>1</ListBoxItem>
    <ListBoxItem>2</ListBoxItem>
    <ListBoxItem>3</ListBoxItem>
</ListBox>

private void lb_Loaded(object sender, RoutedEventArgs e)
{
    ListBoxItem lbi = lb.ItemContainerGenerator.ContainerFromIndex(0) as ListBoxItem;
    if (lbi != null)
    {
        lb.Height = lbi.ActualHeight * lb.Items.Count + /* add some offset */ 5;
    }
}


text:
Q: Convert any SQL query to case insensitive So my users will send a query to my server, something like:
SELECT * WHERE myTable contains "some text"

And then I run that query on their database.
My users are not tech savvy at all. Even that simple query is confusing to them. So in order to make the search case insensitive I have to do:
SELECT * WHERE LOWER(myTable) contains LOWER("some text")

But I don't want my users to have to put in LOWER(). They will really get overwhelmed (they aren't programmers!)
The other problem is, I allow them to do other queries like:
WHERE myTable2 > 5
WHERE order by myTable
WHERE myTable3 matches "text"

Is there a way for me to transform those contains searches to be case insensitive without having my users put in LOWER() ?


text:
Q: CSS Animation doesn't work in Google Chrome but works in other browsers If you look at this example http://codepen.io/jezen/pen/CAHsk, you'll see the animation runs in Chrome (v29) (as well as other modern browsers). I took the exact same CSS code and saved it to my local drive, and created a really simple HTML page that references the CSS file. The page loads and the CSS styles are applied, but the animation doesn't run in my local version.
The HTML file is as simple as this:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Arcs</title>
    <link rel="stylesheet" type="text/css" href="arcs.css">

And the arcs.css file I'm referencing is an exact copy/paste from the source site that I've linked to above.
One other interesting piece of information. If you go to the authors demo site here: http://jezenthomas.com/experiments/arcify/ with the same browser, the animation runs just fine. But if you click on the "HAML" "JS" or "CSS" tabs in the example provide, and then click back to "Results" tab, you'll see that the animation no longer runs.

A: You need to add -webkit- prefix to the animation and transform tags in your css. Currently MS IE10 and FF supports unprefixed transforms. Good luck and let me know how it goes! :)


text:
Q: call function without parenthesis This is confusing me, i am trying to create an identifier like Jquery.
$.ajax
$('object')

the jquery identifier $ can be called without its parenthesis.
Here is some code i got:
function initialized_object(){
    this.method = function(){
        console.log('this is a string');
    }
}
var o = function (args){
    if(arguments.length > 0){
        //return N$(arguments[0], arguments[1]);
    }else{
        return new initialized_object();
    }
};
o.prototype.constructor.toString = function(){
    this.call(this);
}
o().method();

Instead of o().method() i would like to use o.method()

I looked at the jquery source in attempt to find the solution to this with no avail: http://code.jquery.com/jquery-1.11.3.js

This is what i am working with:
( in case you have any ideas )
function N$_no_parameters(){
    this.ajax = function(func){
        func();
    };
};
var N$_np = new N$_no_parameters();

var N$_CURRENT_EVENT_THIS = null;
function N$(selector, within){
    this.co = "hi";
    if (!Array.prototype.indexOf){
        Array.prototype.indexOf = function(elt /*, from*/){
            var len = this.length >>> 0;
            var from = Number(arguments[1]) || 0;
            from = (from < 0) ? Math.ceil(from) : Math.floor(from);
            if (from < 0)
                from += len;
            for (; from < len; from++){
                if (from in this && this[from] === elt)
                    return from;
            }
            return -1;
        };
    }
    var DOM_N$ = function(selector, within, frame){
        this.frame = frame || {
            win: (within != undefined)? within.contentWindow || this.constructor.caller.arguments[0] : this.constructor.caller.arguments[0],
            doc: (within != undefined)? within.contentDocument || this.constructor.caller.arguments[0].document : this.constructor.caller.arguments[0].document,
            this: this.constructor.caller.caller.caller.caller.caller
        };

        if(selector instanceof Object){
            if(selector.defaultView == this.frame.win){//selector is document
                this.selector = selector;
                this.nodes = [this.selector];
            }else if(selector.document == document){//selector is window
                this.selector = selector;
                this.nodes = [this.selector];
            }else if(selector instanceof this.frame.this){// selector is this
                this.selector = N$_CURRENT_EVENT_THIS.selector;
                this.nodes = N$_CURRENT_EVENT_THIS.nodes;//
            }else if(selector instanceof Element){//selector is DOM
                this.selector = selector;
                this.nodes = [this.selector];
            }else{
                this.selector = selector;
                this.nodes = new Array();
                for(var key in selector){
                    var dom_n$_ = N$(selector[key]).nodes;
                    for(var key_ in dom_n$_){
                        if(this.nodes.indexOf(dom_n$_[key_]) == -1){
                            this.nodes.push(dom_n$_[key_]);
                        }
                    }
                }
            }
        }else if(typeof selector == "string"){
            this.selector = selector;
            this.nodes = $prepare(this.selector, this.frame.doc);
        }
        this.event = function(event_, func){
            var that = this;
            actionair(function(node){
                var events = node.events || {};
                if(node.addEventListener){
                    if((event_) in events){
                        node.removeEventListener(event_, events[event_], true);
                        var tmp___ = events[event_];
                        var tmp__ = function(){
                            this.bar = "hello";
                            N$_CURRENT_EVENT_THIS = that;
                            tmp___(node, event_);
                            new func(node, event_);
                            N$_CURRENT_EVENT_THIS = null;
                        };
                        node.addEventListener(event_, tmp__, true);
                        events[event_] = tmp__;
                    }else{
                        var tmp__ = function(){
                            N$_CURRENT_EVENT_THIS = that;
                            new func(node, event_);
                            N$_CURRENT_EVENT_THIS = null;
                        };
                        node.addEventListener(event_, tmp__, true);
                        events[event_] = tmp__;
                    }
                }else if(node.attachEvent){
                    var ie_event = 'on' + event_;
                    if(event_ in events){
                        node.attachEvent(ie_event, function(){
                            N$_CURRENT_EVENT_THIS = that;
                            new func(node, event_);
                            events[event_](node, event_);
                            N$_CURRENT_EVENT_THIS = null;
                        });
                    }else{
                        node.attachEvent(ie_event, function(){
                            N$_CURRENT_EVENT_THIS = that;
                            new func(node, event_);
                            N$_CURRENT_EVENT_THIS = null;
                        });
                    }
                    events[event_] = func;
                }
                node.events = events;

            }, this);
        }

        this.removeEvent = function(event_){
            actionair(function(node, that){
                var events = node.events || {};
                if(node.removeEventListener){
                    if((event_) in events){
                        node.removeEventListener(event_, events[event_], true);
                        events[event_] = null;
                    }
                }else if(node.detachEvent){
                    var ie_event = 'on' + event_;
                    if((event_) in events){
                        node.detachEvent(ie_event, events[event_]);
                        delete events[event_];
                    }
                }
            }, this);
        }
        this.eachNode = function(func){
            actionair(function(node, that){
                N$_CURRENT_EVENT_THIS = N$(node);
                new func(node);
            }, this);
        }
        this.css = function(attr, value){
            N$_CURRENT_EVENT_THIS = this;
            var attribute = "";
            if(attr.indexOf('-') !== -1){
                var split_attr = attr.split('-');
                for (var i = 0; i < split_attr.length; i++) {
                    if(i != 0)
                        attribute += split_attr[i].charAt(0).toUpperCase() + split_attr[i].slice(1);
                    else
                        attribute += split_attr[i].charAt(0).toLowerCase() + split_attr[i].slice(1);
                };
            }else{
                attribute = attr;
            }

            var properties = new Array();

            actionair(function(node, that){
                if(typeof value != 'undefined'){
                    node.style[attribute] = value;
                }
                if (!that.frame.win.getComputedStyle) {//IE
                    that.frame.win.getComputedStyle = function(el, pseudo) {
                        that.el = el;
                        that.getPropertyValue = function(prop) {
                            var re = /(\-([a-z]){1})/g;
                            if (prop == 'float') prop = 'styleFloat';
                            if (re.test(prop)) {
                                prop = prop.replace(re, function () {
                                    return arguments[2].toUpperCase();
                                });
                            }
                            return el.currentStyle[prop] ? el.currentStyle[prop] : null;
                        }
                        return that;
                    }
                }
                properties.push(that.frame.win.getComputedStyle(node, null).getPropertyValue(attr));

            }, this);
            return properties;
        };

        this.text = function(str){
            actionair(function(node, that){
                node.innerHTML = '';
                node.appendChild(that.frame.doc.createTextNode(str));
            }, this);
        };
        this.appendNode = function(tagname, innerHTML){
            actionair(function(node, that){
                var new_node = that.frame.doc.createElement(tagname);
                new_node.innerHTML = innerHTML;
                node.appendChild(new_node);

            }, this);
        };
        this.innerHTML = function(innerHTML){
            actionair(function(node, that){
                node.innerHTML = innerHTML;
            }, this);
        };
        this.removeNode = function(){
            actionair(function(node, that){
                node.parentNode.removeChild(node);
            }, this);
        };
        this.animate = function(func, from, to, speed){

            var that = this;
            actionair(function(node, that){
                (function animate(func, from, to, speed, node){
                    if(from >= to){
                        N$_CURRENT_EVENT_THIS = that;
                        new func(node, to);
                        N$_CURRENT_EVENT_THIS = null;
                    }else{
                        N$_CURRENT_EVENT_THIS = that;
                        new func(node, from);
                        N$_CURRENT_EVENT_THIS = null;
                        setTimeout(
                            function(){
                                animate(func, from+1, to, speed, node);
                            }, speed
                        );
                    }
                })(func, from, to, speed, node);
            }, this);
        }

        function actionair(func, that){
            for (var i = 0; i < that.nodes.length; i++) {
                (function(i_){
                    N$_CURRENT_EVENT_THIS = that;
                    new func(that.nodes[i_], that);
                    N$_CURRENT_EVENT_THIS = null;
                })(i);
            }
        }
        function $prepare(str, doc){
            str = str.replace(/(\s+>\s+)/g,'>');
            str = str.replace(/(\s+)/g,' ');
            var str_ = str;
            var querys = str.split(/[\s\>]+/);
            var querys_des = Array();

            var ascender = new Array();
            for (var i = 0; i < str_.length; i++) {
                if(str_[i] == ">" || str_[i] == " "){
                    var tmp_ = (str_[i] == ">")? 'next_child' : 'ascended';
                    ascender.push( tmp_);
                }
            };
            var recognizes = new Array();
            for (var i = 0; i < querys.length; i++) {
                var asc_child = null;
                asc_child = ascender[i-1];
                var tmp_ = {
                    "selector": querys[i],
                    "i":i
                };
                recognizes[i] = recognize(querys[i], doc);
                if(i != 0){
                    tmp_["asc_child"] = asc_child;
                }else{
                    tmp_["base_selector"] = true;
                }
                querys_des.push(tmp_);
            };
            return $select(querys_des, recognizes, doc);
        }
        function $select(querys_des, recognizes, parent_, doc){
            var parents = parent_ || null;
            for (var i = 0; i < querys_des.length; i++) {
                if('base_selector' in querys_des[i]){
                    parents = recognizes[querys_des[i]['i']];
                }else if('asc_child' in querys_des[i]){
                    var cur_children = recognizes[querys_des[i]['i']];
                    if(querys_des[i]['asc_child'] == 'next_child'){
                        var compatible = compatible_children(parents, cur_children, querys_des[i]['asc_child'], doc);
                        parents = compatible;
                    }else if(querys_des[i]['asc_child'] == 'ascended'){
                        var compatible = compatible_children(parents, cur_children, querys_des[i]['asc_child'], doc);
                        parents = compatible;
                    }
                }
            };

            return parents;
        }

        function compatible_children(parents, children, type, doc){
            var ret = new Array();
            for (var a = 0; a < parents.length; a++) {
                for (var b = 0; b < children.length; b++) {
                    if(type == 'next_child'){
                        if(parents[a] == children[b].parentNode){
                            if(ret.indexOf(children[b]) == -1)
                                ret.push(children[b]);
                        }
                    }else if(type == 'ascended'){
                        if(isin(parents[a], children[b], doc)){
                            if(ret.indexOf(children[b]) == -1)
                                ret.push(children[b]);
                        }
                    }
                }
            }
            return ret;
        }

        function isin(parent, child, doc){
            var child_ = child;
            var ret = new Array();
            while((child_ = child_.parentNode) && child_ != doc.body){
                if(parent == child_){
                    return true;
                }
            }
            return false;
        }

        function recognize(str, doc){
            var identifier = new Array();

            var id_ = false;
            var class_ = false;
            var dom_ = false;
            if(str.indexOf("#") >= 0){
                id_ = true;
                var tmp = str.split("#")[1];
                if(str.indexOf(".") >= 0){
                    identifier['ID'] = tmp.split(".")[0];
                }else{
                    identifier['ID'] = tmp;
                }
            }

            if(str.indexOf(".") >= 0){
                class_ = true;
                var tmp = str.split(".")[1];
                if(str.indexOf("#") >= 0){
                    identifier['CLASS'] = tmp.split("#")[0];
                }else{
                    identifier['CLASS'] = tmp;
                }
            }

            if(id_ && class_){
                if(str.indexOf("#") < str.indexOf(".")){
                    var tmp = str.split("#")[0];
                    if(tmp.length > 0){
                        dom_ = true;
                        identifier['DOM'] = tmp;
                    }
                }else{
                    var tmp = str.split(".")[0];
                    if(tmp.length > 0){
                        dom_ = true;
                        identifier['DOM'] = tmp;
                    }
                }
            }else if(id_){
                var tmp = str.split("#")[0];
                if(tmp.length > 0){
                    dom_ = true;
                    identifier['DOM'] = tmp;
                }
            }else if(class_){
                var tmp = str.split(".")[0];
                if(tmp.length > 0){
                    dom_ = true;
                    identifier['DOM'] = tmp;
                }
            }else{
                if(str.length > 0){
                    dom_ = true;
                    identifier['DOM'] = str;
                }
            }

            var x;
            if(class_){
                if(typeof doc.getElementsByClassName !== 'function') {//Old browsers
                    x = doc.body.getElementsByTagName("*");
                }else{
                    x = doc.getElementsByClassName(identifier['CLASS']);
                }

            }else if(dom_){
                x = doc.getElementsByTagName(identifier['DOM']);
            }else if(id_){
                x = doc.body.getElementsByTagName("*");
                for (var i = 0; i < x.length; i++) {
                    if(x[i].getAttribute("id") != identifier['ID']){
                        delete x[i];
                    }
                };
            }

            var elements = new Array();

            for (var i = 0; i < x.length; i++) {
                if(id_ && class_){
                    if(x[i].getAttribute("id") == identifier["ID"] && x[i].getAttribute("class") == identifier["CLASS"]){
                        if(dom_){
                            if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
                                elements.push(x[i]);
                            }
                        }else{
                            elements.push(x[i]);
                        }
                    }
                }else if(id_){
                    if(x[i].getAttribute("id") == identifier["ID"]){
                        if(dom_){
                            if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
                                elements.push(x[i]);
                            }
                        }else{
                            elements.push(x[i]);
                        }
                    }
                }else if(class_){
                    if(x[i].getAttribute("class") == identifier["CLASS"]){
                        if(dom_){
                            if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
                                elements.push(x[i]);
                            }
                        }else{
                            elements.push(x[i]);
                        }
                    }
                }else{
                    if(dom_){
                        if(x[i].tagName.toLowerCase() == identifier['DOM'].toLowerCase()){
                            elements.push(x[i]);
                        }
                    }else{
                        elements.push(x[i]);
                    }
                }

            };

            return elements;
        }
    };

    var selectors = new Array();
    console.log('arguments' + arguments.length);
    if(arguments.length > 0){
        return new (function(selector, within){
            if(typeof within == typeof {}){
                if(within.nodes != undefined){
                    var ret = new Array();
                    for (var i = within.nodes.length - 1; i >= 0; i--) {
                        ret.push(do_node_select(selector, within.nodes[i]));
                    };
                    return ret;
                }else if(
                    typeof Node === "object" ? within instanceof Node :
                    within && typeof within === "object" && typeof within.nodeType === "number" && typeof within.nodeName==="string"
                ){
                    return do_node_select(selector, within);
                }
            }
            return do_node_select(selector, undefined);

            function do_node_select(selector, node){

                    var N$_new = new ( function(win, doc){
                        return new DOM_N$(selector, node || undefined);
                    })(window);

                    var N$_ = null;
                    if(selectors.length > 0){
                        for (var i = selectors.length - 1; i >= 0; i--) {
                            if(selectors[i].selector == selector){
                                var not_in = new Array();
                                for (var b = N$_new.nodes.length - 1; b >= 0; b--) {
                                    if(selectors[i].nodes.indexOf(N$_new.nodes[b]) == -1){
                                        not_in.push(N$_new.nodes[b]);
                                    }
                                };
                                for (var a = not_in.length - 1; a >= 0; a--) {
                                    if(selectors[i].nodes.indexOf(not_in[a]) == -1){
                                        selectors[i].nodes.push(not_in[a]);
                                    }
                                };
                                N$_ = selectors[i];
                                break;
                            }else{
                                N$_ = N$_new;
                            }
                        };
                    }else{
                        N$_ = N$_new;
                        if(N$_.nodes.length > 0){
                            selectors.push(N$_);
                        }
                    }
                    return N$_;

            }
        })(selector, within || undefined);
    }else{
        return N$_np;
    }

};

N$(window).event('load', function(){

    N$.ajax(function(){ // this will not work but using N$().ajax will
        console.log('aaa');
    });
});

This is a library i am making similar to Jquery, it selects nodes & handles events and more. the reason i would like to call my ajax function without parenthesis is for clarity.

A: $ is a function. But functions in JavaScript are also objects, which in-turn can have functions.
Perhaps this pattern is closer to what you are looking for:
var o = {
    method: function() {
    }
};
o.method();

A:
the jquery identifier $ can be called without its parenthesis.

No. The function isn't being called.
Functions are objects. Objects can have properties. This is simply accessing a property of the function object.

function foo() {
  return 1;
}

foo.bar = 2;

alert(foo.bar);
alert(foo());

Instead of o().method() i would like to use o.method()

Those statements mean different things.
The first calls the method method of the value that is returned when you call the o function.
The second calls the method method of the o function itself.
The second doesn't touch the initialised object (or even create one) at all.

A: Every time you call o() you get a new instance that can behave differently based on how you call it.
If you were to just call o.method, how would it know which reference to use? To be like jQuery,  you would do
o = o() // or o('something')

which would create a global singleton o that you could then call o.method.

A: Quentim's answer is completely correct. You're just acessing a property, no big deal. I just wanted to add that there's a way to "call a function without parenthesis" if you're using getters:
window.__defineGetter__("$", function() {
    //This gets executed when you access $
    console.log('oh hai');
    return { foo: 'bar' }
});

Not that this should be done at all, but this is a way of achieving what's in the question title


text:
Q: Activity is not responding while taking pictures more than one I got a problem. My activity will fail to respond when I take more than one picture. Sometimes taking even the first one has the ANR problem. I don't know why. I write the code according to DEV Guide. Here is my code:
    public class CameraActivity extends Activity implements SurfaceHolder.Callback,OnClickListener,AutoFocusCallback{

    private Button takeShot,goBack;
    private SurfaceView surfaceView;
    private SurfaceHolder holder;
    private Camera camera;

    private ArrayList<String> pictures;

    private PictureDAO pdao;
    public static final int PICTURE_OK=1554;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera);
        pdao=new PictureDAO(this);
        initComponent();
    }

    private void initComponent(){
        surfaceView=(SurfaceView)findViewById(R.id.cameraView);
        holder=surfaceView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        takeShot=(Button)findViewById(R.id.lets_take_it);
        goBack=(Button)findViewById(R.id.back_to_tab3_button);
        takeShot.setOnClickListener(this);
        goBack.setOnClickListener(this);
    }
    /**
     * set camera parameters
     */
    private void setCameraParameters(){
        Parameters para=camera.getParameters();
        para.setPictureFormat(ImageFormat.JPEG);
        Size preSize=para.getSupportedPreviewSizes().get(para.getSupportedPreviewSizes().size()-1);

        para.setPreviewSize(preSize.width, preSize.height);
        Size picSize=para.getSupportedPictureSizes().get(0);
        para.setPictureSize(picSize.width, picSize.height);

        camera.setParameters(para);
        camera.setDisplayOrientation(90);
    }
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        camera=Camera.open();
        setCameraParameters();
        try {
            camera.setPreviewDisplay(holder);
        } catch (Exception e) {
            LogUtil.log(e.getMessage());
            LogUtil.log(e.getLocalizedMessage());
            e.printStackTrace();
        }
        camera.startPreview();
        camera.autoFocus(this);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        releaseCamera();
    }

    private void releaseCamera(){
        if(camera!=null){
            camera.stopPreview();
            camera.release();
            camera=null;
        }
    }

    private void ICatchU(){

        camera.takePicture(null, null, new PictureCallback() {

            @Override
            public void onPictureTaken(byte[] data, Camera camera) {

                camera.stopPreview();

                Bitmap map =BitmapFactory.decodeByteArray(data, 0, data.length);
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                File picPath=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"whycools"+File.separator+"picture"+File.separator+DateUtil.getFormattedDate(DateUtil.JUST_DATE)+File.separator+timeStamp+".jpg");
                try {
                    picPath.getParentFile().mkdirs();
                    picPath.createNewFile();
                    BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(picPath));
                    map.compress(CompressFormat.JPEG, 80, bos);
                    pdao.insertPic(new PictureInfo(picPath.getAbsolutePath(), timeStamp));
                    if(pictures==null){
                        pictures=new ArrayList<String>();
                    }
                    System.out.println(picPath.getAbsolutePath());

                    pictures.add(picPath.getAbsolutePath());
                    bos.flush();
                    bos.close();

                } catch (Exception e) {
                    System.out.println(e.getLocalizedMessage());
                    LogUtil.log(e.getMessage());
                    LogUtil.log(e.getLocalizedMessage());
                    e.printStackTrace();
                }

                camera.startPreview();

            }
        });

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            releaseCamera();
            Intent n=new Intent(this,Tab3Activity.class);
            n.putStringArrayListExtra("picData", pictures);
            n.putExtra("shot_time", DateUtil.getFormattedDate(DateUtil.DATE_AND_MINUTE));
            this.setResult(PICTURE_OK, n);
            this.finish();
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id) {
        case R.id.lets_take_it:ICatchU();break;
        case R.id.back_to_tab3_button:{
            releaseCamera();
            Intent n=new Intent(this,Tab3Activity.class);
            n.putStringArrayListExtra("picData", pictures);
            n.putExtra("shot_time", DateUtil.getFormattedDate(DateUtil.DATE_AND_MINUTE));
            this.setResult(PICTURE_OK, n);
            this.finish();
        };break;
        }
    }

    private void showToastMessage(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onAutoFocus(boolean success, Camera camera) {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(pdao!=null){
            pdao.close();
            pdao=null;
        }
    }

}

----- pid 200 at 2011-12-16 08:38:45 -----
Cmd line: com.google.process.gapps

DALVIK THREADS:
(mutexes: tll=0 tsl=0 tscl=0 ghl=0 hwl=0 hwll=0)
"main" prio=5 tid=1 NATIVE
  | group="main" sCount=1 dsCount=0 obj=0x4001f1a8 self=0xce48
  | sysTid=200 nice=0 sched=0/0 cgrp=default handle=-1345006528
  | schedstat=( 545418989 6032995440 141 )
  at android.os.BinderProxy.transact(Native Method)
  at android.os.IPowerManager$Stub$Proxy.acquireWakeLock(IPowerManager.java:276)
  at android.os.PowerManager$WakeLock.acquire(PowerManager.java:253)
  at com.google.android.gsf.checkin.CheckinService.launchService(CheckinService.java:167)
  at com.google.android.gsf.checkin.CheckinService.access$000(CheckinService.java:64)
  at com.google.android.gsf.checkin.CheckinService$Receiver.onReceive(CheckinService.java:101)
  at android.app.ActivityThread.handleReceiver(ActivityThread.java:1794)
  at android.app.ActivityThread.access$2400(ActivityThread.java:117)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:981)
  at android.os.Handler.dispatchMessage(Handler.java:99)
  at android.os.Looper.loop(Looper.java:130)
  at android.app.ActivityThread.main(ActivityThread.java:3683)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:507)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
  at dalvik.system.NativeStart.main(Native Method)

"RefQueueWorker@org.apache.http.impl.conn.tsccm.ConnPoolByRoute@4050cad0" daemon prio=5 tid=9 WAIT
  | group="main" sCount=1 dsCount=0 obj=0x4055a8f0 self=0x8c270
  | sysTid=220 nice=0 sched=0/0 cgrp=default handle=1013376
  | schedstat=( 1148267 89253041 3 )
  at java.lang.Object.wait(Native Method)
  - waiting on <0x4054f928> (a java.lang.ref.ReferenceQueue)
  at java.lang.Object.wait(Object.java:395)
  at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:107)
  at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:80)
  at org.apache.http.impl.conn.tsccm.RefQueueWorker.run(RefQueueWorker.java:102)
  at java.lang.Thread.run(Thread.java:1019)

"Binder Thread #2" prio=5 tid=8 NATIVE
  | group="main" sCount=1 dsCount=0 obj=0x40511c08 self=0x1ba2a0
  | sysTid=213 nice=0 sched=0/0 cgrp=default handle=1717752
  | schedstat=( 9471974 67681837 3 )
  at dalvik.system.NativeStart.run(Native Method)

"Binder Thread #1" prio=5 tid=7 NATIVE
  | group="main" sCount=1 dsCount=0 obj=0x40511b40 self=0x185d30
  | sysTid=212 nice=0 sched=0/0 cgrp=default handle=1717688
  | schedstat=( 20164408 44832613 4 )
  at dalvik.system.NativeStart.run(Native Method)

"Compiler" daemon prio=5 tid=6 VMWAIT
  | group="system" sCount=1 dsCount=0 obj=0x4050edf8 self=0x185bf8
  | sysTid=211 nice=0 sched=0/0 cgrp=default handle=971936
  | schedstat=( 37893754 117636767 45 )
  at dalvik.system.NativeStart.run(Native Method)

"JDWP" daemon prio=5 tid=5 VMWAIT
  | group="system" sCount=1 dsCount=0 obj=0x4050ed10 self=0x1a33f8
  | sysTid=210 nice=0 sched=0/0 cgrp=default handle=1597960
  | schedstat=( 15809388 276306241 17 )
  at dalvik.system.NativeStart.run(Native Method)

"Signal Catcher" daemon prio=5 tid=4 RUNNABLE
  | group="system" sCount=0 dsCount=0 obj=0x4050ec50 self=0x186018
  | sysTid=203 nice=0 sched=0/0 cgrp=default handle=588480
  | schedstat=( 20070264 129928190 4 )
  at dalvik.system.NativeStart.run(Native Method)

"GC" daemon prio=5 tid=3 VMWAIT
  | group="system" sCount=1 dsCount=0 obj=0x4050eba8 self=0x186f58
  | sysTid=202 nice=0 sched=0/0 cgrp=default handle=588416
  | schedstat=( 112148122 1039499175 25 )
  at dalvik.system.NativeStart.run(Native Method)

"HeapWorker" daemon prio=5 tid=2 VMWAIT
  | group="system" sCount=1 dsCount=0 obj=0x4050eaf0 self=0x142738
  | sysTid=201 nice=0 sched=0/0 cgrp=default handle=588352
  | schedstat=( 105047309 2012821363 24 )
  at dalvik.system.NativeStart.run(Native Method)

----- end 200 -----

A: Thread your onClick() to avoid locking the UI.


text:
Q: sum count() by date and group by on while php i have this on mysql table :

user    |    open    |    date
---------------------------------
User1   |     1      | 2017-05-19
User2   |     1      | 2017-05-19
User3   |     1      | 2017-05-19
User4   |     1      | 2017-05-19
User1   |     3      | 2017-05-18
User2   |     5      | 2017-05-18
User4   |     20     | 2017-05-17
User1   |     2      | 2017-05-17
User2   |     7      | 2017-05-17

i search to make result while data mysql :
open = 2017-05-19
open2 = 2017-05-18
open3 = 2017-05-17

user    |    open    |    open2   |    open3
---------------------------------------------
User1   |     1      |      3     |      2
User2   |     1      |      5     |      7
User3   |     1      |      0     |      0
User4   |     1      |      0     |      20

you have idea ???
i have group by user but after its the problem !!!
thank's by advance for your help.

A: you can use case when
  select user,
      ifnull(case when date  = '2017-05-19' then open end , 0)as open,
      ifnull(case when date  = '2017-05-18' then open end, 0) as open2,
      ifnull(case when date  = '2017-05-17' then open end,0)  as open3,
  from my_table

A: SELECT user,
SUM(IF(date='2017-05-19',open,0)) AS open1,
SUM(IF(date='2017-05-18',open,0)) AS open2,
SUM(IF(date='2017-05-17',open,0)) AS open3
FROM SomeTableName
GROUP BY user;


text:
Q: AOSP Downloading and Moving the android source code I have a slow & erroneous Internet connection which disconnects now & then.
So I like to know, if there is a way to download the android source directly rather than
repo sync
Or If I download the source in another machine, how can I configure/setup in my machine?

A: repo sync is the officially supported method of getting Android sources. You can do repo sync on another machine and move the source to your development machine, there should be no special setup necessary for doing so, just copy the files downloaded by repo to your development machine (take care to copy all the hidden/dot files as well).

A: One option is to use the technique that Lie Ryan mentioned to get it to one machine F via a reliable Internet connection first. After that, you could consider using a tool such as rsync on the machine S with the slower/unreliable connection to keep the entire project tree between F & S in sync (I believe rsync supports resumption automagically, though I have never tested this).
Hope this helps.


text:
Q: Accessing the cakePHP hashed passwords from PHP service We have a few applications that make use of the same database. The user passwords are hashed by cakePHP application. What we would like to do is to compare the passwords hashed by php service and the ones hashed by cakePHP.
Is there a PHP function that would imitate the hashing of CakePHP in order to compare the passwords? If not, what would be the easiest way to go around it?

A: I believe CakePHP uses the function hash inside lib\Cake\Utility\Security.php to get the hashed data of the user and compare it with the hash stored in the password field:
https://github.com/cakephp/cakephp/blob/master/lib/Cake/Utility/Security.php#L107
I also would say that it usually uses the sha1 function of PHP by default which uses the user's password and the Security.salt value (defined in core.php) as the input string.
Therefor, you could do something like this to get the value saved on the password field of the users table:
sha1('cce93fda02c7f3ebf1g46c583589f1fd257e9d5d'. 'mypassword');

This is the full function in CakePHP which makes uses of sha1:
public static function hash($string, $type = null, $salt = false) {
    if (empty($type)) {
        $type = self::$hashType;
    }
    $type = strtolower($type);

    if ($type === 'blowfish') {
        return self::_crypt($string, $salt);
    }
    if ($salt) {
        if (!is_string($salt)) {
            $salt = Configure::read('Security.salt');
        }
        $string = $salt . $string;
    }

    if (!$type || $type === 'sha1') {
        if (function_exists('sha1')) {
            return sha1($string);
        }
        $type = 'sha256';
    }

    if ($type === 'sha256' && function_exists('mhash')) {
        return bin2hex(mhash(MHASH_SHA256, $string));
    }

    if (function_exists('hash')) {
        return hash($type, $string);
    }
    return md5($string);
}

You can read more about it in CakePHP documentation.


text:
Q: How can i mute incoming text on ios I know there is no way to read call/sms record in iOS
But i want to mute incoming text sounds with in my app. This setting seems in ringtone so there may be a solution
Let me know is it possible or not
I found another link but no answer
How can I mute incoming iPhone text messages programmatically?

A: Using public APIs, it is not possible.
The link you found is using private APIs, which aren't documented or guaranteed to work the way you'd expect. If you tried to release an App Store app that called a private API, it would be automatically rejected.


text: Q: How to perform aggregate function in SQL based on a condition of the data? I have a table with fields RegionName, Month and Mo.Rent Price. Each row contains values for a city's average rent price in a particular month. I want to use a SQL Query to pull the cities that have the lowest rent prices for each month. In other words, I don't want to find the city with the min rent overall. I want the min rent from the other rent values in that month. And I want that for each month. Anyone know what query I could use? Thanks I attached the table im working with below


text:
Q: CheckBoxList not updated - ASP.Net I have a checkbox list that get its data from DB. User will select/check boxes and click delete. After the delete, I'm rebinding the new data, but the changes aren't reflected. The page still shows those selected checkboxes. The records are deleted in DB though. am i missing something.
ASPX:
<asp:CheckBoxList ID="cblLanguages" runat="server" AppendDataBoundItems="true"
            DataTextField="LanguageName" DataValueField="PKLanguageId" >
</asp:CheckBoxList>
<asp:Button ID="btnDelete" runat="server" OnClick="btnDelete_Click" Text="Delete" />

C#:
protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            BindData();
        }
    }

protected void btnDelete_Click(object sender, EventArgs e)
    {
       DeleteLanguages();
       BindData();
    }

private void BindData()
{
    DataSet dsData = LanguagesDB.GetLanguages();
    cblLanguages.DataSource = dsData.Tables[0];
    cblLanguages.DataBind();
}
private void DeleteLanguages()
{
   //code to delete selected values
}

A: Every time loading the CheckboxList clear the items and Load.
private void BindData()
{
    if(cblLanguages.Items.Count > 0)
       cblLanguages.Items.Clear();
    DataSet dsData = LanguagesDB.GetLanguages();
    cblLanguages.DataSource = dsData.Tables[0];
    cblLanguages.DataBind();
}


text:
Q: How can Android apps access messenger chats? I want to write an Android App that analyses chats. For each messenger, for each contact, I want to get a list of all messages sent and received (since installing my app). The key thing here, is that I want the list of messages to be in order. My app should support as many messengers as possible. What would be the best way to do this?
I researched and found a few ways to access messengers' messages:

*

*Using accessibility services
(Related: How to read window content (using accessibilityService) and evoking UI using draw over other app permission in Android?)

*

*to read the screen content of other apps that is annotated with accessibility labels

*caveats:

*

*the messenger needs to have accessibility implemented correctly

*I have to filter which text blobs are relevant

*Using NotificationListenerService

*

*to get the content of notifications for received messages

*caveats:

*

*only gets content of messages for which there was a notification

*except for their time, there is no order of the messages given

*taking screenshots and doing optical character recognition

*

*caveats:

*

*probably insane

When I get the messages, I still have to order them. For this, I think, the accessibility services are my best bet as I could use the date information on screen in most messages, and also their position on the screen.
However, there is still an edge case. As I understand it, accessibility services can only see the content currently on the screen. The user might also use another device to chat while the device with the app installed is powered off. Thus, once the device with the app installed is powered on again, the app might not be able to see the old messages written while the device was powered off (until the user scrolls up again).
Are my assumptions correct? Do you know of a better way for my app to read/sort the messages?


text:
Q: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client POST HTTP REQUEST Need some help with this. So im following a tutorial but im facing this error. So im doing a post http request with POSTMAN this is my body
 {

 "userId": "2",

   "products":

   [{"id":"2", "incart":"5"}, {"id": "3", "incart": "8"}]
}

this is my orders.js im using mysqli to connect to my mysql BD
    router.post('/new', (req, res) => {

    let {userId, products} = req.body;

    if (userId !== null && userId > 0 && !isNaN(userId)) {
        database.table('orders')
            .insert({
                user_id: userId
            }).then(newOrderId => {

            if (newOrderId > 0) {
                products.forEach(async (p) => {

                    let data = await database.table('products').filter({id: p.id}).withFields(['quantity']).get();

                    let inCart = p.incart;

                    //    Deduct the number of pieces ordered from the quantity column in database
                    if (data.quantity > 0) {
                        data.quantity = data.quantity - inCart;

                        if (data.quantity < 0) {
                            data.quantity = 0;
                        }

                    } else {
                        data.quantity = 0;
                    }

                    //    INSERT ORDER DETAILS W.R.T THE NEWLY GENERATED ORDER ID
                    database.table('orders_details')
                        .insert({
                            order_id: newOrderId,
                            product_id: p.id,
                            quantity: inCart
                        }).then(newId => {
                        database.table('products')
                            .filter({id: p.id})
                            .update({
                                quantity: data.quantity
                            }).then(successNum => {
                        }).catch(err => console.log(err));
                    }).catch(err => console.log(err));

                });
            } else {
                res.json({message: 'new order failed while adding order details', success: false})
            }
            res.json({
                message: `Order successfully placed with order id ${newOrderId}`,
                success: true,
                order_id: newOrderId,
                products: products
            });
        }).catch(err => console.log(err));
    } else {
        res.json({message: 'New order failed', success: false});
    }

});

Also postman response is new order failed while adding order.
In console is getting the following error
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Any helpers would be appreciated

A: This is happening because you are resetting the res after it is sent.
                });
            } else {
    Here u are setting it once ---->>> res.json({message: 'new order failed while adding order details', success: false})
            }
            res.json({
                message: `Order successfully placed with order id ${newOrderId}`,
                success: true,
                order_id: newOrderId,
                products: products
            }); //<<<<---- You are resetting the response after it is sent

You should return res.json({}) instead of just res.json({}). This will prevent resetting of response.
                });
            } else {
    return it just from here ---->>> return res.json({message: 'new order failed while adding order details', success: false})
            }
            return res.json({
                message: `Order successfully placed with order id ${newOrderId}`,
                success: true,
                order_id: newOrderId,
                products: products
            }); //<<<<---- now, You are not resetting the response after it is sent

Here, I have explained it using this example.
const express = require("express");
const bodyParser = require("body-parser");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));

app.get("/:condition", (req, res) => {
    if (req.params.condition === "true") {
        return res.json({ success: true, msg: "setting true" });
    } else return res.json({ success: false, msg: "setting false" });
    res.json({ success: false, msg: "setting again" });
});

app.listen(8080, function () {
    console.log("Server is running on 8080");
});


text:
Q: inserting the php sendmail fuction into a confirm button within a pop up box I am trying to use the sendmail function in php threw a pop up box. i have gotten as far as making the sendmail function and the pop up to work separately. but i haven't been able to figure out how to connect the sendmail in the right way. below is the last working git version i have. any help would be wonderful.
{

Instrument Serial Number:
<input type="text" class="cInstTravText" name="SerialNumber" id="idSerialNumber"/>
<button onclick="drop_check()">comfirm</button>

A: The approach you're attempting isn't going to work.  The php on your page runs first (server side), and then your pop-up is triggered using JavaScript.  This means you'll need to send the response from the pop-up to another php page which then handles the sendmail.  You can do this via POST in a form submission, or better yet, using an AJAX call, like so (this goes between script tags, preferably at the top or bottom of your page, not in the middle of your HTML):
 if (confirm("transfer and send email!")) {
     //if needed, get values from one or more HTML inputs like so:
     var stuff = $('#someInputId').val();
     $.ajax({
        type: "POST",
        url: "sendmail.php",
        data: { data: stuff }  //if you don't need to send any data from your HTML elements this can be ommitted
     }).success(function() {
     //optional: let the user know email was sent
     });
 }

You would then put your sendmail code in sendmail.php.  If you're sending any data in the AJAX call, you can retrieve it from $_POST.  sendmail.php would look something like:
$body = isset($_POST['stuff']) ? $_POST['stuff'] : 'no stuff';
$to = 'jonsrod1992@gmail.com';
$subject = 'Test email using PHP';
$headers = 'From: jonr@twobtech.com' . "\r\n" .
        'Reply-To: jonr@twobtech.com' . "\r\n" .
        "MIME-Version: 1.0\r\n" .
        "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to,$subject,$body,$headers);

A: Maybe I'm missing something, but... it looks like you may be trying to just throw PHP into your javascript. That is not going to work. Also, if this is just weird reformatting of the code, the sendEmail function is not being called.


text:
Q: Why do I got TypeError: cannot pickle '_thread.RLock' object when using pyspark I'm using spark to deal with my data, like that:
        dataframe_mysql = spark.read.format('jdbc').options(
            url='jdbc:mysql://xxxxxxx',
            driver='com.mysql.cj.jdbc.Driver',
            dbtable='(select * from test_table where id > 100) t',
            user='xxxxxx',
            password='xxxxxx'
        ).load()

        result = spark.sparkContext.parallelize(dataframe_mysql, 1)

But I got this error from spark:

Traceback (most recent call last):
File "/private/var/www/http/hawk-scripts/hawk_etl/scripts/spark_rds_to_parquet.py", line 46, in
process()
File "/private/var/www/http/hawk-scripts/hawk_etl/scripts/spark_rds_to_parquet.py", line 36, in process
result = spark.sparkContext.parallelize(dataframe_mysql, 1).map(func)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pyspark/python/lib/pyspark.zip/pyspark/context.py", line 574, in parallelize
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pyspark/python/lib/pyspark.zip/pyspark/context.py", line 611, in _serialize_to_jvm
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pyspark/python/lib/pyspark.zip/pyspark/serializers.py", line 211, in dump_stream
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pyspark/python/lib/pyspark.zip/pyspark/serializers.py", line 133, in dump_stream
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pyspark/python/lib/pyspark.zip/pyspark/serializers.py", line 143, in _write_with_length
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pyspark/python/lib/pyspark.zip/pyspark/serializers.py", line 427, in dumps
TypeError: cannot pickle '_thread.RLock' object

Am I using it wrong? How should I use SparkContext.parallelize to deal with DataFrame?

A: I got it, dataframe_mysql is already a Dataframe, if want to get a RDD, just use dataframe.rdd instead of parallelize


text:
Q: PDO::ATTR_STRINGIFY_FETCHES=false No longer forces PDO to return INTs Since a couple of days I have one application (on a Clients server I do not have full access to yet) that refuses to obey the PDO::ATTR_STRINGIFY_FETCHES=false setting.
Code below should return integer (as it does on my own servers)
Yet on one server (I mailed them this testcode) it returns string
$PDO = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME . ";charset=utf8", DB_USER, DB_PASS);
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$PDO->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$PDO->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
$stmt = $PDO->prepare("SELECT * FROM information_schema.tables WHERE table_name='TABLES';");
$stmt->execute();
$tables = $stmt->fetch(PDO::FETCH_ASSOC);
echo "<H1>" . gettype($tables['VERSION']) . "</H1>";
var_dump($tables);

Setting PDO::ATTR_STRINGIFY_FETCHES=true of course exhibits the same behaviour on my own servers, as PDO by default returns integers as strings.
But the application requires integers to be integers in PHP.
As said; I do not yet have access to that server. Any pointers though?
Update
I finally got some phpinfo()
MySQLND is (for unknown reason) now missing (it was there before as the application ran fine)
Have directed sys-admins to blogs on activating MySQLND (again)
How to enable mysqlnd for php?


text:
Q: Why my component provided from ViewManager is never resize after setText? Background
I'm an Android Native Developer and I am trying to provide a View named CustomView to react native developer to show it at ReactActivity.
The View provided to react native by ViewManager is like this:

When the SeekBar's progress has been changed, the TextView below the SeekBar will be set a new text according to the new progress.
Question
In short, why the TextView never remeasure and relayout after setText when the CustomView is added in ReactActivity?
When the CustomView is added in NativeActivity, we can see that the TextView can auto remeasure and relayout as expect when we call setText function:

But when the CustomView is added in ReactActivity, the TextView can not auto remeasure and relayout:

The CustomView xml is:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="0dp"
        android:layout_height="56dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/cl_level"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="40dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="40dp"
        android:layout_marginBottom="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/seekbar">

        <TextView
            android:id="@+id/tv_level_name"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:maxLines="1"
            android:textSize="24sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@id/tv_level_no"
            app:layout_constraintHorizontal_chainStyle="packed"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintWidth_default="wrap"
            tools:text="Hello My Long Level Name" />

        <TextView
            android:id="@+id/tv_level_no"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="4dp"
            android:maxLines="1"
            android:textSize="24sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/tv_level_name"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="(Lv1)" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

And the react native code:
const App = () => {
  return (
    <View style={styles.container}>
      <CustomView />
      <Button
        onPress={() => {
          ActivityStarter.navigateToSecondActivity();
        }}
        title="Click to see expected behaviours!"
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
});

export default App;

I also have create an repo to let us reproduce this issue easily


text:
Q: Flink: RowRowConverter seems to fail for nested DataTypes I am trying to load a complex JSON file (multiple different data types, nested objects/arrays etc) from my local, read them in as a source using the Table API File System Connector, convert them into DataStream, and then do some action afterwards (not shown here for brevity).
The conversion gives me a DataStream of type DataStream[Row], which I need to convert to DataStream[RowData] (for sink purposes, won't go into details here). Thankfully, there's a RowRowConverter utility that helps to do this mapping. It works when I tried a completely flat JSON, but when I introduced Arrays and Maps within the JSON, it no longer works.
Here is the exception that was thrown - a null pointer exception:
    at org.apache.flink.table.data.conversion.ArrayObjectArrayConverter.allocateWriter(ArrayObjectArrayConverter.java:140)
    at org.apache.flink.table.data.conversion.ArrayObjectArrayConverter.toBinaryArrayData(ArrayObjectArrayConverter.java:114)
    at org.apache.flink.table.data.conversion.ArrayObjectArrayConverter.toInternal(ArrayObjectArrayConverter.java:93)
    at org.apache.flink.table.data.conversion.ArrayObjectArrayConverter.toInternal(ArrayObjectArrayConverter.java:40)
    at org.apache.flink.table.data.conversion.DataStructureConverter.toInternalOrNull(DataStructureConverter.java:61)
    at org.apache.flink.table.data.conversion.RowRowConverter.toInternal(RowRowConverter.java:75)
    at flink.ReadJsonNestedData$.$anonfun$main$2(ReadJsonNestedData.scala:48)

Interestingly, when I setup my breakpoints and debugger this is what I discovered: RowRowConverter::toInternal, the first time it was called works, will go all the way down to ArrayObjectArrayConverter::allocateWriter()

However, for some strange reason, RowRowConverter::toInternal runs twice, and if I continue stepping through eventually it will come back here, which is where the null pointer exception happens.

Example of the JSON (simplified with only a single nested for brevity). I placed it in my /src/main/resources folder
{"discount":[670237.997082,634079.372133,303534.821218]}

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment
import org.apache.flink.table.api.DataTypes
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment
import org.apache.flink.table.data.conversion.RowRowConverter
import org.apache.flink.table.types.FieldsDataType
import org.apache.flink.table.types.logical.RowType

import scala.collection.JavaConverters._

object ReadJsonNestedData {
  def main(args: Array[String]): Unit = {
    // setup
    val jsonResource = getClass.getResource("/NESTED.json")
    val jsonFilePath = jsonResource.getPath
    val tableName = "orders"
    val readJSONTable =
      s"""
         | CREATE TABLE $tableName (
         |  `discount` ARRAY<DECIMAL(12, 6)>
         | )WITH (
         |    'connector' = 'filesystem',
         |    'path' = '$jsonFilePath',
         |    'format' = 'json'
         |)""".stripMargin

    val colFields = Array(
      "discount"
    )

    val defaultDataTypes = Array(
      DataTypes.ARRAY(DataTypes.DECIMAL(12, 6))
    )

    val rowType = RowType.of(defaultDataTypes.map(_.getLogicalType), colFields)
    val defaultDataTypesAsList = defaultDataTypes.toList.asJava
    val dataType = new FieldsDataType(rowType, defaultDataTypesAsList)
    val rowConverter = RowRowConverter.create(dataType)

    // Job
    val env = StreamExecutionEnvironment.getExecutionEnvironment()
    val tableEnv = StreamTableEnvironment.create(env)
    tableEnv.executeSql(readJSONTable)
    val ordersTable = tableEnv.from(tableName)
    val dataStream = tableEnv
      .toDataStream(ordersTable)
      .map(row => rowConverter.toInternal(row))

    dataStream.print()
    env.execute()
  }

}

I would hence like to know:

*

*Why RowRowConverter is not working and how I can remedy it

*Why RowRowConverter::toInternal is running twice for the same Row .. which may be the cause of that NullPointerException

*If my method of instantiating and using the RowRowConverter is correct based on my code above.

Thank you!
Environment:

*

*IntelliJ 2021.3.2 (Ultimate)

*AdoptOpenJDK 1.8

*Scala: 2.12.15

*Flink: 1.13.5

*Flink Libraries Used (for this example):

*

*flink-table-api-java-bridge

*flink-table-planner-blink

*flink-clients

*flink-json

A: The first call of RowRowConverter::toInternal is an internal implementation for making a deep copy of the StreamRecord emitted by table source, which is independent from the converter in your map function. The reason of the NPE is that the RowRowConverter in the map function is not initialized by calling RowRowConverter::open. You can use RichMapFunction instead to invoke the RowRowConverter::open in RichMapFunction::open.

A: Thank you to @renqs for the answer.
Here is the code, if anyone is interested.
class ConvertRowToRowDataMapFunction(fieldsDataType: FieldsDataType)
    extends RichMapFunction[Row, RowData] {
  private final val rowRowConverter = RowRowConverter.create(fieldsDataType)

  override def open(parameters: Configuration): Unit = {
    super.open(parameters)
    rowRowConverter.open(this.getClass.getClassLoader)
  }

  override def map(row: Row): RowData =
    this.rowRowConverter.toInternal(row)
}

// at main function
// ... continue from previous
val dataStream = tableEnv
      .toDataStream(personsTable)
      .map(new ConvertRowToRowDataMapFunction(dataType))


text:
Q: Using PHP foreach to build stylesheet Okay - so I'm creating a dynamic CSS stylesheet, which I want to set up with an array.
First let me say that I'm not a PHP expert, but I somewhat know my way around it.
Here's my very basic array.
$visual_css = array (
    array(
        "selector"  => "body",
        "property"  => "background",
        "value"     => "#FFF",
        "property2" => "color",
        "value2"    => "#000",
        "type"      => "css"
    )
);

So we have a selector, and two properties with values.
I now want to create the stylesheet, but I'm running into problems due to my lack of PHP knowledge.
foreach ($visual_css as $value) {
    switch ($value['type']) {
        case "css":

            // Open selector
            echo ( !empty($value['selector']) ? $value['selector'] . '{' : null );

            foreach ($value as $key => $item) {
                foreach ($value as $key2 => $item2) {
                    //Match only the id's against the key
                    if (preg_match('/^property/i', $key) && preg_match('/^value/i', $key2)) {
                        // First property
                        echo ( !empty($item) ? $item . ':' : null );
                            echo ( !empty($item2) ? $item2 . ';' : null );
                    }
                }

            }

            // Close selector
            echo ( !empty($value['selector']) ? '}' : null );

        break;
    }
}

Now I know this code isn't correct, as it's outputting the following in the stylesheet:
body{background:#FFF;background:#000;color:#FFF;color:#000;}

This is the desired result:
body{background:#FFF;color:#000;}

So basically, I want to be able to create an unlimited number of properties and values with an incrementing number after them, and have the code write it out.
Can anyone help me?
Thanks!

A: So my approach uses a multidimensional array instead of a flat array to nest properties of selectors in sub-arrays. This way your approach is much more concise by first looping through the first layer, and then going through the children of each parent and composing the CSS for each property / value pair. It also makes iteration a cinch as opposed to having to inspect the values of keys to locate which pair you're at. If you need a different output format, your iteration code can decide that, and it should be left out of the structure
$visual_css = array (
    'body'  => array(
        'background'    => '#FFF',
        'color'         => '#000'
    )
);

$output = '';
foreach($visual_css as $k => $properties) {
    if(!count($properties))
        continue;

    $temporary_output = $k . ' {';

    $elements_added = 0;

    foreach($properties as $p => $v) {
        if(empty($v))
            continue;

        $elements_added++;

        $temporary_output .= $p . ': ' . $v . '; ';
    }

    $temporary_output .= "}\n";

    if($elements_added > 0)
        $output .= $temporary_output;
}

echo $output;
// body {background: #FFF; color: #000; }

A: In your example you are looping over the same array twice, in this piece of code:
foreach ($value as $key => $item) {
    foreach ($value as $key2 => $item2) {

If you structured your data in a more logical way, you could make a cleaner loop code, too. I'd suggest you to structure the array with each property&value as a separate sub-array, for example:
$visual_css = array(
    array(
        'selector' => 'body',
        'properties' => array(
            'background' => '#fff',
            'color' => '#000'
        )
    )
    // ... etc ...
);

And then you can easily loop through it like this:
foreach ($visual_css as $selector)
{
    echo $selector['selector'].' { ';
    foreach ($selector['properties'] as $name => $value)
    {
        echo $name.': '.$value.'; ';
    }
    echo ' } ';
}


text:
Q: Is there built in support in rails for the default value substitution idiom? I often write code to provide a default value upon encountering nil/empty value.
E.g:
category = order.category || "Any"
#  OR
category = order.category.empty? ? "Any" : order.category

I am about to extend the try method to handle this idiom.
category = order.try(:category, :on_nill => "Any")
#  OR
category = order.try(:category, :on_empty=> "Any")

I am wondering if Rails/Ruby has some method to handle this idiom?
Note:
I am trying to eliminate repetition of  || / or / ? operator based idioms.
Essentially I am looking for a equivalent of try method for handling default substitution scenarios.
Without try method:
product_id = user.orders.first.product_id unless user.orders.first.nil?

With try method:
product_id = user.orders.first.try(:product_id)

It is easy to implement a generic approach to handle this idiom, but I want to make sure I do not reinvent the wheel.

A: See this question.  ActiveSupport adds a presence method to all objects that returns its receiver if present? (the opposite of blank?), and nil otherwise.
Example:
host = config[:host].presence || 'localhost'

A: Perhaps this might serve:
class Object
  def subst_if(condition, replacement)
    condition = send(condition) if condition.respond_to?(:to_sym)
    if condition
      replacement
    else
      self
    end
  end
end

Used like so:
p ''.subst_if(:empty?, 'empty')       # => "empty"
p 'foo'.subst_if(:empty?, 'empty')    # => "foo"

It also takes stand-alone conditions, not related to the object:
p 'foo'.subst_if(false, 'bar')    # => 'foo'
p 'bar'.subst_if(true,  'bar')    # => 'bar'

I'm not crazy about the name subst_if.  I'd borrow whatever name Lisp uses for this function, if I knew it (assuming it exists).

A: Pretty sure its not baked in.  Here is a link to a similar question/answer.  It is the approach that I take. Leveraging the ruby: ||= syntax
An aside: This question also reminds me of the first Railscasts of all time: Caching with instance variables which is a useful screencast if you need to do this kind of operation in a Controller

A: fetch will work in the case that you are looking for values by index values of an array or by keys in a hash ( or ActionController::Parameters aka params ). Otherwise, you will have to use the ||= or attempted_value || default_value as described in the other answers.
The current accepted answer's example is rewritten here:
assuming:  config = { my_host_ip: '0.0.0.0' }
 config.fetch(:my_host_ip, 'localhost')
 # => "0.0.0.0"

 config.fetch(:host, 'localhost')
 # => "localhost"

 a_thru_j = ('a'..'j').to_a
 # => ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]

 a_thru_j.fetch(1, 'not here')
 # => "b"

 a_thru_j.fetch(10, 'not here')
 # => "not here"

Note: without the default, you will raise an error when the key/index is not present:
 config.fetch(:host)
 # => KeyError: key not found: :host

 params.fetch(:host)
 # => ActionController::ParameterMissing: param is missing or the value is empty: host

 a_thru_j.fetch(10)
 # => index 10 outside of array bounds: -10...10


text:
Q: How would you test static method URLEncoder.encode? I have this below method.
 protected static String encode(String url) {
    try {
      url = URLEncoder.encode(url, StandardCharsets.UTF_8.toString());
    } catch (Exception e) {
      LOGGER.warn("exception occured while encoding url {}", url);
    }
    return url;
  }

I am unable to provide a junit test for this because I can't mock URLEncoder. There are 2 possible outcomes of this method

*

*encoded url

*original url if there is some exceptions

I am able to create a test method for first outcome. how would you create test method for the second outcome?

A: You could use PowerMockito to mock static methods. Assuming the static method in your post is in a class called HelloWorld, here are the two tests where the first test is testing the positive case and the second test
 is testing the exception case:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.powermock.api.mockito.PowerMockito.doThrow;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest(HelloWorld.class)
public class HelloWorldTest {

    @Test
    public void encode_returnsEncoded() throws UnsupportedEncodingException {
        // given
        mockStatic(URLEncoder.class);
        when(URLEncoder.encode(any(String.class), any(String.class)))
            .thenReturn("testUrlEncoded");

        // when
        String encoded = HelloWorld.encode("testUrl");

        // then
        assertThat(encoded).isEqualTo("testUrlEncoded");
    }

    @Test
    public void encode_returnsInputOnException() {
        // given
        mockStatic(URLEncoder.class);
        doThrow(new Exception("exception from test"))
            .when(URLEncoder.class);

        // when
        String encoded = HelloWorld.encode("testUrl");

        // then
        assertThat(encoded).isEqualTo("testUrl");
    }

}

A:
The fundamental theorem of software engineering (FTSE) is a term originated by Andrew Koenig to describe a remark by Butler Lampson attributed to the late David J. Wheeler:

"We can solve any problem by introducing an extra level of indirection."

[...]
The theorem is often expanded by the humorous clause "…except for the problem of too many levels of indirection," referring to the fact that too many abstractions may create intrinsic complexity issues of their own. (Source: Wikipedia)

So let's say there's a class that has a static method named encode:
public final class UrlHelper {
    protected static String encode(String url) {
        try {
            url = URLEncoder.encode(url, StandardCharsets.UTF_8.toString());
        } catch (Exception e) {
            LOGGER.warn("exception occured while encoding url {}", url);
        }

        return url;
    }
}

and your code depends on it:
public class MyClass {
    public void doSomething(String someUrl) {
        // ...
        String encodedUrl = UrlHelper.encode(someUrl);
        // ...
    }
}

and you want to test MyClass.doSomething(String someUrl) but you want to mock UrlHelper.encode(someUrl). One option is to define another class such as
public final class MyUrlHelper {
    protected String encode(String url) {
        return UrlHelper.encode(someUrl);
    }
}

As MyUrlHelper.encode(String url) is not static, you can refactor your original code and test it by relying on dependency injection and mocking the non-static MyUrlHelper.encode(String url):
// Refactored
public class MyClass {

    private MyUrlHelper myUrlHelper;

    public UrlHelper(MyUrlHelper muUrlHelper) {
        this.myUrlHelper = myUrlHelper;
    }

    public void doSomething(String someUrl) {
        // ...
        String encodedUrl = myUrlHelper.encode(someUrl);
        // ...
    }
}

// Test
@Test
public void myTest() {
    // setup myUrlHelper and configure it
    MyUrlHelper myUrlHelper = mock(MyUrlHelper.class);
    when(myUrlHelper.encode(...)).thenReturn(...);

    // inject
    MyClass myObject = new MyClass(myUrlHelper);

    // stimulate
    myObject.doSomething("...")
}

Another option is to use Mockito using the PowerMockRunner as explained by @Marimuthu Madasamy.

However, I don't see any benefit in mocking UrlHelper.encode or URLEncoder.encode here. It is not an external system (a database, a file system, a message broker, a SOAP API, a REST API, etc.) so I don't see any gains by mocking it.

A: If you are willing to use Lombok, I got a practical approach for you:
@lombok.Generated // Function won't raise up in Jacoco coverage report, see https://stackoverflow.com/a/56327700/1645517
@lombok.SneakyThrows(UnsupportedEncodingException.class) // Suppress handling this exception, see https://projectlombok.org/features/SneakyThrows
private static String urlEncode(final String valueToEncode) {
  return URLEncoder.encode(valueToEncode, StandardCharsets.UTF_8.name());
}

*

*Jacoco will ignore this method

*The UnsupportedEncodingException cannot be thrown here. Let Lombok handle this ugly circumstance.


text:
Q: Lost conection local-remote I'm pretty new to programming and version-control. Working on my course task, I hit a problem with GitLab repository.
Cant resolve it over 2h with searching... and may be I'v messed up things trying different "decision"
My laptop was  accidentally restarted during merging in VS Code. When I turned it on,  somehow lost the connection between my local and remote repository.
Tried with VS and VS Code, but VS Code shows me

"The folder currently open dosent have a git repository" .

VS shows "Add to Source Control" instead of my working branch in  bottom left corner.
In Team explorer / Manage Connection  in  Local Git repositories  this repository missing.
I've tried to add it in  Manage Connection this is the error message

"No new repositories were found. Errors were encountered while searching for repositories. See the Output window for details."

I can clone it again in different folder and handle copy changed files but its  contain my over 20 hour work so I'm looking for something smarter.

A: At first, move to your main project folder. There shloud be hidden folder: .git. It's a you Git database. Check is this folder is here (.git folder can be in diffrent place ),if you find it - your repository has not been deleted.
In the same folder where you find .gir folder ,try run command line (the best will be run git bash, you can run in when you click shift and PPM -> Git bash here ).

*

*It's your hidden git database/git repository

*Git bash here command

Next step -  run command: Git status, propably you will be have unmerged paths like this:

If so, try run at the same main folder VS Code, check or you see your repository on VS Code.
If you will have some diffrence from git output (like corrupt repository, but it's rarity), we can tell you more. Now it's difficul say somethink more withous information from console.
Summary:

*

*Check or you still have .git folder (There should be in your main project folder, but it can be in diffrent place)

*Run git bash and check status by commend: Git Status. Check what git output. If it's neccesary - Send output results

*After step 2 - try running VS Code in the main folder

*Check or the VS Code you see your repository If you will have still any problems send more screen from folders and console output