text:
Q: Listview setOnScrollListener scroll up down I have a ListView, I want to show/hide some content regarding the scroll event.
When it's scrolling down, I want to hide one layout (passing to gone) which is above the ListView. On scroll up, I want to show this layout. I wrote a working code, but I have a problem.
When I slowly scroll my ListView, I have a very bad result: my ListView jumps (but only when I do it slowly).
This is my source:
main_listview.setOnScrollListener(new AbsListView.OnScrollListener() {
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {

            if (mLastFirstVisibleItem > firstVisibleItem) {
                Log.e(getClass().toString(), "scrolling up");
                _title.setVisibility(View.VISIBLE);

            } else if (mLastFirstVisibleItem < firstVisibleItem) {
                Log.e(getClass().toString(), "scrolling down");

                MainActivity.azercell_title.setVisibility(View.GONE);
            }

            mLastFirstVisibleItem = firstVisibleItem;
            mLastVisibleItemCount = visibleItemCount;
        }

        public void onScrollStateChanged(AbsListView listView,
                int scrollState) {

        }
    });

How I can change my code to retrieve the same result (showing/hiding a content on scroll) but without getting some weird jumps?

A: try this :
listview.setOnScrollListener(new OnScrollListener() {

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                        int visibleItemCount, int totalItemCount) {

            if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
                    {
                        if(flag_loading == false)
                        {
                            flag_loading = true;

                        }
                    }
                }
            });

note : after setting the adapter for new pagination items set
flag_loading = true;


text:
Q: What is the difference between an online sorting algorithm and an external sorting algorithm? What is the difference between online sorting algorithm and external sorting algorithm ? Are they same or different?

A: An online sorting algorithm is one that will work if the elements to be sorted are provided one at a time with the understanding that the algorithm must keep the sequence sorted as more and more elements are added in. Algorithms that assume that the entire input will be given in advance, such as heapsort, will not work as online algorithms because they presume that they know all the elements in advance. On the other hand, an algorithm like insertion sort is online, since it purely works from the left to the right and doesn't need to see the entire array as it's working until it tries to process the very last element.
An external sorting algorithm is one where the goal is to sort data, typically provided in advance, that is so large that it cannot fit into main memory. While external sorting algorithms typically don't keep all the data to be sorted in memory at once, they usually assume that they can load any data that they need into memory at any time.
A good way of thinking about the difference is that in an online sorting algorithm, you should assume that you're trying to sort a sequence that is being generated dynamically - not all the data exists prior to the sort starting. In an external sorting algorithm, all the data already exists, but there's so much of it that you can't load everything into memory at once.
Hope this helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Geolocation in Chrome: re-prompt or return geolocation in a Google Maps web app i build a Google Maps Javascrip API web app. I used to init the map with geolocation. So it was asking the browser for permission and it worked fine.
Now my desktop Chrome simply doesn't support the geolocation in my app. I went to Properties to check the geolocation stuff, it was all right. I don't know the reason. Maybe due to the debug process or running a test on my desktop instead of my website (like an issue here).
So what might be the problem and how can I enable geolocation on my website again? Normally I'd like to have a button to prompt geolocation if the site was blocked.

A: Located the problem: something happened with HTTPS redirecting which caused geolocation not to work for it requires HTTPS connection. I fixed it in .htaccess and now it's working.


text:
Q: Async scope in Mule doesn't have copy of MuleMessage? I have following flow in my Mule app:
<flow name="UpdateStatusFlow">
        <vm:inbound-endpoint path="UpdateStatusFlow" exchange-pattern="request-response"/>
        <async processingStrategy="asynchronous">
            <request-reply>
                <vm:outbound-endpoint path="request"/>
                <vm:inbound-endpoint path="reply"/>
            </request-reply>
        </async>
        <custom-transformer class="com.example.EanTransformer"/>
</flow>

In async scope I depend on what has come to vm:inbound-endpoint and I assumed it is copy of that payload, so another copy is sent to EanTransformer which also modify payload. But it seems that no copy is made because in async flow I get already modified by EanTransformer ean code, which is not what I expected. If I add some delay in EanTransformer everything is fine, which means for me that this transformer haven't modify the message yet.
So the question is: if async scope really gets copy of the message (as it is written here: http://www.mulesoft.org/documentation/display/current/Async+Scope+Reference) or work on the same message as next components? Or am I doing something wrong?
I am using Mule 3.3.1.

A: If you read the referenced page further, it states that:

Even though the Async scope receives a copy of the Mule message, the payload is not copied. The same payload object(s) will be referenced by both Mule messages: the one that continues down the original flow and the one processed by the Async scope.
In other words, if the payload of your message is a mutable object
  (for example a bean with different fields in it) and a message
  processor in your async scope changes the value of one of the fields,
  the message processors outside of the Async scope will see the changed
  values.

A: The Async flow does not receive a Copy of the message - rather it receives the original payload. So any changes to the payload should be done before the Async flow. Here it is clearly written:

Even though the Async scope receives a copy of the Mule message, the payload is not copied. The same payload object(s) will be referenced by both Mule messages: the one that continues down the original flow and the one processed by the Async scope.
In other words, if the payload of your message is a mutable object (for example a bean with different fields in it) and a message processor in your async scope changes the value of one of the fields, the message processors outside of the Async scope will see the changed values.


text:
Q: Intermediatevalue-type Proposition for measures Let $(X_n)_{n\in\mathbb{N}}$ and $X$ be real valued random variables on a measure space with measure $\mu$ and let $X_n\rightarrow X$ $\mu$-almost surely. I was wondering if for every $\varepsilon >0$ there exists some $N\in\mathbb{N}$ such that
$$\mu(|X_n-X|>\varepsilon)<\varepsilon$$
Here is my proof for this little proposition and I am unsure if it is correct:
Let $A_n:=\{|X_n-X|>\varepsilon\}$ then because the convergence is almost surely we have
$\bigcap_{n\in\mathbb{N}}A_n\searrow N$ for some $\mu$-nullset $N$. By uppercontinuity of the measure it follows that $\lim_{n\to\infty}\mu(A_n)=\mu(N)=0$. In other words
$$\forall\varepsilon' >0\,\exists N\in\mathbb{N}\,\forall n\ge N\colon |\mu(A_n)-\mu(N)|<\varepsilon'\\
\Leftrightarrow |\mu(A_n)|<\varepsilon'$$
and in particular for $\varepsilon'=\varepsilon$.


text:
Q: "Not found: 'dart:js' export 'dart:js' show allowInterop, allowInteropCaptureThis" error when running tests In my Flutter app, I have a file called web.dart and inside it I have webSaveAs function which saves a file to my local machine in web.
@JS()
library main;

import 'package:js/js.dart';
import 'package:universal_html/html.dart';

/// Annotate `webSaveAs` to invoke JavaScript `window.webSaveAs`
@JS('webSaveAs')
external void webSaveAs(Blob blob, String fileName);

However, when I run any test (using flutter test command) which imports widgets where I have used webSaveAs function, I get the following error:
./../../../development/flutter/.pub-cache/hosted/pub.dartlang.org/js-0.6.3-nullsafety.3/lib/js.dart:8:1: Error: Not found: 'dart:js'
export 'dart:js' show allowInterop, allowInteropCaptureThis;
^

I am using js: ^0.6.2 from https://pub.dev/packages/js and here is the result from flutter doctor command.
╰>>> flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, 1.25.0-8.3.pre, on macOS 11.2.1 20D74 darwin-x64, locale en-SG)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.5)
[✓] IntelliJ IDEA Ultimate Edition (version 2019.3.1)
[✓] VS Code (version 1.53.2)
[✓] Connected device (1 available)

• No issues found!

Could someone help me figure this out? Thanks in advance!

A: Issue:
When you execute flutter test command, Flutter will compile the code in test files to native Dart and run inside a Dart VM where there is no Javascript support. Hence, it will not contain dart:js.

Solution:
You can create a dummy file (let's say web.test.dart) like below to mock the functions that use package:js or dart:js package methods.
web.test.dart
import 'package:universal_html/html.dart';

void webSaveAs(Blob blob, String fileName) {
  // You can remove the below line below and include your own implementation if you need
  throw UnimplementedError();
}

And then create a new file (let's say shared.dart) like below.
shared.dart
export 'web.dart' if (dart.library.io) 'web.test.dart';

When you need to use webSaveAs function, instead of importing web.dart file, you should import shared.dart.

Explanation:
dart.library.io is available in Dart VM and dart.library.js is available in web.
In web, if (dart.library.io) is false. Therefore, it will import web.dart which is what we want.
When running tests, if (dart.library.io) is true since the tests run in Dart VM. Hence, it will import web.test.dart which won't throw any errors since it does not import package:js or dart:js.

References:

*

*https://github.com/dart-lang/sdk/issues/36557

*https://medium.com/@dvargahali/dart-2-conditional-imports-update-16147a776aa8


text:
Q: How to send a Javascript Array and Form Input to PHP File (via $_GET for example)? Let's say I have a basic form like:
<form enctype="text/plain" id="form" action="results.php" method="get">
<input type="checkbox" name="options[]" value="option1">
<input type="checkbox" name="options[]" value="option2">
<input type="checkbox" name="options[]" value="option3">
</form>

and a Global Javascript Array "arr" in the same File and obviously want to send them both to the results.php via GET or POST in order to use them with some php functions. Is there a simple way to achieve this, using only basic Javascript, HTML and PHP? (Well JQuery aswell I guess)
Thanks for your input :)

A: A simple way is to encode the array using JSON, and then add it to the serialized form.
$.post("script.php", $("#form").serialize + '&arr=' + encodeURIComponent(JSON.stringify(arr)), function(response) {
    ...
});

In PHP you would then decode the JSON:
$arr = json_decode($_POST['arr']);


text:
Q: Embed the YouCamMakeup camera functionality I want to embed the YouCamMakeup camera functionality. In this app when i click on camera it detect the real time my face, eye brows and lips and give the option to change eye brows and lips color on live camera. I want to embed this functionality in my app, how i achieve this functionality or tell me any FaceSDK which provide me this functionality.
Here is the screen shot off real time makeover of this app.

A: You have all you need on the apple dev website : https://developer.apple.com/library/ios/documentation/GraphicsImaging/Conceptual/CoreImaging/ci_detect_faces/ci_detect_faces.html
    CIContext *context = [CIContext contextWithOptions:nil];                    // 1
    NSDictionary *opts = @{ CIDetectorAccuracy : CIDetectorAccuracyHigh };      // 2
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeFace
                                              context:context
                                              options:opts];                    // 3

    opts = @{ CIDetectorImageOrientation :
              [[myImage properties] valueForKey:kCGImagePropertyOrientation] }; // 4
    NSArray *features = [detector featuresInImage:myImage options:opts];

for (CIFaceFeature *f in features)
{
    NSLog(NSStringFromRect(f.bounds));

    if (f.hasLeftEyePosition)
        NSLog("Left eye %g %g", f.leftEyePosition.x. f.leftEyePosition.y);

    if (f.hasRightEyePosition)
        NSLog("Right eye %g %g", f.rightEyePosition.x. f.rightEyePosition.y);

    if (f.hasmouthPosition)
        NSLog("Mouth %g %g", f.mouthPosition.x. f.mouthPosition.y);
}

And you can try this framework : https://github.com/kairosinc/Kairos-SDK-iOS
For Android you can try this : http://developer.android.com/reference/android/media/FaceDetector.Face.html (also the official dev android website ..)
You must do your research, we're not here to give you all you need when you need it.
Your question is tagged wth androuid AND iOS, next time be more specific please

A: Use msqrd for face tracking and detection. it is very reliable because Facebook purchases it means something interesting is in it..
click here to go the link


text:
Q: Android Auto application development I want to develop an android auto app.
I have installed android auto apk on my lollipop device and started desktop unit but on mobile screen after some steps and connecting the app to desktop head unit... only android auto is displaying on android device and desktop head unit on desktop showing waiting for phone.
How can I proceed to understand the prospect of desktop head unit android auto apk.
Steps I used while connecting

*

*adb forward tcp:5277 tcp:5277

*./desktop-head-unit

A: There's a missing step in the Android docs.
After enabling dev mode within Android Auto app, in the options menu in the top right corner (the same menu where you can turn on the head unit server), there's another option for "Developer Settings". Go there and then select "Application Mode" > Developer. This allowed ADB to successfully connect to my device by running adb forward tcp:5277 tcp:5277 and then executing ./desktop-head-unit (on mac osx)

A: A colleague of mine had the same thing.
When starting Android Auto Desktop Head Unit on his Windows 10 machine it kept saying "Waiting for Phone", even though the port forwarding seemed fine.
Tried multiple phones and ports, all working fine when connected to my own machine (similar setup).
Right clicking the Desktop Head Unit .exe and then choosing "Open as Administrator" eventually did the trick for us.

A: I ran into the "Waiting for phone..." issue on a couple different devices. Here are the steps that worked for me. I am using DHU release 2.0.0 rc2.

*

*Open Android Auto app on your device.

*Get app in developer mode.

*Start head unit server

*Open the drawer menu in the app and tap "Exit
App" <--- important for successful connection

*Run adb forward tcp:5277 tcp:5277

*Start DHU You should see the permissions screen on the mobile device now.

This behavior is seen due to issue in Android Auto App: https://issuetracker.google.com/issues/171130740

A: I faced the same issue. You can try to change the port and again follow the steps like this:
Go to platform-tools directory and type : adb forward tcp:5999 tcp:5999
Use some different port number instead of 5277 like I used 5999. Once done go to auto directory and run desktop-head-unit.exe
Also, make sure your phone is unlocked while doing this.
It should work fine hopefully!

A: When you use DHU on the Phone for the first time, the initial settings of the Android Auto app are required on the Phone, and the Android Auto app is automatically launched.
At that time, sometimes the Android Auto app is running in the background. Therefore, you need to bring up the Android Auto app from the task on the Phone and continue the setting. For example, swipe the Phone screen from bottom to top and select the Android Auto app from the task list to continue the initial setup.

A: For me, I had to explicitly tell DHU to use port 5277 even it's default.
desktop-head-unit.exe --adb=5277


text:
Q: Can someone explain function names in Objective-C?
Possible Duplicate:
Method Syntax in Objective C

So I totally get the more common functions like:
-(void)viewDidUnload{

    self.controllers = nil;
    [super viewDidUnload];
}

However coming from a different programming background, I sometimes struggle with something like:
-(NSInteger) tableView: (UITableView *)tableView
numberOfRowsInSection:(NSInteger)section{

    return [self.controllers count];

}

So I know the function returns a NSInteger. However I do get a little confused in how to mentally organize the rest of the function name ETC. I need to be able to visualize some structure. Like in this case is the function name numberOfRowsInSection with the parameter called section?
Help in this matter would be appreciated.

A: You can think of it like other programming languages by looking at
[object action:var withFoo:baz]

as
object."action:withFoo:"(var, baz)

Everything before colons is part of the method name, and everything after is arguments, so the name of the method is interleaved with the arguments passed to the method.

A: Yes, the way that Objective-C mixes arguments with parts of the method name seems weird at first. Everyone goes through a short adjustment period in this respect. But give it time -- after a little while, you may not want to ever see a comma-separated, parenthesized list of nameless parameters ever again.
In C++, you'd say something like:
Color *color = new Color(0.5, 0.7, 0.2, 0.8);

You know what those values mean, right? There's four of them, so obviously the parameters are in red, green, blue, alpha order. Or was it alpha, red, green, blue? Of course, it could also be hue, saturation, value, alpha... well, it doesn't really matter because you can always just look it up.
In Objective-C, you say:
UIColor *color = [[UIColor alloc] initWithRed:0.5 green:0.7 blue:0.2 alpha:0.8];

Isn't that better? You'll definitely still need to consult the documentation from time to time to remind yourself exactly what a method does, or what methods a class makes available. But you won't often find yourself consulting the docs just to figure out which parameter goes where.

A: Objective C has a descriptive way of writing methods..
-(NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection:(NSInteger)section{}

It is a methods tableView, returning an NSInteger , takes two argument - a UITableView reference and an integer section. Now consider numberofRowsInSection as a  description of what the argument is all about.Look at this example
-(NSInteger) calculateSum:(NSInteger)operand1 secondOperand:(NSInteger)operand2 andThirdOperand:(NSInteger)operand3{}

and I can call this methods as
[self calculateSum:var1 secondOperand:var2 andThirdOperand:var3];
Here "secondOperand" and "andThirdOperand" are not essential, I can write the above method as
-(NSInteger) calculateSum:(NSInteger)operand1 :(NSInteger)operand2 :(NSInteger)operand3{}

and call this method as
[self calculateSum:var1 :var2 :var3];

But first one is easy to read, if you tell what each variable is ..Hope this helps
Also see I used the word method instead of functions which is normally the objective c way..

A: (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
This is a method that accepts 2 arguments, a UITableView and an NSInteger. It's notated like this: -tableView:numberOfRowsInSection:.

A: Yep that's basically it.  In obj-C the full method names include the arg names.  I believe that convention originated from Smalltalk.


text:
Q: Query in Rails not returning any records This is an extension of my previous question (using a select, assign variable and retrieve records).
I resolved the problem with passing the correct value to the controller, but my query still does NOT return any records, yet there ARE matching records in my database.
NEW edited controller for the app...
# GET /bentries/january
def monthlysumm
   @bentries = Bentry.by_month(params[:billDate])
end

AND here is the addition to the model...
def self.by_month(mon)
   where("strftime('%m', billDate) + 0 = ?", mon)
end

This generates a SQL statement like this...
SELECT "bentries".* FROM "bentries" WHERE (strftime('%m", billDate) + 0 = '2')

If I go into SQLite Manager in Firefox and type (the equivalent) SQL statement of...
SELECT * FROM bentries WHERE (strftime('%m', billDate) + 0 = 2)

It returns the expected 3 records from the "bentries" table, but yet the code in app generates NO resulting recordset.
Can anyone see where I have gone wrong in the controller or model?!?

A: Your queries are not the same.
The one generated is looking for a string, the one you are typing in is looking for an integer.
Parameters come into the controller as strings so you need to make it an integer if necessary.  For example:
def self.by_month(mon)
   where("strftime('%m', billDate) + 0 = ?", mon.to_i)
end

Or you can do it in the call to by_month, depending on whether you want the month in your by_month method to be an integer or a string.


text:
Q: Why is Google Chrome websocket sending me smiley faces, not a mirror? I'm testing pings and pongs in my websocket application. I pinged a websocket client in Chrome.
Google Chrome sent me back smiley faces. The data was: ☺☻♥´┐¢´┐¢´┐¢
In Scala, here is how I am generating the byte array:
val byteData = (new String(Array[Byte](1,2,3,-1,-2,-127).map(_.toChar))).toCharArray.map(_.toByte)

Can anyone confirm is this really the data that Google needs to be sending back? Does Google Chrome not mirror the bytes I send to it?
Thanks

A: Looks like you are getting the same thing back, and this is just an artifact of how you are printing out the binary data that you receive. It looks like your encoding/font is similar to this:
http://usefulshortcuts.com/alt-codes/bullet-alt-codes.php


text: Q: Calendar reminder not working for onePlus Device I am using cordova plugin "cordova-plugin-calendar" to add reminder events to the calendar from my cordova application. For all other device it is working as expected. In OnePlus device the event is getting added first then if we refresh the calendar or check the calendar in some time, the event is getting disappeared. I don't know why it is happening only in OnePlus device. Have any of you faced this kind of issue?.Any help in sorting out this issue would be much appreciated. Thanks!!


text:
Q: Multiple query results I am currently running a query in MS Access where i am searching for matching fields, the only problem is is that it is returning  multiple fields which are all identical, is there anyway of limiting the results if the are identical?

A: What you need is DISTINCT.
Try something like this.
SELECT DISTINCT
  table.*
FROM table


text:
Q: How to write values in csv based on quotation mark and ignore commas inside the quotation? I would like to write some items of a list in a csv, the items are within quotation marks and have commas in between. How can I write them so that the items are not separated due to commas? I looked at many questions that are similar but did not find particular solution to my problem.
['Saks, Lord & Taylor data breach may affect 5 million customers', (u'By Mike Murphy', u'April 1, 2018, 5:24 p.m. EST')]
['Why The China Hustle is a finance documentary all U.S. investors need to see', (u'By MarketWatch', u'NewsWatch')]
['Trump says no deal for Dreamers, again threatens to end Nafta in Easter tweets', (u'By Mike Murphy', u'April 1, 2018, 4:49 p.m. EST')]

Expected answer:
first column = 'Saks, Lord & Taylor data breach may affect 5 million customers'
                'Why The China Hustle is a finance documentary all U.S. investors need to see'
                'Trump says no deal for Dreamers, again threatens to end Nafta in Easter tweets'

second column = 'By Mike Murphy'
                'By MarketWatch'
                'By Mike Murphy'

third column =  'April 1, 2018, 5:24 p.m. EST'
                'NewsWatch'
                'April 1, 2018, 4:49 p.m. EST'

A: It's as simple as:
x=[['Saks, Lord & Taylor data breach may affect 5 million customers', (u'By                                                      Mike Murphy', u'April 1, 2018, 5:24 p.m. EST')],['Why The China Hustle is a finance documentary all U.S. investors need to see', (u'By MarketWatch', u'NewsWatch')],['Trump says no deal for Dreamers, again threatens to end Nafta in Easter tweets', (u'By Mike Murphy', u'April 1, 2018, 4:49 p.m. EST')]]
import csv
with open('bla.csv','w') as fd:
    writer=csv.writer(open('bla.csv','w'))
    writer.writerows(x)

Note "Why The China ..." is not quoted in the csv as it does not contain any commas. If you want it quoted you can use quoting=QUOTE_ALL in the writer constructor.

A: How about this?
next_field<-function(stream) {
  p<-seek(stream)
  d<-readChar(stream,1)
  seek(stream,p)
  if(d=="\"")
    field<-scan(stream,"",1,sep=",",quote="\"",blank=FALSE)
  else
    field<-scan(stream,"",1,sep=",",quote="",blank=FALSE)
  return(field)
}

s<-file("C:/your_path_here/sample.csv",open="rt")
header<-readLines(s,1)
header<-scan(what="",text=header,sep=",")
line<-replicate(length(header),next_field(s))

setNames(as.data.frame(lapply(line,type.convert)),header)


text:
Q: Is the free product of residually finite groups always residually finite? Suppose groups $G$ and $H$ are residually finite. Does that imply, that $G \ast H$ is residually finite?
What have I tried to prove this:
Suppose, $a = g_1h_1g_2h_2…g_nh_n \in G \ast H$, $g_1, .. g_n \in G$, $h_1, … , h_n \in H$ and $b = g_1g_2…g_n \neq e$, then the natural homomorphism $\alpha: G \ast H \to \frac{G \ast H}{\langle \langle H \rangle \rangle} \cong G$ maps $a$ to $b$. Now suppose, that $\beta$ is the homomorphism from $G$ to a finite group $K$, such that $\beta(b)$ is non-trivial (such homomorphism exists as $G$ is residually finite). Then $\beta \alpha$ is the homomorphism that maps $a$ to a non-trivial element of a finite group.
The same arguments can be applied in case, when $h_1h_2 …  h_n \neq e$. However, I do not know, what to do in case, when $g_1g_2…g_n = h_1h_2 …  h_n = e$.

A: Yes. This reduces to the case of a free product of finite groups, which is free-by-finite, and therefore residually finite.
To see this, take your alternating product $a = g_1 h_1 \cdots g_n h_n\neq 1$ in $G\ast H$, and choose normal subgroups $N$ and $K$, of finite index in $G$ and $H$, respectively, such that $a_1 , a_2 ,\ldots , a_n\not\in N$ and $b_1, b_2, \ldots, b_n \not\in K$. (This can be done since, by definition, there are normal subgroups of $G$ excluding each of the $a_i$, and then their intersection excludes all of them and still has finite index in $G$.  Likewise for the $b_i$ in $H$.)  Then the natural homomorphisms $G\to \overline{G} = G/N$ and $H\to\overline{H}=H/K$ extend to a homomorphism $\phi : G\ast H \to \overline{G}\ast\overline{H}$ for which $\overline{a} = \phi(a)\neq 1$.  (Indeed, $\overline{a} = \overline{g_1}\overline{h_1}\cdots\overline{g_n}\overline{h_n}$ is a reduced alternating product in $\overline{G}\ast\overline{H}$ as all of the $\overline{a_i}$ and $\overline{b_j}$ are non-trivial in their respective finite factors.)  Since $\overline{G}\ast\overline{H}$ is a free product of the finite groups $\overline{G}$ and $\overline{H}$, it is free-by-finite, so it is residually finite.  Hence, there is a homomorphism $\psi : \overline{G}\ast\overline{H} \to Q$, where $Q$ is finite, such that $\psi(\overline{a})\neq 1$.  Then $\psi(\phi(a))\neq 1$, and $\psi\circ\phi$ is a homomorphism from $G\ast H$ to the finite group $Q$ for which $(\psi\circ\phi)(a)\neq 1$.
(There is a tiny corner case to tidy up, where $a\in G\cup H$ but, as $G$ and $H$ are each homomorphic images of $G\ast H$, this is easy to handle.)


text:
Q: Apache commons-exec not able to run a mysql script file on command line I am trying to run a mysql command from java that takes input from an sql script file using apache commons-exec as shown below
    filepath = /path/to/file.sql
    CommandLine commandLine = new CommandLine("mysql -uuser -ppassword dbname");
    commandLine.addArgument("<");
    commandLine.addArgument(filepath);
    Executor executor = new DefaultExecutor();
    executor.execute(commandLine);

But I keep getting the following error

[junit] java.io.IOException: Cannot run program "mysql -uuser
  -ppassword  dbname" (in directory "."): error=2, No such file or directory

When I run on the terminal,
the command executes normally and db gets modified. Why is this happening ?

A: Try CmdTool library.
    String filepath ="/path/to/file.sql";
    List<String> commandLine = new ArrayList<>(Arrays.asList("mysql", "-uuser", "-ppassword", "dbname"));
    commandLine.add("<");
    commandLine.add(filepath);
    new Cmd().command(commandLine).execute();

Or simpler
new Cmd().command("mysql", "-uuser", "-ppassword", "dbname", "<", filepath).execute();

You can find more examples here.


text:
Q: Why basic bootstrap collapse button doesnt work for me? I am struggling with some basic. I linked bootstrap and jQuery cdn to my project and I try to create a collapse button which doesn't work for me.
Basic html page:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

          Link with href

        <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
          Button with data-target
        </button>

            Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

What can go wrong here?

A: Whenever you are migrating to a new version of a framework like Bootstrap it's always important to review their migration documentation.  In your case the issue is your use of data-*.  In Bootstrap 5.x they updated all of their data attributes to data-bs-* to avoid conflicts.
If we modify your code to adopt the updated data attribute declarations your collapse functions as expected.

Link with href
<button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">Button with data-bs-target</button>

    Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

Also, note that you don't actually need to include jQuery in Bootstrap 5.x as they have shifted from using the jQuery framework for their plugins to using native JavaScript.


text:
Q: Directives are overwriting each other I have two directives, one checks the size of the file, while the other one ensures that the user is uploading a valid file format. They are both assigned to a input=file element, and seperate they work, but together, the validFileSize directive seems to cause the selectNgValidationFiles to not work.
//view

<input type="file" name="uploadedDocs" id="uploadedDocs" data-ng-model="fileStore.file" select-ng-validation-files valid-file-size multiple>

//controller

function validFileSize($parse){

    return {
        require: 'ngModel',
        restrict: 'A',
        link: function(scope, el, attrs, ngModel) {

            var model = $parse(attrs.ngModel);
            var modelSetter = model.assign;
            var maxSize = 2000; //2000 B
            el.bind('change', function() {

                scope.$apply(function() {
                    scope.fileStore.maxSizeError = false;
                    if (el[0].files.length > 1) {
                        modelSetter(scope, el[0].files);
                    } else {
                        modelSetter(scope, el[0].files[0]);
                    }

                    if(el[0].files.length > 0) {
                        var fileSize = el[0].files[0].size;
                        if (fileSize === 0) {
                           scope.fileStore.maxSizeError = true;
                        }
                    }

                });
            });
        }

    }
}

function selectNgValidationFiles() { //if files to be uploaded vary in future, add condition to check type or create new directive
    return {
        require: "ngModel",
        link: function postLink(scope,elem,attrs,ngModel) {
            var validFormats = ['pdf', 'PDF', 'doc', 'DOC', 'docx', 'DOCX', 'jpg', 'JPG', 'jpeg', 'JPEG','png', 'PNG', 'gif', 'GIF', 'pptx', 'PPTX', 'csv', 'CSV', 'xlsx', 'XLSX', 'zip', 'ZIP'];
            elem.bind('change', function () {
                validFile(false);
                scope.$apply(function () {
                    ngModel.$render();
                });
            });
            ngModel.$render = function () {
                console.log('elem : ',elem)
                ngModel.$setViewValue(elem[0].files[0]);
            };
            function validFile(bool) {
                ngModel.$setValidity('pdfIncorrect', bool);
            }
            ngModel.$parsers.push(function(value) {
                var ext = value.name.substr(value.name.lastIndexOf('.')+1);
                if(ext=='') return;
                if(validFormats.indexOf(ext) == -1){
                    console.log('not valid format')
                    return value;
                }
                validFile(true);
                return value;
            });
        }
    }
};

question
What is causing my directives to break one another? I assume one is overwriting the other somehow but I can't work out how to fix it.

A: Could you not merge them into one directive or one service function?
Check file format first, if ok then proceed with file size check.
It's probably because you are now calling the $scope apply function twice (one in each directive), which generally does not work well.


text:
Q: How to give deadline to okio via okHttp From looking at okHttp source code, when call.execute() is called the body being transferred from server to the client.
It doesn't make sense because it makes impossible to set deadline to okio which means i cannot give timeout to the whole request but only readTimeout and connectTimeout which have effect only until the first byte is ready for read.
Am i missing something here?

A: There's no way to give a deadline to the entire request. You should open a feature request on this! OkHttp's use of Okio is one of it's differentiating features, and exposing more Okio functionality through OkHttp's API is a great way to put more power in OkHttp's users.

A: This is on the schedule for the next version of okhttp (https://github.com/square/okhttp/issues/2840), but for now we successfully implemented a deadline for both the request and response body reading by subclassing Call in our application in production:
package com.pushd.util;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http2.StreamResetException;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;

/**
 * An okhttp3.Call with a deadline timeout from the start of isExecuted until ResponseBody.source() is closed or unused.
 */
public class DeadlineCall implements Call {
    private final static Logger LOGGER = Logger.getLogger(DeadlineCall.class.getName());

    private static AtomicInteger sFutures = new AtomicInteger();
    private static final ScheduledExecutorService sHTTPCancelExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "DeadlineCallCancel");
            t.setDaemon(true);
            t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    });

    private final Call mUnderlying;
    private final int mDeadlineTimeout;
    private volatile ScheduledFuture mDeadline;
    private volatile boolean mDeadlineHit;
    private volatile boolean mCancelled;
    private volatile BufferedSource mBodySource;

    DeadlineCall(Call underlying, int deadlineTimeout) {
        mUnderlying = underlying;
        mDeadlineTimeout = deadlineTimeout;
    }

    /**
     * Factory wrapper for OkHttpClient.newCall(request) to create a new DeadlineCall scheduled to cancel its underlying Call after the deadline.
     * @param client
     * @param request
     * @param deadlineTimeout in ms
     * @return Call
     */
    public static DeadlineCall newDeadlineCall(@NonNull OkHttpClient client, @NonNull Request request, int deadlineTimeout) {
        final Call underlying = client.newCall(request);
        return new DeadlineCall(underlying, deadlineTimeout);
    }

    /**
     * Shuts down thread that cancels calls when their deadline is hit.
     */
    public static void shutdownNow() {
        sHTTPCancelExecutorService.shutdownNow();
    }

    @Override
    public Request request() {
        return mUnderlying.request();
    }

    /**
     * Response MUST be closed to clean up deadline even if body is not read, e.g. on !isSuccessful
     * @return
     * @throws IOException
     */
    @Override
    public Response execute() throws IOException {
        startDeadline();

        try {
            return wrapResponse(mUnderlying.execute());
        } catch (IOException e) {
            cancelDeadline();
            throw wrapIfDeadline(e);
        }
    }

    /**
     * Deadline is removed when onResponse returns unless response.body().source() or a method using
     * it is called synchronously from onResponse to indicate caller's committment to close it themselves.
     * This includes peekBody so prefer DeadlineResponseBody.peek unless you explicitly close after peekBody.
     * @param responseCallback
     */
    @Override
    public void enqueue(final Callback responseCallback) {
        startDeadline();

        mUnderlying.enqueue(new Callback() {
            @Override
            public void onFailure(Call underlying, IOException e) {
                cancelDeadline(); // there is no body to read so no need for deadline anymore
                responseCallback.onFailure(DeadlineCall.this, wrapIfDeadline(e));
            }

            @Override
            public void onResponse(Call underlying, Response response) throws IOException {
                try {
                    responseCallback.onResponse(DeadlineCall.this, wrapResponse(response));
                    if (mBodySource == null) {
                        cancelDeadline(); // remove deadline if body was never opened
                    }
                } catch (IOException e) {
                    cancelDeadline();
                    throw wrapIfDeadline(e);
                }
            }
        });
    }

    private IOException wrapIfDeadline(IOException e) {
        if (mDeadlineHit && isCancellationException(e)) {
            return new DeadlineException(e);
        }

        return e;
    }

    public class DeadlineException extends IOException {
        public DeadlineException(Throwable cause) {
            super(cause);
        }
    }

    /**
     * Wraps response to cancelDeadline when response closed and throw correct DeadlineException when deadline happens during response reading.
     * @param response
     * @return
     */
    private Response wrapResponse(final Response response) {
        return response.newBuilder().body(new DeadlineResponseBody(response)).build();
    }

    public class DeadlineResponseBody extends ResponseBody {
        private final Response mResponse;

        DeadlineResponseBody(final Response response) {
            mResponse = response;
        }

        @Override
        public MediaType contentType() {
            return mResponse.body().contentType();
        }

        @Override
        public long contentLength() {
            return mResponse.body().contentLength();
        }

        /**
         * @return the body source indicating it will be closed later by the caller to cancel the deadline
         */
        @Override
        public BufferedSource source() {
            if (mBodySource == null) {
                mBodySource = Okio.buffer(new ForwardingSource(mResponse.body().source()) {
                    @Override
                    public long read(Buffer sink, long byteCount) throws IOException {
                        try {
                            return super.read(sink, byteCount);
                        } catch (IOException e) {
                            throw wrapIfDeadline(e);
                        }
                    }

                    @Override
                    public void close() throws IOException {
                        cancelDeadline();
                        super.close();
                    }
                });
            }

            return mBodySource;
        }

        /**
         * @return the body source without indicating it will be closed later by caller, e.g. to peekBody on unsucessful requests
         */
        public BufferedSource peekSource() {
            return mResponse.body().source();
        }

        /**
         * Copy of https://square.github.io/okhttp/3.x/okhttp/okhttp3/Response.html#peekBody-long- that uses peekSource() since Response class is final
         * @param byteCount
         * @return
         * @throws IOException
         */
        public ResponseBody peek(long byteCount) throws IOException {
            BufferedSource source = peekSource();
            source.request(byteCount);
            Buffer copy = source.buffer().clone();

            // There may be more than byteCount bytes in source.buffer(). If there is, return a prefix.
            Buffer result;
            if (copy.size() > byteCount) {
                result = new Buffer();
                result.write(copy, byteCount);
                copy.clear();
            } else {
                result = copy;
            }

            return ResponseBody.create(mResponse.body().contentType(), result.size(), result);
        }
    }

    private void startDeadline() {
        mDeadline = sHTTPCancelExecutorService.schedule(new Runnable() {
            @Override
            public void run() {
                mDeadlineHit = true;
                mUnderlying.cancel(); // calls onFailure or causes body read to throw
                LOGGER.fine("Deadline hit for " + request()); // should trigger a subsequent wrapIfDeadline but if we see this log line without that it means     the caller orphaned us without closing
            }
        }, mDeadlineTimeout, TimeUnit.MILLISECONDS);

        LOGGER.fine("started deadline for " + request());

        if (sFutures.incrementAndGet() == 1000) {
            LOGGER.warning("1000 pending DeadlineCalls, may be leaking due to not calling close()");
        }
    }

    private void cancelDeadline() {
        if (mDeadline != null) {
            mDeadline.cancel(false);
            mDeadline = null;
            sFutures.decrementAndGet();
            LOGGER.fine("canceled deadline for " + request());
        } else {
            LOGGER.info("deadline already canceled for " + request());
        }
    }

    @Override
    public void cancel() {
        mCancelled = true;

        // should trigger onFailure or raise from execute or responseCallback.onResponse which will cancelDeadline
        mUnderlying.cancel();
    }

    @Override
    public boolean isExecuted() {
        return mUnderlying.isExecuted();
    }

    @Override
    public boolean isCanceled() {
        return mCancelled;
    }

    @Override
    public Call clone() {
        return new DeadlineCall(mUnderlying.clone(), mDeadlineTimeout);
    }

    private static boolean isCancellationException(IOException e) {
        // okhttp cancel from HTTP/2 calls
        if (e instanceof StreamResetException) {
            switch (((StreamResetException) e).errorCode) {
                case CANCEL:
                    return true;
            }
        }

        // https://android.googlesource.com/platform/external/okhttp/+/master/okhttp/src/main/java/com/squareup/okhttp/Call.java#281
        if (e instanceof IOException &&
                e.getMessage() != null && e.getMessage().equals("Canceled")) {
            return true;
        }

        return false;
    }
}

Note that we also have a separate interceptor to timeout DNS since even our deadline doesn't cover that:
/**
 * Based on http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java/31643186#31643186
 * as per https://github.com/square/okhttp/issues/95
 */
private static class DNSTimeoutInterceptor implements Interceptor {
    long mTimeoutMillis;

    public DNSTimeoutInterceptor(long timeoutMillis) {
        mTimeoutMillis = timeoutMillis;
    }

    @Override
    public Response intercept(final Chain chain) throws IOException {
        Request request = chain.request();
        Log.SplitTimer timer = (request.tag() instanceof RequestTag ? ((RequestTag) request.tag()).getTimer() : null);

        // underlying call should timeout after 2 tries of 5s:  https://android.googlesource.com/platform/bionic/+/android-5.1.1_r38/libc/dns/include/resolv_private.h#137
        // could use our own Dns implementation that falls back to public DNS servers:  https://garage.easytaxi.com/tag/dns-android-okhttp/
        if (!DNSResolver.isDNSReachable(request.url().host(), mTimeoutMillis)) {
            throw new UnknownHostException("DNS timeout");
        }
        return chain.proceed(request);
    }

    private static class DNSResolver implements Runnable {
        private String mDomain;
        private InetAddress mAddress;

        public static boolean isDNSReachable(String domain, long timeoutMillis) {
            try {
                DNSResolver dnsRes = new DNSResolver(domain);

                Thread t = new Thread(dnsRes, "DNSResolver");
                t.start();
                t.join(timeoutMillis);
                return dnsRes.get() != null;
            }  catch(Exception e)  {
                return false;
            }
        }

        public DNSResolver(String domain) {
            this.mDomain = domain;
        }

        public void run() {
            try {
                InetAddress addr = InetAddress.getByName(mDomain);
                set(addr);
            } catch (UnknownHostException e) {
            }
        }

        public synchronized void set(InetAddress inetAddr) {
            this.mAddress = inetAddr;
        }
        public synchronized InetAddress get() {
            return mAddress;
        }
    }
}


text:
Q: How to syntactically ignore a part of an expression in an Antlr BNF? I would like to use Antlr to parse SQL table DDL statements. But I need only the column identifiers and column types. I do not care about any constraints and I would like to avoid to write the whole syntax especially for CHECK constraints, because it seems to me that this is almost everything of SQL.
This is an example for a constraint:
 CREATE TABLE "T" (
   "A" CHAR (1) CHECK ( "A" IN ('N', 'Y')),
   "B" CHAR (1) CHECK ( "B" IN ('N', 'Y'))
 );

And this is the part of the BNF, which is modeled after Jonathan Leffler's hyperlinked SQL BNF:
column_definition
    : ID data_type column_constraint_definition*
    ;

column_constraint_definition
    : constraint_name_definition? column_constraint constraint_characteristics?
    ;

constraint_name_definition
    : CONSTRAINT ID
    ;

column_constraint
    : NOT NULL
    | UNIQUE | PRIMARY KEY
    | references_specification
    | check_constraint_definition
    ;

references_specification
    : REFERENCES ID ( '(' ID ( ',' ID )? )?
    ;

check_constraint_definition
    : CHECK '(' boolean_value_expression ')'
    ;

My problem is how to ignore any boolean value expression without specifying its content in detail?
I would like to ignore everything between the left and right parenthesis. But there are nested parenthesis allowed. So I can not ignore everything up to the closing parenthesis. Instead I have to count the opening and closing parenthesis. How can this be expressed in the Antlr (4) BNF?

A: I would think something like this would work.
check_constraint_definition
    : CHECK '(' boolean_value_expression ')'
    ;
boolean_value_expression
    : (~')')+
    | '(' boolean_value_expression ')'
    ;


text:
Q: Using Java 7 u21 in compile and Java 7 u13 in Run-time We have a build server that has Java 7 update 21 version, for the run time environment we have configured Java 7 update 13. What are all the problems will I face by having this setup?

A: You will face confusion as to what differences it will make when it will make almost no difference what so ever.
If you want to be paranoid, I suggest you look at the list of bug that have been fixed since Java 7 update 13 and update 25 and this will give you an idea of what bugs might impact you.


text:
Q: MongoDB Aggregate Query Group By And Count I have a subscribers collection:
 {id: ObjectId ('52dskf45f10dsd4775'), agencyCode: '4579520',
        listOfSubscriptions: [
        {name: 'william', CreatedAt: ISODate ('2019-01-02'), subscriptionType: 'smartphones'},
        {name: 'marianna', CreatedAt: ISODate ('2019-02-02'), subscriptionType: 'smartphones'},
        {name: 'Freewind', CreatedAt: ISODate ('2019-04-02'), subscriptionType: 'smartphones'}
       ]
 }

The agencys collection contains the following data:
{agencyCode: '4579520', BU: 'finances', company: ObjectId (' 445700500b24dsjdfm ')}
{agencyCode: '45007', BU: 'finances', company: ObjectId (' 445700500b24dsjdfm ')}

Collection subscriptionsType:
 {id:ObjectId ('5lkf81gf45005drkj') ,nameSubscription: 'intense',SubscriptionType: 'smartphones' }
 {id:ObjectId ('eb4512ezope780') ,nameSubscription: 'other',SubscriptionType: 'other' }

I want to do a cont on the subscribers by type of subscription.
Here is my request mongodb:
 subscribers.aggregate(
    [
    {
        $lookup: {
          from: "agencys",
          localField: "agencyCode",
          foreignField: "agencyCode",
          as: "data_agency"
        }
      },
      { $unwind: "$data_agency" },
      { $unwind: "$listOfSubscriptions" },
      {
        $match: {
          $and: [
            { $agencyCode: '4579520' },
            { "data_agency.BU": 'finances' },
            { "data_agency.company": mongoose.Types.ObjectId('445700500b24dsjdfm') },

          ]
        }
      },
      {
        $group: {
          "_id": "$listOfSubscriptions.subscriptionType",
          countLines: { $sum: 1 },
        }
      },
]

result of my request:
 {
    "_id": "smartphones",
     "countLines": 3
  }

the result of my request does not display the rest of the subscription type.
I want to display all subscription types like this for the agency '4579520':
{
    "_id": "smartphones",
     "countLines": 3
  },
{
    "_id": "other",
     "countLines": 0
  }

Thanks,


text:
Q: Android. Weird behavior when deleting a column in room (Foreign key) I have an android note pet project with room database where I store files and related pages to the file. One to many relationship:
@Entity(tableName = NotepadDatabase.FILES_TABLE)
data class RoomNoteFile(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    @ColumnInfo(name = "file_name") val name: String,
    @ColumnInfo(name = "number_of_pages") val pagesAmount: Int,
)

@Entity(
    tableName = NotepadDatabase.PAGES_TABLE,
    foreignKeys = [ForeignKey(
        entity = RoomNoteFile::class,
        parentColumns = arrayOf("id"),
        childColumns = arrayOf("related_file"),
        onDelete = ForeignKey.CASCADE
    )]
)
data class RoomNotePage(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    @ColumnInfo(name = "page_text") val text: String,
    @ColumnInfo(name = "page_number") val pageNum: Int,
    @ColumnInfo(name = "related_file", index = true) val fileId: Int,
)

So I noticed that if I delete a file, instead of deleting the file's pages with it (as i expect it to work). Room changes the ids (related_file id) of all the pages of this file and gives them the id of the next file in database, then all the pages shift and the last file's pages get deleted. I can't imagine what might cause that.

A: From the supplied code, there is not an issue. So your issue is within other than the supplied code. You may wish to edit your question. However, you should certainly investigate the other code. Perhaps consider the following code to get some ideas that could help you pinpoint the issue(s)
As an example consider the following test/demo that uses the code you have supplied plus:-
NotePadDatabaseDao (i.e. Dao's for inserting, deleting and extracting):-
@Dao
interface NotepadDatabaseDao {
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(noteFile: RoomNoteFile): Long
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(notePage: RoomNotePage): Long

    @Delete
    fun delete(noteFile: RoomNoteFile): Int
    @Delete
    fun delete(notePage: RoomNotePage): Int

    @Query("SELECT * FROM ${NotepadDatabase.FILES_TABLE}")
    fun getAllFiles(): List<RoomNoteFile>
    @Query("SELECT * FROM ${NotepadDatabase.PAGES_TABLE} WHERE related_file=:fileId")
    fun getPagesForAFileId(fileId: Int): List<RoomNotePage>
}

NotePadDatabase a pretty stock @Database annotated class BUT allows the testing to be run on the main thread (perhaps running on other threads may be  an issue, something to check/consider):-
@Database(entities = [RoomNoteFile::class, RoomNotePage::class], version = NotepadDatabase.DATABASE_VERSION, exportSchema = false)
abstract class NotepadDatabase: RoomDatabase() {
    abstract fun getInstance(): NotepadDatabaseDao

    companion object {
        const val FILES_TABLE = "file"
        const val PAGES_TABLE = "page"
        const val DATABASE_VERSION = 1
        const val DATABASE_NAME = "notepad.db"

        @Volatile
        private var instance: NotepadDatabase? = null
        fun getInstance(context: Context): NotepadDatabase {
            if (instance == null) {
                instance = Room.databaseBuilder(context,NotepadDatabase::class.java,NotepadDatabase.DATABASE_NAME)
                    .allowMainThreadQueries()
                    .build()
            }
            return instance as NotepadDatabase
        }
    }
}

To test, MainActivity, this inserts some data (Files and then Related pages (3 files each with 3 related pages)), extracts the data and outputs it to the log, also deleting 1 File (ID=1), then extracts the changed data outputting it to the log :-
class MainActivity : AppCompatActivity() {
    lateinit var db: NotepadDatabase
    lateinit var dao: NotepadDatabaseDao
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        db = NotepadDatabase.getInstance(this)
        dao = db.getInstance()

        val f1id = dao.insert(RoomNoteFile(0,"File1",0))
        val f2id = dao.insert(RoomNoteFile(0,"File2",1))
        val f3id = dao.insert(RoomNoteFile(0,"File3",2))

        val p1id = dao.insert(RoomNotePage(0,"F1Page1",1,f1id.toInt()))
        val p2id = dao.insert(RoomNotePage(0,"F1Page2",2,f1id.toInt()))
        val p3id = dao.insert(RoomNotePage(0,"F1Page3",3,f1id.toInt()))
        dao.insert(RoomNotePage(0,"F2Page1",1,f2id.toInt()))
        dao.insert(RoomNotePage(0,"F2Page2",2,f2id.toInt()))
        dao.insert(RoomNotePage(0,"F2Page3",3,f2id.toInt()))
        dao.insert(RoomNotePage(0,"F3Page1",1,f3id.toInt()))
        dao.insert(RoomNotePage(0,"F3Page2",2,f3id.toInt()))
        dao.insert(RoomNotePage(0,"F3Page3",3,f3id.toInt()))

        for (rnf in dao.getAllFiles()) {
            logFile(rnf,"_STEP1")
            if (rnf.id == 1) {
                dao.delete(rnf)
            }
        }
        for (rnf in dao.getAllFiles()) {
            logFile(rnf,"_STEP2")
        }
    }

    fun logFile(roomNoteFile: RoomNoteFile,suffix: String) {
        Log.d("NPDBINFO$suffix","NAME=${roomNoteFile.name} ID=${roomNoteFile.id} AMOUNT=${roomNoteFile.pagesAmount} ${getFilePagesForLogging(roomNoteFile)}")
    }

    fun getFilePagesForLogging(roomNoteFile: RoomNoteFile): String {
        val sb: StringBuilder = java.lang.StringBuilder()
        for (page: RoomNotePage in dao.getPagesForAFileId(roomNoteFile.id.toInt())) {
            sb.append("\n\tID=${page.id} TEXT=${page.text} PAGE#=${page.pageNum} FILEID=${page.fileId}")
        }
        if (sb.isEmpty()) {
            sb.append("No Pages Found")
        }
        return sb.toString()
    }
}

The resultant output being :-
2022-05-27 05:16:23.256 D/NPDBINFO_STEP1: NAME=File1 ID=1 AMOUNT=0
        ID=1 TEXT=F1Page1 PAGE#=1 FILEID=1
        ID=2 TEXT=F1Page2 PAGE#=2 FILEID=1
        ID=3 TEXT=F1Page3 PAGE#=3 FILEID=1
2022-05-27 05:16:23.259 D/NPDBINFO_STEP1: NAME=File2 ID=2 AMOUNT=1
        ID=4 TEXT=F2Page1 PAGE#=1 FILEID=2
        ID=5 TEXT=F2Page2 PAGE#=2 FILEID=2
        ID=6 TEXT=F2Page3 PAGE#=3 FILEID=2
2022-05-27 05:16:23.260 D/NPDBINFO_STEP1: NAME=File3 ID=3 AMOUNT=2
        ID=7 TEXT=F3Page1 PAGE#=1 FILEID=3
        ID=8 TEXT=F3Page2 PAGE#=2 FILEID=3
        ID=9 TEXT=F3Page3 PAGE#=3 FILEID=3

2022-05-27 05:16:23.262 D/NPDBINFO_STEP2: NAME=File2 ID=2 AMOUNT=1
        ID=4 TEXT=F2Page1 PAGE#=1 FILEID=2
        ID=5 TEXT=F2Page2 PAGE#=2 FILEID=2
        ID=6 TEXT=F2Page3 PAGE#=3 FILEID=2
2022-05-27 05:16:23.265 D/NPDBINFO_STEP2: NAME=File3 ID=3 AMOUNT=2
        ID=7 TEXT=F3Page1 PAGE#=1 FILEID=3
        ID=8 TEXT=F3Page2 PAGE#=2 FILEID=3
        ID=9 TEXT=F3Page3 PAGE#=3 FILEID=3

i.e. As far as from the File being deleted that has worked and no Page relationships have changed to belong to another File.
From  the database aspect, via App Inspection, it can be seen that the pages are as they should be. i.e. only 6 rows remain and 3 are related to File2 and 3 are related to File3:-

i.e. The CASCADE has done what is expected
As such I believe that you need to look for the issue in other that the code you have provided.

A: I found the issue, it's just view pager rewrites the values of all data that was after the deleted file


text:
Q: Как вернуть данные между Fragment'ами? Есть MainActivity, у него есть контейнер, туда подгружаю fragment A и по нажатию на кнопку заменяю (replace) на fragment B, как мне вернуть данные из фрагмента В на А, типа onActivityResult, как мне это реализовать?

A: Официальный способ или EventBus – pavlofff 5 июн в 12:51

A: MainFragment - fragment A
public class MainFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        view.findViewById(R.id.click).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NextFragment fragment = new NextFragment();
                //Для идентификации именно этого результата используем код (например 120)
                fragment.setTargetFragment(MainFragment.this, 120);
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.cont, fragment).addToBackStack("null").commit();
            }
        });
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //Проверяем по коду нужный результат
        if(requestCode == 120){
            if(resultCode == Activity.RESULT_OK){
                //Действия при возврате результата
                String value1 = data.getStringExtra("key1");
                String value2 = data.getStringExtra("key2");
            }else{
                //Действия при отмене
            }
        }
    }
}

fragment - B
public class NextFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_next, container, false);
    view.findViewById(R.id.clickBack).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.putExtra("key1", "value1");
            intent.putExtra("key2", "value2");
            getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
            getFragmentManager().popBackStack();
        }
    });
    return view;
}

}

A: Набросал быстрый пример. Этот вариант подразумевает общение фрагментов через Activity. В примере фрагмент 2 передает данные фрагменту 1.
Код MainActivity
    import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Добавляем фрагмент - F1
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.add(R.id.fContainer, new F1(), "f1");
    ft.commit();
}

public void  replaceFragment1ToFragment2() {

    //Меняем фрагмент - F1 на фрагмент - F2
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.fContainer, new F2());
    ft.commit();
}

public void  replaceFragment2ToFragment1(String text) {
    //Меняем фрагмент - F2 на фрагмент - F1
    //И передаем в F1 результаты из F2
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    F1 f1 = new F1();
    ft.replace(R.id.fContainer, f1);
    ft.commit();

    //Отправляем результаты
    f1.setData(text);
}

}

Код первого фрагмента:
    import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class F1 extends Fragment implements View.OnClickListener {

String text = "";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_f1, container, false);
    Button b = (Button) v.findViewById(R.id.btnStartF2);
    b.setOnClickListener(this);

    //Если нет результатов, оставляем оригинальное название кнопки
    if (!text.equals("")) b.setText(text);

    return v;
}

@Override
public void onClick(View view) {
    ((MainActivity) getActivity()).replaceFragment1ToFragment2();
}

public void setData(String text) {
    this.text = text;
}

}

Код второго фрагмента:
    import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class F2 extends Fragment implements View.OnClickListener {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_f2, container, false);
    ((Button) v.findViewById(R.id.btnStartF1)).setOnClickListener(this);
    return v;
}

@Override
public void onClick(View view) {
    ((MainActivity) getActivity()).replaceFragment2ToFragment1(
            ((EditText) getView().findViewById(R.id.textToF1)).getText().toString());
}
}

Разметка MainActivity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>

Разметка первого фрагмента:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/btnStartF2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Запускаем F2"/>
</LinearLayout>
</FrameLayout>

Разметка второго фрагмента:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:id="@+id/btnStartF1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Возвращаем результат в F1"/>
    <EditText
        android:id="@+id/textToF1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Отправим этот текст в F1"/>
</LinearLayout>
</FrameLayout>


text:
Q: SVG: How to make a stroke of an object overlap an object rendered after it I have a SVG-image map with many polygons, which are directly bordering and all have a white stroke. On hovering, that stroke should turn darkgrey and become wider. Easy CSS.
But my problem: As objects in SVG are rendered after one another, the wider stroke will not overlap the other object, but underlap it, which looks super ugly. Is there a way to make it overlap instead?
Thanks in advance,
snow


text:
Q: Pattern with pure virtual functions getting advantage of polymorphism Suppose the following code:
struct Piece_t {
    virtual ~Piece_t() = default;
    std::string type;
};

struct Empty_t : Piece_t {
    Empty_t() { };
    bool run() { return false; };
};

struct Pawn_t : Piece_t {
    Pawn_t() {
        type = "Pawn";
    }
    bool move() {
        return false;
    }
};

struct Board_t {
    using Cols = std::vector<Piece_t>;
    using Board = std::vector<Cols>;
    Board_t(size_t N = 8) : b{ Board(N, Cols(N, Empty_t())) } {
        for (size_t i = 0; i < N; i++) {
            b[1][i] = Pawn_t();
            b[N - 2][i] = Pawn_t();
        }
        //more init's here...
    }
    Board b;
};

Here I have a Piece_t, and Im creating a Board_t, which has a std::vector<std::vector<Piece_t>>.
Fair enough, however, now suppose that I want to add a pure virtual function to Piece_t, like move:
struct Piece_t {
    virtual bool move() = 0;
    virtual ~Piece_t() = default;
    std::string type;
};

Doing this, however, is going to give me compilation errors, because I can not instantiate a std::vector<Piece_t> like I do in Board. This seems strange to me, because I'm actually doing an init with Empty_t, and not with Piece_t.
So here are my questions:

*

*Why is not letting me to compile the code with this modification? Suppose that I' have already implemented move in the other two structs.

*What should be the correct pattern to create the desired behaviour? (Being creating a base class with a virtual pure funct. and later using that definition to getting advantage of polymorphism.

A:
Why is not letting me to compile the code with this modification?

You are experiencing object slicing. std::vector<Piece_t> stores only objects of type Piece_t. Imagine a contiguous array of Piece_t classes back-to-back. There is no room to store anything more in between.
Since Pawn_t is a Piece_t, it's sliced back down to Piece_t and that part gets stored. Unfortunately an instance of Piece_t can't exist since it's an abstract class, hence the compile error.

What should be the correct pattern to create the desired behaviour?

Store pointers (or references) to objects instead.
For example, using std:vector<std::unique_ptr<Piece_t>>.
struct Board_t {
    using Row = std::vector<std::unique_ptr<Piece_t>>;
    using Board = std::vector<Row>;
    Board_t(size_t N = 8) : b(N) {
        for (auto& row : b)
            row.resize(N);
        for (size_t i = 0; i < N; i++) {
            b[1][i] = std::make_unique<Pawn_t>();
            b[N - 2][i] = std::make_unique<Pawn_t>();
        }
        //more init's here...
    }
    Board b;
};

A: c++ runtime polymorphism is usually obtained instantiating the derived classes on the heap and accessing them via base class pointers/references, for example:
class Piece_t {};
class Empty_t : Piece_t {};
class Pawn_t : Piece_t {};
std::vector<std::unique_ptr<Piece_t>> vec;

std::unique_ptr<Piece_t> e1 = std::make_unique<Empty_t>();
vec.push_back(std::move(e1));
vec.push_back(std::make_unique<Pawn_t>());

vec[0]->some_virtual_method();

Note that this is not the only polymorphic mechanism available in c++.
You may want to read a good c++ book while experimenting.


text:
Q: Is there a simple encrypting archiver which is just like WinZip except for the glaring security hole? I find it quite annoying that WinZip (and 7-zip, etc) does not encrypt the file names in the archive, just the file contents.
This is a glaring security hole as the file & folder names can contain quite a bit of information such as names, account numbers, account types, etc.
Are there any good alternatives out there? A good alternative should be easy-to-use, and hopefully backward-compatible with regular Zip utilities to the extent possible (for instance, by allowing file contents to be retrieved in WinZip/7zip even if that requires a separate rename step).

A: I'm not an expert, but judging from the description of the ZIP file format, it looks like having plaintext filenames is a limitation of all ZIP archives, not one of WinZip or any particular ZIP archiver.
One workaround to be fully compatible with current ZIP archivers would be to ZIP your files twice: Once to contain everything into a single ZIP archive, then again with a password. This way you cannot see filenames unless you decrypt the outer archive.
In other words, your archive may look like this:
MyFiles.zip.zip (password protected)
    |- MyFiles.zip
        |- file1.txt
        |- file2.txt
        |- ...

Be aware though that ZIP encryption may not be considered strong security; if you have serious security needs your best bet is to use a different file format.

A: The 7z format used by 7zip can encrypt filenames in the archive.
But you can't do this with Zip files until someone establishes a widely used update to the Zip file format.
The only way is to cheat and store a zip within a zip - so you'd create a zip file called (say) no-peeping.zip (or even rename it to something inconspicuous like "untitled.txt") with all your files inside, then add that to another zip file.

A: Winrar have an option to encrypt filenames (The encryption doesn't work with zip files, only with rar, despite the fact that winrar could handle zip files)

A: WinRAR does exactly this, but only for RAR files. You could create a self-extracting RAR if the person on the other end of the archive refuses to install it, or 7z. Plaintext filenames is, alas, a limitation of the zip file format, and the encryption algorithms leave a lot to be desired. Zip encryption is not security anymore!

A: I would suggest you to take a look at TrueCrypt: it's multiplatform and could handle files as well as entire partitions or drives.
I'm using it, and the security it provides seems to be of a very fine quality.
Regards


text:
Q: Future events times and Lévy processes If I am at time $t$ and I know that in the future, at time $t+h$ a process $X_s$ will jump by a random quantity, can $X_s$ be a Lévy process? ($X_s$ jumps before and after $t+h$ at random times)
If not what properties of Levy processes does it violate?
If yes how does the filtration of time $t$ relates to the filtration of time $t+h$?
Shouldn't the knowledge of jump time  $t+h$ be included only in the filtrations $\mathcal{F}_w$ for $w\geq t+h$?

A: No it's not a Lévy process because Lévy processes must have the property (which is almost equivalent to a definition(*)) to be continuous in probability, in other words almost surely at a time s (for example t+h) the paths of the process are continuous. As you know that the process is almost surly discontinuous your process is not Lévy.
For a reference look at the first chapter of Protter's book on stochastic calculus.
Best regards
Edit :
(*)Yo have to independent and stationary increments hypotheses to get a Lévy process.


text:
Q: Upload video to Facebook from the server I have a problem when uploading videos to Facebook.
I use Facebook SDK for Android: https://github.com/facebook/facebook-android-sdk to get the access token with the following permissions: "publish_stream","email","video_upload","publish_actions"
Then I send token to the server, which should upload the video. The server tries to upload video using following code:
string fullurl = string.Format("https://graph-video.facebook.com/me/videos?title={0}&description={1}&access_token={2}", HttpUtility.UrlEncode(fileName), HttpUtility.UrlEncode(description), token);

Facebook returns an error:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
   at System.Net.WebClient.UploadFile(Uri address, String method, String fileName)
   at System.Net.WebClient.UploadFile(String address, String fileName)

But, when I check token with the following link: https://graph.facebook.com/me?access_token=myToken Facebook returns user info. That means that token is valid. But, if this request returns error code, where I can find information about error codes?
This solution works perfectly for some users, for other users it works unstable ( 4 of 6 videos uploading failed. Facebook returns that: "connection closed by remote server"). And have not worked for some users with error: "The remote server returned an error: (400) Bad Request".
What is wrong in my code?

A: I've solve the problem. I have start using facebook SDK for .NET http://facebooksdk.net/ and it works for me.
      Facebook.FacebookClient fb = new FacebookClient(facebookEditTask.facebookToken);
      fb.PostCompleted += (o, e) =>
      {
           if (e.Cancelled || e.Error != null)
           {
                return;
           }

           var result = e.GetResultData();
           facebookVideoUrl = CreateLinkToVideo(result.ToString());
       };

       dynamic parameters = new ExpandoObject();
       parameters.source = new FacebookMediaStream
       {
             ContentType = "video/mp4",
              FileName = Path.GetFileName(facebookEditTask.FilePath)
       }.SetValue(File.OpenRead(facebookEditTask.FilePath));

       parameters.message = fbMessage;

       Task t = fb.PostTaskAsync("me/videos",
                    new { message = fbMessage, parameters.source });


text:
Q: awk passing shell variables through awk commands In an .xml file , I have some information:
 <var name="site1">
     <location lat="45.4558" lon="-98.4131" ht="422.0"/>
 </var>
 <var name="site2">
     <location lat="35.1497" lon="-106.8239" ht="1814.0"/>
 </var>
 <var name="site3">
     <location lat="36.9839" lon="-77.0075" ht="78.0"/>
 </var>

And I would like to extract the line after I search for 'sitex'. This is easily done with:
 awk '/site1/{getline;print}'

which, would correctly output:
 <location lat="45.4558" lon="-98.4131" ht="422.0">

Now if I want to get the lat information, I am able to do this with the complete line:
 awk '/site1/{getline;print}' | awk '{print $2}' | cut -d \" -f2

Which would produce 45.4558, correctly.
Now if I want to pass a variable into awk which can be done with the '-v' command, I have something that looks like below:
 locc="site1"
 awk -v var="$locc" '/var/{getline;print}' | awk '{print $2}' | cut -d \" -f2

However, this produces nothing (i.e., no output). What might the issue be here? If I simply try:
 awk -v var="$locc" 'BEGIN{print var}'

I get site1 as output. Therefore, it is correctly loading in the string I pass, but not parsing through the information correctly.

A: Could you please try following.
var="site1"
awk -v val="$var" 'index($0,val){found=1;next} found{print;found=""}' Input_file

To get only specific value try following.
awk -v val="$var" 'BEGIN{FS="[\"=]"}index($0,val){found=1;next} found{print $3;found=""}' Input_file

Output will be 45.4558 for above command.


text:
Q: aaai.sty problem with 'Abstract' section The AAAI LaTeX style file 'aaai.sty' defines the abstract section as follows:
\renewenvironment{abstract}{\centerline{\bf
Abstract}\vspace{0.5ex}\begin{quote}\small}{\par\end{quote}\vskip 1ex}

However I can't get it to work properly.
If I use:
\begin{document}
\maketitle
\abstract
  This is an abstract of my paper.
\section{Introduction}
  My introduction...
\include{biblio}
\end{document}

Though my document view shows the title, abstract, and introduction, I get an error on the \end{document} line stating:
\begin{quote} on input line 83 ended by \end{document}. \end{document}

The bibtex part doesn't run because of the error.
I can't seem to find a latex example using the aaai.sty online to help me, so I've posted here.
If I need to post more information, please indicate what is needed.  Cheers.

A: The abstract is (as in most, but not all classes) an environment. So use
\begin{abstract}
...
\end{abstract}


text:
Q: How ca I use an Image for entire application without downloading again In my Android application I have to fetch some images from the server and show them.Same image is shown in some of the pages.Now I am downloading the same image in each page and getting out of memory error.How can I reuse the one that I have downloaded earlier in each page

A: Use Android Query, and then Image Loading in particular. It's really easy and performs well.


text:
Q: Grails dependency error-only looks in grailsCentral not other repos Grails 2.5...
I have a plugin in an SVN repository.
Here is the build config (minus authentication credentials)....
grails.project.dependency.resolver = "maven" // maven or ivy

grails.project.dependency.resolution = {
   inherits("global") {
    // specify dependency exclusions here; for example, uncomment this to disable ehcache:
    // excludes 'ehcache'
}
log "warn" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
checksums true // Whether to verify checksums on resolve
legacyResolve false // whether to do a secondary resolve on plugin installation, not advised and here for backwards compatibility
repositories {
    inherits true // Whether to inherit repository definitions from plugins

    grailsPlugins()
    grailsHome()
    grailsCentral()

    mavenLocal()
    mavenCentral()

    mavenRepo "http://repo.grails.org/grails/plugins"

    mavenRepo name:"*********", root: "*********************"

}
 plugins {

   runtime ':org-calendar-viewer:0.7.9'

}

But I always get a dependency resolve error it could not find the plugin at grailsCentral. Of course it couldn't the plugin is in a different repo. Is grailsCentral the last place it looks? Or the first place it looks?
Resolve error obtaining dependencies: Could not find artifact in grailsCentral (https://repo.grails.org/grails/plugins)

I tried commenting out the grails repos and then it fails as
Resolve error obtaining dependencies: Could not find artifact  in mavenCentral (https://repo1.maven.org/maven2/)

So it seems it is throwing an error after only checking one(first) location?


text:
Q: Laravel: Error When Using a Factory for a Foreign Key I have the following migration (for a pivot table):
        Schema::create('category_news', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->unsignedBigInteger('category_id');
            $table->unsignedBigInteger('news_id');

            $table->unique(['category_id', 'news_id']);

            $table->foreign('news_id')->references('id')->on('news')->onDelete('cascade');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        });

I want to seed that table with some dummy data -- to do so, I have created the following factory:
$factory->define(CategoryNews::class, function (Faker $faker) {

  return [
    'category_id' => $faker->numberBetween($min = 1, $max = 35),
    'news_id' => $faker->numberBetween($min = 1, $max = 150)
  ];

});

However, when I run the following command: php artisan migrate:fresh --seed, I get the following error:
 Illuminate\Database\QueryException

  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`startup-reporter`.`category_news`, CONSTRAINT `category_news_news_id_foreign` FOREIGN KEY (`news_id`) REFERENCES `news` (`id`) ON DELETE CASCADE) (SQL: insert into `category_news` (`category_id`, `news_id`, `updated_at`, `created_at`) values (16, 13, 2020-03-31 10:44:04, 2020-03-31 10:44:04))

  at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
    665|         // If an exception occurs when attempting to run a query, we'll format the error
    666|         // message to include the bindings with SQL, which will make this exception a
    667|         // lot more helpful to the developer instead of just the database's errors.
    668|         catch (Exception $e) {
  > 669|             throw new QueryException(
    670|                 $query, $this->prepareBindings($bindings), $e
    671|             );
    672|         }
    673|

  1   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
      PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`startup-reporter`.`category_news`, CONSTRAINT `category_news_news_id_foreign` FOREIGN KEY (`news_id`) REFERENCES `news` (`id`) ON DELETE CASCADE)")

  2   C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
      PDOStatement::execute()

Any idea why and what I need to do to fix it?
Thanks.

A: I figured it out -- I had to reorder my DatabaseSeeder.php file to call the NewsTableSeeder file before I called the CategoryNewsTableSeeder file.

A: you are trying to add a new record category_news with category_id=16
while you don't have a category with id =16, so the constraint will throw an error ...
you can't use random int to assign it to your foreign keys references ...
you can simply do something like this:
$factory->define(CategoryNews::class, function (Faker $faker) {

  return [
    'category_id' => Category::all()->random()->id,
    'news_id' => News::all()->random()->id,
  ];
});

i have found this way here :
https://stackoverflow.com/a/44102531/10573560


text:
Q: Switch statement in LaTeX using package pseudocode I am using \usepackage{pseudocode} in LaTeX for writing pseudocode.
How to write switch statement using this package?
I write more 90% pseudocode using the package pseudocode. In function Validate i want to write switch Statement.
\PROCEDURE{Validate}{location1,location2}
l1 \GETS 0 \\
l2 \GETS 0 \\
validate \GETS true \\
\IF board[location1] \neq 0 \THEN
    \BEGIN
    l1 \GETS board[location1]
    l2 \GETS board[location2]
    \IF l1 + l2 is odd and l2 \neq 0 \THEN
        validate \GETS false
    \ELSE
        \BEGIN
            %\SWITCH  here i want to write switch statement
                   %\BEGIN

            %\END
        \END
    \END

 \RETURN {validate}\\
 \ENDPROCEDURE

I can find add switch statement in pseudocode using other packages like algorithmicx and algorithm. There is any way to add switch statement using pseudocode package ?

A: I'm really not sure whether this is what you're after, but it's a first go:

\documentclass{article}
\usepackage{amsmath,pseudocode}% http://ctan.org/pkg/{amsmath,pseudocode}
\newcommand{\algvar}[1]{\text{\ttfamily\upshape#1}}
\makeatletter
\newcommand{\SWITCH}{\mbox{\bfseries switch }}
\renewcommand{\CASE}{\mbox{ \bfseries case }}
\newcommand{\CASEELSE}{\mbox{ \bfseries else }}
\makeatother
\begin{document}
\begin{pseudocode}{Validate}{\algvar{location1}, \algvar{location2}}
    \PROCEDURE{Validate}{\algvar{location1}, \algvar{location2}}
    l_1 \GETS 0 \\
    l_2 \GETS 0 \\
    \algvar{validate} \GETS \TRUE \\
    \IF \algvar{board}[\algvar{location1}] \neq 0 \THEN
        \BEGIN
        l_1 \GETS \algvar{board}[\algvar{location1}] \\
        l_2 \GETS \algvar{board}[\algvar{location2}] \\
        \IF (l_1 + l_2 \text{ is odd}) \AND (l_2 \neq 0) \THEN
            \algvar{validate} \GETS \FALSE
        \ELSE
            \BEGIN
                \SWITCH i
                    \BEGIN
                        \CASE 1 \text{ Something 1} \\
                        \CASE 2 \text{ Something 2} \\
                        \CASE 3 \text{ Something 3} \\
                        \CASE 4 \text{ Something 4} \\
                        \CASEELSE \text{ Something else}
                    \END
            \END
        \END \\
        \RETURN {\algvar{validate}} \\
    \ENDPROCEDURE
\end{pseudocode}
\end{document}

The constructions used by pseudocode is based on arrays, so it's easily modifiable. However, it depends on what you're after in terms of the look of a \SWITCH command, in terms of placement, alignment and justification.


text:
Q: How was the universe created? I do not know much beyond high school Physics. Thus, I am asking this question from almost layman's perspective:

What, as per the best of our existing knowledge and widely accepted among the scientific community, are the models of creation of the universe, and what is their core argument?

A: If you mean by world the earth, you can find a fairly good discussion at
http://en.wikipedia.org/wiki/Formation_and_evolution_of_the_Solar_System
If you mean by world the universe:
The big bang is a singularity, and we can study scientifically only what came out of it. See, e.g.,
http://en.wikipedia.org/wiki/Big_Bang
Thus there is no model of creation of the universe widely accepted among the scientific community.
However, there are various scientific speculations based on physical reasoning, e.g.,
Eternal inflation, http://arxiv.org/abs/hep-th/0702178
Extra dimensions, http://www.superstringtheory.com/cosmo/cosmo4.html
Big crunch, http://arxiv.org/pdf/hep-th/0108187
Cyclic universe, http://arxiv.org/abs/hep-th/0111098
Big bang particle lattice, http://www.awesomeanimator.com/bigbangstatevector.pdf
Now or in former times widely accepted models for the creation of the universe can be found not in science but in theology, e.g.,
http://www.catholic.com/tracts/creation-and-genesis
http://www.talkorigins.org
http://www.aljazeerah.info/Islamic%20Editorials/2007/October/Creation%20and%20Evolution%20in%20the%20Holy%20Qur%27an%20By%20Hassan%20El-Najjar.htm
http://www.answering-islam.org/Shamoun/creationdays.htm
or mythology, e.g.,
http://dept.cs.williams.edu/~lindsey/myths/myths.html
http://www.desy.de/gna/interpedia/greek_myth/creation.html
http://www.egyptartsite.com/crea.html

A: The most widely supported theory for the creation of the universe is the Big Bang Theory. It states that the universe was created about 13.7 billion years ago from a singularity (a very, very hot point with an infinitely small volume and infinitely large density) and it has been expanding ever since (so getting less dense and less hot). Click here for a timeline since the Big Bang.
The 4 main arguments supporting this theory are sometimes called the 4 pillars of the Big Bang Theory, click here for an article regarding those core arguments. Also, this video regarding 'Olbers' Paradox' might be of interest to you too, it's actually one of the most blatantly obvious arguments for the Big Bang Theory.
Of course, there are alternate theories, but at the moment this is the most widely supported one.

A: The book about the first three minutes of the universe from Steven Weinberg mentioned in Jerry's comment, I've not yet read but it looks good from afar.
In his inflationary universe Alan Guth explains in a very accessible way the formarly unsolved problems in cosmology and how thinking about them lead him to the idea of inflation. The many personal notes and experiences Alan Guth has included in his book make it a lot of fun to read.
The above two books due not directly explain the absolut beginning of the universe which would probably involve some kind of something-out-of-nothing process. To explain the very beginning of the universe some kind of quantum gravity is certainly needed, as for example explained by  Stephen Hawking here (this book is admittedly written in a very cheerful, and some would say over optimistic, tone) or by Martin Bojowald here (these are "lecture notes" but I could not find a popular book about this).

A: There are over 50 billion universes.  Our universe has over 50 billion galaxies.
  In our universe there are hundreds of millions intelligent civilizations.  Simply proven by math, and our unique knowledge of existence.


text:
Q: How to change textView value when getting a notification? I'm trying to make a program where the value of a TextView is changed when a notification appears on the phone.
In my MainActivity I have a method:
private void changeText(){
    TextView textNotificationView = (TextView) findViewById(R.id.textNotificationView);
    textNotificationView.setText(R.string.textGotNotification);
}

I would like to call changeText() from MainActivity whenever I get a notification. For this I have created a class called NotificationListener that extends NotificationListenerService.
public class NotificationListener extends NotificationListenerService {

@Override
public IBinder onBind(Intent intent) {
    return super.onBind(intent);
}

@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    //Change value of TextView
}

@Override
public void onNotificationRemoved(StatusBarNotification sbn){

}
}

Basically, I would like to call the changeText()-method inside the onNotificationPosted(StatusBarNotification sbn)-method.
How should I do this?

A: I have a solution, that is using EventBus
first, create a event
public class NotificationPosted {
// empty if you don't need to pass data
}

second, register this event in MainActivity
@Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

@Override
protected void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}

  @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
        public void onEvent(NotificationPosted notificationPosted) {
            changeText()
        }

finally, post your event in NotificationListener
public void onNotificationPosted(StatusBarNotification sbn) {
    EventBus.getDefault().post(new NotificationPosted());
}

A: You need an callback from your non-activity class to Activity class.
public class MainActivity extends Activity implements INotificationCallback {
    public void setText(String value) {
        TextView textNotificationView = (TextView) findViewById(R.id.textNotificationView);
        textNotificationView.setText(value);
    }
}

public NotificationListener extends NotificationListenerService {
    public interface INotificationCallback {
        public void setText(String value);
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        activity.setText(value);
    }
}


text:
Q: Django - consecutive dumpdata calls fail, even though work correctly when run separately I've run into an issue trying to set up automatic backups on my site. The problem boils down to the following.
I open the Python shell and I call the dumpdata command twice. It works for the first time and it returns empty list the second time. After that all further dumpdata calls return empty list:
>>> python manage.py shell
>>> from django.core.management import call_command
>>> call_command("dumpdata")
[{"pk": 1, (...) // lots of data //
>>> call_command("dumpdata")
>>> []

To make it work again I need to restart the python shell.
Edit: I use Django 1.4 and Python 2.6
Edit2: My current hypothesis is that the problem is related to this issue: https://code.djangoproject.com/ticket/5423 - identified 5 years ago and according to Django 1.5 release notes, to-be resolved in the next release. Does anybody have an idea how to workaround this issue without altering the 1.4 framework code being run on the machine?
Edit3: However sql dump of the whole database is only 0.5 MB, which makes it rather unprobable that the serialization is running out of memory. And anyway, wouldn't I get an explicit error in such case?
Edit4: Mystery solved. As Tomasz Gandor correctly determined, the problem was that shell executes the commands in one transaction, and after one of the commands causes DBError, further DB calls are ignored, as described here: https://code.djangoproject.com/ticket/10813 . Why the DB error during the first dumpdata wasn't explicitely reported remains a mystery to me.

A: I see that django is messing something with transactions.
I executed a simple example under the debugger:
# test.py
from django.core.management import call_command
call_command("dumpdata")
print "\n---"
call_command("dumpdata")
print

And called it like:
DJANGO_SETTINGS_MODULE=settings python test.py > log.txt

My log.txt ended with "---\n[]\n"
After running it in the debugger i found, deep down in
django.core.management.commands.dumpdata.handle()
that model.objects.all() keeps returning [].
I called model.objects.iterator(), and got the exception:
(Pdb) list(model.objects.iterator())
*** Error in argument: '(model.objects.iterator())'
(Pdb) p list(model.objects.iterator())
*** DatabaseError: DatabaseError('current transaction is aborted, commands ignored    until end of transaction block\n',)
(Pdb)

So, I hacked together code, which plays with the transaction itself:
# test.py version 2.0!

#!/usr/bin/env python
# from django.core.management import call_command
import django.core.management as mgmt
from django.db import transaction

'''
try:
    import settings # Assumed to be in the same directory.
except ImportError:
    import sys
    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
    sys.exit(1)
'''

@transaction.commit_manually
def main():
    # mgmt.call_command('dumpdata', use_base_manager=True)
    mgmt.call_command('dumpdata')
    transaction.rollback()
    print
    print '---'
    print
    """
    mgmt._commands = None
    import sys
    reload(sys.modules['django.core.management.commands.dumpdata'])
    """
    mgmt.call_command('dumpdata')
    transaction.rollback()
    print

if __name__ == "__main__":
    main()

This spits out the whole database - every time!


text:
Q: Unique eigenvector representation without discontinuities Suppose a matrix in $\mathbb{R}^n$ has $n$ different real eigenvalues. There are now $n$ eigenvectors that are unique up to a scaling factor. By requiring them to be of unit length, they are unique up to a sign.
Now, I can try to define the first component of the vector to be positive in order to resolve the sign issue. However, not only do I run into problems when said component is zero, it also leads to discontinuities: When the eigenvector is changed by a small amount, the representation can jump to a different value.
Is there a unique representation that resolves this issue? The representation does not necessarily have to be a valid eigenvector itself.
All I can think of  is to use the matrix $\frac{vv^\top}{\|v\|^2}$ to uniquely represent eigenvector $v$, but that isn't very compact as the number of components is squared.
In the special case of $\mathbb{R}^2$ I suppose I can obtain the angle of the vector, and construct a new vector with exactly twice the angle and unit length. Can this be extended to arbitrary dimensions.


text:
Q: Hazelcast client time to live setup for individual client I am using SpringBoot with Hazelcast.
In my setup I have one Hazelcast server(3.12.6) up and running I am connecting that with Hazelcast client in my SpringBoot application.
hazelcast-client.yaml
hazelcast-client:
  network:
    cluster-members:
      - 127.0.0.1
    smart-routing: false

I have checked the setup in Hazelcast server, there is a global configuration in hazelcast.xml that helps in configuration of Time to live configuration.
hazelcast.xml
<?xml version="1.0" encoding="UTF-8"?>

<group>
    <name>dev</name>
</group>
<management-center enabled="true">http://mc_server:8080/hazelcast-mancenter</management-center>
<map name="default">
    <time-to-live-seconds>10</time-to-live-seconds>
    <max-idle-seconds>10</max-idle-seconds>
</map>

My question is:
Is there any way I can configure time to live and other settings using my springboot client on my server?

A: Here is an example of Dynamic configuration from a Hazelcast Client.
HazelcastInstance client = HazelcastClient.newHazelcastClient();
MapConfig mCfg = new MapConfig("test");
mCfg.setTimeToLiveSeconds(15);
client.getConfig().addMapConfig(mCfg);
HazelcastClient.shutdownAll();

Details and limitations are here - https://docs.hazelcast.org/docs/3.12.6/manual/html-single/index.html#dynamically-adding-data-structure-configuration-on-a-cluster
Thanks, Sharath