text:
Q: Forecasting hierarchical time series R package I have to forecast a large set of (hierarchical) time series and since the R package hts allows for confidence intervals for their ensemble, I'd like to use it. I haven't found an example of how to use it, yet. How should I forecast the following series with it: The time series have a simple form. The sum of $n_3$ level-$3$-series make up a level-$2$-series and the sum of $n_2$ level-$2$-series make up a level-$1$-series and the sum of $n_1$ level-$1$-series make up the top-most level-$0$-series (where sums are taken over series in one point in time, $n_j$ natural numbers for  $j=0,1,2,3$).

A: Here is one example taken from the documentation in the package:
abc <- ts(5 + matrix(sort(rnorm(200)), ncol = 4, nrow = 100))
x <- hts(abc, c(1,1,2,2))
y <- gts(abc, rbind(c(1,1,2,2), c(1,2,1,2)))

The first line generates a matrix of four time series, each of 100 observations.
The second line interprets the four time series as hierarchical, with the first two series in one group and the second two series in a second group:
      Total
        |
    |-------|
    A       B
    |       |
  -----   -----
  |   |   |   |
  A1  A2  B1  B2

This gives seven series in all including the aggregations.
> x
Hierarchical Time Series
   3 Levels
   Number of series at each level: 1 2 4
   Total number of series: 7
   Number of observations per series: 100

The third line of the example interprets the four series as grouped rather than hierarchical, with one grouping variable treating the first two series in one group and the remaining two series in the second group. The other grouping variable takes the first and third series in one group and the second and fourth in the other group. So in this interpretation, the four series can be grouped as in the hierarchy above, or as in the hierarchy below:
      Total
        |
    |-------|
    X       Y
    |       |
  -----   -----
  |   |   |   |
  A1  B1  A2  B2

So there are nine series in all under this structure, due to the additional grouping variable.
> y
Grouped Time Series
   4 Levels
   Number of groups at each level: 1 2 2 4
   Total number of series: 9
   Number of observations per series: 100


text:
Q: How to dual boot Windows 10 and Ubuntu I've loaded Ubuntu 14.04 onto a USB stick, and can get it to launch. However when I attempt to actually install Ubuntu it doesn't give me an option to dual boot. I only have the option to completely erase everything and install Ubuntu or do things manually, which I don't know how to do. I've heard it could be an issue with one operating system doing BIOS while the other is using UEFI, however windows is running BIOS and I think Ubuntu is as well. Does anyone know how to fix this?

A: One big question: have you partitioned your hard drive?
If you haven't I'd have a look at this:
http://www.howtogeek.com/howto/windows-vista/resize-a-partition-for-free-in-windows-vista/
(I know this is for Vista but it works on any modern Windoze version including 10)
Once you set up a separate partition for Ubuntu (and probably another much smaller space for Linux swap) then you can dual-boot by installing Ubuntu to that partition you set aside for it. Then when it asks for where to install grub, select /dev/sda (or whatever the name of your hard drive is)
Have no fear, the BIOS/UEFI thing is not an issue. I made my Ubuntu/Windoze system work on the first try!

redpajama_set_name: RedPajamaStackExchange


text:
Q: telethon doesn't get all the users, only ~90% of the user extracted from a public group The code below works ok to extract users from TG groups, but I don't know why it only extracts like 90% of the users, not all of them... couldn't find a reason online.
I got the below code from a tutorial here: https://python.gotrained.com/scraping-telegram-group-members-python-telethon/
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
import csv

api_id = 123456
api_hash = 'YOUR_API_HASH'
phone = '+111111111111'
client = TelegramClient(phone, api_id, api_hash)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter the code: '))

chats = []
last_date = None
chunk_size = 200
groups=[]

result = client(GetDialogsRequest(
             offset_date=last_date,
             offset_id=0,
             offset_peer=InputPeerEmpty(),
             limit=chunk_size,
             hash = 0
         ))
chats.extend(result.chats)

for chat in chats:
    try:
        if chat.megagroup== True:
            groups.append(chat)
    except:
        continue

print('Choose a group to scrape members from:')
i=0
for g in groups:
    print(str(i) + '- ' + g.title)
    i+=1

g_index = input("Enter a Number: ")
target_group=groups[int(g_index)]

print('Fetching Members...')
all_participants = []
all_participants = client.get_participants(target_group, aggressive=True)

print('Saving In file...')
with open("members.csv","w",encoding='UTF-8') as f:
    writer = csv.writer(f,delimiter=",",lineterminator="\n")
    writer.writerow(['username','user id', 'access hash','name','group', 'group id'])
    for user in all_participants:
        if user.username:
            username= user.username
        else:
            username= ""
        if user.first_name:
            first_name= user.first_name
        else:
            first_name= ""
        if user.last_name:
            last_name= user.last_name
        else:
            last_name= ""
        name= (first_name + ' ' + last_name).strip()
        writer.writerow([username,user.id,user.access_hash,name,target_group.title, target_group.id])
print('Members scraped successfully.')


text:
Q: How to add elements before other elements using javaparser? I try to add new FieldDeclarations to my Main Class in CompilationUnit before all other existing FieldDeclarations.
mainClassInCompilationUnitDeclaration.addPrivateField("Type", "fieldName");

Where mainClassInCompilationUnitDeclaration is a ClassOrInterfaceDeclaration representing the first declared Class in the CompilationUnit.
Unfortunately, all added Declarations get serialized on the end of the class.
This is logical as the elements are added at the end of the tree.
How can I change where they get added?
Is there any "insertBefore" in Javaparser?

A: I think you have to make a work around to handle this case for example you can make these steps:

*

*Get the existing elements and save them in another reference and remove them from your
compilation unit .

*Add the new elements you have made

*Add the old elements again to your compilation unit
by doing that you now have the desired order.


text:
Q: Examples about compactness Compactness implies countably compactness which in turn implies limit-point compactness.
Sequentially compactness implies limit point compactness.
$Z_{+} \times \{0,1\}$ with two-point indiscrete space $\{0,1\}$ is limit-point compact but not sequentially compact.
First uncountable ordinal is sequentially compact, countably compact, but not compact.
Can anybody give me any examples for

*

*Sequentially compact but not countably compact space (hence limit-point compact but not compact)

*Countably compact but neither compact nor sequentially compact space.
?
Thanks in advance.

A: Actually, sequentially compact implies countably compact, so no example for (1) exist. The proof is actually quite straightforward:

Assume that $X$ is not countably compact. Then there exists a countable open cover $X = \bigcup_{n=1}^\infty U_n$ that has no finite subcover.
For each $m$, let $x_m \in X \setminus \bigcup_{n=1}^m U_n$. The sequence $x_m$ cannot have a limit point $x \in X$, otherwise it would be true that $x \in X \setminus (\bigcup_{n=1}^m U_n)$ for every fixed $m$, which implies that $x \in X \setminus (\bigcup_{n=1}^\infty U_n) = \emptyset$. Therefore, the sequence $x_m$ has no convergent subsequence.

As for (2), there's an example in the book Counterexamples in Topology, by  Steen and Seebach (example 106): Let $\omega_1$ be the smallest uncountable ordinal with the order topology, and let $I = [0,1]$. Then $X = \omega_1 \times I^I$ is countably compact (because $\omega_1$ is sequentially compact and $I^I$ is compact) but neither sequentially compact nor compact (these properties are preserved by the projections).

A: Sequential compactness implies countable compactness, so you can't get a countably compact space that's not sequentially compact. You can, however, get a limit point compact space that's not compact: for each $n\in\Bbb N$ let $U_n=\{k\in\Bbb N:k<n\}$, and let $\tau=\{\Bbb N\}\cup\{U_n:n\in\Bbb N\}$. Then $\tau$ is a $T_0$ topology on $\Bbb N$, and $\{U_n:n\in\Bbb N\}$ is an open cover of $\Bbb N$ with no finite subcover, but if $\varnothing\ne A\subseteq\Bbb N$, then every $n\in\Bbb N$ satisfying $n>\min A$ is a limit point of $A$.
For your second example, let $D$ be the discrete two-point space, and let $X=D^{\wp(\Bbb N)}\times\omega_1$. Since $\omega_1$ is not compact, neither is $X$, and since $D^{\wp(\Bbb N)}$ is not sequentially compact, neither is $X$. However, $D^{\wp(\Bbb N)}$ is compact, and $\omega_1$ is countably compact, so $X$ is countably compact. This space has cardinality $2^{2^\omega}$; there are more complicated examples of cardinality $2^\omega$, and in some models of set theory there are smaller examples yet.


text:
Q: How do I take advantage of Python generators when reading in a huge file and parsing by word? Here is the relevant code I have.  It is using a generator to get the words from the file.  However, the words are first stored into a variable before entering a function.  Is this correct?
Does this take advantage of the generator functionality?
def do_something(words):
    new_list = {}
    for word in words:
        // do stuff to each word
        // then add to new_list
    return new_list

def generate_words(input_file):
    for line in input_file:
        for word in line.split(' '):
            // do stuff to word
            yield word

if __name__ == '__main__':
    with open("in.txt") as input_file:
        words = generate_words(input_file)
        do_something(words)

Thank you

A: When you make words = generate_words(input_file), you are simply giving it a reference to the newly created generator. When you run do_something, that's when the generator is actually iterated through, words is just a reference to it. So the answer is yes, you are taking advantage of generators.

A: The code looks fine. What is being stored in words is a fresh generator prepared to run the code in generate_words; the code will only actually run when the for word in words: is triggered. If you want to know more, this SO question has a whole heap of information.

A: There is no advantage of using generators in given example.
The main purpose is reduce memory usage.
In the code:
for line in input_file:

line already beed read from file and consumed memory. Then split operation create new list and memory been consumed one more time.
So all you have to do is iterate through list items.
While usage of generators will lead creating generator object which yield objects from existing list. It is completely useless.


text:
Q: FileMaker Pro 10 - How to Extract Layout and Scripts from fp7 File? I want to start tracking my FileMaker changes in Subversion but all I have a big binary file with everything.  Is there a way to extract the layout and script parts into a text format so that I can see diffs of what was changed?
I'm thinking maybe there's a 3rd party tool for that?

A: I think the closest thing you're going to find is FileMaker Pro Advanced's Database Design Report, which will export an XML or HTML representation of all of the elements in a FileMaker database. The report will include all of the script steps for a file and all of the position and other information for the layout objects, but depending on the size of your FileMaker system, it may take a while to generate each time.
I use version control for my FileMaker systems but don't bother with diffs, just making sure that I provide adequate comments for my commits.

A: You should check out FMDiff. It reads the original filemaker files (without needing to generate a DDR) and shows differences between multiple versions of the same file. I've not used it before, but always intended to.


text:
Q: How to clean up the temp folders of RAD 8? I am receiving the javax.servlet.UnavailableException: (SRVE0203E). As far as I know, this means that not all libraries that I use in the classpath for compiling with RAD are present in the runtime classpath. The error message from the log file outputs the runtime classpath and when I compare it with my compile classpath I can't find missing libraries. The only difference is that the runtime classpath contains 2 old libraries, which I deleted last week from my system. They are before the new versions, which means, that the integrated app server tries to use them.
For example:
class-path: [C:\workspace\MYEAR\commons-beanutils-1.7.0.jar;
C:\workspace\MYEAR\commons-beanutils-1.8.3.jar;
C:\workspace\MYEAR\commons-collections-3.1.jar;
C:\workspace\MYEAR\commons-collections-3.2.1.jar;...................]

How can I delete those old references? They are perhaps defined in a file somewhere in a temp folder... That's why I'd like to delete all RAD 8 temp folders.
Any help is appreciated!
Thanks!

A: Start the RAD with clean option.
Ofcourse I assume that you have the correct class paths and libraries now.
So go to the IBM install directory that has a eclipse.exe
and type this in command prompt:
eclipse.exe -clean
this should take some time in starting up but it will mostlikely solve your problem.

A: In your WAR modules, check:

*

*Classpath: project/.classpath

*Deployment assembly: project/.setings/org.eclipse.wst.common.component

*Bundled dependencies: project/WebContent/WEB-INF/lib
In your EAR, check:

*

*Deployment assembly: project/.setings/org.eclipse.wst.common.component

*Deployment descriptor: project/META-INF/application.xml


text:
Q: Generating the tetrahedral element with nodal quadrature rule By default, we do not have the possibility of using linear Tetrahedral elements with nodal quadrature in AceGen/AceFEM. But I suppose that there should be a way to construct it through the modification of the linear tetrahedral elements with Gauss quadrature. For example, for hexahedral elements, this can be easily done upon modifying the linear hexahedral elements using the SMSSign function in the shape functions as
Node\[Xi]\[Eta]\[Zeta] = {{-1 , -1 , -1} , {1 , -1 , -1} , {1 ,
    1 , -1} , {-1 , 1 , -1} , {-1 , -1 , 1} , {1 , -1 , 1} , {1 , 1 ,
    1} , {-1 , 1 , 1}};
Ni \[DoubleRightTee]
  Table[1/8 (1 + SMSSign[\[Xi]] Node\[Xi]\[Eta]\[Zeta][[i , 1]]) (1 +
      SMSSign[\[Eta]] Node\[Xi]\[Eta]\[Zeta][[i, 2]]) (1 +
      SMSSign[\[Zeta]] Node\[Xi]\[Eta]\[Zeta][[i, 3]]) , {i , 1 , 8}];

Then by using the 2*2*2 Gauss integration rule (code 7), the integration points are transferred to nodes.
A similar way is not possible for tetrahedral elements because there is no SMSRound function that can be used in linear tetrahedral shape functions (knowing that abscissa is between 0 and 1). Is there any other way to do it?


text:
Q: Mid sentence insertion in the English Language, does it exist or not? I have been having quite a bit of debate with someone about inserting a slight digression in the middle of a sentence. My native language is Turkish and in the literary sense we use it quite often such as this mot à mot translation;

In London, where diverse cultures meet, which neighbourhood do you
  prefer to live in?

A trained translator told me that in Turkish you can insert a sentence with different subject between commas and go on about your main subject, but using this in English is not proper. Is that so, or can I use commas to mention an off-topic subject in the mid-sentence?
So should I have written like something "Where would you like to live in London where diverse cultures meet?"

NB My sentences are short as this is about a twitter post which has a 140 character limit, and I also want to add hashtags and links etc.


text:
Q: understanding output from opencv neural network I am testing the opencv neural network.
The training input I am using is
12 16 14
10 5  7.5
8  10 9
5  4  4.5
12 6  9

Finding the mean of the two numbers and the third one is the expected output. I am using 3 levels with 2 neurons for the input, 3 for hidden and 1 for output with equal weights.
I am using back propagation technique.
The output I am getting for
Predict(0,0);  ----> 13.121479
Predict(40,60);  ----> 6.043900
Predict(120,180);  ----> 5.801756
Predict(10,5);  ----> 10.095689

can someone explain the prediction results I am getting.


text:
Q: Javascript - List (array) length and getting an item from the list not working I'm practicing JavaScript (just started this week) on vscode with the Quokka.js extension. Right now I'm initializing a list called "things" and trying to get the length of the list and getting some items out of it. This is my code:
var things = ['bananas', 'apples', 7];
things.length;
things[0];

The last two rows return nothing to me, not even "undefined".
How do I get vscode to return the length and the first object from the list using [0]? If it is not possible in vscode, what program should I use for learning JavaScript?
I also tried initializing the list as an array with
Array things = ['bananas', 'apples', 7];

but this does not seem to be allowed.
Moreover, for example the command
things.splice

seems to work in vscode.

A: Even if you're using Quokka, it's better to output using console.log. Quokka works very well with console.log.
Also try not to use var or declare array using Array. This is JavaScript, not Java.
// Do not use var
let things = ['bananas', 'apples', 7];
console.log(things.length);
console.log(things[0]);

// This will not work
// This does not make any sense either
Array things = ['bananas', 'apples', 7];

JavaScript Array is not Class or an interface by using which you can declare it's instances. JavaScript Array is a global object. There are no classes in JavaScript.


text:
Q: android WebView shouldOverrideUrlLoading() Hi this doesnt work for me:
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    s="url clicked: "+url;
    view.loadDataWithBaseURL(null, s, "text/html", "utf-8", null);
    return true;
}
});

I have  links in my html, it shows during loading in main activity,
but when I click them I get a white blank screen
I want to be able to read what those urls are, in the program, and I assume this url override function is the purpose for this.
I have tried with loadData() as well.
Thank you

A: You're not passing the new url to the WebView.
Should be
 view.loadDataWithBaseURL(url, null, "text/html", "utf-8", null);

Edit: This also gives me a blank screen because loadDataWithBaseUrl expects you to provide some text or html as the data parameter yourself. Just use
view.loadUrl(url);

A: I didn't write http:// in my links, and wrote only x. This was the problem, it works now.


text:
Q: Android Weird Null Object Reference on Button.setText(mText) I'm stuck with the weirdest error I've ever got since I started programming. I'm setting a text to a button. Nothing complicated there!
I do it this way:
btnButton.setText(cell.getText());

btnButton exists since I've passed some others things to it before setting its text and cell.getText() is not null either since I can log the text in my console.
Still, I get this weird error:
03-31 14:58:35.407 24398-24398/ca.gggolf.agggolf.full E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: ca.gggolf.agggolf.full, PID: 24398
                                                                    java.lang.NullPointerException: Attempt to read from field 'int android.view.ViewGroup$LayoutParams.width' on a null object reference
                                                                        at android.widget.TextView.checkForRelayout(TextView.java:6836)
                                                                        at android.widget.TextView.setText(TextView.java:4063)
                                                                        at android.widget.TextView.setText(TextView.java:3921)
                                                                        at android.widget.TextView.setText(TextView.java:3896)
                                                                        at ca.gggolf.agggolf.activities.fragments.AutoGridFragment.displayAutoGridBody(AutoGridFragment.java:467)
                                                                        at ca.gggolf.agggolf.activities.fragments.AutoGridFragment.createAutogridBody(AutoGridFragment.java:206)
                                                                        at ca.gggolf.agggolf.activities.fragments.AutoGridFragment.onCreate(AutoGridFragment.java:94)
                                                                        at android.support.v4.app.Fragment.performCreate(Fragment.java:1939)
                                                                        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
                                                                        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
                                                                        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
                                                                        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
                                                                        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:135)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:372)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

Can someone help me fix this? It sometimes work but it depends from where in the application that I come from.
Thanks!
EDIT
Here's my whole code when creating the button. I assign it's width and initial text and then if the text should be truncated, I measure to make sure that my button will still fit in the size I gave it otherwise, I change it to textView.
It's when I set it back to normal after that it gives me the error.
Button btnButton = new Button(getActivity());
btnButton.setWidth(width);
btnButton.setText(cell.getText());
if(adjustedAutogrid.getColumn(indexCell).isTruncated()){
    btnButton.setText("…");
    btnButton.measure(0, 0);
    if(btnButton.getMeasuredWidth() > width){
        TextView btnText = new TextView(getActivity());
        btnText.setWidth(width);
        btnText.setText(cell.getText());
        cell.getCSS().applyToTextView(btnText);
        btnText.setEllipsize(TextUtils.TruncateAt.END);
        btnText.setLines(1);
        layout.addView(btnText);
        break;
    }
    btnButton.setText(cell.getText());
    btnButton.setEllipsize(TextUtils.TruncateAt.END);
    btnButton.setLines(1);
}

And for those wondering from where it causes problem, well it's a bit complicated. I receive information through internet (an XML) that I convert to a table that I show. I must set the different cells the appropriate size and content. When I load what we call an AutoGrid coming from the XML, all my AutoGrid works except for one...
Edit 2
Everything works fine if I leave the text to the ellipsize symbol (…). It really is when i try to set the text again that it doesn't work..

A: I don't know why but it seems that if I set the text later with my button that everything is fine...
btnButton.setWidth(width);
btnButton.setEllipsize(TextUtils.TruncateAt.END);
btnButton.setLines(1);
btnButton.setText(cell.getText()); // this line used to be the first one

If someone has an explanation, please fill free to enlighten me!


text:
Q: How do I access a dynamic button's event handler? Visual Studio 2015 WPF I'm trying to learn C# again and I was wondering what is the approach to achieve the result I needed, this is my code, it creates the label and button when I click a button.
    private void button_Copy_Click(object sender, RoutedEventArgs e)
    {
        counter++;

        Label lbl = new Label();
        lbl.Content = counter.ToString();
        lbl.HorizontalAlignment = HorizontalAlignment.Center;
        lbl.VerticalAlignment = VerticalAlignment.Center;
        lbl.FontSize = 50;

        Button bt = new Button();
        bt.Content = "X";
        bt.HorizontalAlignment = HorizontalAlignment.Right;
        bt.VerticalAlignment = VerticalAlignment.Top;

        grid.Children.Add(lbl);
        grid.Children.Add(bt);
    }

However I'm having a problem determining where to put the click event since it was created dynamically. What I wanted to happen was when I click the X button, it will remove the specific label and x button I clicked. So if I clicked the main button twice, it would show a 1 with an x on the top left and a 2 with an x on the top left and when I click the 2's x, it will remove both the label with 2 and the x button for 2.

A: Just add an event handler to the button:
private void button_Copy_Click(object sender, RoutedEventArgs e)
{
    counter++;

    Label lbl = new Label();
    lbl.Content = counter.ToString();
    lbl.HorizontalAlignment = HorizontalAlignment.Center;
    lbl.VerticalAlignment = VerticalAlignment.Center;
    lbl.FontSize = 50;

    Button bt = new Button();
    bt.Content = "X";
    bt.HorizontalAlignment = HorizontalAlignment.Right;
    bt.VerticalAlignment = VerticalAlignment.Top;

    // add subscriber
    bt.Click += Button_Click;

    grid.Children.Add(lbl);
    grid.Children.Add(bt);
}

// On click event for button
private void Button_Click(object sender, EventArgs e)
{
    // do whatever when button is clicked

    // this is a reference to the button that was clicked,
    // you can delete it here or do whatever with it
    Button buttonClicked = (Button)sender;
}

Now, when the button is clicked, "Button_Click" will be fired off.

A: You can add a handler to your button's Clicklike this
bt.Click += (a,b) => grid.Children.Remove( a );

but you really should do it with a ListView and templates, as slugster suggested.


text:
Q: Compile replacement for Python's re.sub before the loop I have trivial code to replace substrings using Python's re :
pattern = re.compile(r'(--type-header )([^ ]*)')
for x in somelist:
    filename = '...'  # here is a filename
    switches = x.replace('alice', 'bob')  # simple string
    switches = pattern.sub(
        r'\1' + f'{os.path.dirname(filename)}/' + r'\2',
        switches
    )

The substring I'd like to replace:
--type-header cond_enum_04.h

Everything works like a charm on Linux/macOs. But on Windows I get:

re.error: bad escape \c at position 16

for about 250 iteration of the loop (249 iterations are successful). I suspect that this is a distinctive feature re in loops under the Windows. Is there some way to compile the replacement before entering the loop?

A: The problem is due to the directory separator on Windows being interpreted as an escape character (see here).
One possible solution is to use pathlib to handle the path, and call its .as_posix method to render the path string in a consistent format across the various platforms, suitable then for applying the regex.
So in this case, replacing this:
f'{os.path.dirname(filename)}/'

with something like this:
f'{Path(filename).parent.as_posix()}/'


text:
Q: Multilanguage site from plain HTML/JS I got plain .html and .js files (lots of code) and web site needs to support multiple languages. I know how to use ASP.NET local and global resource files, so...
...is there any less painful way to achieve this, than rewriting all the .html to .aspx and write httpHandler for .js files?

A: Yes there is a really cool service from Google which translate your pages on the fly..
https://translate.google.com/translate_tools
It can even save your preferred translation so that you can personalize translations for your website
even Microsoft also provide similar service
http://www.microsoft.com/web/solutions/mstranslator.aspx


text:
Q: PHP cURL: modify/overwrite Connection header With PHP cURL library I have ability to operate with HTTP headers, but how about Connection header? When I'm sending any request, cURL always appends it with Connection: Keep-Alive and when I'm trying to modify this header to this one Connection: keep-alive (lowercase 'keep-alive'), it append instead, two lines as result:
Connection: Keep-Alive
Connection: keep-alive

How can I change it instead of append?
Thanks.
UPDATE:
I'm doing it in this way:
$url = 'http://some.host/path';
$ch = curl_init();
$hdrs = array(  'Host: some.host',
                'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0',
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US;q=0.5,en;q=0.3',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive');
curl_setopt($ch, CURLOPT_HTTPHEADER, $hdrs);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);

UPDATE 1:
Only solution I found (probably not the best) is to edit php_curl library file with hex editor.


text:
Q: Matrix of quadratic form (in Serre's general notion)? I am currently reading Serre's book on arithmetic. In chapter four (page 27) he defines a general notion of the quadratic form as:
Let $V$ be a module of a commutative ring $A$. A function $Q$ is called a quadratic form on $V$ if:
\begin{align*}
&1) Q(ax)=a^2Q(x) \textrm{ for }a \in A \textrm{ and }x \in V$ \\
&2) \textrm{The function }(x,y) \rightarrow Q(x+y)-Q(x)-Q(y) \textrm{ is a bilinear form }
\end{align*}
Also he defines a sort of product:
\begin{align*}
x \cdot y = \frac{1}{2}(Q(x,y)-Q(x)-Q(y))
\end{align*}
Then he gives a matrix of a quadratic form, which is the matrix $A=(a_{ij})$ where $a_{ij}=e_i \cdot e_j$, for a basis $(e_i)_{1\leq i \leq n}$ of $V$. Now I don't see how it is easy to see that this matrix is the matrix with respect to $Q$, considering this specially product $\cdot$ that he defined. Can someone explain me how this works?

A: The short answer is that these are related in exactly the same way as the "usual" inner product on $\mathbb{R}^n$ and the (identity) matrix corresponding to the form $x_1^2 + \ldots x_n^2$.
I can't recall exactly the assumptions in Serre's book on the module $V$, but let's assume that it's a free module over some unital commutative ring $R$, so that it admits an $R$-basis $\{e_1,\ldots,e_n\}$ and we may identify $V$ with $R^n$. The relationship between a quadratic form $Q$ on $V$ and its matrix $A = A_Q$ is that for $x = (x_1,\ldots,x_n)^t \in R^n$ (identified with $\sum_k x_k e_k$ and with $x^t$ denoting the transpose of $x$) is
$$
    Q(x) = x^t A x.
$$
If we write $A = (a_{i,j})$ where $a_{i,j} \in R$ for each pair $(i,j)$, then the above equation says that
\begin{align*}
    Q(x) &= (x_1,\ldots,x_n)\begin{pmatrix}a_{1,1}x_1 + a_{1,2}x_2 + \ldots + a_{1,n}x_n \\ \vdots \\ a_{n,1}x_1 + a_{n,2}x_2 + \ldots + a_{n,n}x_n\end{pmatrix} \\
    &= a_{1,1}x_1^2 + a_{1,2}x_1x_2 + \ldots + a_{1,n}x_1x_n \\
    &\,+ a_{1,1}x_1x_2 + a_{1,2}x_2^2 + \ldots + a_{1,n}x_2 x_n \\
    &\,+ \ldots \\
    &\,+ a_{1,1}x_1x_n + a_{1,2}x_2x_n + \ldots + a_{1,n}x_n^2 \\
    &= \sum_{i=1}^n\sum_{j=1}^n a_{i,j}x_ix_j.
\end{align*}
So, how does this relate to the inner product $x \cdot y = \frac{1}{2}[Q(x+y) - Q(x) - Q(y)]$? For convenience, I'll set $B(x,y) = x\cdot y$.
Then we can see from the above derivation that
$$
  B(x,y) = \frac 1 2\left[ \sum_{i,j} a_{i,j}(x_i+y_i)(x_j+y_j) - \sum_{i,j} a_{i,j}x_ix_j - \sum_{i,j} a_{i,j}y_iy_j \right],
$$
and so, expanding $(x_i + y_i)(x_j + y_j)$ and simplifying,
$$
  B(x,y) = \sum_{i,j} a_{i,j}x_iy_j.
$$
We are now in a position to see why $a_{i,j} = B(e_i,e_j) = e_i\cdot e_j$. Notice that under the identification of $V$ and $R^n$ above that $e_i$ corresponds to the vector with $1$ in its $i$-th entry and $0$ elsewhere. Denote by $\delta_{a,b}$ for $a,b \in \{1,\ldots,n\}$ the usual Kronecker delta
$$
    \delta_{a,b} = \begin{cases} 1 & \text{if $a = b$}\\ 0 &\text{if $a\neq b$}\end{cases}
$$
(here $1$ and $0$ are taken to be in $R$) for convenience, so that, for example $e_i$ is identified with the vector $(\delta_{i,1},\ldots,\delta_{i,n})$ in $R^n$. Then it follows from the simplified form of $B(x,y)$ above that
$$
    B(e_i,e_j) = \sum_{r,s}a_{r,s}\delta_{i,r}\delta_{j,s} = a_{i,j}
$$
since $\delta_{i,r}\delta_{j,s} = 0$ unless $r = i$ and $s = j$.


text:
Q: Additional colors in Firefox options In Firefox → options → content → fonts & colors → colors , there is a palette with 70 predefined colors to choose from.

Is it possible to apply a different non predefined color?

A: You can use this addon Color toggle which will enable you to use hex value of colors in additional with keyboard shortcuts to change the color scheme. There is no way to change the predefined ones, unless you recompile Firefox (I don't know if any Addon can do that).


text:
Q: Should I Play the Previous Halo's before Halo 5? I have always wanted to play Halo for a long time and I was so happy that they finally gave it a T rating.
So I might buy Halo 5 because it just came out + it got  rated T.
My dad wont let me buy the other Halo's because they are rated M.
Do I need to play the previous Halos to be able to understand/play this one?

A: Halo 1-3,ODST and kind of Reach are of a different saga, so although important to the whole series, not as important to the current "Reclaimer Saga" which began with Halo 4.
Although it's highly recommended that you play the previous games, especially 4. The Halo Universe is much bigger than just the games, and you can get a much better understanding of the happenings in Halo 5 by reading the books, watching the movies, and other media on Waypoint.
The easiest and shortest method would be to get the Master Chief Collection, as it contains all games that matter, as well as additional lore to help, but if M rated games are banned for you, you will probably be ok just exploring the wikia and the many imgur albums that explain the lore quickly and deeply (just not as fun as actually playing it...).


text:
Q: Why the "RemoveAllAnimations()" doesn't stop my animation? I have a very simple sample that allows to drag an UIView around. When touch up, I will have an inertia effect on the dragging direction for a second. While if I touch down again, I need to stop all the inertia animation and start to do another drag. Here is my code, the "clearAllAnimations" doesn't stop my animation. How could I implement that?
import UIKit

class ViewController: UIViewController {
    var tile : UIView = UIView()
    var labelView = UITextView()
    var displayLink : CADisplayLink?

    override func viewDidLoad() {
        super.viewDidLoad()

        tile.frame = CGRect(x: 0, y: 0, width: 256, height: 256)
        tile.backgroundColor = UIColor.redColor()
        view.addSubview(tile)

        var panGesture = UIPanGestureRecognizer(target: self, action: Selector("panHandler:"))
        view.addGestureRecognizer(panGesture)

        labelView.frame = CGRect(x: 0, y: 100, width: view.frame.width, height: 44)
        labelView.backgroundColor = UIColor.clearColor()
        view.addSubview(labelView)
    }

    func panHandler (p: UIPanGestureRecognizer!) {
        var translation = p.translationInView(view)
        if (p.state == UIGestureRecognizerState.Began) {
            self.tile.layer.removeAllAnimations()
        }
        else if (p.state == UIGestureRecognizerState.Changed) {
            var offsetX = translation.x
            var offsetY = translation.y

            var newLeft = tile.frame.minX + offsetX
            var newTop = tile.frame.minY + offsetY

            self.tile.frame = CGRect(x: newLeft, y: newTop, width: self.tile.frame.width, height: self.tile.frame.height)
            labelView.text = "x: \(newLeft); y: \(newTop)"
            p.setTranslation(CGPoint.zeroPoint, inView: view)
        }
        else if (p.state == UIGestureRecognizerState.Ended) {
            var inertia = p.velocityInView(view)
            var offsetX = inertia.x * 0.2
            var offsetY = inertia.y * 0.2
            var newLeft = tile.frame.minX + offsetX
            var newTop = tile.frame.minY + offsetY

            UIView.animateWithDuration(1, delay: 0, options:UIViewAnimationOptions.CurveEaseOut, animations: {_ in
                self.tile.frame = CGRect(x: newLeft, y: newTop, width: self.tile.frame.width, height: self.tile.frame.height)
                }, completion: nil)

        }
    }
}

A: Setting UIViewAnimationOptions.AllowUserInteraction does the trick. The new code to start animation is this:
UIView.animateWithDuration(animationDuration, delay: 0, options:UIViewAnimationOptions.CurveEaseOut | UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.BeginFromCurrentState, animations: {_ in
            self.tile.frame = CGRect(x: newLeft, y: newTop, width: self.tile.frame.width, height: self.tile.frame.height)
            }, completion: nil)


text:
Q: Use Fetch API to pass innerHTML data to flask without json I have an html form that sends data to my flask application. In addition, to the form's input fields, I also want to pass data from a DIV's innerHTML. I've been able to get data from the input fields to pass over to the flask side, but I haven't been able to get the DIVs innerHTML.
I've read a lot of questions on here that seem similar. But the answers for those questions all revolve around using json to pass the data. However, I don't think my data fits the json format since it's being generated dynamically by the user.
So how can I pass data from a DIV's innerHTML? Am I right in assuming that this isn't a case for json. Here's what I've tried:
When I run the code below, the data for amount comes over in the console. The innerHTML returns 'NONE'
HTML
<form id="action_id" action="/" method="post">

          <input class="col-12 action_info" type="text" id="amount" name="amount" placeholder="Amount">

          <button id="action_button" type="submit" value="submit">Submit</button>

    </form>

JAVASCRIPT
document.addEventListener('DOMContentLoaded', function() {

    document.querySelector('#action_id').onsubmit = function() {

        const myform = document.querySelector('#action_id');
        let data = new FormData(myform);

        fetch("/", {
            "method": "POST",
            "body": data,
        })
        .then(response => response.text)

        .then(data => {
            flop_one = document.querySelector('#flop_one').innerHTML;
        })
        .catch(error => {
            console.log('Error:', error);
        });
        return false;
    }
});

PYTHON
@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "GET":
        return render_template("index.html")

    elif request.method == "POST":

        flop_one = request.form.get("flop_one")
        app.logger.info(flop_one)

        amount = request.form.get("amount")
        app.logger.info(amount)

        return render_template("index.html")

A: I believe your form data is being submitted, but without using the Fetch API, for the following reasons.
The listener for the 'DOMContentLoaded' event is associated with the window and not the document. It will never catch an event the way you use it.
window.addEventListener('DOMContentLoaded', () => {
    // ...
});

The listener for the 'submit' event does not prevent the form from default behavior. Thus, the form is submitted as usual and the use of the Fetch API is never called.
form.addEventListener('submit', function(event) {
    event.preventDefault();
    // ...
});

The data from your div element is not added to the form data to be submitted, so it is not present on the server side.
const flopOne = document.getElementById('flop_one');
const formData = new FormData(this);
formData.append('flop_one', flopOne.innerHTML);

When using the Fetch API, keep in mind that the calls to the .then blocks are used to handle the server's response, as these are not automatically processed by the browser.
Unfortunately, your question does not explain what should happen once the data has been transferred.
Here is the complete example for sending the entire data via Fetch-API.
window.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('action_id');
    form.addEventListener('submit', function(event) {
        event.preventDefault();
        const flopOne = document.getElementById('flop_one');
        const formData = new FormData(this);
        formData.append('flop_one', flopOne.innerHTML);

        fetch('/', {
            method: 'POST',
            body: formData
        })
        // If you expect a response from the server and want to process it,
        // use the "then" block here.
    })
});


text:
Q: Add from:to range per group as a column I am currently struggling with a dataset. I have some fundamental values of different companies for different years. I want to add the years to that dataset.
Current dataset:
FirmA  EBITDA
FirmA  EBITDA
FirmA  EBITDA
FirmB  EBITDA
FirmB  EBITDA
FirmB  EBITDA

Goal is to add the dates, whereas I know that the first entry of FirmA is 2017, the second is 2016 and the third 2015 and it repeats without exceptions.
2017 FirmA  EBITDA
2016 FirmA  EBITDA
2015 FirmA  EBIDTA
2017 FirmB  EBITDA
2016 FirmB  EBITDA
2015 FirmB  EBITDA

Any suggestions on how to do this?
I am using R but if there is an easy solution in Python or Excel I am open to try it out.

A: You can make use of R's recycling rule
transform(df, year = 2017:2015)
#     V1     V2 year
#1 FirmA EBITDA 2017
#2 FirmA EBITDA 2016
#3 FirmA EBITDA 2015
#4 FirmB EBITDA 2017
#5 FirmB EBITDA 2016
#6 FirmB EBITDA 2015

or simply
df$year <- 2017:2015

Sample data
df <- read.table(text =
    "FirmA  EBITDA
FirmA  EBITDA
FirmA  EBITDA
FirmB  EBITDA
FirmB  EBITDA
FirmB  EBITDA", header  = F)

A: Or you could use data.table
# I used sample data from @Maurits Evers
library(data.table)
setDT(df)[, year:= paste(2017:2015), by = V1]

And the output
      V1     V2 year
1: FirmA EBITDA 2017
2: FirmA EBITDA 2016
3: FirmA EBITDA 2015
4: FirmB EBITDA 2017
5: FirmB EBITDA 2016
6: FirmB EBITDA 2015


text:
Q: Two tables match on JOIN condition. First table has no records How can I find the records in one table for which there are no records in a second table that match based on a join condition?
For example, given the two tables:
Titles
TitleID, ArtistID, Title, StudioID, Genre
Artists
ArtistID, ArtistName, City, Region, Country
How can I find the records in one table for which there are no records in a second table that match based on a join condition?
Or how would I modify these tables to conform to my question (above)?

A: You can use a LEFT JOIN
SELECT t.*
FROM Titles t
LEFT JOIN Artists a ON t.ArtistsID = a.ArtistsID
WHERE a.ArtistID IS NULL


text:
Q: ${user.home} in Ubuntu 14.04 LTS Disk I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
This is one of my config class
@Configuration
@EnableTransactionManagement
@EnableCaching
@PropertySource("file:///${user.home}/.devices/application-common.properties")
public class DeviceApplicationConfig {
..
}

I enter in the linode machine with devuser:
devuser@localhost:~$ pwd
/home/devuser

then I run the SpringBoot app. from the folder /var/devices, But I have this error, while I was expecting the program search the file in: /home/devuser/.devices/application-common.properties
Caused by: java.io.FileNotFoundException: /root/.devices/application-common.properties (No such file or directory)

and checking the processes it seems than the application is run by devuser:
devuser  12922  1.3 12.3 2478348 252840 ?      Sl   15:16   0:37 java -jar devices-0.0.1-SNAPSHOT.jar

A: you need to configure user.home directory and run application from this user. for configuration of user.home you can refer bellow stackoverflow link :
Command to change the default home directory of a user


text:
Q: Searching for Python MSDOS parser library Does anyone knows a good Python library to parse MSDOS files and obtain metadata and start()'s bytecodes? Like an alternative version of pefile library but for MSDOS? I can't seems to find any via Google.
If there isn't, is there a good source to refer to on MSDOS's file format? This way, I can create my own parser instead. I know there are tools like IDA Pro and Reko decompiler but I need a MSDOS file parser to automate some stuff. Thank you in advanced!

A: Reko decompiler maintainer here. For what it's worth, you can use Reko's MS-DOS source code and translate it to Python. It's not a lot of code and MS-DOS executables aren't that complex to parse -- it's quite a simple format. The relevant files are:
https://github.com/uxmal/reko/blob/master/src/ImageLoaders/MzExe/ExeImageLoader.cs
https://github.com/uxmal/reko/blob/master/src/ImageLoaders/MzExe/MsdosImageLoader.cs
You could also try executing the Reko code directly from Python. The Reko binaries are available as a nuget package: https://www.nuget.org/packages/Reko.Decompiler.Runtime
Use the class Reko.ImageLoaders.MzExe.ExeImageLoader in the Reko.ImageLoaders.MzExe class. Integration could be done with http://pythonnet.github.io/


text:
Q: How to detect device to show model of mobile? In a website, how to detect device => model name of mobile when using mobile ? How to ideas

A: Use:
    $_SERVER['HTTP_USER_AGENT'];
You can read more about $_SERVER calls here

A: Although you can directly use the $_SERVER variable, there is a small PHP library called Mobile_Detect.php that makes your files very clean.
I think it runs through the $_SERVER variable, anyways, but it looks nicer to just call is_iPhone() than to parse through the header and possibly miss something.

A: This code can help you to do it.
<?php

$mobile_browser = '0';

if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
    $mobile_browser++;
}

if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
    $mobile_browser++;
}

$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
$mobile_agents = array(
    'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
    'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
    'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
    'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
    'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
    'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
    'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
    'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
    'wapr','webc','winw','winw','xda ','xda-');

if (in_array($mobile_ua,$mobile_agents)) {
    $mobile_browser++;
}

if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini') > 0) {
    $mobile_browser++;
}

if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows') > 0) {
    $mobile_browser = 0;
}

if ($mobile_browser > 0) {
   // do something
}
else {
   // do something else
}

?>

for more information see here


text:
Q: sort string according to first characters matlab I have an cell array composed by several strings
names = {'2name_19surn', '3name_2surn', '1name_2surn', '10name_1surn'}

and I would like to sort them according to the prefixnumber.
I tried
[~,index] = sortrows(names.');
sorted_names = names(index);

but I  get
sorted_names = {'10name_1surn', '1name_2surn', '2name_19surn', '3name_2surn'}

instead of the desired
sorted_names = {'1name_2surn', '2name_19surn', '3name_2surn','10name_1surn'}

any suggestion?

A: As long as speed is not a concern you can loop through all strings and save the first digets in an array. Subsequently sort the array as usual...
names = {'2name_2', '3name', '1name', '10name'}
number_in_string = zeros(1,length(names));

% Read numbers from the strings
for ii = 1:length(names)
    number_in_string(ii) = sscanf(names{ii}, '%i');
end

% Sort names using number_in_string
[sorted, idx] = sort(number_in_string)
sorted_names = names(idx)

A: Simple approach using regular expressions:
r = regexp(names,'^\d+','match'); %// get prefixes
[~, ind] = sort(cellfun(@(c) str2num(c{1}), r)); %// convert to numbers and sort
sorted_names = names(ind); %// use index to build result

A: Take the file sort_nat from here
Then
names = {'2name', '3name', '1name', '10name'}
sort_nat(names)

returns
sorted_names = {'1name', '2name', '3name','10name'}

A: You can deal with arbitrary patterns using a regular expression:
names = {'2name', '3name', '1name', '10name'}

match = regexpi(names,'(?<number>\d+)\D+','names'); % created with regex editor on rubular.com
match = cell2mat(match); % cell array to struct array
clear numbersStr
[numbersStr{1:length(match)}] = match.number; % cell array with number strings
numbers = str2double(numbersStr); % vector of numbers
[B,I] = sort(numbers); % sorted vector of numbers (B) and the indices (I)
clear namesSorted
[namesSorted{1:length(names)}] = names{I} % cell array with sorted name strings


text:
Q: Zend 3 Argument 1 passed to Application\Controller\IndexController::__construct() must be an instance of , none given, This configuration works on my local install, but not on remote site.
ExampleManager.php
<?php
namespace Application\Service;

use Application\Entity\SomeTable;

class ExampleManager
{

    /**
     * Entity manager.
     * @var Doctrine\ORM\EntityManager
     */
    private $entityManager;

    public function __construct($entityManager)
    {
      $this->entityManager = $entityManager;
    }

ExampleManagerFactory.php
<?php

namespace Application\Service\Factory;

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Application\Service\ExampleManager;

class ExampleManagerFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container,
    $requestedName, array $options = null)
    {
        $entityManager = $container->get('doctrine.entitymanager.orm_default');

        // instantiate the service and inject dependencies
        return new ExampleManager($entityManager);
    }
}

IndexControllerFactory.php
<?php

namespace Application\Controller\Factory;

use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
use Application\Controller\IndexController;

class IndexControllerFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $exampleManager = $container->get(\Application\Service\ExampleManager::class);

        // instantiate the controller and inject dependencies
        return new IndexController($exampleManager);
    }
}

IndexController.php
<?php
/**
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Service\ExampleManager;

class IndexController extends AbstractActionController
{
    /**
     * Example manager.
     * @var Application\Service\ExampleManager
     */
    private $exampleManager;

    public function __construct(ExampleManager $exampleManager)
    {
      $this->exampleManager = $exampleManager;
    }

module.config.php
<?php
/**
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Application;

use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Application\Service\ExampleManager;

return [
    'router' => [
        'routes' => [
            'home' => [
                'type' => Literal::class,
                'options' => [
                    'route'    => '/',
                    'defaults' => [
                        'controller' => Controller\IndexController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
            'application' => [
                'type'    => Segment::class,
                'options' => [
                    'route'    => '/application[/:action]',
                    'defaults' => [
                        'controller' => Controller\IndexController::class,
                        'action'     => 'index',
                    ],
                ],
            ],
        ],
    ],
    'controllers' => [
        'factories' => [
            Controller\IndexController::class => Controller\Factory\IndexControllerFactory::class,
        ],
    ],
    'service_manager' => [
        'factories' => [
            ExampleManager::class => Service\Factory\ExampleManagerFactory::class,
        ],
    ],
    'view_manager' => [
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => [
            'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
            'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ],
        'template_path_stack' => [
            __DIR__ . '/../view',
        ],
    ],
    'doctrine' => [
        'driver' => [
            __NAMESPACE__ . '_driver' => [
                'class' => AnnotationDriver::class,
                'cache' => 'array',
                'paths' => [__DIR__ . '/../src/Entity']
            ],
            'orm_default' => [
                'drivers' => [
                    __NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
                ],
            ],
        ],
    ],
];

Argument 1 passed to Application\Controller\IndexController::__construct() must be an instance of Application\Service\ExampleManager, none given

Seems strange for it to work locally, but not from a remote site. Is it not finding the path to my service for some reason?

A: SOLVED
Wow, ok so this happened because when I had initially installed zend-skeleton awhile back I had disabled development mode, but cache files of the existing config had been created in data/cache. I discovered this while trying to think what could be different between my local and remote install. The fix is to remove the cache files.
A better explanation and credit for the solution is here:
https://stackoverflow.com/a/45146213/5133172
Files are back to read only, dev mode is disabled and all works perfectly. :)


text:
Q: Xamarin Android file system paths I'm trying to write and read a file on the Android file system. A task you would think would be straight forward, but I just can't seem to find the right enumerator for a folder/path that actually exists.
I have read several posts on the same subject but none of them give a straight answer to this question and those that seem to have fixed their issues, has done so with paths that doesn't seem to work for me.
Some suggestions seem to be related to System.IO while others seem to be of the Java equivalent.
What I'm trying to do is something as simple as to create a file somewhere in the internal storage (NOT external SD card or something) that is accessible from the device itself (via File Browser app or similar).
If that goes well (which it currently doesn't) then I would also like to read it later on.
I'm not looking for code to write or read files - I'm looking for something that can give me the correct path to a folder where I can do this.
I have tried many different variants, some of which are:
Environment.GetFolderPath (Environment.SpecialFolder.Personal);
returns the path: /data/data/my_app_full_name/files/
global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath.ToString();
returns the path: /storage/emulated/0/
Can anyone give a clear answer as to which enumerator to use for this? - would be much appreciated.
PS. I'm launching the app on an actual device (Android 5.0.2) from Xamarin Studio via USB.
EDIT: The answer, for me at least, is found under the comments for replay by misho.

A: I think this is what you need:
Edit
public static string Directorypath
    {
        get
        {
            return System.IO.Path.Combine((string)Android.OS.Environment.ExternalStorageDirectory, "FolderPath");
        }
    }


text:
Q: Is the window size in ksqlDB configurable after creation of the query? I am working on a use case where I am checking the number of salary raises an employee has for a particular time frame. I wanted the time frame that is the window size to be configurable at a later stage when the need arises. For example, for the following query:

create table salary_hike_frequency as select
   empID, count(*) as cnt,
   latest_by_offset(name->first_name) as name,
   latest_by_offset(salary->base_salary) as salary
   from emp_salary
   window tumbling (size 180 days)
   group by empID having count(*) > 2
   emit changes;

If I now want to update the query ( basically change the window size ) to

create table salary_hike_frequency as select
       empID, count(*) as cnt,
       latest_by_offset(name->first_name) as name,
       latest_by_offset(salary->base_salary) as salary
       from emp_salary
       window tumbling (size 30 days)
       group by empID having count(*) > 2
       emit changes;

I get the following error
Cannot add table 'salary_hike_frequency': A table with the same name already exists
Now I don't want to create another topic for the updated window size. The only workaround I found was to terminate the query, drop the table and then run the query with the updated window size again. This then adds data to the same topic 'salary_hike_frequency', although starting from the beginning of the 'emp_salary' topic. ( I have set 'auto.offset.reset' to 'earliest')
However, this process seems very hacky and neither using variables as parameters for the window worked nor using in-place upgrades. Both gave the following errors respectively (for reference only):-

-- the queries using variables
ksql> define windowsize = '30';
ksql> create table salary_hike_frequency as select
>   empID, count(*) as cnt,
>   latest_by_offset(name->first_name) as name,
>   latest_by_offset(salary->base_salary) as salary
>   from emp_salary
>   window tumbling (size ${windowsize} days)
>   group by empID having count(*) > 2
>   emit changes;

-- the error
line 6:26: mismatched input '${windowsize}' expecting {'-', INTEGER_VALUE, DECIMAL_VALUE, FLOATING_POINT_VALUE}
Statement: create table salary_hike_frequency as select
   empID, count(*) as cnt,
   latest_by_offset(name->first_name) as name,
   latest_by_offset(salary->base_salary) as salary
   from emp_salary
   window tumbling (size ${windowsize} days)
   group by empID having count(*) > 2
   emit changes;
Caused by: line 6:26: mismatched input '${windowsize}' expecting {'-', INTEGER_VALUE, DECIMAL_VALUE, FLOATING_POINT_VALUE}
Caused by: org.antlr.v4.runtime.InputMismatchException

and

-- the query trying for in-place upgrades
create or replace table salary_hike_emp as
>   select empID, count(*) as cnt,
>   latest_by_offset(name->first_name) as name,
>   latest_by_offset(salary->base_salary) as salary
>   from emp_salary
>   window tumbling (size 30 days)
>   group by empID having count(*) > 2
>   emit changes;

-- the error
Cannot upgrade data source: DataSource '`SALARY_HIKE_EMP`' has topic = KsqlTopic{kafkaTopicName='SALARY_HIKE_EMP',keyFormat=KeyFormat{format=FormatInfo{format=KAFKA, properties={}}, features=[], window=Optional[WindowInfo{type=TUMBLING, size=Optional[15552000000]}]}, valueFormat=ValueFormat{format=FormatInfo{format=AVRO, properties={}}, features=[]}} which is not upgradeable to KsqlTopic{kafkaTopicName='SALARY_HIKE_EMP',keyFormat=KeyFormat{format=FormatInfo{format=KAFKA, properties={}}, features=[], window=Optional[WindowInfo{type=TUMBLING, size=Optional[2592000000]}]}, valueFormat=ValueFormat{format=FormatInfo{format=AVRO, properties={}}, features=[]}}

I wanted to know if there was any other way of tackling this problem other than replacing upgrades?
I am using the confluent platform 6.1.0 through the docker-compose file for my cluster. No. of Partition for the above topics is 1 as well as the replication factor, any other values are default.


text:
Q: Axion quantum corrections I've seen theories of multiple axions written down, e.g.
$$
V(a,\phi) = \Lambda_{\rm QCD}^4\left(1 - \cos \frac{a}{f_a}\right) + \Lambda_{\rm ALP}^4\left(1 - \cos \left(\frac{a}{f_a} + \frac{\phi}{f}\right)\right)
$$
where, for example, $a$ is a QCD axion and $\phi$ is an ALP with corresponding decay constants $f_a$ and $f$. Usually, we'd expect $\Lambda_{\rm ALP}$ to differ from $\Lambda_{\rm QCD}$ by orders of magnitude, since they are generated by instantons, and thus are exponentially suppressed by the instanton action.
Now, I've seen the words that the "discrete shift symmetry of the axions" protect their potential from quantum corrections. Is the axion potential protected from quantum corrections only from other fields that would break this shift symmetry? If so, then to what extent is it self-consistent to write down a potential of the form I've written above?


text:
Q: git-http-backend with AuthzUnixGroup not working properly I am trying to set up a git repository over my Apache 2.2 on a CentOS 6 box, with git installed. I have tried following many different directions, and I am at a loss. My current situation comprises of being able to clone normally, but being completely unable to push.
It seems as though I am incapable of getting the authentication bit to work properly, as I can normally perform the push while setting http.receivepack to true.
I have installed AuthzUnixGroup as well as mod_authz_external.
I went to /var/www/git and created a repo named my-repo.git and did a git init --bare inside it.
Then I set up my git.conf file inside /etc/httpd/conf.d/ as follows:
<VirtualHost "*:80">
  SetEnv GIT_HTTP_EXPORT_ALL
  SetEnv GIT_PROJECT_ROOT /var/www/git
  SetEnv REMOTE_USER=$REDIRECT_REMOTE_USER
  ScriptAlias /git /usr/libexec/git-core/git-http-backend
  AddExternalAuth pwauth /usr/local/libexec/pwauth
  SetExternalAuthMethod pwauth pipe

  <Directory "/usr/libexec/git-core/">
    AllowOverride None
    Options +ExecCGI -Includes
    Order allow,deny
    Allow from all
  </Directory>

  <Location "/git">
    AuthzUnixGroup on
    AuthType Basic
    AuthName "Git repository"
    AuthBasicProvider external
    AuthExternal pwauth
    Require group git
  </Location>

</VirtualHost>

Pointing my web browser to mysite/git nicely shows me the HTTP basic login dialog, which works perfectly. I have added myself to the group git, and doing a groups on my shell returns:
naseri sudo git

which is as expected.
When I do git clone http://mysite/git/my-repo.git I get the following from the access_log file for httpd under /var/logs/httpd/access_log:
2.177.130.21 - - [11/Jun/2014:18:51:07 +0000] "GET /git/my-repo.git/info/refs?service=git-upload-pack HTTP/1.1" 401 480 "-" "git/1.8.5.2 (Apple Git-48)"
2.177.130.21 - - [11/Jun/2014:18:51:08 +0000] "GET /git/my-repo.git/info/refs?service=git-upload-pack HTTP/1.1" 401 480 "-" "git/1.8.5.2 (Apple Git-48)"
2.177.130.21 - naseri [11/Jun/2014:18:51:08 +0000] "GET /git/my-repo.git/info/refs?service=git-upload-pack HTTP/1.1" 200 256 "-" "git/1.8.5.2 (Apple Git-48)"
2.177.130.21 - naseri [11/Jun/2014:18:51:09 +0000] "POST /git/my-repo.git/git-upload-pack HTTP/1.1" 200 368 "-" "git/1.8.5.2 (Apple Git-48)"

On the client, the cloneing works properly. I change stuff around, then try to push after a commit by git pushing the content.
This is what I get on the server side log:
2.177.130.21 - - [11/Jun/2014:18:53:26 +0000] "GET /git/my-repo.git/info/refs?service=git-receive-pack HTTP/1.1" 401 480 "-" "git/1.8.5.2 (Apple Git-48)"
2.177.130.21 - naseri [11/Jun/2014:18:53:27 +0000] "GET /git/my-repo.git/info/refs?service=git-receive-pack HTTP/1.1" 401 480 "-" "git/1.8.5.2 (Apple Git-48)"
2.177.130.21 - naseri [11/Jun/2014:18:53:30 +0000] "GET /git/my-repo.git/info/refs?service=git-receive-pack HTTP/1.1" 403 - "-" "git/1.8.5.2 (Apple Git-48)"

I can see that my "Authentication Required" response is being sent back by Apache on the first line of response (401) but the client shows me:
fatal: unable to access 'http://mysite/git/my-repo.git/': The requested URL returned error: 403

I am clueless as to the problem, as pointing my browser to the same URL properly brings up authentication and it even works right.

A: This older answer

git-http-backend is returning a 403/Forbidden code when the client asks to use the git-receive-pack method.
  It then falls back to WebDAV, but using WebDAV is not necessary.
I had the same problem; in my case this was due to REMOTE_USER not being set

Since any of my Apache config uses an '=' when setting a variable, check if this works better:
SetEnv REMOTE_USER $REDIRECT_REMOTE_USER

(no '-' between the two variables)
Check also if not (re)defining REMOTE_USER works too (because it might already been defined, while REDIRECT_REMOTE_USER might not): try without that line.
I never have to define it in my Apache Git config.
Note: with Git 2.21 (Q1 2019, 5+ years later), Git should be more robust.

A: I have been in situation like this, and found that trying to use Apache to serve git is anything but easy or simple.
Instead, I would recommend installing Gerrit - it allows to host multiple repositories, and most importantly has extremely flexible user/group management and permission model. As a nice bonus, it also happens to be very powerful code review engine, but it is completely optional - you don't have to use code review features if you don't want to.
Other known solutions for this are Gitlab and Gitolite - you might want to look into them as well.


text:
Q: Copying files with wildcard * why isn't it working? There are 3 txt files called
1.txt 2.txt 3.txt
I want to batch copy with the name
1.txt.cp 2.txt.cp 3.txt.cp
using the wildcard *
I entered the command cp *.txt *.txt.cp
but it wasn't working...
cp : target *.txt.cp : is not a directory
what was the problem???

A: Use: for i in *.txt; do cp "$i" "$i.cp"; done
Example:
$ ls -l *.txt
-rw-r--r-- 1 halley halley 20 out 27 08:14 1.txt
-rw-r--r-- 1 halley halley 25 out 27 08:14 2.txt
-rw-r--r-- 1 halley halley 33 out 27 08:15 3.txt
$ ls -l *.cp
ls: could not access '*.cp': File or directory does not exist
$ for i in *.txt; do cp "$i" "$i.cp"; done
$ ls -l *.cp
-rw-r--r-- 1 halley halley 20 out 27 08:32 1.txt.cp
-rw-r--r-- 1 halley halley 25 out 27 08:32 2.txt.cp
-rw-r--r-- 1 halley halley 33 out 27 08:32 3.txt.cp
$ for i in *.txt; do diff "$i" "$i.cp"; done
$

A: If you are used to MS/Windown CMD shell, it is important to note that Unix system handle very differently the wild cards. MS/Windows has kept the MS/DOS rule that said that wild cards were not interpreted but were passed to the command. The command sees the wildcard characters and can handle the second * in the command as noting where the match from the first should go, making copy ab.* cd.* sensible.
In Unix (and derivatives like Linux) the shell is in charge of handling the wildcards and it replaces any word containing one with all the possible matches. The good news is that the command has not to care about that. But the downside is that if the current folder contains ab.txt ab.md5 cd.jpg, a command copy ab.* cd.* will be translated into copy ab.txt ab.md5 cd.jpg which is probably not want you would expect...
The underlying reason is Unix shells are much more versatile than the good old MS/DOS inherited CMD.EXE and do have simple to use for and if compound commands. Just look at @Halley Oliveira's answer for the syntax for your use case.


text:
Q: WP Cli does not print on terminal when executing code from file I have installed WP Cli successfully on my mac. I want to run PHP code from a file by wp shell command which is available in WP Cli
Work: when interactive mode like

*

*First, run wp shell

*then get_bloginfo( 'version' ) it's printing what expected.

Doesn't Work when trying to code from a file. After executing its print nothing!
Here test.php contains get_bloginfo( 'version' ) code.
Try 1: more "/Users/jhon/test.php" | wp shell --path="/Users/jhon/wp-project"
Try 2: more "/Users/jhon/test.php" | php wp shell --path="/Users/jhon/wp-project"


text:
Q: Serve different images to different user agents using htaccess I am planning to build a responsive website. Though I want the images to look good on all devices without having to change the content.
Is there a way to serve different images to different user agents or screen resolutions, using only htaccess?
For example have two folders "/images" and "/imagesiphone" and if user agent is ihpone it sends images from imagesiphone istead of images (of course I would have to duplicate all the images in the folder "imagesiphone").
Would there be any spam reactions if you send different content for the same requested image?
Note: I dont want to use any javsacript.

A: RewriteCond %{HTTP_USER_AGENT}  ^.*iPhone.*
RewriteRule ^images/(.*)$ imagesiphone/$1 [NC,L]


text:
Q: SQL: EXCEPT Query Here is a basic example of what I am trying to achieve:
create table #testing (
     tab varchar(max), a int, b int, c int )

insert into #testing VALUES ('x',1, 2, 3)
insert into #testing VALUES ('y',1, 2, 3)
insert into #testing VALUES ('x', 4, 5, 6)

select * from #testing

Which will Produce the table:
 tab     a    b    c
-----------------------
  x      1    2    3
  y      1    2    3
  x      4    5    6

I then want to compare rows on 'tab' based on the values of a,b,c:
select a,b,c from #testing where tab = 'x'
except
select a,b,c from #testing where tab= 'y'

Which gives me the answer I was expecting:
a    b    c
------------
4    5    6

However I want to also include the Tab column in my resultset, so I want somthing like this:
 Select tab,a,b,c from #testing where ????
            (select a,b,c from #testing where tab = 'x'
             except
             select a,b,c from #testing where tab= 'y')

How would I achieve this?

A: Use not exists:
select a.*
from #testing a
where a.tab = 'x'
      and not exists (
                       select *
                       from #testing t
                       where t.a = a.a and t.b = a.b and t.c = a.c and t.tab = 'y'
                     )

And here you get SQL Fiddle demo: DEMO

A: Although the answer from @gzaxx does produce a correct result for this test data, the more generalized version is below, where I left 'x' and 'y' out of the statements.
select a.*
from #testing a
where not exists (
                   select *
                   from #testing t
                   where t.a = a.a and t.b = a.b and t.c = a.c and t.tab <> a.tab
                 )

A: Please Try it
 with cte as
 (
 select *,rn = ROW_NUMBER() over(PARTITION by tab order by tab)from #testing
 )
 select tab,a,b,c from cte where rn>1


text:
Q: I want to change the key binding for Tab key for a JButton Here is my code for customizing the key binding but this doesn't seem to work. It works for other keys (I tried it with key M) but whenever I press TAB focus shifts to next component instead of showing message dialog with "Hello" text.
JButton button= new JButton();
     button.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0),"sayHello");
button.getActionMap().put("sayHello", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(null,"Hello");
    }
});

A: Tabbing is handled by the focus manager so the Tab key is intercepted before the Key Bindings are processed.
Try removing the Tab key from the focus manager when you create the button:
button.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
//button.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);


text:
Q: Android App crashes on opening I have a problem with an Android app of mine.It crashes on startup and I don't know much about LogCat .Can anyone suggest me the best way to solve the problem.I have no idea what is wrong.
It is a MediaPlayer app which loops the audio.
Before I wrote (setOnClickListerner) It didn't crashed.
What could cause the problem?
MainActivity.java :
        package com.jobyreuben.dholakloops;

   public class MainActivity extends AppCompatActivity {

Button dholak01;
Button dholak02;
Button dholak03;
Button dholak04;
Button dholak05;
Button dholak06;
Button dholak07;
Button dholak08;
Button dholak09;
Button dholak10;
Button dholak11;
Button dholak12;
Button dholak13;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    dholak01 = (Button) findViewById(R.id.button_1);
    final MediaPlayer dk1 = MediaPlayer.create(MainActivity.this, R.raw.dholak01);
    dholak02 = (Button) findViewById(R.id.button_2);
    final MediaPlayer dk2 = MediaPlayer.create(MainActivity.this, R.raw.dholak02);
    dholak03 = (Button) findViewById(R.id.button_3);
    final MediaPlayer dk3 = MediaPlayer.create(MainActivity.this, R.raw.dholak03);
    dholak04 = (Button) findViewById(R.id.button_4);
    final MediaPlayer dk4 = MediaPlayer.create(MainActivity.this, R.raw.dholak04);
    dholak05 = (Button) findViewById(R.id.button_5);
    final MediaPlayer dk5 = MediaPlayer.create(MainActivity.this, R.raw.dholak05);
    dholak07 = (Button) findViewById(R.id.button_6);
    final MediaPlayer dk6 = MediaPlayer.create(MainActivity.this, R.raw.dholak06);
    dholak08 = (Button) findViewById(R.id.button_7);
    final MediaPlayer dk7 = MediaPlayer.create(MainActivity.this, R.raw.dholak07);
    dholak09 = (Button) findViewById(R.id.button_8);
    final MediaPlayer dk8 = MediaPlayer.create(MainActivity.this, R.raw.dholak08);
    dholak10 = (Button) findViewById(R.id.button_9);
    final MediaPlayer dk9 = MediaPlayer.create(MainActivity.this, R.raw.dholak09);
    dholak11 = (Button) findViewById(R.id.button_10);
    final MediaPlayer dk10 = MediaPlayer.create(MainActivity.this, R.raw.dholak10);
    dholak12 = (Button) findViewById(R.id.button_11);
    final MediaPlayer dk11 = MediaPlayer.create(MainActivity.this, R.raw.dholak11);
    dholak13 = (Button) findViewById(R.id.button_12);
    final MediaPlayer dk12 = MediaPlayer.create(MainActivity.this, R.raw.dholak12);

    dholak01.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dk1.isPlaying()) {
                dk1.pause();
                dholak01.setBackgroundResource(R.drawable.dholak);

            } else {
                dk1.start();
                dholak01.setBackgroundResource(R.drawable.dholakp);
                dk1.setLooping(true);

            }

        }
    });

    dholak02.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dk2.isPlaying()) {
                dk2.pause();
                dholak02.setBackgroundResource(R.drawable.dholak);

            } else {
                dk2.start();
                dholak02.setBackgroundResource(R.drawable.dholakp);
                dk2.setLooping(true);

            }

        }
    });
    dholak03.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dk3.isPlaying()) {
                dk3.pause();
                dholak03.setBackgroundResource(R.drawable.dholak);

            } else {
                dk3.start();
                dholak03.setBackgroundResource(R.drawable.dholakp);
                dk3.setLooping(true);

            }

        }
    });
    dholak04.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dk4.isPlaying()) {
                dk4.pause();
                dholak04.setBackgroundResource(R.drawable.dholak);

            } else {
                dk4.start();
                dholak04.setBackgroundResource(R.drawable.dholakp);
                dk4.setLooping(true);

            }

        }
    });
    dholak05.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dk5.isPlaying()) {
                dk5.pause();
                dholak05.setBackgroundResource(R.drawable.dholak);

            } else {
                dk5.start();
                dholak05.setBackgroundResource(R.drawable.dholakp);
                dk5.setLooping(true);

            }

        }
    });
    dholak06.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dk6.isPlaying()) {
                dk6.pause();
                dholak06.setBackgroundResource(R.drawable.dholak);

            } else {
                dk6.start();
                dholak06.setBackgroundResource(R.drawable.dholakp);
                dk6.setLooping(true);

            }

        }
    });
    dholak07.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dk7.isPlaying()) {
                dk7.pause();
                dholak07.setBackgroundResource(R.drawable.dholak);

            } else {
                dk7.start();
                dholak07.setBackgroundResource(R.drawable.dholakp);
                dk7.setLooping(true);

            }

        }
    });
    dholak08.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dk8.isPlaying()) {
                dk8.pause();
                dholak08.setBackgroundResource(R.drawable.dholak);

            } else {
                dk8.start();
                dholak08.setBackgroundResource(R.drawable.dholakp);
                dk8.setLooping(true);

            }

        }
    });
    dholak09.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dk9.isPlaying()) {
                dk9.pause();
                dholak09.setBackgroundResource(R.drawable.dholak);

            } else {
                dk9.start();
                dholak09.setBackgroundResource(R.drawable.dholakp);
                dk9.setLooping(true);

            }

        }
    });
    dholak10.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dk10.isPlaying()) {
                dk10.pause();
                dholak10.setBackgroundResource(R.drawable.dholak);

            } else {
                dk10.start();
                dholak10.setBackgroundResource(R.drawable.dholakp);
                dk10.setLooping(true);

            }

        }
    });
    dholak11.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dk11.isPlaying()) {
                dk11.pause();
                dholak11.setBackgroundResource(R.drawable.dholak);

            } else {
                dk11.start();
                dholak11.setBackgroundResource(R.drawable.dholakp);
                dk11.setLooping(true);

            }

        }
    });

    dholak12.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (dk12.isPlaying()) {
                dk12.pause();
                dholak12.setBackgroundResource(R.drawable.dholak);

            } else {
                dk12.start();
                dholak12.setBackgroundResource(R.drawable.dholakp);
                dk12.setLooping(true);

            }

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.id_about) {
        Intent intentabout = new Intent(MainActivity.this, About.class);
        startActivity(intentabout);
        return true;
    }
    if (id == R.id.id_contact)

    {
        Intent intentabout = new Intent(MainActivity.this, Contact.class);
        startActivity(intentabout);
        return true;
    }

    if (id == R.id.id_otherapps) {
        return true;
    }
    return true;
}

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.id_about) {
        Intent intentabout = new Intent(MainActivity.this, About.class);
        startActivity(intentabout);
        return true;
    }
    if (id == R.id.id_contact)

    {
        Intent intentabout = new Intent(MainActivity.this, Contact.class);
        startActivity(intentabout);
        return true;
    }

    if (id == R.id.id_otherapps) {
        return true;
    }
    return true;
    }
 }

Here's the LogCat log:
 --------- beginning of crash
                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                          at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                          at com.jobyreuben.dholakloops.MainActivity.onCreate(MainActivity.java:149)
                                                                          at android.app.Activity.performCreate(Activity.java:6679)
                                                                          at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                          at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

A: You have missed dholak04 . Make the reference of dholak04 button to the xml button .
change dholak05 = (Button) findViewById(R.id.button_4);
to
 dholak04 = (Button) findViewById(R.id.button_4);

And also you have made several mistakes in initializing . e.g init 5 with 6


text:
Q: Using sql, I am trying to show the names of the constraints used over many tables Using sql, I am trying to show the names of the constraints used over many tables.
I tried using:
SELECT constraint_name, constraint_type FROM user_constraints;

And I'm not sure what I'm looking at when the tables show up.
I know that if I add WHERE table_name = <table name> that I can get the constraints for a single table, but I was wondering if there is syntax for more than one table?

A: select
  table_schema,
  constraint_name,
  table_name
from
  information_schema.table_constraints


text:
Q: Laravel one to many relationship issue with credits name I'm defining a simple one to many relationship in laravel. A User has many Credits and a Credit belongs to a User.
User Model
/**
 * Relationship to the users credits
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function credits()
{
    return $this->hasMany(Credit::class);
}

Credit Model
/**
 * Relationship to the user that this credit belongs to
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function user()
{
    return $this->belongsTo(User::class);
}

Controller
/**
 * Return a user
 *
 * @param $user_id
 *
 * @return User
 */
public function getUser($user_id)
{
    $user = $this->user->findOrFail($user_id);
     // Dumping and Dieing works fine, but when i return
     // the User instance i get an error.
     // dd($user->toArray());
    return $user;
}

Error that I am getting:
"error":0,"message":"Object of class Illuminate\Database\Eloquent\Collection could not be converted to int"

A: Found the issue.
There was another place in the model that expected the $this->credits to return null.  That code was anticipating this code update but did not account for the fact that $this->credits would be a collection.

A: if you want to get the user from this user_id just write User::where('user_id', '=', $user_id)->first() in your controller.
and don't forget to pass user_id from your blade to controller.
I hope that's work for you


text:
Q: Ember Transaction has no method add I'm attempting to create an ember transaction to commit a single model to the backend api.
Coffeescript:
comic = App.Comic.createRecord(title: @get('comicTitle'))
transaction = comic.get('store').transaction
transaction.add(comic)
transaction.commit()

Which gives the javascript error:
Uncaught TypeError: Object function () {
    return DS.Transaction.create({ store: this });
  } has no method 'add'

I've googled various different ways to use ember transactions, but I'm not sure where I'm going wrong. I'm using the latest version of ember data.

A: The coffeescript to js translation may not be happening correctly. Try changing to
transaction = @get('store').transaction()

I have found the implicit method invocation in coffeescript trips up in Ember occasionally.


text:
Q: Float Formatting I will need to format a float value to string as given below
1.0E11 -- 1.0E11
1.21 -- 1.21

When tried with ToString("0.00") I got the following values:
1.0E11- "10000000000.00"
1.21 - 1.21

How can we convert the float value to string with exponential value, if it has exponential?

A: String.Format("{0:E4}", myFloat);

or
myFloat.ToString("E4"); // Where 4 is the number of decimal places

Reference: http://blogs.msdn.com/b/kathykam/archive/2006/03/29/564426.aspx

A: I think .ToString("G3") comes close to what you want, but you don't specify how you want intermediate numbers, like 666.123f, to be formatted.


text:
Q: ifPresent return something orElse I need some help with the below code snippet.. raiseWorkQueueTask should return the notification if it can find any null != previousPeriod.getOldId() and the outcomeCode of the riseWorkQueue is "L3".... but I get an error at
*.ifPresent(()->proceedWorkQueue(ip)).orElse(null);*

I get an error saying "Cannot infer functional interface" .. I also tried other variations ...
.ifPresent(()->proceedWorkQueue(ip).orElse(null));
.ifPresent(proceedWorkQueue(ip).orElse(null));

private Optional<Notification> riseWorkQueueTask(IP ip) {
    return ip.getPreviousPeriods().stream()
              .filter(previousPeriod -> null != previousPeriod.getOldId())
              .findAny()
              .ifPresent(() -> proceedWorkQueue(ip))
              .orElse(null);
}

private Optional<Notification> proceedWorkQueue(Ip ip) {
    EntryParametersDTO entryParametersDTO = new EntryParametersDTO();
    Insurance insurance = ip.getInsurance();
    //.....
    return queueClient.riseWorkQueue(entryParametersDTO)
              .filter(w -> w.getStateDTO() != null)
              .filter(w -> StateConstants.L3.equalsIgnoreCase(
                              w.getStateDTO().getOutcomeCode()))
              .flatMap(flag -> retrieveNotificationFromDB(insurance));
}

A: You're possibly looking out for map as:
private Optional<Notification> riseWorkQueueTask(IP ip) {
    return ip.getPreviousPeriods().stream()
            .filter(previousPeriod -> null != previousPeriod.getOldId())
            .findAny()
            .map(i -> proceedWorkQueue(i).orElse(null));
    // orElse if 'proceedWorkQueue' returns empty Optional
}

or rather simply using flatMap as:
private Optional<Notification> riseWorkQueueTask(IP ip) {
    return ip.getPreviousPeriods().stream()
            .filter(previousPeriod -> null != previousPeriod.getOldId())
            .findAny()
            .flatMap(i -> proceedWorkQueue(i));
}

A: ifPresent is a void method which is meant to process the ultimate value of the optional. But the error you're getting is due to the fact that you're passing a lambda that doesn't match the signature of the expected functional interface. It should be:
//the lambda must take 1 parameter, even if you don't use it
.ifPresent(period -> proceedWorkQueue(ip))

If you need to just run proceedWorkQueue(ip) if the optional has a value, you can either call map (kind of cheating):
return ip.getPreviousPeriods().stream()
        .filter(previousPeriod -> null != previousPeriod.getOldId())
        .findAny()
        .map(period ->{proceedWorkQueue(ip); return period;});

Or write it in a readable way by using an if block:
Optional<Notification> value = ip.getPreviousPeriods().stream()
        .filter(previousPeriod -> null != previousPeriod.getOldId())
        .findAny();

if(value.isPresent()) {
    proceedWorkQueue(ip);
}

return value;


text:
Q: Vaadin Grid ItemClickListener fails to register clicks on column with ImageRenderer I have the following code which is supposed to show a clickable icon which opens a popup dialog reading out a lengthy note.
        this.capacityCommentColumn = this.facilityGrid.addColumn(
                    p -> {
                        if (Strings.isNullOrEmpty(p.getCapacityComment())) {
                            return null;
                        } else {
                            return new ThemeResource("img/note.svg");
                        }
                    },
                    new ImageRenderer<>())
                    .setWidth(80)
                    .setCaption("Note");

        this.facilityGrid.addItemClickListener(new ItemClickListener<MapQueryService.RowResult>() {
            @Override
            public void itemClick(Grid.ItemClick<MapQueryService.RowResult> event) {
                if (event.getColumn() == capacityCommentColumn && !Strings.isNullOrEmpty(event.getItem().getCapacityComment())) {
                    final NoteWindow noteWindow = new NoteWindow();
                    noteWindow.txtDescription.setValue("test");
                    noteWindow.show();
                }
            }
        });

The problem is the code does not respond to clicks on the actual image, only on the outside.  You can see this below.  Any idea if its possible to make the image clickable?

A: You need to add a click listener to the Renderer as well. For example:
Grid<Integer> grid = new Grid();

private void addIconColumn() {
    ImageRenderer<Integer> renderer = new ImageRenderer<>();
    renderer.addClickListener(e -> iconClicked(e.getItem())); // allow clicks on the image

    Grid.Column<Integer, ThemeResource> iconColumn = grid.addColumn(i -> new ThemeResource("img/icon.svg"), renderer)
            .setCaption("Icon");

    grid.addItemClickListener(e -> { // allow clicks on the cell
        if (iconColumn.equals(e.getColumn())) {
            iconClicked(e.getItem());
        }
    });
}

private void iconClicked(Integer i) {
    ... your UI logic here ...
}

You can see a working example here: https://github.com/alejandro-du/community-answers/tree/master/click-image-in-grid


text:
Q: Dealing with OS pop up windows in Selenium I have a question regarding how to deal with an OS specific pop up window (in this case Windows) and if it is possible to access the elements in them for things such as photo uploads, document uploads, etc. So say if I have an "Add Photo" button and I click it, it will then lead me to a window like this..

So I am wondering if there is a way i can just do element.sendKeys(absolute path url) for the File Name.. Has anyone had success with something like this? Thanks!

A: Yes you are able to sendKeys() to the actual button for example:
WebElement button = driver.findElement(by.id("buttonId"));
button.sendKeys(pathToFile);