Q:

Is this reason realistic for aliens to kidnap humans?

First of all I want to say sorry for my bad english and it is great to have someone help me brainstorming my ideas.
Let's say there is an alien race that kidnapped humans from Earth to another planet a long time ago (maybe prehistoric) and still continue until now. Because of that, a new human civilization grows on that new planet. The reason behind it is to place all of the kidnapped humans on that new planet, that has been terraformed in such a way to be the lab for them to observe and do the experiment to human in the large scale.
Is this reason plausible?? Or maybe there is something else that I have to consider?

A:

As @Amoeba mentioned in the comment, I think the most important thing is to consider the motivation behind the experiments, especially because creating a terraformed planet to be a lab is a considerably expensive endeavour.
It must also be answered why such an endeavour would be better than observing and doing experiments on the humans in their natural habitat, i.e. the Earth. In other words, what experimental/scientific advantages would they have in doing the experiments on another planet?
We can compare at least the following three lab settings:

The native environment (the Earth): preserves the nativeness but compromises the degree of control of variables
A regular laboratory without any attempt to emulate the native environment for humans: higher degree of control over the experimental variables but lack of nativeness may cause humans to behave differently
A terraformed planet: a bit of (1) and (2)

So you may want to think of the kind of experiments that would be best conducted on a terraformed planet as opposed to other options -- the kind of experiments that requires certain features of the native environment but also a certain degree of control.
From here, you can then design the experiments and what the controls are going to be. For example:

Can the humans remember the abduction event?
Can they remember the pre-abduction events?
How similar is the terraformed planet to the Earth?

to suggest a few.

A:

Is this reason plausible??

Sure.  (Humans "terraform" the environment to make it suitable for non-native species, populate the terraformed environment and call it a Zoo.  There's nothing to stop interstellar space aliens from doing the same thing.)

A:

Cost is very high

Cost of terraformation : it is a lot of work. So if they invest so much money, why do they not use the planet for themselves?

The cost of transportation and logistics: You need to go to earth, take some humans and bring them to the new planet, which is likely quite far away so that they don’t see each other too easily. You also need to do so in a hidden way, so humans on earth don’t see you too much and organize resistance.

Cost of maintenance: If you want it to work on long term (from prehistoric to today is a lot of years), you need to make sure the terraformed earth don’t break down. That humans on it don’t attack each other too much, don’t die from epidemics and so on. You also need to maintain your scientific research, archives, researchers, …

Purpose
Because the price is so high, you need to find a reason that is very strong for the aliens to do it. What type of experiment needs so much time to yield results?

If it’s biological, it’s likely that in a few years you will have all the results that you want. Especially if you have such an advanced technology.
If it’s sociological, why can’t you do it on earth directly by observation?
If it’s a zoo, why not put a few humans on an island, or in a big building. So they can do it on their own planet and don’t have to space travel to go and see it.
If it’s for hunting, why not hunt on earth? Or on their own world? Why would they need a whole planet and all these costs to do it?

Proposition
A better way to explain it, would be the aliens wanting to protect the human race. They think that we are likely to destroy ourselves, either by war or by destroying the planet’s environment. So they decided to build a backup for us. If the human race disappears from earth, it would still exist on another planet.
They are just very philanthropic.


Q:

Closing a JFrame using a button in eclipse

I'm a rookie when it comes to programming. We have this project about a log-in profile account. I just started doing it; and I came across a specific problem. I want to close a frame using a button.
buttonenter.setText("Enter");
     buttonenter.addActionListener(new ActionListener (){
       public void actionPerformed (ActionEvent ae){

           }
    });

I tried placing my frame.dispose();, set.Visible(false) etc.  but i just got an error. I don't quite get. I really appreciate the help! Thank you!

A:

Here's a simple example of what you're trying to do. What errors are you receiving?
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton btnClose = new JButton("CLOSE");
    btnClose.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            frame.setVisible(false);
        }
    });
    frame.getContentPane().add(btnClose, BorderLayout.NORTH);
}

A:

from JButtons ActionListener you can to call

JFrame#dispose(); (terminating current JVM)
JFrame#setVisible(false); (hide JFrame)
System.exit(0); (terminating current JVM)

and/or with (another standard ways are)

setDefaultCloseOperation();
add WindowListener and override proper event windowClosing();


Q:

If $N$ is a complete linear subspace of $H$ and $\inf_{f \in N} |f-g| = d$, prove that $\exists f'$ such that $f' \in N$ and $|f'-g|=d$

The problem as stated is

Let $H$ be a Hilbert space.  If $N$ is a complete linear subspace of $H$ and $\inf_{f \in N} |f-g| = d$, prove that $\exists f'$ such that $f' \in N$ and $|f'-g|=d$.

I would like to try to prove that there exists a Cauchy sequence which converges to $f'$, but I am only able to put an upper bound of order $d$ on $|f_n-f_m|$. This is because it is possible that any two functions which are within $d+\epsilon$ of $g$ may still be up to $2d+2\epsilon$ away from each other.
I am working from the following definition of $\inf$:

If $\inf_{f \in N} |f-g| = d$ then $\forall \epsilon > 0$ $\exists$ $f'' \in N$ such that $|f''-g|<d+\epsilon$.

Edit: Ideally, the answer would prove this using a Cauchy sequence or in some other elementary way, without referring to other known results about $H$.
In other words I'm looking to show that there exists a Cauchy sequence that converges to $f'$.

A:

Let $(f_n)$ be a sequence in $N$ with $$\lim_{n\to\infty} \lvert f_n - g\rvert = d.$$
Then $(f_n)$ is a Cauchy sequence, and by continuity its limit $f'$ lies in $N$ and satisfies $\lvert f' - g\rvert = d$. And it is the unique best approximation to $g$ in $N$.
The last assertion follows by applying the argument to the sequence alternating between $f'$ and $f''$ if both $f'$ and $f''$ realise the distance.
So it remains to show that a minimising sequence is a Cauchy sequence. For that, we need that $N$ is convex (midpoint-convex suffices), and the parallelogram identity
$$\lvert x-y\rvert^2 + \lvert x+y\rvert^2 = 2\lvert x\rvert^2 + 2\lvert y\rvert^2\tag{1}$$
for all $x,y$. The identity $(1)$ follows directly from $\lvert z\rvert^2 = \langle z,z\rangle$ and the properties of an inner product.
We apply $(1)$ to $x = f_n - g$ and $y = f_m - g$ and obtain
$$\lvert f_n - f_m\rvert^2 + \lvert (f_n+f_m) - 2g\rvert^2 = 2\lvert f_n - g\rvert^2 + 2 \lvert f_m - g\rvert^2$$
and from that
$$\lvert f_n - f_m\rvert^2 = 2\lvert f_n - g\rvert^2 + 2 \lvert f_m - g\rvert^2 - 4 \left\lvert \frac{f_n+f_m}{2}-g\right\rvert^2.$$
Now, $\frac12(f_n + f_m) \in N$, so we have
$$\lvert f_n - f_m\rvert^2 \leqslant 2\lvert f_n-g\rvert^2 + 2\lvert f_m-g\rvert^2 - 4 d^2.\tag{2}$$
Since $\lvert f_n - g\rvert \to d$, for all $\varepsilon > 0$ there is an $N_\varepsilon$ with $n \geqslant N_\varepsilon \Rightarrow \lvert f_n -g \rvert^2 < d^2 + \varepsilon^2/2$. Then, for $n,m \geqslant N_\varepsilon$, $(2)$ implies $\lvert f_n - f_m\rvert < \varepsilon$, hence $(f_n)$ is a Cauchy sequence.


Q:

Getting CamelContext parameters from java bean

I have an issue with Spring and Camel.
I'm sorry I can't paste real code ...
So, I'm trying to get properties defined in the camel Context with a placeholder. But the properties are Empty.
<bean id="mySuperClass"
        class="com.lol.rofl.MySuperClass">
</bean>
<camelContext id="blablabla" xmlns="http://camel.apache.org/schema/spring">
<propertyPlaceholder id="myProp"
        location="classpath:camel/contexts/myprops.properties" />
....
Some fantastique code that use the properties and works.
....
</camelContext>

the .java :
public class MySuperClass implements CamelContextAware
{

    public void getCCProperties()
    {
           final Map<String, String> camelContextProperties = camelContext.getProperties();
            crawlerOutputDirectory = camelContextProperties.get("my.super.pro");
    }
}

I just think I'm not trying the right way, thanks for you help

SOLUTION
Properties in placeHolders can be found this way :
camelContext.resolvePropertyPlaceholders("{{" + propertyName + "}}");

ex : camelContext.resolvePropertyPlaceholders("{{output.directory}}");

A:

Read the javadoc of the methods, getProperties on CamelContext is not for property placeholder. Use resolvePropertyPlaceholders for property placeholder
javadoc for CamelContext: http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/CamelContext.html


Q:

How to make a fixed Toast notification

I'm new to Windows Phone development and I've found something about background agents in WP 7.5:
http://code.msdn.microsoft.com/wpapps/CSWP7ScheduledTaskAgent-6450bcf1
I wasn't able to find a way of making the toast notification fixed, I mean, when it appears on the screen it should disappear.
Is there any way of doing this? any advices, documentation should be great.
Thanks.

A:

Toast Notification by the OS
When a toast notification is created, the OS handles the amount of time it is displayed for...

A toast notification displays for about 10 seconds unless the user
  dismisses it with a flick to the right. If the user taps the toast, by
  default, your app's start screen launches. Or, you can choose to
  specify which screen of your app will launch.

Taken from the official documentation.
The API for toast notifications does not allow you to specify a time. Only a title, content and deep link into your app. This is the only type of toast/notification that can be used by a Background Agent. But it will appear:

on the Start screen
when your app is being used
when any other app is being used.

Custom toast-like notification (eg. Coding4Fun Toolkit's Toast Prompt)
A custom toast notification, although more flexible, must obey all the system rules unlike the system's Toast Notification which has special permissions.
This means the Coding4Fun Toolkit's Toast Prompt cannot:

Display notifications when your app is not running (apps cannot run in the background, they are essentially paused)
Display notifications when the user is on the Start screen or not using your app

Having a permanently (or long) displaying toast notification would be annoying to the user (hence the 10 second limit by the OS version) so do think carefully about why you need it - is the System Tray or MessageBox a better idea?
If you're new to Windows Phone, I would recommend using a handset for a while to get the feel for how the system works and how other apps use all kinds of notifications.


Q:

Win 10 : what registry keys entries are needed to reg my app for tel protocol

About tel protocol handler : My app works fine except under window 10. What extra registry keys entries are needed under window 10 to registry app for tel protocol (so my app becomes default for tel protocol) ? My app doesn't have CLSID.

A:

You can find a bunch of keys which are needed for tel protocol on net. But the most important for win 10 is [HKEY_CURRENT_USER\SOFTWARE\RegisteredApplications] MyApp="Software\MyApp\Capabilities". Of course under Capabilities you have to have tel protocol.


Q:

Unfortunately (app) has stopped android developer error

I am getting an "unfortunately (app) has stopped" error when I try to run my app on my android phone. The app is supposed to provide an easy interface for controlling a arduino with a bluetooth module Below is my Logcat.  Please provide help with this error, I am a first time eclipse user so as many details as possible would be great.
04-12 14:14:54.848: D/AndroidRuntime(20026): Shutting down VM
04-12 14:14:54.848: W/dalvikvm(20026): threadid=1: thread exiting with uncaught  exception (group=0x415a9b90)
04-12 14:14:54.858: E/AndroidRuntime(20026): FATAL EXCEPTION: main
04-12 14:14:54.858: E/AndroidRuntime(20026): Process: com.example.fridgeshoot, PID: 20026
04-12 14:14:54.858: E/AndroidRuntime(20026): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fridgeshoot/com.example.fridgeshoot.MainActivity}: java.lang.SecurityException: Need BLUETOOTH permission: Neither user 10117 nor current process has android.permission.BLUETOOTH.
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.app.ActivityThread.access$700(ActivityThread.java:135)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.os.Handler.dispatchMessage(Handler.java:102)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.os.Looper.loop(Looper.java:137)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.app.ActivityThread.main(ActivityThread.java:4998)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at java.lang.reflect.Method.invokeNative(Native Method)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at java.lang.reflect.Method.invoke(Method.java:515)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at dalvik.system.NativeStart.main(Native Method)
04-12 14:14:54.858: E/AndroidRuntime(20026): Caused by: java.lang.SecurityException: Need BLUETOOTH permission: Neither user 10117 nor current process has android.permission.BLUETOOTH.
04-12 14:14:54.858: E/AndroidRuntime(20026):    at    android.os.Parcel.readException(Parcel.java:1461)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.os.Parcel.readException(Parcel.java:1415)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.bluetooth.IBluetooth$Stub$Proxy.isEnabled(IBluetooth.java:575)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.bluetooth.BluetoothAdapter.isEnabled(BluetoothAdapter.java:452)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at com.example.fridgeshoot.MainActivity.checkBTState(MainActivity.java:180)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at com.example.fridgeshoot.MainActivity.onCreate(MainActivity.java:53)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.app.Activity.performCreate(Activity.java:5243)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-12 14:14:54.858: E/AndroidRuntime(20026):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
04-12 14:14:54.858: E/AndroidRuntime(20026):    ... 11 more
04-12 14:21:20.479: D/AndroidRuntime(20303): Shutting down VM
04-12 14:21:20.479: W/dalvikvm(20303): threadid=1: thread exiting with uncaught exception (group=0x415a9b90)
04-12 14:21:20.479: E/AndroidRuntime(20303): FATAL EXCEPTION: main
04-12 14:21:20.479: E/AndroidRuntime(20303): Process: com.example.fridgeshoot, PID: 20303
04-12 14:21:20.479: E/AndroidRuntime(20303): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fridgeshoot/com.example.fridgeshoot.MainActivity}: java.lang.SecurityException: Need BLUETOOTH permission: Neither user 10117 nor current process has android.permission.BLUETOOTH.
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.app.ActivityThread.access$700(ActivityThread.java:135)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.os.Handler.dispatchMessage(Handler.java:102)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.os.Looper.loop(Looper.java:137)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.app.ActivityThread.main(ActivityThread.java:4998)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at java.lang.reflect.Method.invokeNative(Native Method)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at java.lang.reflect.Method.invoke(Method.java:515)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at dalvik.system.NativeStart.main(Native Method)
04-12 14:21:20.479: E/AndroidRuntime(20303): Caused by: java.lang.SecurityException: Need BLUETOOTH permission: Neither user 10117 nor current process has android.permission.BLUETOOTH.
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.os.Parcel.readException(Parcel.java:1461)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.os.Parcel.readException(Parcel.java:1415)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.bluetooth.IBluetooth$Stub$Proxy.isEnabled(IBluetooth.java:575)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.bluetooth.BluetoothAdapter.isEnabled(BluetoothAdapter.java:452)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at com.example.fridgeshoot.MainActivity.checkBTState(MainActivity.java:180)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at com.example.fridgeshoot.MainActivity.onCreate(MainActivity.java:53)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.app.Activity.performCreate(Activity.java:5243)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-12 14:21:20.479: E/AndroidRuntime(20303):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
04-12 14:21:20.479: E/AndroidRuntime(20303):    ... 11 more
04-12 14:21:20.489: I/Process(20303): Sending signal. PID: 20303 SIG: 9
04-12 14:30:39.706: W/ActivityThread(20973): Application com.example.fridgeshoot is waiting for the debugger on port 8100...
04-12 14:30:39.716: I/System.out(20973): Sending WAIT chunk
04-12 14:30:39.916: I/dalvikvm(20973): Debugger is active
04-12 14:30:39.916: I/System.out(20973): Debugger has connected
04-12 14:30:39.926: I/System.out(20973): waiting for debugger to settle...
04-12 14:30:40.127: I/System.out(20973): waiting for debugger to settle...
04-12 14:30:40.327: I/System.out(20973): waiting for debugger to settle...
04-12 14:30:40.527: I/System.out(20973): waiting for debugger to settle...
04-12 14:30:40.727: I/System.out(20973): waiting for debugger to settle...
04-12 14:30:40.928: I/System.out(20973): waiting for debugger to settle...
04-12 14:30:41.128: I/System.out(20973): waiting for debugger to settle...
04-12 14:30:41.338: I/System.out(20973): waiting for debugger to settle...
04-12 14:30:41.538: I/System.out(20973): waiting for debugger to settle...
04-12 14:30:41.738: I/System.out(20973): debugger has settled (1447)
04-12 14:30:42.669: D/dalvikvm(20973): threadid=1: still suspended after undo (sc=1 dc=1)

A:

As chrylis already mentioned, error-message speaks for itself:
Need BLUETOOTH permission
Your AndroidManifest.xml should be like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.appname" >

<uses-permission android:name="android.permission.BLUETOOTH"/>
<application
    <<<there goes the rest of manifest>>>


Q:

Unimplemented type 'builtin' in 'coerceToReal' [Rcpp]

I have just started with Rcpp. I have a simple program which takes two numerical vectors, computes their union and returns a numerical vector. The listing is pasted below (test.cpp).
#include <Rcpp.h>
#include <algorithm>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector test(NumericVector x, NumericVector y) {
  int n = x.size() + y.size();
  std::vector<int> v(n);
  std::vector<int>::iterator it;

  std::sort(x.begin(), x.end());
  std::sort(y.begin(), y.end());

  it=std::set_union(x.begin(), x.end(), y.begin(), y.end(), v.begin());
  v.resize(it-v.begin());

  return wrap(v);
}

/*** R
x <- c(5,10,15,20,25)
y <- c(50,40,30,20,10)
test(x, y)
*/

When I try to run the program with values
x <- sample(20000)
y <- sample(20000)
test(x, y)

the function works. But when I increase number of values
x <- sample(1000000)
y <- sample(1000000)
test(x, y)

the program crashes with the output
Error in .Primitive(".Call")(<pointer: 0x7f1819d8af20>, x, y) :
  unimplemented type 'builtin' in 'coerceToReal'

Any ideas what is happening? Thanks for any pointer or reference.

A:

Replace your NumericVectors by IntegerVectors.
Or work with std::vector<double>.


Q:

How can I make keyboard cursor move faster?

How can I make my keyboard faster? For example if I press arrow keys the cursor moves with a certain speed. I want it at least 2x faster.
In Control Panel all speed settings are at maximum. I have a gamer keyboard: Raze Black Widows (but not because I am a gamer :)

A:

Solved here (totally different question):
Keyboard - Repeat Rate/Repeat Delay values in Win7
Edit [HKEY_CURRENT_USER\Control Panel\Accessibility\Keyboard Response]
to be:
[HKEY_CURRENT_USER\Control Panel\Accessibility\Keyboard Response]
"AutoRepeatDelay"="150"
"AutoRepeatRate"="15"
"DelayBeforeAcceptance"="0"
"Flags"="59"

IT IS A HACK! Not totally happy with it. But it works.
Drawback: a new icon ('Accessibility', looks like a stopwatch) will appear in system tray. Hide it. Never open it. If you open it and you press OK, your current registry values will be overwritten.


Q:

Can I use generics wildcard in List declaration?

Consider the following codes:
class Super {}
class Sub extends Super {}
class Test {
    public static void main(String[] args) {
        List<? extends Super> list = new ArrayList<Sub>(); //1
        list.add(new Sub()); //2
    }
}

Line 1 compiles successfully, but line 2 fails compilation:
The method add(capture#2-of ? extends Super) in the type List<capture#2-of ? extends Super> is not applicable for the arguments (Sub)

My questions are:
1) Why does line 1 successfully compile?
2) Is line 1 a good practice in declaring a List (or other collections)?
3) Why does line 2 fail compilation, after list was declared to be type Sub in line 1?
4) Eclipse's autocompletion says only "null" elements are allowed in list now. Why?
Thanks a lot!

A:

1) Why does line 1 successfully compile?

The first line compiles because List<Sub> is subclass of List<? extends Super> and that can only be true if List does not allow you to add any new members to it.
? means that you don't exactly know that it is a List<Sub> or List<Sub1>, so it is unsafe to allow adding of new elements into the list and so it does not allow it.

2) Is line 1 a good practice in declaring a List (or other
  collections)?

If you already know that it is going to be List<Sub> then I don't find any use, but wildcards are used much when you are passing the List around to other classes like Utilities.

3) Why does line 2 fail compilation, after list was declared to be
  type Sub in line 1?

Because as I already explained it is unsafe to add any element to list when you dont know the exact type.

4) Eclipse's autocompletion says only "null" elements are allowed in
  list now. Why?

Because null is of every reference type, this is why you can assign any object a value of null.
Always remember PECS (Producer Extends Consumer Super) rule by Josh Bloch when working with generics
Good References:

Difference between ? extends and ? super
When do we require <? extends T> as compared to <T>

A:

Capturing declarations as in line 1 are good in method arguments. See Collection.addAll(Collection<? extends E>). If you need a list with something extends Super, just use List<Super>.


Q:

C#.NET, Adding AD user to AD group - The object already exists

I've been tasked with creating a solution to add and remove AD users to and from AD groups. The following code is functional, except when I try to save the group. I'm getting an exception of "The object already exists." I've narrowed down the issue (I think) to the SamAccountName, and I think that is what is causing the exception.
I don't have access to modify anything in AD aside from the permissions I've been granted to modify the groups designated to have users added/removed from them. I've done endless research, and I just haven't been able to determine a solution. Any help would be deeply appreciated. Thanks in advance.
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "address", "DN", "username", "password");
GroupPrincipal grp = new GroupPrincipal(ctx, sGroup);
UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, sUser);
if (grp != null)
{
    grp.Members.Add(usr);
    grp.Save();
}

A:

It appears to me that you are creating a new group with the same name as an existing one. Instead of
GroupPrincipal grp = new GroupPrincipal(ctx, sGroup);

could you try
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, sGroup);

to get the existing group and then modify that?


Q:

OCSP Stapling for Thawte certificates does not work

OCSP Stapling does not work for Thawte certificates on Nginx, what could be the problem?
Configured Nginx to work with OCSP Stapling.
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /ssl/ssl_trusted_certificate.crt;

The ssl_trusted_certificate.crt certificate includes the stitched root.crt and intermediate.crt.
The verification request indicates that OCSP Stapling is still off:
Openssl s_client -connect xxx.xxx:443 -tls1 -tlsextdebug -status

Result:
OCSP Response: No response sent

Who knows this problem?

A:

As it turned out, the problem was not in the certificate and server settings. In order for OCSP Stapling to work, you need to go through a couple of pages of the site. On the first request, the server will request data from the certification center servers, and then go to OCSP.


Q:

Recurrences using Substitution Method

Determine the positive number c & n0 for the following recurrences (Using Substitution Method):

T(n) = T(ceiling(n/2)) + 1 ... Guess is Big-Oh(log base 2 of n)
T(n) = 3T(floor(n/3)) + n ... Guess is Big-Omega (n * log base 3 of n)
T(n) = 2T(floor(n/2) + 17) + n ... Guess is Big-Oh(n * log base 2 of n).

I am giving my Solution for Problem 1:
Our Guess is: T(n) = O (log_2(n)).
By Induction Hypothesis assume T(k) <= c * log_2(k) for all k < n,here c is a const & c > 0
     T(n) = T(ceiling(n/2)) + 1
<=>  T(n) <= c*log_2(ceiling(n/2)) + 1
<=>   "   <= c*{log_2(n/2) + 1} + 1
<=>   "    = c*log_2(n/2) + c + 1
<=>   "    = c*{log_2(n) - log_2(2)} + c + 1
<=>   "    = c*log_2(n) - c + c + 1
<=>   "    = c*log_2(n) + 1
<=>   T(n) not_<= c*log_2(n)      because c*log_2(n) + 1 not_<= c*log_2(n).

To solve this remedy used a trick a follows:
    T(n) = T(ceiling(n/2)) + 1
<=>  "  <= c*log(ceiling(n/2)) + 1
<=>  "  <= c*{log_2 (n/2) + b} + 1             where  0 <= b < 1
<=>  "  <= c*{log_2 (n) - log_2(2) + b) + 1
<=>  "   = c*{log_2(n) - 1 + b} + 1
<=>  "   = c*log_2(n) - c + bc + 1
<=>  "   = c*log_2(n) - (c - bc - 1)      if c - bc -1 >= 0
                                             c >= 1 / (1 - b)
<=> T(n) <= c*log_2(n) for c >= {1 / (1 - b)}

so T(n) = O(log_2(n)).

This solution is seems to be correct to me ... My Ques is: Is it the proper approach to   do?

Thanks to all of U.

A:

For the first exercise:
We want to show by induction that T(n) <= ceiling(log(n)) + 1.
Let's assume that T(1) = 1, than T(1) = 1 <= ceiling(log(1)) + 1 = 1 and the base of the induction is proved.
Now, we assume that for every 1 <= i < nhold that T(i) <= ceiling(log(i)) + 1.
For the inductive step we have to distinguish the cases when n is even and when is odd.

If n is even: T(n) = T(ceiling(n/2)) + 1 = T(n/2) + 1 <= ceiling(log(n/2)) + 1 + 1 = ceiling(log(n) - 1) + 1 + 1 = ceiling(log(n)) + 1.

If n is odd: T(n) = T(ceiling(n/2)) + 1 = T((n+1)/2) + 1 <= ceiling(log((n+1)/2)) + 1 + 1 = ceiling(log(n+1) - 1) + 1 + 1 = ceiling(log(n+1)) + 1 = ceiling(log(n)) + 1

The last passage is tricky, but is possibile because n is odd and then it cannot be a power of 2.


Q:

Whether the dedicated camera module of raspberry pi 3 is a not available in Windows 10 IoT Core

All.
I am using a dedicated camera module for the raspberry pi 3.
The operating system is using Windows10 IoT Core.
I'd like to operate the camera module previously described by universal Windows application, but I saw an article that is not available other than the Web camera.
However, such as Windows10 IoT Core of raspberry pi 3 in one article is insider preview is, also the official version in some articles, I am confused by the variety of articles.
https://developer.microsoft.com/en-us/windows/iot/docs/hardwarecompatlist#Cameras
Dedicated camera module Will that not available from the current even Windows 10 IoT Core.
Thank you.

A:

Dedicated pi camera module is not supported by windows IoT core yet, see to this post.。
But it's definitely on the way. And if you may find something useful, this is the official ms iot bsp repository.
So, stay tuned.


Q:

A Question About The Tower Of Hanoi

I've been reading through an inductive proof on why the minimum number of moves in a Tower of Hanoi with n disks is $2^n -1$. The proof is based on the fact that the minimum amount of moves for $k+1$ disks is $2T(k) + 1$: $T(k+1) =2T(k)+1$.
I understand that this is because you need to move the top $k$ disks to the center post, which can be done in a minimum of $T(k)$ moves. Then, you need to move the bottom disk to the final post, which can be done in $1$ move. Finally, you need to move the top $k$ disks to the final post, which can be done in a minimum of $T(k)$ moves.
But what I don't understand is why this method of moving disks is the quickest: why isn't there a method of moving disks that is quicker than this, that requires less moves? I haven't been able to devise a method that is quicker than the above, but that doesn't show that the method above is the quickest either!
So my question is, why is this method of moving disks the quickest? How can it be proved?
Thanks in advance.

A:

Here is a reply to the OP's comment:
For $1$ disk, the quickest way is by moving the disk to the rightmost pole, which takes $1$ move.
For $2$ disks, we have one disk on top, which we already figured out how we can move the quickest. We first move the disk on top, then move the disk on the bottom to the final position, then move the disk on top to the final position.
For $3$ disks, consider the top $2$ disks as one object, where we know the quickest way to move the $2$ disks. Then we have to move the bottom disk and the top two disks, which we can treat as two separate objects, and we proceed in the same way like we had with $2$ disks.
In general, given $n$ disks, the top $n-1$ disks are one object which we cannot move any faster. Then by adding another disk on the bottom, we can extend the quickest way of moving to $n$ disks. In other words, we can successively reduce a problem involving $n$ disks to a problem that only includes $2$ objects.
What justifies all of this is that we know the 'fastest method' you mentioned works for $n = 1$. Induction proves that given the base case $n=1$ holds, the next case holds. Repeating the process of induction arbitrarily many times ensures that this can be proved for any $n$.


Q:

Can't use options with io.elementary.terminal

For example :
io.elementary.terminal -h
produces the following output
[DEBUG 21:57:54.738715] Settings.vala:163: Loading settings from schema 'io.elementary.terminal.settings'
Usage:
  io.elementary.terminal [OPTION…]

Why do I need this to work?

I have to change "Terminal to launch console program" from xterm -T $TITLE -e to elementary's OS (Juno) io.elementary.terminal -e in CodeBlocks.

A:

Well this works for me in Hera 5.1.3 in codeblocks. Copy paste this to Settings>Environment settings>Terminal to launch console program
io.elementary.terminal -t $TITLE -x


Q:

Text-align :center not working even after setting display:block

I am trying to center the form contents .But its not working even after setting display:block for the container of form and then applying text-align:center;I did another work around put padding:0 33% it centered the form contents but with different view port sizes it would shrink the text box size .I want to center the form elements and want them to occupy the container size and please explain why this is happenning and what is that I have overlooked .I want it to able work for all view port sizes .I want to know the reason causing this which overrides even inline code
Demo
CSS
 #Banner{
         background:url('http://i67.tinypic.com/midkki.png') no-repeat center center fixed;
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
         width:100%;
         min-height:960px;

         }
         #Menu{
          min-height:120px;

         }
         body,html{
         padding:0;
         margin:0;
         }
         .nopm{
         padding:0;
         margin:0;
         }
        #Menu ul{
          padding:0;
         margin:0;

         }
        #Menu li{
         list-style:none;
         float:left;
         padding:1em .3em;
         float:left;
         margin:2em 0;

         }
         #Menu a{

           text-decoration:none;
           font-family: Rockwell,Courier Bold,Courier,Georgia,Times,Times New Roman,serif;
        font-size: 24px;
        font-style: normal;
        font-variant: normal;
        font-weight: 600;
        line-height: 28px;
        color:#fff;
        margin:1em .5em;
        padding:10px;
        border:2px solid #fff;

         }
         a:hover{

          border:4px solid #FFD700;
            -webkit-transition-delay: 2s; /* Safari */
        transition-delay: 2s;
         }
           @media (max-width:420px){

        li{

            width:100%;
      text-align:center;

        }
          img{
       display:block;
       width:90px;
       height:90px;
       margin:0 auto;
      }
      }
    h1,h3{color:#fff;
        text-align:center;

        }
        #Slogan
    {
    padding:2em 0;
    }
    #SignUpWrapper{
    width:100%;
     text-align: center;
    display:block;
    }
    form{

    width:100%;
    }
    input[type="text"],[type="email"],[type="password"]{
    font-family: Rockwell,Courier Bold,Courier,Georgia,Times,Times New Roman,serif;
        font-size: 19px;
        font-style: normal;
        font-variant: normal;
        font-weight: 600;
        line-height: 25px;
        color:#000 !important;
    padding:.5em;
    width:100%;

    }

HTML

            Events

            Login

Welcome to Meet Up Place

SignUp to create your own events

                    <form  autocomplete="on">

                                First Name

                                 <input class="form-control" id="fName" type="text" placeholder="First Name"   >

                            Last Name

                            <input id="lName" type="text" placeholder="Last Name" />

                            E-Mail

                            <input id="lName" type="email" placeholder="E-Mail" />

                    </form>

A:

Put display: inline-block; and remove width: 100%; on the form and it works.
See it here
If you want to center the inner content, try this :
.input-group { display: block !important; }
.form-control, input[type="text"], [type="email"], [type="password"] { text-align : center !important;}

I use !important because the style is in the HTML panel instead of the CSS one.
Your inline style is applied :


Q:

Проблема с открытием View Controller "Assertion failure in.."

При нажатии на кнопку должен открыть View Controller.
- (IBAction)open:(id)sender {
ExtendedFormViewController *extView = [[ExtendedFormViewController alloc] initWithNibName:@"ExtendedFormViewController" bundle:nil];
    [self presentViewController:extView animated:YES completion:nil];
}

Но вылетает ошибка:
*** Assertion failure in -[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:animation:], /SourceCache/UIKit/UIKit-2903.23/UIWindowController.m:223
Что странно, такая ошибка вылетает если я пытаюсь загрузить новые, созданные сейчас View Controller'ы. Если попробовать загрузить созданный ранее контроллер, то все получается нормально.
Попробовал очистить Derived Data, но безуспешно. Такое ощущение, будто я превысил лимит вью контроллеров в проекте:/
Update: Может ли быть в ошибка в этом:
При запуске приложения, самым первым загружается View Controller(форма регистрации, если пользователь не зарегистрирован), который в методе  - (void)viewDidLayoutSubviews проверяет в NSUserDefaults, заполнено ли поле @"mode", и если оно не пустое, то загружет соответствующий вью контроллер.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *mode = [userDefaults objectForKey:@"mode"];
if ([mode isEqualToString:@"client"]) {
        ClientViewController *secondViewController = [[ClientViewController alloc]initWithNibName:@"ClientViewController"               bundle:nil];
        [self presentViewController:secondViewController animated:NO completion:nil];
    } else if ([mode isEqualToString:@"driver"]) {
        DriverViewController *secondViewController = [[DriverViewController alloc]initWithNibName:@"DriverViewController"               bundle:nil];
        [self presentViewController:secondViewController animated:NO completion:nil];
    }

А в  ClientViewController, есть этот метод open, который не работает.
Может я неправильно использую presentViewController?
Еще похожая проблема была в этой теме, которую заминусовали - здесь
UPDATE 2: Проблема решена. Дети, всегда проверяйте от какого класса наследуется контроллер. Я вместо UIViewController, наследовал от обычного ViewController.

A:

Какой-то исполняемый код, выполняется до того как контроллер прогрузится. проверьте реализацию ExtendedFormViewController точно ли он наследуется от UIViewController.
и второе, может быть нарушена иерархия вьюх и контролов, хотя это врядли.
еще можете попробывать очистить проект CMD+shift+K (+option для полной очистки билд папки)
А, ну и дебагер в помощь.


Q:

Multiple SOAP endpoints with one namespace & localpart

I created a SOAP web service server with SpringBoot and I was able to successfully create one endpoint.
However, I cannot create multiple endpoints and access them with different URLs.
I want to handle the process by URL to access.
The SOAP message received by each endpoint has the same schema. (Namespace and localpart are the same !!!)
And I don't want to make the WSDL public.
For example.
userA sends the following SOAP message to the following URL: http://soap.example.com/ws/userA
<S:Envelope>
    <SOAP-ENV:Header>
    </SOAP-ENV:Header>
    <S:Body>
        <testsoap:post
            xmlns:testsoap="http://soap.example.com/">
            <testsoap:message>
                I am UserA
            </testsoap:message>
        </testsoap:post>
    </S:Body>
</S:Envelope>

userB sends the following SOAP message to the URL: http://soap.example.com/ws/userB
<S:Envelope>
    <SOAP-ENV:Header>
    </SOAP-ENV:Header>
    <S:Body>
        <testsoap:post
            xmlns:testsoap="http://soap.example.com/">
            <testsoap:message>
                I am UserB
            </testsoap:message>
        </testsoap:post>
    </S:Body>
</S:Envelope>

The source code is as follows.
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {

    @Autowired
    CustomConfig customConfig;

    @Bean
    public ServletRegistrationBean<MessageDispatcherServlet> messageDispatherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);
        return new ServletRegistrationBean<MessageDispatcherServlet>(servlet, "/ws/*");
    }
}

I want to access at http://soap.example.com/ws/userA
@Endpoint
public class SoapRequestEndpoint {
    private static final String NAMESPACE_URI = "http://soap.example.com/";

    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "post")
    @ResponsePayload
    public JAXBElement<PostResponse> postForA(MessageContext messageContext) {
        // do something for userA
    }
}

I want to access at http://soap.example.com/ws/userB
@Endpoint
public class SoapRequestEndpoint {
    private static final String NAMESPACE_URI = "http://soap.example.com/";

    @PayloadRoot(namespace = NAMESPACE_URI, localPart = "post")
    @ResponsePayload
    public JAXBElement<PostResponse> postForB(MessageContext messageContext) {
        // do something for userB
    }
}

Thanks.
Updated on September 24th, 2019
I have worked hard since then, but I still don't understand.
I don't think it's written in the official reference.
Do you have any ideas?
Updated on October 3, 2019
I haven't solved it yet.
If this is the case, it will be difficult to work.
Please help someone.

A:

Try to create an additional Wsdl11Definition method in the WebServiceConfig class and annotate the method with @Bean(name = "UserB").
You have only shown a snippet from your WebServiceConfig class, I am assuming that this is absent from the class.
Your class should look similar to this:
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {

    @Autowired
    CustomConfig customConfig;

    @Bean
    public ServletRegistrationBean<MessageDispatcherServlet> messageDispatherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        servlet.setTransformWsdlLocations(true);
        return new ServletRegistrationBean<MessageDispatcherServlet>(servlet, "/ws/*");
    }
}

@Bean(name = "userA")
    public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema [randomMethodSchema]) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("userAPort");
        wsdl11Definition.setLocationUri("/ws");
        wsdl11Definition.setTargetNamespace("http://soap.example.com/");
        wsdl11Definition.setSchema([randomMethodSchema]);
        return wsdl11Definition;
    }

@Bean(name = "userB")
    public DefaultWsdl11Definition defaultWsdl11Definition2(XsdSchema [randomMethodSchema]) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("userBPort");
        wsdl11Definition.setLocationUri("/ws");
        wsdl11Definition.setTargetNamespace("http://soap.example.com/");
        wsdl11Definition.setSchema([randomMethodSchema]);
        return wsdl11Definition;
    }

    @Bean
    public XsdSchema [randomMethodSchema]() {
        return new SimpleXsdSchema(new ClassPathResource([schema name].xsd));
    }
}

HTH


Q:

Values for uilabels of custom tableview cell is not being set

Im using a tableview with custom cells.
Following is my cellForRowAtIndexPath method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

//    AssigneeCell *cell = (AssigneeCell *)[tableView dequeueReusableCellWithIdentifier:@"Cell"];

    static NSString *cellIdentifier = @"Cell";
    AssigneeCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (!cell)
    {
        [tableView registerNib:[UINib nibWithNibName:@"AssigneewiseView" bundle:nil] forCellReuseIdentifier:@"Cell"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];

        NSLog(@"call");
    }

    cell.unitNameVal = unitNameResult[indexPath.row];
    cell.domainNameVal = domainNameResult[indexPath.row];
    cell.compliedVal = compliedResult[indexPath.row];
    cell.delayedVal = delayedResult[indexPath.row];
    cell.inProgressVal = inProgressResult[indexPath.row];
    cell.notCompliedVal = notCompliedResult[indexPath.row];
    cell.totalVal = totalValResult[indexPath.row];

    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return [compliedResult count];
}

numberOfRowsInSection is called and hence my tableview contains  multiple views depending upon the count of compliedResult.
But the problem is that, the values for uilabels present in my custom cell is not being assigned and hence its not visible. Why is that so?

A:

First suggestion, create your model:
@interface Result: NSObject
@property (nonatomic) NSString* unitName;
@property (nonatomic) NSString* domainName;
@property (nonatomic) NSString* complied;
@property (nonatomic) NSString* delayed;
@property (nonatomic) NSString* inProgress;
@property (nonatomic) NSString* notComplied;
@property (nonatomic) NSString* totalVal;
@end

In this way, your viewController will have an array of Result object.
Inside your custom cell, define:
@implementation AssigneeCell

+ (NSString*)cellIdentifier {
   return @"Cell";
}

- (void)setupWithResult:(Result*)result {
    self.unitNameVal.text = result.unitName;
    self.domainNameVal.text = result.domainName;
    self.compliedVal.text = result.complied;
    self.delayedVal.text = result.delayed;
    self.inProgressVal.text = result.inProgress;
    self.notCompliedVal.text = result.notComplied;
    self.totalVal.text = result.totalVal;
}

@end

Finally in your view controller:
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView registerNib:[UINib nibWithNibName:@"AssigneewiseView" bundle:nil] forCellReuseIdentifier:[AssigneeCell cellIdentifier]];
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    static NSString* cellIdentifier = [AssigneeCell cellIdentifier];
    AssigneeCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    [cell setupWithResult: results[indexPath.row]];
    return cell;
}

This ensure clean code and code reuse.


Q:

SQL Matching many-to-many dates for ID field

Edit: Fixed Start Date for User 2
I have a list of user ids, each having many start dates and many end dates.
A start date can be recorded many times after the "actual" start date of an "event", same goes for the end date.
The result should be each the first start date and first end date for each user "event"
I hope that makes sense, see the example below.
Thanks!
Assuming the Following tables are given:
Start Table:
+--------+-------------+
| UserID |  Start      |
+--------+-------------+
|      1 | 2019-01-01  |
|      1 | 2019-01-02  |
|      1 | 2019-01-03  |
|      1 | 2019-04-01  |
|      1 | 2019-04-02  |
|      1 | 2019-04-03  |
|      2 | 2019-06-01  |
|      2 | 2019-06-02  |
|      2 | 2019-10-01  |
|      2 | 2019-10-02  |
+--------+-------------+

End Table:
+--------+------------+
| UserID |  End       |
+--------+------------+
|      1 | 2019-03-01 |
|      1 | 2019-03-02 |
|      1 | 2019-03-03 |
|      1 | 2019-05-01 |
|      1 | 2019-05-02 |
|      1 | 2019-05-03 |
|      2 | 2019-08-01 |
|      2 | 2019-08-02 |
|      2 | 2019-12-01 |
|      2 | 2019-12-02 |
+--------+------------+

Result:
+--------+------------+------------+
| UserID |   Start    |  End       |
+--------+------------+------------+
|      1 | 2019-01-01 | 2019-03-01 |
|      1 | 2019-04-01 | 2019-05-01 |
|      2 | 2019-06-01 | 2019-08-01 |
|      2 | 2019-10-01 | 2019-12-01 |
+--------+------------+------------+

A:

Not sure I agree with your 2019-10-02
Here is one solution
Example
Select UserID
      ,[Start]  = min([Start])
      ,[End]
From (
        Select A.*
              ,[End] = (Select min([End]) From EndTable Where UserID=A.UserID  and [End] >= A.Start )
        From  StartTable A
     ) A
Group By UserID,[End]

Returns
UserID  Start       End
1       2019-01-01  2019-03-01
1       2019-04-01  2019-05-01
2       2019-06-01  2019-08-01
2       2019-10-01  2019-12-01


Q:

Closed form for $\int \left(1-x^{2/3}\right)^{3/2}\:dx$

Find a closed-form solution to
\begin{align}\int_0^1 \left(1-x^{2/3}\right)^{3/2}\:dx\tag{1},\end{align}
or even more generally, is there a methodology to solving integrals of the type
\begin{align}
\int_0^1\left(1-x^r\right)^{1/r}\:dx,\:\:r\in\left\{s\in\mathbb{Q}:0<s<1\right\}.\tag{2}
\end{align}
This integral arose when trying to calculate the area of a Superellipse.
Thank you for your time,

A:

Since $x\leq1$
 , we can try $x=\sin^{3}\left(y\right)$
  and then $dx=3\sin^{2}\left(y\right)\cos\left(y\right)dy$
 , whence$$\intop\left(1-x^{2/3}\right)^{3/2}dx=3\intop\cos^{4}\left(y\right)\sin^{2}\left(y\right)dy.$$
Maybe this last integral is easier to work.

A:

Through the Euler's Beta function it is not difficult to show (like in this closed question) that for any $p,q>0$ we have:
$$\int_{0}^{1}(1-x^p)^{\frac{1}{q}}\,dx=\int_{0}^{1}(1-x^q)^{\frac{1}{p}}\,dx =\frac{\Gamma\left(1+\frac{1}{p}\right)\Gamma\left(1+\frac{1}{q}\right)}{\Gamma\left(1+\frac{1}{p}+\frac{1}{q}\right)} $$
hence by choosing $p=q=\frac{2}{3}$ we have:
$$ I = \frac{\Gamma\left(\frac{5}{2}\right)^2}{\Gamma(4)} = \color{red}{\frac{3\pi}{32}}$$
and if $p=q=r$
$$ I = \frac{\Gamma\left(1+\frac{1}{r}\right)^2}{\Gamma\left(1+\frac{2}{r}\right)}=\frac{r}{2}\cdot\frac{\Gamma\left(\frac{1}{r}\right)^2}{\Gamma\left(\frac{2}{r}\right)}=\frac{r\sqrt{\pi}}{2^{2/r}}\cdot\frac{\Gamma\left(\frac{1}{r}\right)}{\Gamma\left(\frac{1}{2}+\frac{1}{r}\right)} $$
by Legendre's duplication formula.


Q:

Javascript object key is not accessible

I am using the Samsung Tizen SDK for SmartTV app development. I have some code that converts CSV to a Javascript object. I am having problems accessing one of the keys in the object that is created from the code.
Code:
function csvJSON(csv) {

var lines = csv.split("\n");

var result = [];

var headers = lines[0].split(",");

for (var i = 1; i < lines.length; i++) {

    var obj = {startTime:'',
            endTime:'',
            day:''};

    var currentline = lines[i].split(",");

    for (var j = 0; j < headers.length; j++) {
        obj[headers[j]] = currentline[j];
    }

    result.push(obj);

}

return result; // JavaScript object

}
My inputs to this function look like:
Input to function
While debugging the return result line in the console developer mode (I set a local watch of obj.endTime), I cannot access the endTime key, despite it showing up in the debugger. It is almost as if a special character is involved somehow.
endTime key
I tried the same snippet of code in jsFiddle and it worked ... so it seems like something related to the version of Javascript/ECMAScript that is running on the Tizen Emulator. Perhaps this was an issue in earlier versions of Javascript ?
Thanks!

A:

I would check that endTime in your csv header is truly equal to endtime, i.e.

endTime1 = 'endTime'
endTime2 = '\uff45ndTime'
console.log(`${endTime1} equals ${endTime2} is ${endTime1 === endTime2}`)
// endTime equals ｅndTime is false

obj = {}
obj[endTime1] = 'endTime1'
obj[endTime2] = 'endTime2'
console.log(obj)
// {
//   "endTime": "endTime1",
//   "ｅndTime": "endTime2"
// }

Any reason why you are not using a library for this?, e.g.
http://papaparse.com/docs#csv-to-json


Q:

TextView inside ListView get changed on scrolling

I have a custom adapter that displays the messages in conversation. Now I want to bold the textview if the message is not read and otherwise unbold it. However when I scroll the listview of that adapter, the TextViews do not keep the previous setup, they lose the bolded text or bold the read text. I have tried many solutions on SO, however nothing has worked so far.
I have put all the variables into a holder class:
private class Holder {
    public TextView messageTo, messageContent, date;
    public ImageView imgView;
    public Typeface face, bold;
    public int boldText, normalText;
    public int readState;
}

and in getView I get the message item at the position and retrieve the readState from there (some redundant parts have been omitted)
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View convertView1 = convertView;
    LayoutInflater vi = (LayoutInflater) ctx
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Message message = getItem(position);
    if (convertView1 == null) {
        holder = new Holder();
        convertView1 = vi.inflate(R.layout.list_view_main, parent,
                false);
        holder.messageTo = (TextView) convertView1
                .findViewById(R.id.address);
        holder.messageContent = (TextView) convertView1
                .findViewById(R.id.previewMsg);
        holder.date = (TextView) convertView1.findViewById(R.id.showDate);
        holder.imgView = (ImageView) convertView1
                .findViewById(R.id.quickBadge);
        holder.face = Typeface.createFromAsset(ctx.getAssets(),
                "fonts/helveticaneuelight.ttf");
        holder.bold = Typeface.createFromAsset(ctx.getAssets(),
                "fonts/helveticaneue.ttf");
        holder.boldText = Typeface.BOLD;
        holder.normalText = Typeface.NORMAL;
        holder.readState = getItem(position).readState;
        convertView1.setTag(holder);
    } else {
        holder = (Holder) convertView1.getTag();
    }

    if(holder.readState==0) {
        holder.messageTo.setText(message.messageNumber);
        holder.messageContent.setText(message.messageContent);
        holder.date.setText(message.messageDate);
        holder.messageTo.setTypeface(holder.bold, holder.boldText);
        holder.messageContent.setTypeface(holder.face, holder.boldText);
        holder.date.setTypeface(holder.face, holder.boldText);
    } else {
        holder.messageTo.setText(message.messageNumber);
        holder.messageContent.setText(message.messageContent);
        holder.date.setText(message.messageDate);
        holder.messageTo.setTypeface(holder.bold, holder.normalText);
        holder.messageContent.setTypeface(holder.face, holder.normalText);
        holder.date.setTypeface(holder.face, holder.normalText);
    }
    return convertView1;
}

But it does not work. Anyone has a solution for this?

A:

Try this
if(message.readState==0) {
    // keep your other part of the code as it is
    // set font
} else {
   // keep your other code as it is
    // set font
}

You can get rid of
 holder.readState = getItem(position).readState;

To understand how it works
How ListView's recycling mechanism works


Q:

Disabling error logging in CodeIgniter for a specific helper/library

I am using the mPDF class to generate PDFs from HTML.
While the PDFs show exactly like they should, my CodeIgniter error log gets packed with error notices that seem to be due to some bug in mPDF.
Since these notices are harmless and the PDFs come out perfectly, all I'd like is to disable the CodeIgniter error logging specifically when I run this class.
But I haven't found a way to do this.
Here's my code:
CONTROLLER
$this->load->helper('mpdf');
mpdf($html, $filename);

HELPER (mpdf_helper.php)
function mpdf($html, $filename)
{
    $CI =& get_instance();
    $CI->config->set_item('log_threshold', 0);
    include('mpdf/mpdf.php');

    $mpdf=new mPDF('', 'letter');
    $mpdf->SetHTMLHeader('powered by example.com');
    $mpdf->WriteHTML($html, 0);
    $mpdf->Output($filename, 'I');
}

As you can see I am trying to manually set config for log_threshold to 0, but that does not prevent error logging.
FYI my index.php has
define('ENVIRONMENT', 'production');

which sets error_reporting(0).
Do you know what I should do to stop CodeIgniter from logging errors only when I run mPDF?
ERROR EXAMPLES
ERROR - 2012-08-04 23:03:59 --> Severity: Notice  --> Undefined index: direction /var/www/vhosts/asd.com/httpdocs/application/helpers/mpdf/mpdf.php 21103

ERROR - 2012-08-04 23:06:07 --> Severity: Notice  --> Undefined index: MARGIN-TOP /var/www/vhosts/asd.com/httpdocs/application/helpers/mpdf/mpdf.php 17271

A:

It's because codeigniter's error logging hooked up with set_error_handler, and php will fire handler whatever the error_reporting value is. As the php manual says:

...however you are still able to read the current value of error_reporting and act appropriately.

CI's default error handler doesn't do that for logging (but does for error displaying), just logs everything that comes in if CI's internal error level demands logging. (the log_threshold config value 1, see the function called by php error handler.)
If you want to make the CI logger respect the error_logging level you can extend the CI_Exception class with the standard method like this:
class MY_Exceptions extends CI_Exceptions {
    function log_exception($severity, $message, $filepath, $line) {
        $current_reporting = error_reporting();
        $should_report = $current_reporting & $serverity;

        if ($shoud_report) {
            // call the original implementation if we should report the error
            parent::log_exception($severity, $message, $filepath, $line);
        }
    }
}

Once you got this in place, you can fiddle with error_reporting around or in your library calls.


Q:

how can i get the result of the output clause in an update statement

im programming in c++ using ado, the documnet on tsql says the OUTPUT clause can return the result to the calling program, is there anyway i can retrieve it with ado in c++ ? if it is possible how to do that ?

A:

Setup an extra parameter in your ADO object and have the parameter direction as output. Then have your original update statement define an extra variable (which is the output variable) and assign your result to that output variable.


Q:

Repositories and Services, MVC Model

So I've been learning about the Repository model, and it seems that it is expected that Repositories do not do a lot of intricate logic. However I also read that most of the business logic should not be inside of my Controllers. So where do I put it?
I've looked at some sample applications and it seems that they have another layer called Services that do more intricate logic for things. So how does this factor into the MVC pattern?
Do I want to build my services to access my repositories, and then my controllers to access my services? Like this?
interface IMembershipService
{
 bool ValidateUser(string username, string password);
 MembershipCreateStatus Create(string username, string password);
}
interface IMembershipRepository
{
 MembershipCreateStatus Create(string username, string password);
}

class MembershipRepository : IMembershipRepository
{
 public MembershipRepository(ISession session)
 {
  **// this is where I am confused...**
 }
}
class MembershipService : IMembershipService
{
 private readonly IMembershipRepository membershipRepository;
 public MembershipService(IMembershipRepository membershipRepository)
 {
  this.membershipRepository = membershipRepository;
 }

 public bool ValidateUser(string username, string password)
 {
   // validation logic
 }
 public MembershipCreateStatus Create(string username, string password)
 {
  return membershipRepository.Create(username, password);
 }
}

class MembershipController : Controller
{
 private readonly IMembershipService membershipService;

 public MembershipController(IMembershipService membershipService)
 {
  this.membershipService = membershipService
 }
}

The marked part of my code is what confuses me. Everything I have read said I should be injecting my ISession into my repositories. This means I could not be injecting ISession into my services, so then how do I do Database access from my Services? I'm not understanding what the appropriate process is here.
When I put ValidateUser in my IMembershipRepository, I was told that was 'bad'. But the IMembershipRepository is where the database access resides. That's the intention, right? To keep the database access very minimal? But if I can't put other logic in them, then what is the point?
Can someone shed some light on this, and show me an example that might be more viable?
I am using Fluent nHibernate, ASP.NET MVC 3.0, and Castle.Windsor.
Should I instead do something like ...
class MembershipService
{
 private readonly IMembershipRepository membershipRepository;

 public MembershipService(ISession session)
 {
  membershipRepository = new MembershipRepository(session);
 }
}

And never give my Controllers direct access to the Repositories?

A:

Everything I have read said I should be injecting my ISession into my repositories.

That's correct. You need to inject the session into the repository constructor because this is where the data access is made.

This means I could not be injecting ISession into my services, so then how do I do Database access from my Services?

You don't do database access in your services. The service relies on one or more repositories injected into its constructor and uses their respective methods. The service never directly queries the database.
So to recap:

The repository contains the simple CRUD operations on your model. This is where the data access is performed. This data access doesn't necessary mean database. It will depend on the underlying storage you are using. For example you could be calling some remote services on the cloud to perform the data access.
The service relies on one or more repositories to implement a business operation. This business operation might depend on one or more CRUD operations on the repositories. A service shouldn't even know about the existence of a database.
The controller uses the service to invoke the business operation.
In order to decrease the coupling between the different layers, interfaces are used to abstract the operations.


Q:

iOS - update UILabel text periodically with our user interaction

I have some labels on my UI which show something like "2s ago", "1h ago"...
Now I want to update them periodically without user interaction. How could I achieve that?

A:

Use NSTimer. When the screen opens and you display the label, decide when you want it updated next. Say, you just updated the labels saying "2s ago", and the next thing that you want your users to see is "1m ago". You schedule a timer task to fire in 58 seconds, and provide a callback selector that updates the label, and schedules the next firing of the timer.
Since you are likely to update using irregular intervals (60 seconds for the first hour, then 60 minutes for the next 23 hours; one day after that) you should set your timer up without repeating.
Do not forget to cancel the timer when the view disappears.


Q:

C# List in Class - how to show everything in DataGridView

I have a problem, and I don't know how to solve it. I have searched for few hours but I stuck.
I have a class:
public class MyClass
    {
        (...)

    public MyClass(string name1, string name2, List<MyClass2> name3)
        {
            (...)
        }
    }

public class MyClass2
    {
        (...)
        public MyClass2(int number, string name4)
        {
            (...)
        }
    }

And the question is - how to put MyClass into DataGridView in a way that DataGridView can display the columns with names from MyClass and MyClass2? Is it possible?

A:

This is a little trickier in a DataGridView. Typically I would recommend something like two DataGridViews side by side, one for the list of MyClass, and one for the list of MyClass2s that reside in the active row's databound object (an instance of MyClass) in the MyClass DataGridView. Then I would set the 'selected row changed' event so that when you clicked on a row in the first DataGridView, the sublist of MyClass2s would appear in second DataGridView. It's elegant, and it works.
If you're looking for proper subrows, that's going to be a lot harder in a DataGridView. I'd suggest spoofing it by manually adding a row for the MyClass and two extra columns for the first MyClass2 in the MyClass's list. Then I would repeat that for every MyClass2 in that list.
DataGridViews don't work well with multi-level classes like this, so usually one of those two options works well in its place. I really recommend the first, as it's much simpler.
The concept is similar to what was done in my solution for this question: How to display a dictionary which contains a list in a listBox C#


Q:

how to find that there is a "Promoted to front page" node and load it in page.tpl.php?

because front page has no arg(1) (node id)  I cannot load promoted node[s] in page.tpl.php .
all I want to do is print something in one part of front page if a specific content type node in about to load in node.tpl.php.
I search it alot but find no answer.

A:

You mean a custom function?
I did a lot of this for a current project where we needed short little lists of nodes with different criterion all over.  I found Views bulky and overkill in some places, so I added small functions to template.php.  They're really just simple SQL SELECT statements.
For example:
function home_channel_list($title, $tids, $limit){

    $query = "SELECT t1.nid, MAX(t1.vid), t1.title, UNIX_TIMESTAMP(t2.field_pubdate_value) AS pubdate
                FROM {node} t1
                    JOIN field_revision_field_pubdate t2 ON t1.nid = t2.entity_id AND t1.vid = t2.revision_id
                    JOIN field_revision_field_channel t3 ON t1.nid = t3.entity_id AND t1.vid = t3.revision_id
                WHERE t3.field_channel_tid IN(".$tids.")
                    GROUP BY t1.nid ORDER BY pubdate DESC LIMIT ".$limit."";

        $result = db_query($query);

        // Container div and title
        print '

'.$title.'
';

        // Article list
        foreach ($result as $record) {
            $mypubdate = format_date($record->pubdate, 'custom', 'F j, Y, g:iA');
            print '
nid.'">'.$record->title.'
';
            print '
'.$mypubdate.'
';
        }

        // Clear and close the container div
        print '

';
}


Q:

How to implement a send button in a chat client GUI

I have implemented a chat client. And as of now it only fully works in cmd, because I can't figure out how I'm supposed to implement the send button in the chat client GUI.
So this is my chat client class:
class ChatClientClass {

    private String host;
    private int port;
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    private BufferedReader stdIn;

    ChatWindow chatWindow = new ChatWindow();

    public ChatClientClass(String host, int port) {
        try {
            this.socket = new Socket(host, port);

            this.out =
                new PrintWriter(socket.getOutputStream(), true);
            this.in =
                new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            this.stdIn =
                new BufferedReader(
                    new InputStreamReader(System.in));

            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                chatWindow.addText("You: " + userInput);
                String serverMessage = in.readLine();
                chatWindow.addText(serverMessage);
            }
        } catch (UnknownHostException e) {
            System.err.println("Couldn't not find host " + host);
            e.printStackTrace();
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " + host);
            e.printStackTrace();
            System.exit(1);
        }
    }
}

As of now, I can only write stuff in the command prompt. But what I've written as well as what the server answers will appear in my GUI. The addText(String text)-method adds the input and the output to my GUI.
But I can't figure out how to implement my send button. An easy way would be if I could just send a reference to the PrintWriter and a reference to the GUI when I call the constructor of my ActionListener class, and just do something like: thePrintWriter.println( [get the value of the text area that belongs to the send button] ) in the public void actionPerformed(ActionEvent e)-method. But since I can't/shouldn't call the constructor of my ActionListener from my chat client class, hence sending those references. That wont be possible, right?
I also thought about making the PrintWriter variable static, and also making the JTextArea containing the message I want to send variable static, and then create static methods to access these two variables. But it just feels like I'm doing something terribly wrong when I'm doing that. And I can't get that to work either.
So how is a send button in a chat client supposed to be implemented?
Thanks in advance!

A:

If you are new in GUI building in java/eclipse.
I suggest you the gui builder:
http://www.eclipse.org/windowbuilder/
Its really easy to use, and you can make simple GUI-for your app.
To your problem you will need a button to your frame, and you need to add an actionlistener than if you fire it you can do what you want.
    import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

public class ButtonAction {

    private static void createAndShowGUI()  {

        JFrame frame1 = new JFrame("JAVA");
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton button = new JButton(" >> JavaProgrammingForums.com <<");
        //Add action listener to button

        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
                 //Here call your sender fucntion
           out.println(userInput);
           chatWindow.addText("You: " + userInput);
           String serverMessage = your_jtext.getText();
           chatWindow.addText(serverMessage);
                System.out.println("You clicked the button");
            }
        });

        frame1.getContentPane().add(button);
        frame1.pack();
        frame1.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}


Q:

HighCharts - two Y-axis, one with max value

I have problem with Highcharts, I've set right Y-axis to min:0 and max:100 (it's %) but it won't work and make 125 percentage.
What's wrong?
http://jsfiddle.net/SdTcU/
$(function () {
        $('#container').highcharts({
            chart: {
                type: 'area'
            },
            title: {
                text: ''
            },
            colors: ['#c42525','#8bbc21'],
            xAxis: {
                categories: [
                            '07:00:00','07:15:00','07:30:00','07:45:00','08:00:00','08:15:00','08:30:00','08:45:00','09:00:00','09:15:00','09:30:00','09:45:00','10:00:00','10:15:00','10:30:00','10:45:00','11:00:00','11:15:00','11:30:00','11:45:00','12:00:00','12:15:00','12:30:00','12:45:00','13:00:00','13:15:00','13:30:00','13:45:00','14:00:00','14:15:00','14:30:00','14:45:00','15:00:00','15:15:00','15:30:00','15:45:00','16:00:00','16:15:00','16:30:00','16:45:00','17:00:00','17:15:00','17:30:00','17:45:00','18:00:00','18:15:00','18:30:00','18:45:00','19:00:00','19:15:00','19:30:00','19:45:00','20:00:00','20:15:00','20:30:00','20:45:00','21:00:00','21:15:00','21:30:00','21:45:00','22:00:00','22:15:00','22:30:00','22:45:00','23:00:00','23:15:00'
                            ],
                labels: {
                    step: 4,
                    rotation: -45,
                    align: 'right',
                    style: {
                        fontSize: '10px',
                        fontFamily: 'Verdana, sans-serif'
                    }
                }
            },
            yAxis: [{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: '#89A54E'
                    }
                },
                title: {
                    text: '1',
                    style: {
                        color: '#89A54E'
                    }
                }
            }, { // Secondary yAxis
                min: 0,
                max: 100,
                title: {
                    text: '%',
                    style: {
                        color: '#4572A7'
                    }
                },
                labels: {
                    format: '{value}%',
                    style: {
                        color: '#4572A7'
                    }
                },
                opposite: true
            }],
            credits: {
                enabled: false
            },
            tooltip: {
                pointFormat: '{series.name} produced {point.y:,.0f}
warheads in {point.x}'
            },
            plotOptions: {
                area: {
                    marker: {
                        enabled: false,
                        symbol: 'circle',
                        radius: 2,
                        states: {
                            hover: {
                                enabled: true
                            }
                        }
                    }
                }
            },
            series: [{
                name: '1',
                data: [
                    null, null, 43000, 41000, 39000, 37000,
                    35000, 33000, 31000, 29000, 27000, 25000,
                    35000, 33000, 31000, 29000, 27000, 25000,
                    24000, 23000, 22000, 21000, 20000,
                    null, null, 43000, 41000, 39000, 37000,
                    24000, 23000, 22000, 21000, 20000,
                    24000, 23000, 22000, 21000, 20000
                    ]
            }, {
                name: '2',
                data: [
                    1, null, null, null, null, 1005, 1436, 2063, 3057, 4618,27387, 29459, 31056, 31982, 32040, 26956, 27912, 28999, 28965, 27826,
                    100, 1005, 1436, 2063, 3057, 4618,27387, 29459, 31056, 31982, 32040, 26956, 27912, 28999, 28965, 27826,
                    1000, 1005, 1436, 2063, 3057, 4618,27387, 29459, 31056, 31982, 32040, 26956, 27912, 28999, 28965, 27826
                    ]
            },
            {
                name: '%',
                color: '#4572A7',
                type: 'spline',
                yAxis: 1,
                data: [80,70,78,86,64,51,58,88,88,100,100,95,68,91,92,93,94,85,100]
            }
            ]
        });
    });

A:

The problem you're having is that highcharts is trying to align the ticks. There are two ways of handling this problem with the current data set:
max: 100

changes to
max: 75

or, you need to set alignTicks as false
chart: {
    type: 'area',
    alignTicks: false
}

A:

You may also use a combination of the solutions above (worked for me):
alignTicks: false (chart)
max:100 (on % axis)
gridLineWidth: 0 (on second Y axis)

A:

I figure it out.
Better way to fix this issue is use tickinterval.
Here is sample
http://jsfiddle.net/SdTcU/1/
$(function () {
        $('#container').highcharts({
            chart: {
                type: 'area'
            },
            title: {
                text: ''
            },
            colors: ['#c42525','#8bbc21'],
            xAxis: {
                categories: [
                            '07:00:00','07:15:00','07:30:00','07:45:00','08:00:00','08:15:00','08:30:00','08:45:00','09:00:00','09:15:00','09:30:00','09:45:00','10:00:00','10:15:00','10:30:00','10:45:00','11:00:00','11:15:00','11:30:00','11:45:00','12:00:00','12:15:00','12:30:00','12:45:00','13:00:00','13:15:00','13:30:00','13:45:00','14:00:00','14:15:00','14:30:00','14:45:00','15:00:00','15:15:00','15:30:00','15:45:00','16:00:00','16:15:00','16:30:00','16:45:00','17:00:00','17:15:00','17:30:00','17:45:00','18:00:00','18:15:00','18:30:00','18:45:00','19:00:00','19:15:00','19:30:00','19:45:00','20:00:00','20:15:00','20:30:00','20:45:00','21:00:00','21:15:00','21:30:00','21:45:00','22:00:00','22:15:00','22:30:00','22:45:00','23:00:00','23:15:00'
                            ],
                labels: {
                    step: 4,
                    rotation: -45,
                    align: 'right',
                    style: {
                        fontSize: '10px',
                        fontFamily: 'Verdana, sans-serif'
                    }
                }
            },
            yAxis: [{ // Primary yAxis
                gridLineWidth: 1,
                tickInterval:10750, //get max value from highest area and divide it by 4
                labels: {
                    format: '{value}',
                    style: {
                        color: '#89A54E'
                    }
                },
                title: {
                    text: '1',
                    style: {
                        color: '#89A54E'
                    }
                }
            }, { // Secondary yAxis
                tickInterval:20, //set ticks to 20
                min: 0,
                max: 100,
                title: {
                    text: '%',
                    style: {
                        color: '#4572A7'
                    }
                },
                labels: {
                    format: '{value}%',
                    style: {
                        color: '#4572A7'
                    }
                },
                opposite: true
            }],
            credits: {
                enabled: false
            },
            tooltip: {
                pointFormat: '{series.name} produced {point.y:,.0f}
warheads in {point.x}'
            },
            plotOptions: {
                area: {
                    marker: {
                        enabled: false,
                        symbol: 'circle',
                        radius: 2,
                        states: {
                            hover: {
                                enabled: true
                            }
                        }
                    }
                }
            },
            series: [{
                name: '1',
                data: [
                    null, null, 43000, 41000, 39000, 37000,
                    35000, 33000, 31000, 29000, 27000, 25000,
                    35000, 33000, 31000, 29000, 27000, 25000,
                    24000, 23000, 22000, 21000, 20000,
                    null, null, 43000, 41000, 39000, 37000,
                    24000, 23000, 22000, 21000, 20000,
                    24000, 23000, 22000, 21000, 20000
                    ]
            }, {
                name: '2',
                data: [
                    1, null, null, null, null, 1005, 1436, 2063, 3057, 4618,27387, 29459, 31056, 31982, 32040, 26956, 27912, 28999, 28965, 27826,
                    100, 1005, 1436, 2063, 3057, 4618,27387, 29459, 31056, 31982, 32040, 26956, 27912, 28999, 28965, 27826,
                    1000, 1005, 1436, 2063, 3057, 4618,27387, 29459, 31056, 31982, 32040, 26956, 27912, 28999, 28965, 27826
                    ]
            },
            {
                name: '%',
                color: '#4572A7',
                type: 'spline',
                yAxis: 1,
                data: [80,70,78,86,64,51,58,88,88,100,100,95,68,91,92,93,94,85,100]
            }
            ]
        });
    });


Q:

Proof with compact sets in Hausdorff space

Prove that every compact set in Hausdorff space is closed.
Let $(X,\tau)$ be Hausdorff space and $A,B$ compact, disjont subsets of $(X,\tau)$. Prove that exist two disjoint sets $V,W$ open in $(X,\tau)$, so $A \subset V$, $B \subset W$.

I'have got an idea with 1.
Let K be a compact set in Hausdorff space $(X,\tau )$ and let $a \not\in K$.
$\forall x \in K$ we choose a pair of disjoint open sets $V (x), W(x) \in \tau$ : $a \in V (x)$ and $x \in W(x)$. Because of K compactness, we can choose $x_1, . . . , x_n \in K$ : $K \subset W(x_1) \  \cup . . . \cup  \ W(x_n) = W$. Then $V = V (x_1) \cap . . . \cap V (x_n)$ is a neighbourhood of $ a $ disjoint with $W$, so with $K$ as well. Therefore  $a \not\in K$, and finally $\overline{K} = K$
Is this correct? Actually I don't have idea about 2nd part. I think this proof might be useful.

A:

HINT: Your argument for (1) is correct. You can indeed use the same idea for (2). Note that (1) essentially proves the special case of (2) in which $A=\{a\}$ for some $a\in X$. In general, then, you can separate each $a\in A$ from $B$ with disjoint open sets. And then?


Q:

Strange syntax error "unexpected unary+" related to a space after `+`

Given that a is undefined, the following looks fine:
a + b + blah
# => NameError: undefined local variable or method `a' for main:Object

Removal of space seems to matter:
a + b +blah
# => syntax error, unexpected unary+, expecting keyword_do or '{' or '('

What does this mean, and why does this occur by just removing a space? Is + not treated normal here? If I define a and b, it becomes:
a, b = 1, 1
a + b +blah
# => NameError: undefined local variable or method `blah' for main:Object

where it again looks like + is treated correctly.

A:

The unary +@ operator is a valid one on its own (takes a single operand and returns its value - eg. +4 returns 4). Not to be confused with the addition operator + which works on two operands.
Also, it takes precedence over the normal + addition operator.
Hence, +c in a + b +c in a + b +c is getting parsed as the equivalent of a + b c, which is not valid, as Ruby is unable to determine whether the +c is a normal method argument () or block {}.


Q:

Subdivision Surface Modifier Mask?

Can I mask certain edges/vertices/faces from a subdivision surface modifier? I am working with small models and want to have some edges sharp yet others smoothed. Because of how think the object is and how I beveled it, it looks horrible when smoothed. I'd like it if I could somehow mask certain edges or faces from it, or to choose faces that should be sharper?
I have tried to add loop cuts and bevels, but with how badly I made the model, it wont work with the vertices. I will try moving them and seeing if they may be overlapping, or I messed up by making a complicated panel without extra edges. But loop cutting isn't working as it should.
I also tried adding creases but they didn't change anything about how the model looks with the modifier. I will show images of all that I tried. I want to have the sides sharp, but the inside smoothed out. I don't know if shade smooth renders, but it it does it still looks weird for what I am going for.
I also tried using an edge split modifier, but it didn't change anything either, like the previous answers. I did clean up the vertices, there aren't doubles.

A:

The basic problem you have is the topology. Avoid faces that have more than 4 vertices. Those will not work for what you want to do.
All of those examples don't work because of those n-gons.
Start with a shape like this:

You can create all kinds of "unusual shapes", but you have to have the topology in mind when creating them.
Then you will be able to appreciate the difference between all of the proposed ways to mix smooth and hard edges.


Q:

htaccess rewriterule for profile.php query

I am trying to write a .htaccess RewriteRule for a profile page. I want the rule to query a SQL database for a user profile and if that data returns a result to load the profile.php page. Example:

www.example.com/username
or www.example.com/user.name
or www.example.com/user.name123 and the like...

However, I have other pages like /login, /registration, /, /chat, and so on. Every time I try something I keep running into an issue.
I have tried the following:
RewriteEngine On
RewriteRule ^(login)$ login.php [QSA]
RewriteRule ^(logout)$ logout.php [QSA]
RewriteRule ^([\w-]+)/?$ profile.php?pid=$1 [L,QSA]

I am trying to learn as much as I can but I am not comprehending the regex syntax and the conditions. The above rules let me use all the previous pages but it will catch everything else in the profile.php page. What am I doing wrong?

A:

Please try following regex, I hope it will solve your problem.
^([\w]+|[\w-]+\.+[\w]+)$

you can always use this link to test your regex.


Q:

Kotlin Intent error

I have the following code and am getting an error with the Intent. It is because of the this I am fairly certain.
listView.onItemClickListener = object : OnItemClickListener {
            override
            fun onItemClick(parent: AdapterView<*>, view: View,
                            position: Int, id: Long) {
                val intent = Intent(this, MyActivity::class.java)
                startActivity(intent)
            }

        }

A:

It has two solutions you can use either:
val intent = Intent(this@YourActivity, MyActivity::class.java)
                startActivity(intent)

or :
 val intent = Intent(applicationContext, MyActivity::class.java)
                    startActivity(intent)


Q:

How can I add a nix package when using buildPythonPackage?

The Python Part
I have a python application with multiple entrypoints, json_out and json_in.  I can run them both with this default.nix
with import <nixpkgs> {};
(
  let jsonio = python37.pkgs.buildPythonPackage rec {
    pname = "jsonio";
    version = "0.0.1";
    src = ./.;
  };
  in python37.withPackages (ps: [ jsonio ])
).env

Like so:
$ nix-shell --run "json_out"
    { "a" : 1, "b", 2 }

$ nix-shell --run "echo { \"a\" : 1, \"b\", 2 } | json_in"
    keys: a,b
    values: 1,2

The System Part
I want to also invoke jq in the nix shell, like this:
$ nix-shell --run --pure "json_out | jq '.a' | json_in"

But I can't because it is not included.  I know that I can include jq into the nix shell using this default.nix
with import <nixpkgs> {};

stdenv.mkDerivation rec {
  name = "jsonio-environment";
  buildInputs = [ pkgs.jq ];
}

And it works on its own:
$ nix-shell --run --pure "echo { \"a\" : 1, \"b\", 2 } | jq '.a'"
    { "a" : 1 }

But now I don't have my application:
$ nix-shell --run "json_out | jq '.a'"
    /tmp/nix-shell-20108-0/rc: line 1: json_out: command not found

The Question
What default.nix file can I provide that will include both my application and the jq package?

A:

My preferred way to achieve this is to use .overrideAttrs to add additional dependencies to the environment like so:
with import <nixpkgs> {};
(
  let jsonio = python37.pkgs.buildPythonPackage rec {
    pname = "jsonio";
    version = "0.0.1";
    src = ./.;
  };
  in python37.withPackages (ps: [jsonio ])
).env.overrideAttrs (drv: {
  buildInputs = [ jq ];
})


Q:

What's wrong with my XSD schema?

Here is the schema:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:complexType name="entry">
    <xs:attribute name="key" type="xs:string" use="required"/>
  </xs:complexType>
  <xs:element name="p">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="entry" minOccurs="0" maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

This XML should fail validation against this schema, because key attribute is missed:

<entry/>

But it doesn't fail. What am I doing wrong?

A:

The name attribute in the entry element defintion does not link to a type definition.
You just have to add a reference to the type in your entry element definition (to effectively type it) :
<xs:element type="entry" name="entry" minOccurs="0" maxOccurs="unbounded"/>


Q:

Remove duplicate comma separated values from mysql

How can I remove duplicate comma separated values returned from database?
I have it in this format:
XL,L,XXL
XL
M,L,XL
L,XL,M

What I tried:
$new_str = array_unique(array_map('trim', explode(',', $srow['size'])));
$string = implode(',', $new_str);

But I still get duplicate values. Is there a better way of doing it?

A:

Since your data is stored as comma separated values in the database, you will need to aggregate all the values as you loop over fetching from the database and then remove duplicates e.g.
while ($srow = $result->fetch_assoc()) {
    $sizes[] = $srow['size'];
    // do other stuff with fetched data
    // ...
}
$sizes = array_unique(array_map('trim', explode(',', implode(',', $sizes))));
sort($sizes);
$string = implode(',', $sizes);

Demo on 3v4l.org (with simulated database fetch)


Q:

Selecting all elements up until reaching a specific one

There is a container div which has other divs inside of it, these child divs contain text with some links in them. I'm trying to select all the anchor tags that are inside of this container div except for those that come after a child div which has a specific class to it.

  some text link

  some text link

 ... more regular divs below...

  this is not text

  some text link

 ... more divs come below...

So, from the HTML above I'd like to select only the links before the div which class is "NOT_a_regular_child".
I googled it but it seems like there isn't a selector for getting elements before another (?)
I believe I could select all the child divs then loop through them and dump their links to an array until I reach that specific one but isn't there a way to do this using css selectors only?
I cannot change the structure of the HTML because I'm just writing a google chrome extension to work on a existing web site.

A:

Pure CSS
Nothing complex about setting up a pure css way to target those using the general sibling selector ~.
See this fiddle for the below code performance.
.the_container a {
    color: blue;
    /* base link color and styling for container
       this will be applied to all links above the class
    */
}

/* second selector is optional only if you need to
handle links in that specially classed container */

.the_container > div.NOT_a_regular_child ~ div a,
.the_container > div.NOT_a_regular_child a /* <-- optional */
{
    color: red;
    /* base link color and styling for container
       this will be applied to all links above the class
    */
}


Q:

For loop proceeding out of order

new at this, please tell me if I'm leaving information out or anything like that.
The code I'm working on can be seen here: http://codepen.io/hutchisonk/pen/mVyBde and I have also pasted the relevant section of javascript below.
I'm having trouble understanding why this code is behaving as it is. Quick outline - I have defined a few variables at the top, made a function that fetches the data I need and builds it into a pretty little list. This seems to be working as planned.
With the function outlined, I then loop through each "friend" in the "friends" array, calling the function once each time. I have numbered the friends on the output to help clarify what is going on. I have tried this a number of ways, including with the "for loop" syntax that's currently implemented, as well as the "forEach" syntax that's commented out.
Two main questions:
1) The number in front of each name is the "i" in my for loop. Why is this "i" not going in order from 0 to 10? How do I get it to do so? It appears to be in a different order every time the code is run. And, it repeats the numbers it has looped through previously on each new iteration. I would like to understand why this is happening.
2) The code seems to be running out of order. The unexpected behavior can be seen in the console.log - the for loop outputs the first two lines of console.log on a loop, then jumps out and console.logs the test variable "a" and the other text below the for loop, and then jumps back into the for loop and console.logs the output from the function. I'm looking at the console in google chrome and I did read that there can be timing inconsistancies with regard to the console, but I don't understand how the loop is being split in half - the first two lines, and then the function call being logged after the later code.
What is the best way to iterate through an array? Any insights on how to call a function within a loop correctly or resources you can provide are much appreciated.
$("document").ready(function(){

  var friends = ["lainzero", "freecodecamp", "storbeck", "terakilobyte", "habathcx","RobotCaleb","thomasballinger","noobs2ninjas","beohoff", "dtphase", "MedryBW"];
  var html = "";
  var url = "";

  function getStreamingData(eachfriend, number) {
     url = "https://api.twitch.tv/kraken/streams/"+eachfriend;

  $.ajax({
  dataType: "jsonp",
  url: url,
  success: function(result) {
      console.log(result+", "+result.stream);

    if(result.stream !== null) {
      html+= "
"+number+": "+eachfriend;
      html +="";
    } else if (result.stream === null) {
      html+= "
"+number+": "+eachfriend;
      html +="";
    }
     html +="
";
    $("#all ul").append(html);

    }//success
  });//$ajax
}//getstreamingdata function

for (var i=0;i<friends.length;i++) {
  console.log(i);
  console.log(friends[i]);
  getStreamingData(friends[i], i);
}

//Same as for loop above, but using forEach. This produces the same results.
/*
var i=0;
friends.forEach(function(friend) {
   getStreamingData(friend, i);
   i++;
});
  */

  var a = 4;//testing console output
  console.log(a);
  console.log("why is this showing up before the getStreamingData function's console output?");
  console.log("but it's showing up after the console.log(i) and console.lg(friends[i]) output? So this section is interupting the for loop above");
  console.log(" and why is the for loop out of order and repeating itself?");

 });//doc ready

A:

You are doing an asynchronous task in your loop. You should not expect those async tasks finish in the order that they have started.
The function getStreamingData is the one that I'm talking about.
Related: Asynchronous for cycle in JavaScript
This is one snippet that I wrote long time ago and I'm still using it in small projects. However there are many libraries out there which do the same plus many more.
Array.prototype.forEachAsync = function (cb, end) {
    var _this = this;
    setTimeout(function () {
        var index = 0;
        var next = function () {
            if (this.burned) return;
            this.burned = true;
            index++;
            if (index >= _this.length) {
                if (end) end();
                return;
            }
            cb(_this[index], next.bind({}));
        }
        if (_this.length == 0) {
            if (end) end();
        }else {
            cb(_this[0], next.bind({}));
        }
    }, 0);
}

It is not a good practice to touch the prototype like this. But just to give you an idea how you can do this ...
After that code, you can loop over arrays asynchronously. When you are done with one element, call next.
var array = [1, 2, 3, 4]
array.forEachAsync(function (item, next) {
    // do some async task
    console.log(item + " started");
    setTimeout(function () {
        console.log(item + " done");
        next();
    }, 1000);
}, function () {
    console.log("All done!");
});


Q:

How to Sum array parts within a loop with time-complexity of Big O(N)

I have this function that returns the minimum difference between the sum of two parts of an array based on the position P the Array is partitioned. The programmed is tested to to run at O(N * N) time complexity and 0% performance though O(N) is was expected.
Question: Is there any aspect of this I can change to improve on the performance? Is there a better way to summing array within a loop without using a sub-loop? Thanks
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts:
 A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of:
 |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
https://jsbin.com/mehisi/edit
function solution(A) {

  'use strict';

  if(arguments.length === 1 && typeof A === "object" && A.length > 1 ){
    try{
      const N = A.length;

      let diff;
      for( let P =1 ; P < N ; P++) {
        // For each value of P, calc the difference
        //|(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|

        // use slice to prevent modification of oraginal copy
        var A2 = A.slice(0) ;
        //splice array into two A1 and A2
        let A1 = A2.splice(0, P);  // All Element from start up to P
        console.log("From Array " + A  + " Remove "+ A1 + " Remaining " + A2);
        // reduce((a, b) => a + b, 0);
        let diffp = Math.abs((A1.reduce(function(a, b) { return a + b; }, 0)) -
            (A2.reduce(function(a, b) { return a + b; }, 0))) ;

        if(diff > diffp || diff === undefined ){
          diff = diffp ;
        }
        console.log(P + "Difference ="+ diff + " Instead of " + diffp + " \r\n " );
      }

      // Return the Minimum value of P
      return diff  ;
    }
    catch(err){
     console.log("Error: " + err );
    return 0 ; // undefined ;
    }
  }else{
     console.log("Invalid parameter(s)");
    return 0 ; // undefined ;
  }

}

var A = [] ;
  A[0] = 5
  A[1] = 1
  A[2] = 2
  A[3] = 7
  A[4] = 4
console.log(solution(A)) ;

A:

Yes, it's pretty trivial to do this in linear time (and even constant space) with a running sum.
function solution(arr) {
    var leftSum = 0; // sum from 0 to P
    var rightSum = arr.reduce((a, b) => a + b, 0); // sum from P to N
    var min = Math.abs(leftSum - rightSum); // initial value for p=0
    for (var p = 0; p < arr.length; p++)
        // move the element from the right to the left side
        leftSum += arr[p];
        rightSum -= arr[p];
        // then update minimum difference
        min = Math.min(min, Math.abs(leftSum - rightSum));
    }
    return min;
}