text:
Q: Add warning/notice about responding to a long-dead discussion Occasionally, I get notifications about a comment response, and it seems someone has noticed some question or answer from 3, 5, 10 years ago, and decided to join the "lively" discussion without noticing it's long dead.
Perhaps the top of the comment box could include some warning or notice that the last comment is X years old? Perhaps with some extra wording regarding the rationale for commenting or whatever.

A: If a question or answer still needs improvement then I do not think that it matters how old it is when the next comment is made there.
I would rather see the odd unseen comment made, rather than have a comment discouraged from being made where a clarification sought belatedly might lead to a post becoming more upvoted due to its having been improved.

A: So, first, "lively discussion" shouldn't be sticking around for years. Comments are intended to be temporary notices for improving the post and then removed after their usefulness is done. So, generally, this whole problem case doesn't occur if cleanup is happening regularly.
The age of the answer/comments is not going to be a good predictor of how likely that comment is to be useful.
Even assuming the comments that the person are responding to are useful and purposefully left,  responses to it can still be useful no matter how old the post or the previous comments are. I've seen comments on 6-7 year-old answers prompt edits, improvements to posts and spur other questions even. Sometimes comments on a post are useful to people other than the poster of the question/answer. Regardless, the age of the previous comments does not say anything about the likelihood of that comment to be useful. Sometimes even long-inactive OPs come back and respond or make edits in response to a comment.
Warning a person about the age of the comments is guaranteed to dissuade some percentage of commenters from leaving that comment and with no guarantee that the age has any relevance to how their comment will be received/acted on. So I think this suggestion would not really bring any benefit.


text:
Q: When does the isomorphism $G\simeq \ker(\phi)\times \operatorname{im}(\phi)$? hold? Suppose you have a group isomorphism given by the first isomorphism theorem:
$$G/\ker(\phi) \simeq \operatorname{im}(\phi)$$
What can we say about the group $\ker(\phi)\times \operatorname{im}(\phi)$? In particular, when does the following hold:
$$G\simeq \ker(\phi)\times \operatorname{im}(\phi)?$$
I ask this question because i want to prove that $GL_n^+(\mathbb{R}) \simeq SL_n(\mathbb{R}) \times \mathbb{R}^*_{>0}$, with $GL_n^+(\mathbb{R})$ the group of matrices with positive determinant. I proved that $SL_n(\mathbb{R})$ is a normal subgroup and that $GL_n^+(\mathbb{R})/  SL_n(\mathbb{R}) \simeq \mathbb{R}^*_{>0}$, using the surjective homomorphism $\det(M)$. I tried something with semidirect products but I got stuck.

A: Let $N = ker(\phi)$ and $K = im(\phi)$, then you're asking when, given an exact sequence $1 \to N \to G \to K \to 1$ is trivial.

*

*First you need the extension to be split, that is, there must exist a morphism $s : K \to G$ such that the composition $\phi \circ s$ is the identity. In this case $G \simeq N \rtimes K$, the semidirect product of $N$ and $K$ : this is the splitting lemma (for non-abelian groups).

*Now you want this semidirect product to be direct; this is true iff $K$ is also normal in $G$, or equivalently that there exists a morphism $G \to N$ which is the identity on $N$.

I don't include proofs here, as they're found in any basic group theory notes.

In fact you can get away with the first condition. Indeed, if there exists a map $p : G \to N$ which is the identity on $N$, then a section of $\phi$ automatically exists and the isomorphism $G \cong \operatorname{im}(\phi) \times \operatorname{ker}(\phi) = K \times N$ holds. The required isomorphism is $(\phi, p) : G \to K \times N$ (it's not hard to check that this is in fact an isomorphism).

A: Even if it can't be applied to your example, I would like to point out that in the abelian case (more generally in any abelian category) it's equivalent to have a split exact sequence: $0 \to \ker(\phi) \to G \to Im(\phi) \to0$

A: In your special case you actually have a morphism $GL_n ^+ \to SL_n \times \mathbb{R}^+ $ given by
$$ M \mapsto (M/(\det M)^{1/n}, \det M) $$
the inverse being given by $(N, t) \mapsto t^{1/n} N$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular - How can I move ngClass logic from template to ts file? In Angular application I am using dropdown filters for user selection. I have add logic in ngClass
           <div [ngClass]="i > 2 && 'array-design'">
How can I move the logic for classed to the controller? As when they are in the template it not possible to unit test them.
<ng-container *ngIf="searchFilters.length > 0; else loading">
        <div class="filter-items" *ngFor="let filter of searchFilters; index as i">
            <div [ngClass]="i > 2 && 'array-design'">
                <app-multi-select [items]="filter.navigators" [title]="filter.name"></app-multi-select>
            </div>
        </div>
    </ng-container>

.scss
  .cross-reactivity, .array-design{
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-right: 5px;
  }

A: You can move the conditional statement into a function and use its return in HTML.

html
[ngClass]="filterClass(i)"

ts
const filterClass = (i) => i > 2 && 'array-design';


text:
Q: I can't see why I'm getting a 'cannot resolve symbol' error Why am I getting a cannot resolve symbol (red text) in my java class?  I know this has something to do with my Gradle file but even if it does, I can't see why because I'm pretty sure everything in it is correct.
What I've done so far:

*

*File > Invalidate Caches/Restart.

*Build > Clean Project.

*Build > Rebuild Project.

*Close Android-Studio & restart my computer.

None of them worked.
Java class
Gradle

A: In the future, please post code, not images to code.
Notice the red font on Activity.  That means the Activity class isn't recognized.  You need to either import Activity, or extend AppCompatActivity instead.  Right now you're extending a class that isn't imported so the compiler doesn't know it. That makes the override annotation is invalid (for an override annotation to be valid, it needs to be know the parent class so it can check if the signature of the function is the same as one in the parent class).


text:
Q: JSON parsing with GSON Structure I've tried to do this in another project, and as per the tutorials I've seen, I know I am on the right track, but I cannot get this parsing correctly:
(Much Simplified) JSON Output:
{
"data":{
  "info":{
      "username": "something"
      "email" : "something"
   }
..
..

}
I am trying to get "username" and "email using the following classes:
class ProfileResponse {
static Data data;

public static Data getData() {
    return data;
}

public static void setData(Data data) {
    ProfileResponse.data = data;
}

}
Class Data {
@SerializedName("info")
static Info info;

public static Info getInfo() {
    return info;
}

public static void setInfo(Info info) {
    Data.info = info;
}

}
class Info {
@SerializedName("username")
static String username;
@SerializedName("email")
static String email;

public static String getUsername() {
    return username;
}

public static String getEmail() {
    return email;
}

}

and Deserializing the JSON String (could it be a problem that it's a String?) like so:
           Gson gson = new Gson();
                        gson.fromJson(response, ProfileResponse.class);
                        if (Info.getUsername() == null
                                || Info.getUsername().isEmpty()) {
                            System.out.println("NO USERNAME");
                        } else {
                            System.out.println("USERNAME: "
                                    + Info.getUsername());
                        }

This is printing "NO USERNAME" each time it's run.

A: static fields are by default excluded from serialization/deserialization.
Remove all the static keywords from your classes (fields and methods), call fromJson() correctly, and you will then get the result you're looking for.
Gson instantiates an instance of your class(es) from your JSON. After modifying your classes, you then will do:
ProfileResponse pr = gson.fromJson(response, ProfileResponse.class);


text:
Q: Doubts regarding Pagerank execution I'm trying to execute the code below : http://blog.xebia.com/2011/09/27/wiki-pagerank-with-hadoop/
The javac shows no errors, but I don't know how to get the output? These are the execution steps I'm following:
$ javac -Xlint -classpath /home/james/Downloads/hadoop-0.20.203.0/hadoop-core-0.20.203.0.jar -d  doc WikiPageRanking.java
$ jar -cvf WikiPageRanking.jar -C doc/ .
$ bin/hadoop dfs -mkdir /user/james/wiki/in
$ bin/hadoop dfs -copyFromLocal wiki-micro.txt /user/james/wiki/in
$ bin/hadoop jar WikiPageRanking.jar org.myorg.WikiPageRanking /user/james/wiki/in /user/james/wiki/result

Is this right? I seriously doubt the last step - the input and output paths!! In the code, they have used wiki/in, that's why I gave the same path here, and I have copied my sample dataset to this path. The map reduce process starts, but I get no output!!

A: What does the following commands give you:
hadoop fs -ls /user/james/wiki/result

hadoop fs -text /user/james/wiki/result/part*

Running a job does not automatically dump the results of the job to the console - they are most typically stored in HDFS (in your case in the path /user/james/wiki/result). You can view the contents of this directory using the first command, and assuming there are some part* files, the second command will dump their contents to disk
Final point to note - if the output format is SequenceFileOutputFormat and you're using custom key / value objects, you'll need to amend the second command to include your jar:
hadoop fs -libjars WikiPageRanking.jar -text /user/james/wiki/result/part*


text:
Q: Where does Liferay keep the system bundle? I'm looking for the jar for the com.liferay.blogs.service.permissions package. I've managed to track it down to an export of the system bundle, i.e. bundle 0. But I can't figure out where Liferay keeps this bundle.
My question, then, is as follows: where does Liferay DXP deployment?

A: Liferay keeps bundles for the OSGi framework at the osgi directory.
The blogs bundle is actually inside a wrapping file (Liferay package) inside the osgi/marketplace
ps: you can extract those packages by the way, similar to jars, on to this date at least, they are just compressed files.


text:
Q: How to set environment variable of Google Chrome for Flutter 2 Web on Arch Linux Using flutter doctor I understand that flutter cant find google-chrome executable.
I'm using fish shell.
I set the environment variable in /. config/fish using the set CHROME_EXECUTABLE /usr/bin/google-chrome-stable command how doctor says, but it didn't help.

A: On Arch Linux, the executive file of the proprietary version of google chrome has the name google-chrome-stable, but flutter tries to find exactly google-chrome. Therefore, setting the environment variable for /usr/bin/google-chrome-stable has no effect.
Therefore, to solve the problem, you need to create a link to google-chrome-stable with the name google-chrome using the command sudo ln -s /usr/bin/google-chrome-stable /usr/local/bin/google-chrome


text:
Q: d3 v4 zoom event not firing for mousewheel/touchscreen I recently migrated to D3 v4.10.2. I am calling the zoom behavior as instructed in the documentation, however the callback is not executed when zooming with the mouse-wheel or touch-screen. I am using the latest version of chrome:
 var some_svg = d3.select('body').select("#some-svg");
 var some_svg_rect =  some_svg.append("g").append("rect")
                                          .attr("fill","none")
                                          .attr("width",900)
                                          .attr("height",400);
 some_svg_rect.call(d3.zoom()
                     .on("zoom", function () {/*this code fails to execute*/}));

Thanks the zooming is working after setting "pointer-events" to "all" however the drag behavior only works on drag "start" is something missing there?:
some_svg_rect.call(d3.drag()
               .on("start", function () {/*this code works*/})
               .on("drag", function () {/*this code fails toexecute*/})
               .on("end", function () {/*this code fails to execute*/}));

A: The problem with your code is the default pointer-events for the SVG, in which:

The element can only be the target of a mouse event when the visibility attribute is set to visible and when the mouse cursor is over the interior (i.e., 'fill') of the element and the fill attribute is set to a value other than 'none', or when the mouse cursor is over the perimeter (i.e., 'stroke') of the element and the stroke attribute is set to a value other than none. (emphasis mine)

However, I advise you to do not set the fill to transparent (as suggested in the other answer), which is normally a bad idea: despite some browsers supporting it, transparent is not part of the SVG specs.
Instead of that, just set the pointer-events to visible or all:
.attr("pointer-events", "all")

Here is a demo (shamelessly copying the code of the other answer)

var some_svg = d3.select('body').select("#some-svg");
var some_svg_rect = some_svg.append("g").append("rect")
  .attr("fill", "none")
  .attr("pointer-events", "all")
  .attr("width", 400)
  .attr("height", 250);
some_svg_rect.call(d3.zoom()
  .on("zoom", function() {
    console.log("zoom works")
  }));
.as-console-wrapper { max-height: 20% !important;}
svg{
  border: 1px solid gray;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg id="some-svg" width=400 height=250></svg>

A: Instead of
.attr("fill","none")
use
.attr("fill","transparent")
working code below

var some_svg = d3.select('body').select("#some-svg");
 var some_svg_rect =  some_svg.append("g").append("rect")
                                          .attr("fill","transparent")
                                          .attr("width",900)
                                          .attr("height",400);
 some_svg_rect.call(d3.zoom()
                     .on("zoom", function () {
                     console.log("hi")
                     }));
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg id="some-svg" width=1000 height=2000></svg>


text:
Q: Xamarin.Forms UWP - Requesting to enable app to run at startup I am wanting my app to launch when the user logs into Windows. Currently, I can do this by opening up Task Manager > Startup > and setting 'Enable' for my app. I am wanting to do this within my app though, and have followed this guide. However, when requesting the app to run at startup, it always throws the exception below:
The group or resource is not in the correct state to perform the requested operation.

This doesn't make sense to me, as my app only calls RequestEnableAsync() if the StartupTaskState is Disabled, as seen in my code below:
private async Task<bool> SetLaunchOnLogin_UWP_Async(bool shouldLaunchOnLogin)
{
    try
    {
        var startupTask = await StartupTask.GetAsync("MyProjectStartupId");

        switch (startupTask.State)
        {
            case StartupTaskState.Disabled:

                Debug.WriteLine("Startup is disabled. Will ask");
                // The code reaches here, but always throws an exception
                // when calling RequestEnableAsync():
                var newState = await startupTask.RequestEnableAsync()
                return newState == StartupTaskState.Enabled;
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(
            "SpecificPlatformFunctions_UWP - SetLaunchOnLogin_UWP_Async ERROR: "
            + ex.ToString());
    }

    return false;
}

And the full error output:
Startup is disabled. Will ask
Exception thrown: 'System.Exception' in System.Private.CoreLib.ni.dll
SpecificPlatformFunctions_UWP - SetLaunchOnLogin_UWP_Async ERROR: System.Exception: The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MyProject.UWP.DependencyServices.SpecificPlatformFunctions_UWP.<SetLaunchOnLogin_UWP_Async>d__13.MoveNext()

The code above is called via a DependencyService, when a button is clicked.

A: I was able to solve this simply by running the code on the main thread. IE, wrapping it inside of Device.BeginInvokeOnMainThread(async () => { ... });


text:
Q: How is a debugger like GDB able to run a program one instruction at a time? I can understand how a program that is compiled specifically for debugging can have breakpoints and traps inserted in the code, but how are programs like GDB able to do this on pre-compiled programs? How are they able to halt the execution of a program after every single instruction?
I am working on a Windows machine, but I'd be willing to learn how this works on Linux too.
Any direction or resources would be appreciated, since Googling returns instructions on how to use GDB, not how it works at a low level.

A:
How are they able to halt the execution of a program after every single instruction?

Most processors, including all i*86 ones, support single-step execution.
When GDB is asked to execute a single machine instruction on such a processor, it's a very simple procedure:

*

*arrange for the processor to execute in single-step mode (this is processor specific, read about i*86 implementation here).

*resume the inferior process

*wait for interruption (which will come immediately after 1 instruction has finished if step 1 worked).

On a processor without single-step support, GDB's job is a bit more complicated:

*

*disassemble current instruction (to know where the next one begins; this is trivial on RISC processors with fixed instruction size),

*insert a temporary breakpoint on the next instruction (this is a bit complicated due to control transfer instructions -- the next instruction may be far away)

*resume the inferior process

*wait for interruption (which will come immediately after 1 instruction has finished if step 2 worked).

*remove the temporary breakpoint inserted in step 2.

Resources:

*

*you can read the source of GDB, though it's not the easiest code to navigate.

*there was a series of blog posts by Joseph Kain explaining how things work, though it appears to have stalled.


text:
Q: King on Reduced Chessboard I've been set this as a task: On a chessboard, a king is to be allowed to move one square at a time: horizontally to the right, vertically downward, or diagonally to the right and downward. Imagine a reduced 4x4 chessboard, with the king beginning in the top-left square. By how many routes can he reach the bottom-right square? By how many routes can a similar journey be made on a full 8x8 chessboard?
I've searched on the web and it always comes up with matrixes. We haven't done any of those in class and my teacher will find out as we have to include our working out. Is there any other way of doing this? Or can someone help me understand matrixes?

A: HINT:
Try labeling each of the squares of the chessboard with the number of routes from the beginning square to that square:
The beginning square has just one route because the only way to get there is just to start there. The next square its right has only one route too because the only way is to move from the beginning one square to the right. The square below the beginning square has only one route as well because the only way to get there is to move one square down from the beginning.
But the square diagonally to the right and downward from the beginning square has three routes: to the right and down, down and to the right, or diagonally in one step.
So if you label the squares this way, the upper left hand corner will look like:
$$\begin{array}1 1&1\\1&3\end{array}$$
Now note that to get to any square in a single move, you have to have come from at most 3 others (which three?), and ask yourself: how is the number of routes to such-and-such a particular square related to the number of routes to the squares you could get to it from?
(By the way, I agree with you and JazzyMatrix that for the $4\times 4$ board, the right answer is 63.)

A: One way to introduce diagonals into this pathway problem is use the pascals triangle. I am assuming that you know what it is and if you don't, it's very simple to look up. The Pascal's triangle can be used to solve pathway problems when there are no diagonals. Imagine that the board is rotated and the number of pathways are labeled with each corresponding number on the pascals triangle. This will work for only horizontal and vertical movement and each number is the sum of the 2 above it:

However, when you add the use of diagonals, you will need to add the top 3 numbers to get the next number:
                                           1
                                         1   1
                                       1   3   1
                                     1   5   5   1
                                   1   7   13   7  1
                                 1   9   25  25  9   1
                               1   11  41  63  41  11  1

Ex. 63 = 25+25+13
As you can see, the answer 63 is in the answer. If you want to visualize the grid, you can tilt your head and see that a 4x4 grid starting on the top will be 63


text:
Q: Xamarin Forms - Lifetime of Pages in Navigation Stack I've got two pages in my Xamarin Forms app, and I'm trying to do basic navigation:
public partial class Page1
{
   void OnAddButtonClicked (object sender, EventArgs args)
   { Navigation.PushAsync (new Page2 ()); }
}

public partial class Page2
{
   ~Page2()
   { Debug.WriteLine ("Page2.~Page2()"); }
   protected override void OnAppearing ()
   { Debug.WriteLine ("Page2.OnAppearing()"); }
   protected override void OnDisappearing ()
   { Debug.WriteLine ("Page2.OnDisappearing()"); }
}

public class App : Application
{
   public App()
   {
      MainPage = new NavigationPage(new Page1());
   }
}

When I click on the button, the second page appears as desired, and when I click either back button (the OS back button or the left-arrow in the title bar) it does return to the first page but what is concerning me is that my second page is never destructed.  I realize the garbage collector runs whenever it darn well pleases, but I can switch between pages multiple times (creating a new Page2 each time) and sit without touching the app for minutes and none of the Page2 objects are ever destructed.
The official documentation doesn't say anything about destructing old pages, but there is another thread on stackoverflow that implies I am responsible for the lifetimes of my pages.  So what's my final answer - do I need to manually destruct my pages, or will Xamarin eventually take care of that for me?


text:
Q: How to repair irreparable files? In Windows 8.1 sfc /scannow and DISM /Online /Cleanup-Image /RestoreHealth are unable to repair "aspnet_state_perf.ini" "aspnet_perf2.ini" and "aspnet_perf.h".
which are part of "NetFx-AspNet-NonWow64-Shared".
CBS.log (Full error log here)
2015-01-28 23:55:54, Info                  CSI    00000529 [SR] Cannot repair member file [l:42{21}]"aspnet_state_perf.ini" of NetFx-AspNet-NonWow64-Shared, Version = 4.0.9600.17635, pA = PROCESSOR_ARCHITECTURE_AMD64 (9), Culture neutral, VersionScope = 1 nonSxS, PublicKeyToken = {l:8 b:b03f5f7f11d50a3a}, Type neutral, TypeName neutral, PublicKey neutral in the store, hash mismatch
2015-01-28 23:55:54, Info                  CSI    0000052b [SR] Cannot repair member file [l:32{16}]"aspnet_perf2.ini" of NetFx-AspNet-NonWow64-Shared, Version = 4.0.9600.17635, pA = PROCESSOR_ARCHITECTURE_AMD64 (9), Culture neutral, VersionScope = 1 nonSxS, PublicKeyToken = {l:8 b:b03f5f7f11d50a3a}, Type neutral, TypeName neutral, PublicKey neutral in the store, hash mismatch
2015-01-28 23:55:54, Info                  CSI    0000052d [SR] Cannot repair member file [l:26{13}]"aspnet_perf.h" of NetFx-AspNet-NonWow64-Shared, Version = 4.0.9600.17635, pA = PROCESSOR_ARCHITECTURE_AMD64 (9), Culture neutral, VersionScope = 1 nonSxS, PublicKeyToken = {l:8 b:b03f5f7f11d50a3a}, Type neutral, TypeName neutral, PublicKey neutral in the store, hash mismatch

The update package is:
"Package_3_for_KB2969357~31bf3856ad364e35~amd64~~6.3.1.35.2969357-692_neutral_GDR"

How can I fix this?

A: Uninstalling Windows Update KB2969357 in the Control Panel fixed the corrupted files.
However sfc /scannow still reported not being able to repair some unnamed files. System Restore failed several times and added more errors to the table.
Ultimately I used a Windows 8.1 RTM DVD and choose Upgrade. Windows retained all programs and settings, plus no more integrity violations.
And the Windows folder shrinked from 24GBs to 14 GBs :)


text:
Q: Regular Expression help needed for extracting text from lines I have the following text:
:10A: <any characters here>\r\n
<any characters here>\r\n
<any characters here>\r\n
.
.
.
:11A: or :12P:

There can be up to 10 lines between the two ":XXX:" signs (including the first row).
I need to extract (using only REGEX, no Java methods) the first one to four lines (including the first line, without the ":10A:").
Examples 1:
:10A: Line number 1\r\n
Line number 2\r\n
Line number 3\r\n
Line number 4\r\n
Line number 5\r\n
Line number 6\r\n
:11A:

Will extract:
Line number 1\r\n
Line number 2\r\n
Line number 3\r\n
Line number 4\r\n

Example 2:
:10A: Line number 1\r\n
Line number 2\r\n
:12P:

Will extract:
Line number 1\r\n
Line number 2\r\n

Any help would be greatly appreciated.
Thanks.

A: You can use this regex
(?<=:.{3}:)(.*?(\\r?\\n)){1,4}

A: Description
This expression will capture the first 4 lines of text of each section.
^:[^:]*:(.*?(?:^(?:(?!^:[^:]*:|[\r\n]|\Z).)*[\r\n\Z]*){3})

Expanded

*

*^:[^:]*: match the section break

*.*?  match the line of text on the same line as the section break

*(? this capture group will match an entire line which is not a section break

*

*^ match the start of the line

*(?:(?!^:[^:]*:|[\r\n]|\Z).)* match all characters on the line providing they are not a section title, new line characters, or the end of the string

*[\r\n\Z]* match any number of new line characters or end of string

*){3} attempt to match three of those lines. Note the internal condition is auto limited and will prevent capturing more lines then a section may contain.

Java Code Example:
Input text
:10A: Line number 1
Line number 2
Line number 3
Line number 4
Line number 5
Line number 6
:11A:Line number 1
Line number 2
Line number 3
Line number 4
:10A: Line number 1
Line number 2
:12P:Line number 1
Line number 2

Code
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class Module1{
  public static void main(String[] asd){
  String sourcestring = "source string to match with pattern";
  Pattern re = Pattern.compile("^:[^:]*:(.*?(?:^(?:(?!^:[^:]*:|[\r\n]|\Z).)*[\r\n\Z]*){3})",Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
  Matcher m = re.matcher(sourcestring);
  int mIdx = 0;
    while (m.find()){
      for( int groupIdx = 0; groupIdx < m.groupCount()+1; groupIdx++ ){
        System.out.println( "[" + mIdx + "][" + groupIdx + "] = " + m.group(groupIdx));
      }
      mIdx++;
    }
  }
}

Matches
This is only showing capture group 1. Capture group 0 is the entire matched string
$matches Array:
(
   [1] => Array
        (
            [0] =>  Line number 1
Line number 2
Line number 3
Line number 4

            [1] => Line number 1
Line number 2
Line number 3
Line number 4

            [2] =>  Line number 1
Line number 2

            [3] => Line number 1
Line number 2
        )

)

A: Maybe a regex to start with:
:(?:.*?):((?:.*?[\r\n]){1,4})(?:.*?):(?:.*?):

The first matching group will return up to four lines of the text.
Important note: you must turn on the "dotall" option in Java like in Pattern.compile(pStr, Pattern.DOTALL) or a similar option (single-line mode /.../s in Perl or RegexOptions.Singleline in .NET), otherwise the regex will not work due to the fact that you are working on multiline data.


text:
Q: Neo4j pipe data Hi there I am on neo4j and I am having some trouble I have one query where I want to return a the a node (cuisine) with the highest percentage like so
// 1. Find the most_popular_cuisine
MATCH (n:restaurants)
WITH COUNT(n.cuisine) as total
MATCH (r:restaurants)
RETURN r.cuisine , 100 * count(*)/total as percentage
order by percentage desc
limit 1

I am trying to extend this even further by getting the top result and matching to that to get nodes with just that property like so
WITH COUNT(n.cuisine) as total
MATCH (r:restaurants)
WITH r.cuisine as cuisine , count(*) as cnt
MATCH (t:restaurants)
WHERE t.cuisine = cuisine AND count(*) = MAX(cnt)
RETURN t

A: I think you might be better off refactoring your model a little bit such that a :Cuisine is a label and each cuisine has its own node.
(:Restaurant)-[:OFFERS]->(:Cuisine)

or
(:Restaurant)-[:SPECIALIZES_IN]->(:Cuisine)

Then your query can look like this
MATCH (cuisine:Cuisine)
RETURN cuisine, size((cuisine)<-[:OFFERS]-()) AS number_of_restaurants
ORDER BY number_of_restaurants DESC

A: I wasn't able to use WITH r.cuisine as cuisine , count(*) as cnt in a WITH rather than a RETURN statement, so I had to resort to a slightly more long-winded approach.
There might be a more optimized way to do this, but this works too,
// Get all unique cuisines in a list
MATCH (n:Restaurants)
WITH COUNT(n.Cuisine) as total, COLLECT(DISTINCT(n.Cuisine)) as cuisineList

// Go through each cuisine and find the number of restaurants associated with each
UNWIND cuisineList as c
MATCH (r:Restaurants{Cuisine:c})
WITH total, r.Cuisine as c, count(r) as cnt
ORDER BY cnt DESC
WITH COLLECT({Cuisine: c, Count:cnt}) as list

// For the most popular cuisine, find all the restaurants offering it
MATCH (t:Restaurants{Cuisine:list[0].Cuisine})
RETURN t


text:
Q: aarch64 gcc support --fix-cortex-a53-843419 I download arm64 arch toolchain from linaro.com
But when i start to build latest kernel with arm64 defconfig
It will show the below error, which means that my arm64 gcc doesn't support --fix-cortex-a53-843419 option.
Is there anyone knows which gcc I can use to fix that problem ?

linux git:(master) make ARCH=arm64 aarch64-linux-gnu- -j8
arch/arm64/Makefile:23: ld does not support --fix-cortex-a53-843419; kernel may be susceptible to erratum
arch/arm64/Makefile:44: Detected assembler with broken .inst; disassembly will be unreliable

linux git:(master) aarch64-linux-gnu-gcc -v
Using built-in specs.
COLLECT_GCC=aarch64-linux-gnu-gcc
COLLECT_LTO_WRAPPER=/home/miracle/Misc/gcc-linaro-7.1.1-2017.08-x86_64_aarch64-linux-gnu/bin/../libexec/gcc/aarch64-linux-gnu/7.1.1/lto-wrapper
Target: aarch64-linux-gnu
Configured with: '/home/tcwg-buildslave/workspace/tcwg-make-release/builder_arch/amd64/label/tcwg-x86_64-build/target/aarch64-linux-gnu/snapshots/gcc.git~linaro-7.1-2017.08/configure' SHELL=/bin/bash --with-mpc=/home/tcwg-buildslave/workspace/tcwg-make-release/builder_arch/amd64/label/tcwg-x86_64-build/target/aarch64-linux-gnu/_build/builds/destdir/x86_64-unknown-linux-gnu --with-mpfr=/home/tcwg-buildslave/workspace/tcwg-make-release/builder_arch/amd64/label/tcwg-x86_64-build/target/aarch64-linux-gnu/_build/builds/destdir/x86_64-unknown-linux-gnu --with-gmp=/home/tcwg-buildslave/workspace/tcwg-make-release/builder_arch/amd64/label/tcwg-x86_64-build/target/aarch64-linux-gnu/_build/builds/destdir/x86_64-unknown-linux-gnu --with-gnu-as --with-gnu-ld --disable-libmudflap --enable-lto --enable-shared --without-included-gettext --enable-nls --disable-sjlj-exceptions --enable-gnu-unique-object --enable-linker-build-id --disable-libstdcxx-pch --enable-c99 --enable-clocale=gnu --enable-libstdcxx-debug --enable-long-long --with-cloog=no --with-ppl=no --with-isl=no --disable-multilib --enable-fix-cortex-a53-835769 --enable-fix-cortex-a53-843419 --with-arch=armv8-a --enable-threads=posix --enable-multiarch --enable-libstdcxx-time=yes --enable-gnu-indirect-function --with-build-sysroot=/home/tcwg-buildslave/workspace/tcwg-make-release/builder_arch/amd64/label/tcwg-x86_64-build/target/aarch64-linux-gnu/_build/sysroots/aarch64-linux-gnu --with-sysroot=/home/tcwg-buildslave/workspace/tcwg-make-release/builder_arch/amd64/label/tcwg-x86_64-build/target/aarch64-linux-gnu/_build/builds/destdir/x86_64-unknown-linux-gnu/aarch64-linux-gnu/libc --enable-checking=release --disable-bootstrap --enable-languages=c,c++,fortran,lto --build=x86_64-unknown-linux-gnu --host=x86_64-unknown-linux-gnu --target=aarch64-linux-gnu --prefix=/home/tcwg-buildslave/workspace/tcwg-make-release/builder_arch/amd64/label/tcwg-x86_64-build/target/aarch64-linux-gnu/_build/builds/destdir/x86_64-unknown-linux-gnu


text:
Q: Is it possible to run a stored procedure in Oracle for loop? I have a question about a possibility. I have created a stored procedure in Oracle database version 12c. It takes one parameter in order to run. So that it runs correctly by passing the parameter as following:
EXEC My_Procedure_Name(parameter_value);

And everything goes well by running above code.
Now, I am going to run this procedure (in fact the above code) for two months on a daily basis. Therefore, I have wrote a script like this:
declare stmt varchar2(100);
 begin
   for i in (days of months)
  loop
    stmt:='EXEC My_Procedure_Name(parameter_value);';
    EXECUTE IMMEDIATE stmt;
    commit;
  end loop;
 end;

My question would be: is the mentioned script correct? And will it work? Is there any problem with my script?
Thanks

A: To call a procedure in a loop, the syntax is like this:
begin
    for i in 1..5 loop
        dbms_output.put_line(i);
    end loop;
end;

I'm assuming that for i in (days of months) is pseudocode and you will actually use some valid construction to meet your requirement.
If you really need to use dynamic code, that can be done, but note that PL/SQL has no EXEC keyword. You would need something like:
begin
    for i in 1..5 loop
        execute immediate 'begin dbms_output.put_line(:i); end;' using i;
    end loop;
end;

or
begin
    for i in 1..5 loop
        execute immediate 'call dbms_output.put_line(:i)' using i;
    end loop;
end;

(Notice that PL/SQL has a ; statement terminator, but SQL does not.)
As you can see, dynamic code is more complicated so it is best to avoid it unless there is no other option.

A: Rather than this you may try below code without using execute immediate but just referring the loop variable -
declare stmt varchar2(100);
 begin
   for i in (days of months)
  loop
    My_Procedure_Name(i.parameter_value);
    commit;
  end loop;
 end;


text:
Q: jQuery inArray() disabling days with select option in FullCalendar I am trying to disable specific days within FullCalendar. I have an array of dates from my database which will block or unblock days.
When i use the inArray() as below it blocks all days within the calendar. Not a jQuery guru so i need some help here please.
This is what i have so far;
select: function(start, end, jsEvent, view) {
    var disabledDates = ['2017-03-17', '2017-03-23'];

    if($.inArray(disabledDates) !== -1) {
        swal({
          title: "Date is blocked",
          text: "Sorry, the maximum Daily Bookings have been reached. Please select another date.",
          type: "warning"
        });

        $('#calendar').fullCalendar('unselect');
        return false;
    } else {
        $('#ModalAdd .start').val(moment(start).format('YYYY-MM-DD HH:mm:ss'));
        $('#ModalAdd .end').val(moment(end).format('YYYY-MM-DD HH:mm:ss'));
        $('#ModalAdd').modal('show');

        $('#calendar').fullCalendar('unselect');
        return true;
    };
}

Any suggestions will be greatly accepted.
EDIT
I have edited my question above, but still cannot get this to work, it should just return either true or false.
The reason i am using select: function is the i just want the model not to show if there is a date in the array.
Why won't this work?

A: Just in case anyone needs this solution, i finally got it working.
select: function(start, end, jsEvent, view) {
    var disabledDates = ['2017-03-17', '2017-03-23'];
    var selectedDate = moment(start).format('YYYY-MM-DD');

    if($.inArray(selectedDate, disabledDates) !== -1) {
        swal({
          title: "Date is blocked",
          text: "Sorry, the maximum Daily Bookings have been reached. Please select another date.",
          type: "warning"
        });

        $('#calendar').fullCalendar('unselect');
        return false;
    } else {
        $('#ModalAdd .start').val(moment(start).format('YYYY-MM-DD HH:mm:ss'));
        $('#ModalAdd .end').val(moment(end).format('YYYY-MM-DD HH:mm:ss'));
        $('#ModalAdd').modal('show');

        $('#calendar').fullCalendar('unselect');
        return true;
    };
}


text:
Q: jsTree drag item disintegration I'm dynamically creating some elements that should be drop-able onto a JSTree component. The tree is configured and the drag process is working, it's just not working as one would expect.
Take this HTML fragment:

    #
    asdfasdf

    (LICENSE)

That is a container div assigned a class of "newDragEntry" - and that is what the jsTree is configured to recognize. The problem is that whichever inner-element a user happens to grab when they initiate the drag becomes the actual drag object. So, if they grab the text "LICENSE" then that's what gets ghosted and dragged -- rather than the entire #newDragEntry_1 element (which just resembles a button when styled-out.)
Anyone got any ideas?
(FWIW - I can get the drag behavior I'm looking for by using jq's .draggable() method directly, but then I don't seem to get any drop events fired by jstree?)

A: After a pile of digging I've come to the conclusion that the solution to this problem would require a codebase modification within jsTree OR a healthy dose of manual event tracking (ie., your own superimposed drag logic.)
If anyone finds themselves here looking for a resolution, the place to start is this snip from the jstree sourcecode (version : jsTree 1.0-rc3):
var s = this._get_settings().dnd;
if(s.drag_target) {
  $(document)
    .delegate(s.drag_target, "mousedown.jstree-" + this.get_index(), $.proxy(function (e) {
  o = e.target;
  $.vakata.dnd.drag_start(e, { jstree : true, obj : e.target }, "" + $(e.target).text() );

The last line is the important one. At the end you'll see that it is extracting the TEXT from the bubbled drag event originator - hence the disintegration of a composite  like my example above. This means that any stylized formatting will be excluded from the ghost helper (among other things).
My solution: not very elegant to be sure, but I had to redo the composition of the drag source so that only a smaller text-based portion was jstree-draggable.


text:
Q: WPF Datagrid time field format hh:mm I use a WPF Toolkit Datagrid with a LINQ to SQL
       <my:DataGrid AutoGenerateColumns="False" Name="dataGrid2">
        <my:DataGrid.Columns>
            <my:DataGridTextColumn Header="Date" MinWidth="80"
                                       Binding="{Binding Date, StringFormat=d}"
                                       CanUserSort="False"/>
            <my:DataGridTextColumn Header="Time"  MinWidth="70"
                                       Binding="{Binding Time}"
                                       CanUserSort="False" />
            <my:DataGridTextColumn Header="Description" MinWidth="200"
                                       Binding="{Binding Description}"
                                       CanUserSort="False"/>
        </my:DataGrid.Columns>
    </my:DataGrid>

Column Time is bound to a SQL Server table field of a Time datatype. Now time value on the Datagrid is displayed in a format hh:mm:ss.
How could I change a time represantation in the Time column of a Datagrid to hh:mm, removing seconds?
EDIT:
Using  StringFormat=t gives no result.
<my:DataGridTextColumn Header="Time"  MinWidth="70"
                                       Binding="{Binding Time, StringFormat=t}"
                                       CanUserSort="False" />

A: <toolkit:DataGridTextColumn
                    IsReadOnly="True"
                    Width="SizeToCells"
                    Header="F. Resolución"
                    Binding="{Binding ColName, StringFormat=MM/dd/yyyy}" />

A: without seconds
<toolkit:DataGridTextColumn
                    IsReadOnly="True"
                    Width="SizeToCells"
                    Header="F. Resolución"
                    Binding="{Binding ColName, StringFormat='MM/dd/yyyy HH:mm'}" />

with seconds
<toolkit:DataGridTextColumn
                    IsReadOnly="True"
                    Width="SizeToCells"
                    Header="F. Resolución"
                    Binding="{Binding ColName, StringFormat='MM/dd/yyyy HH:mm:ss'}" />

here is only time with seconds:
<toolkit:DataGridTextColumn
                    IsReadOnly="True"
                    Width="SizeToCells"
                    Header="F. Resolución"
                    Binding="{Binding ColName, StringFormat='HH:mm:ss'}" />

A: Can be done using ValueConverter:
This can help:
Built-in WPF IValueConverters

A: You will need to convert your type from SqlDateTime to DateTime in order for the string format to work. Do this by casting your parameter to datetime. So for example when using c# to bring in your table.
dlEntry.StartTime = (DateTime)reader.GetSqlDateTime(3);

This will give you the ability to use the C# default converter for time.
<my:DataGridTextColumn Header="Time"  MinWidth="70"
Binding="{Binding Time, StringFormat=t}"
CanUserSort="False" />


text:
Q: What regex for jQuery satisfies these conditions? I have a field for which can have:

*

*Up to potentially 2 decimals places

*Up to potentially 6 non-decimal places

*No more than 8 digits altogether (the max 2 decimals plus max 6 non-decimals)

*Be a positive number

So correct inputs would be range from 0.01 to 999999.99, and trailing zeroes isn't an issue, so 4.00 is just as fine as 4.

A: You could try something like so:

*

*Up to potentially 2 decimals places: (\.\d{1,2})? - This will match a decimal point followed by a minimum of 1, and a maximum of 2 digits. This is optional.

*Up to potentially 6 non-decimal places: \d{1,6} - This will match a minimum of 1 digit and a maximum of 6 digits.

*No more than 8 digits altogether (the max 2 decimals plus max 6 non-decimals): You can combing the two above to get this: \d{1,6}(\.\d{1,2})?.

*Be a positive number: Change the above to this: ^\d{1,6}(\.\d{1,2})?$. This should make sure that any number you pass to it, does not start with a negative sign. The ^ and $ anchors instruct the regex engine to start matching at the beginning of the string and complete the matching at the end. This should allow you to be sure that the string you are matching is indeed a number.

That being said, you should really be doing numerical range checks using the appropriate mathematical operations which your language (in this case JavaScript) provides. A small change in the numerical range you are after will most likely bring a large change in your regular expression.

A: Try this pattern:
^[0-9]{1,6}(?:\.[0-9]{1,2}0*)?$

If you want to allow leading and trailing whitespace, add \s* to the beginning and the end of the pattern, right after ^ and right before $.
That said, this task is something you might want to accomplish without regex. Why don't you just read the value of the input, parse it and then simply perform a numeric validation? You could even round the input to two decimal places.

A: This might validate it
 #  /^(?=.*[1-9].*$)(?=[.]?(?:\d[.]?){1,8}$)(?=\d{0,6}(?:[.]\d{0,2})?$)/

 ^
 (?=                      # must be a positive number
      .* [1-9] .* $
 )
 (?=
      [.]?
      (?:                 # 1 to 8 digits
           \d
           [.]?
      ){1,8}
      $
 )
 (?=
      \d{0,6}             # 0 to 6 non-decimal places
      (?:
           [.]            # 0 to 2 decimal places
           \d{0,2}
      )?
      $
 )


text:
Q: How to combine the last 2 dimensions of Numpy Array I already saw How to combine dimensions in numpy array?
And tried that, but when I tried
imgs.reshape(img.shape[:-2]+(-1))

which I assumed would be the logical extension, I get an error:
can only concatenate tuple (not "int") to tuple

I was going to comment on the accepted answer from the linked question and ask them for help directly instead of creating a new thread for this but I don't have the required reputation to comment.
Edit:
For example, I have an input array that is of shape (x,y,8,8) where x and y can change depending on the image that is fed into the function. I want to make it into an array of shape (x,y,64). The 64 in this case never changes.

A: You must add a comma for it to be recognized as a tuple. Try
imgs.reshape(img.shape[:-2] + (-1,))

Or, use unpacking:
imgs.reshape((*img.shape[:-2], -1))


text:
Q: Heavy Duty use of SQL Compact with WebMatrix I've been told not to use SQL Server Compact that comes with WebMatrix for any heavy duty stuff. But, just exactly how heavy is "heavy duty"?
If I have a couple thousand products in a SQL Server Compact DB, plus a couple tables for registration and a couple tables for random stuff, would that be okay? Will SQL Server Compact be sufficient?

A: Your description of usage suggests that SQL Server Compact 4 would be sufficient for your usage. Your scenario is generally the reason SQL Compact was created. If you don't already have a full SQL Server instance at the ready, then consider choosing the SQL Compact solution.
It sounds like the advice given was focused on 'heavy-duty'. I'd consider heavy-duty to be sustained reads and writes, or requiring features not in SQL Compact: stored procedures, procedural TSQL, replication. See more on feature sets of SQL CE 4 & SQL Server 2008. Obvious advice would be to pick the engine that your web app needs.
The great thing about SQL Compact is that you can scale up/migrate to a SQL Server instance without much effort if/when your requirements change.


text:
Q: Don't you heard OR haven't you heard I am asking about a place from someone that you know this place or not.
So what is the correct line?
don't you heard about that place

OR
haven't you heard about that place

A: Haven't you heard about that place?
Don't you get news from John any more ?
'have' is used with the past participle of 'hear'. (Present Perfect)
The time period is your life - like saying: Haven't you ever heard of that place?
'don't' is used with the infinitive. (Simple Present)
(for a present truth)

A: There are two correct ways:
Didn't you hear about the place? (Past tense)
Haven't you heard about the place? (Present perfect).


text:
Q: Python equivalent of `final field` in java in dataclass Is it possible to have something like
class MyAbstract {
   final int myFieldSomebodyHasToDefine;
}

class MyAbstractImplementation extends MyAbstract {
   final int myFieldSomebodyHasToDefine = 5;
}

using dataclasses in python?

A: If you are working with a python interpreter before version 3.8, there is no straightforward way. However, since python 3.8, the final decorator has been added to the language. After importing it from the typing module in python, you can use it for methods and classes.
You may also use FINAL type for values.
Here is an example
from typing import final, Final

@final
class Base:
    @final
    def h(self)->None:
        print("old")

class Child(Base):
    # Bad overriding
    def h(self) -> None:
        print("new")

if __name__ == "__main__":
    b = Base()
    b.h()
    c = Child()
    c.h()
    RATE: Final = 3000
    # Bad value assignment
    RATE = 7
    print(RATE)

Important note: Python does not force the developer with final and FINAL. You can yet change the values upon your wish. The decorators of mostly informative for developers.
For more information, you may visit: https://peps.python.org/pep-0591/
Update: This is also an instance for dataclass
@dataclass
class Item:
    """Class for keeping track of an item in inventory."""
    price: float
    quantity_on_hand: int = 0
    name:Final[str] = "ItemX"

    def total_cost(self) -> float:
        return self.unit_price * self.quantity_on_hand

As you can see, name is a final field. However, you must put the final values with a default value below all of the fields without an initial value.


text:
Q: Keyboard shortcut to activate overlay "Replace" widget in VSCode? In VSCode, Ctrl+F activates a little "overlay" Find window that searches for a string in the current editor.
Edit --> Replace activates a similar overlay Replace window.
Is there a keyboard shortcut to activate this overlay Replace window, or can one be configured?
I went to Preferences --> Keyboard Shortcuts and searched for "replace", but the Replace action mentioned there (Ctrl+H) does something different: it opens a sidebar which can do find/replace in the entire workspace. I don't see any other actions there that activate the overlay Replace window.


text:
Q: Different loss values and accuracies of MLP regressor in keras and scikit-learn I have a neural network with one hidden layer implemented in both Keras and scikit-learn for solving a regression problem. In scikit-learn I used the MLPregressor class with mostly default parameters and in Keras I have a hidden Dense layer with parameters set to the same defaults as scikit-learn (which uses Adam with same learning rate and epsilon and a batch_size of 200). When I train the networks the scikit-learn model has a loss value that is about half of keras and its accuracy (measured in mean absolute error) is also better. Shouldn't the loss values be similar if not identical and the accuracies also be similar? Has anyone experienced something similar and able to make the Keras model more accurate?
Scikit-learn model:
clf = MLPRegressor(hidden_layer_sizes=(1600,), max_iter=1000, verbose=True, learning_rate_init=.001)

Keras model:
inputs = keras.Input(shape=(cols,))
x = keras.layers.Dense(1600, activation='relu', kernel_initializer="glorot_uniform", bias_initializer="glorot_uniform", kernel_regularizer=keras.regularizers.L2(.0001))(inputs)
outputs = keras.layers.Dense(1,kernel_initializer="glorot_uniform", bias_initializer="glorot_uniform", kernel_regularizer=keras.regularizers.L2(.0001))(x)
model = keras.Model(inputs=inputs, outputs=outputs)
model.compile(optimizer=keras.optimizers.Adam(epsilon=1e-8, learning_rate=.001),loss="mse")
model.fit(x=X, y=y, epochs=1000, batch_size=200)

A: It is because the formula of mean squared loss(MSE) from scikit-learn is different from that of tensorflow.
From the source code of scikit-learn:
def squared_loss(y_true, y_pred):
    return ((y_true - y_pred) ** 2).mean() / 2

while MSE from tensorflow:
backend.mean(math_ops.squared_difference(y_pred, y_true), axis=-1)

As you can see the scikit-learn one is divided by 2, coherent with what you said:

the scikit-learn model has a loss value that is about half of keras

That implied the models from keras and scikit-learn actually achieved similar performance. That also implied learning rate 0.001 in scikit-learn is not equivalent to the same learning rate in tensorflow.
Also, another smaller but significant difference is the formula of L2 regularization.
From the source code of scikit-learn,
# Add L2 regularization term to loss
values = 0
for s in self.coefs_:
   s = s.ravel()
   values += np.dot(s, s)
loss += (0.5 * self.alpha) * values / n_samples

while that of tensorflow is loss = l2 * reduce_sum(square(x)).
Therefore, with the same l2 regularization parameter, tensorflow one has stronger regularization, which will result in poorer fit to the training data.


text:
Q: Get array type in runtime objective-c Is there any ways in objective-c to find type of property which is declareted in next way:

@property(nonatomic, strong) NSArray<CustomClass *> *array;

I can get type of this property as NSArray, but are any ways to get CustomClass type?
Thanks in advance.

A: There is no way to receive information about generics declaration in runtime. Objective-C generics is a recent addition to language. They are used for compile-time checks only, so no any additional runtime information created. Note, that generic declaration doesn't strictly prevent storing objects of other class in array - compiler warning may be suppressed, although it's a bad practice.
But, there is still a possibility to determine classes of objects, stored in array. For example, you can use code like [array valueForKey:@"class"] to receive array of classes, corresponding to each element.

A: Type hints in lightweight generics are mainly used by compilers to raise warnings and it will not be available during runtime.
This SO link provides additional information and references to Apple docs/ videos. For convenience, I'm adding some information here.

So the entire lightweight generics feature is based on a type erasure model. Which means that the compiler has all of this rich static type information but it erases that information when generating code.


text:
Q: Magic v1 does not support record headers - Appdynamics Adding SingularityHeader I am facing Magic v1 does not support record headers while consuming the messages form Kafka. I understand this comes for the older kafka client version. But in my case AppDynamics is injecting a SingularityHeader as given below -
singularityheader: [110, 111, 116, 120, 100, 101, 116, 101, 99, 116, 61, 116, 114, 117, 101, 42, 99, 116, 114, 108, 103, 117, 105, 100, 61, 49, 53, 54, 54, 50, 55, 55, 56, 49, 52, 42, 97, 112, 112, 73, 100, 61, 50, 56, 48, 42, 110, 111, 100, 101, 105, 100, 61, 50, 50, 54, 52, 48, 57, 55]

Kafka Client Version - 0.10.2.0. I need suggestions here other than Upgrading Kafka Client version to 0.11.x from 0.10.2.0 (that is not an option). Is there a way to disable this from APPD itself ?

A: For anyone who is looking for an answer here. This is resolved by unchecking the Extended  tracking option for kafka in AppDynamics Console. The option will be there in Automatic Backend Discovery. Hope this helps.

A: *

*Disable default Kafka configuration on "Backend Detection" page

*Define a new "Custom Exit Point" with the last class and method which you see on the call graphs before Kafka exit call

*Don't forget to click on "Is High Volume" checkbox.


text:
Q: Как вывести данные менеджеров, у которых более 5 подчиненных, используя подзапрос? Есть такая задача:
Используя таблицу HR.EMPLOYEES, отобразить данные о сотрудниках (имя и фамилия, оклад, идентификатор департамента, номер телефона и e-mail), каждый из которых является менеджером для более 5 подчиненных.
Попробовал реализовать вот так, но выходит ошибка:
select first_name, last_name, department_id, phone_number, email from hr.employees
where (select manager_id from hr.employees
        where count(manager_id) > 5)

База данных выглядит вот так:
EMPLOYEE_ID FIRST_NAME  LAST_NAME   EMAIL   PHONE_NUMBER    HIRE_DATE   JOB_ID  SALARY COMMISSION_PCT   MANAGER_ID  DEPARTMENT_ID
   100   Steven           King     SKING    515.123.4567    17-JUN-03   AD_PRES   24000      -         -             90

A: Выводим список сотрудников, у которых в подчинении более 5 сотрудников:
Вложенным запросом получаем ID сотрудников, у которых более 5 подчиненных и по этим ID фильтруем.
select
    emp.first_name
  , emp.last_name
  , emp.department_id
  , emp.phone_number
  , emp.email
from hr.employees emp
where emp.EMPLOYEE_ID in (
    select manager_id
    from HR.EMPLOYEES
    group by manager_id
    having count(*) > 5
);

A: Наверное как-то так
select first_name, last_name, department_id, phone_number, email from hr.employees
where employee_id IN (
select manager_id from (select manager_id, COUNT(*) AS cnt from hr.employees) AS t
where t.cnt > 5)

Т.е. сначала мы считаем количество подчиненных для каждого менеджера, а потом выбираем идентификаторы менеджеров у которых подчиненных больше пяти. А уже потом полученные идентиифкаторы вставляем в условие для выборки сотрудников.


text:
Q: S4 object with a pointer to a C struct I have a third-party C library I am using to write an R extension. I am required to create a few structs defined in the library (and initialize them) I need to maintain them as part of an S4 object (think of these structs as defining to state of a computation, to destroy them would be to destroy all remaining computation and the results of all that has been already computed).
I am thinking of creating a S4 object to hold pointers these structs as void* pointers but it is not at all clear how to do so, what would be the type of the slot?

A: As pointed out by @hrbrmstr, you can use the externalptr type to keep such objects "alive", which is touched on in this section of Writing R Extensions, although I don't see any reason why you will need to store anything as void*. If you don't have any issue with using a little C++, the Rcpp class XPtr can eliminate a fair amount of the boilerplate involved with managing EXTPTRSXPs. As an example, assume the following simplified example represents your third party library's API:
#include <Rcpp.h>
#include <stdlib.h>

typedef struct {
    unsigned int count;
    double total;
} CStruct;

CStruct* init_CStruct() {
    return (CStruct*)::malloc(sizeof(CStruct));
}

void free_CStruct(CStruct* ptr) {
    ::free(ptr);
    ::printf("free_CStruct called.\n");
}

typedef Rcpp::XPtr<CStruct, Rcpp::PreserveStorage, free_CStruct> xptr_t;

When working with pointers created via new it is generally sufficient to use Rcpp::XPtr<SomeClass>, because the default finalizer simply calls delete on the held object. However, since you are dealing with a C API, we have to supply the (default) template parameter Rcpp::PreserveStorage, and more importantly, the appropriate finalizer (free_CStruct in this example) so that the XPtr does not call delete on memory allocated via malloc, etc., when the corresponding R object is garbage collected.
Continuing with the example, assume you write the following functions to interact with your CStruct:
// [[Rcpp::export]]
xptr_t MakeCStruct() {
    CStruct* ptr = init_CStruct();
    ptr->count = 0;
    ptr->total = 0;

    return xptr_t(ptr, true);
}

// [[Rcpp::export]]
void UpdateCStruct(xptr_t ptr, SEXP x) {
    if (TYPEOF(x) == REALSXP) {
        R_xlen_t i = 0, sz = XLENGTH(x);
        for ( ; i < sz; i++) {
            if (!ISNA(REAL(x)[i])) {
                ptr->count++;
                ptr->total += REAL(x)[i];
            }
        }
        return;
    }

    if (TYPEOF(x) == INTSXP) {
        R_xlen_t i = 0, sz = XLENGTH(x);
        for ( ; i < sz; i++) {
            if (!ISNA(INTEGER(x)[i])) {
                ptr->count++;
                ptr->total += INTEGER(x)[i];
            }
        }
        return;
    }

    Rf_warning("Invalid SEXPTYPE.\n");
}

// [[Rcpp::export]]
void SummarizeCStruct(xptr_t ptr) {
    ::printf(
        "count: %d\ntotal: %f\naverage: %f\n",
        ptr->count, ptr->total,
        ptr->count > 0 ? ptr->total / ptr->count : 0
    );
}

// [[Rcpp::export]]
int GetCStructCount(xptr_t ptr) {
    return ptr->count;
}

// [[Rcpp::export]]
double GetCStructTotal(xptr_t ptr) {
    return ptr->total;
}

// [[Rcpp::export]]
void ResetCStruct(xptr_t ptr) {
    ptr->count = 0;
    ptr->total = 0.0;
}

At this point, you have done enough to start handling CStructs from R:

*

*ptr <- MakeCStruct() will initialize a CStruct and store it as an externalptr in R

*UpdateCStruct(ptr, x) will modify the data stored in the CStruct, SummarizeCStruct(ptr) will print a summary, etc.

*rm(ptr); gc() will remove the ptr object and force the garbage collector to run, thus calling free_CStruct(ptr) and destroying the object on the C side of things as well

You mentioned the use of S4 classes, which is one option for containing all of these functions in a single place. Here's one possibility:
setClass(
    "CStruct",
    slots = c(
        ptr = "externalptr",
        update = "function",
        summarize = "function",
        get_count = "function",
        get_total = "function",
        reset = "function"
    )
)

setMethod(
    "initialize",
    "CStruct",
    function(.Object) {
        .Object@ptr <- MakeCStruct()
        .Object@update <- function(x) {
            UpdateCStruct(.Object@ptr, x)
        }
        .Object@summarize <- function() {
            SummarizeCStruct(.Object@ptr)
        }
        .Object@get_count <- function() {
            GetCStructCount(.Object@ptr)
        }
        .Object@get_total <- function() {
            GetCStructTotal(.Object@ptr)
        }
        .Object@reset <- function() {
            ResetCStruct(.Object@ptr)
        }
        .Object
    }
)

Then, we can work with the CStructs like this:
ptr <- new("CStruct")
ptr@summarize()
# count: 0
# total: 0.000000
# average: 0.000000

set.seed(123)
ptr@update(rnorm(100))
ptr@summarize()
# count: 100
# total: 9.040591
# average: 0.090406

ptr@update(rnorm(100))
ptr@summarize()
# count: 200
# total: -1.714089
# average: -0.008570

ptr@reset()
ptr@summarize()
# count: 0
# total: 0.000000
# average: 0.000000

rm(ptr); gc()
# free_CStruct called.
#          used (Mb) gc trigger (Mb) max used (Mb)
# Ncells 484713 25.9     940480 50.3   601634 32.2
# Vcells 934299  7.2    1650153 12.6  1308457 10.0

Of course, another option is to use Rcpp Modules, which more or less take care of the class definition boilerplate on the R side (using reference classes rather than S4 classes, however).


text:
Q: Nativescript imagepicker .getImage() is not a function error I have been trying to implement the answer to this question but keep getting the error "selected.getImage is not a function".
I have tried multiple different code examples at this point and I'm stumped.  It seems like this is a type error, but I'm not sure where I can correct this.
I am looking to select a single image and return the path to that image in order to upload to the server. I don't need to display it on the device, though that is an option I suppose.  Seems easy enough, but apparently I'm missing something.
I'm using v. 6.0.1 or the imagepicker plugin. I'd quote the code, but at this point I am using the exact example provided by Shiva Prasad in the above question.
Adding code per Max Vollmer:

var context = imagepickerModule.create({
    mode: "single" // allow choosing single image
});
context
    .authorize()
    .then(function () {
        return context.present();
    })
    .then(function (selection) {
        console.log("Selection done:");
        setTimeout(() => {
            selection.forEach(function (selected) {
                selected.getImage().then((source) => {
                    console.log(selected.fileUri); // this is the uri you need
                });
            });
        }, 1000);
    }).catch(function (e) {
        console.log(e);
    });

A: I was facing the exact same error yesterday.
I use the fromAsset function directly on the "selected" because apparently with the new version of this plugin, "selected" is an Asset. So you got an imageSource and you can use the "saveToFile" function that will copy the Asset into a new location (get this location using fileSystemModule from TNS). Use the path of this new location for your UI, and the image will appear. You can also create a file object from this location fileSystemModule.File.fromPath(path);, I use for upload.
context
            .authorize()
            .then(function () {
                return context.present();
            })
            .then(function (selection) {
                selection.forEach(function (selected) {

                    let file;

                    if (selected._android) {

                        file = fileSystemModule.File.fromPath(selected._android);
                        //viewModel.uploadFile(file);

                    }else{

                        imageSourceModule.fromAsset(selected).then((imageSource) => {

                        const folder = fileSystemModule.knownFolders.documents().path;
                        const fileName = "Photo.png";
                        const path = fileSystemModule.path.join(folder, fileName);
                        const saved = imageSource.saveToFile(path, "png");

                        if (saved) {
                            console.log("Image saved successfully!");
                            file = fileSystemModule.File.fromPath(path);
                            //viewModel.uploadFile(file);
                        }else{
                            console.log("Error! - image couldnt save.");
                        }
                    });
                }
            });
            }).catch(function (e) {
                console.log(e);
                // process error
            });

Explanation
The uncommented snippet (//viewModel.uploadFile(file);), viewModel reference (will be different on your app) and the function: uploadFile for example is where you would pass the file to upload it or set it to the image.src etc
Make sure to declare imageSourceModule at the top.
const imageSourceModule = require("tns-core-modules/image-source");


text:
Q: cakephp 2.0.5 Sqlserver requires a database connection I'm trying to access a second MS SQL database with cakephp 2.0.5 on Linux.
I have setup an Sqlserver datasource in Config/database.php
public $msdb = array(

'datasource' => 'Database/Sqlserver',

'persistent' => false,

'host' => 'xxx.xxx.xxx.xxx',

'port' => '1433',

'login' => 'username',

'password' => 'password',

'database' => 'DB',

'prefix' => '',

);

However I get this error:

Missing Database Connection
Error: Sqlserver requires a database connection
Error: Confirm you have created the file : app/Config/database.php.
Notice: If you want to customize this error message, create app/View/Errors/missing_connection.ctp.

Stack Trace
#0 /var/www/html/modip/cakephp-cakephp-6864406/lib/Cake/Model/ConnectionManager.php(101): DboSource->__construct(Array)

#1 /var/www/html/modip/cakephp-cakephp-6864406/lib/Cake/Model/Model.php(3234): ConnectionManager::getDataSource('msdb')

#2 /var/www/html/modip/cakephp-cakephp-6864406/lib/Cake/Model/Model.php(1030): Model->setDataSource('msdb')

#3 /var/www/html/modip/cakephp-cakephp-6864406/lib/Cake/Model/Model.php(3258): Model->setSource('PERSON')

#4 /var/www/html/modip/cakephp-cakephp-6864406/lib/Cake/Model/Model.php(2483): Model->getDataSource()

#5 /var/www/html/modip/cakephp-cakephp-6864406/lib/Cake/Controller/Component/PaginatorComponent.php(172): Model->find('all', Array)

#6 /var/www/html/modip/cakephp-cakephp-6864406/lib/Cake/Controller/Controller.php(1025): PaginatorComponent->paginate(NULL, Array, Array)

#7 /var/www/html/modip/app/Controller/PersonsController.php(7): Controller->paginate()

#8 [internal function]: PersonsController->index()

#9 /var/www/html/modip/cakephp-cakephp-6864406/lib/Cake/Controller/Controller.php(473): ReflectionMethod->invokeArgs(Object(PersonsController), Array)

#10 /var/www/html/modip/cakephp-cakephp-6864406/lib/Cake/Routing/Dispatcher.php(104): Controller->invokeAction(Object(CakeRequest))

#11 /var/www/html/modip/cakephp-cakephp-6864406/lib/Cake/Routing/Dispatcher.php(86): Dispatcher->_invoke(Object(PersonsController), Object(CakeRequest), Object(CakeResponse))

#12 /var/www/html/modip/app/webroot/index.php(96): Dispatcher->dispatch(Object(CakeRequest), Object(CakeResponse))

#13 {main}

Outside of cakephp I can access it without any problem using

mssql_connect("ip_addr:1433", $user, $pass);

Is there something more I should do?
I've debuged it a bit more and see that it fails in
lib/Cake/Model/Datasource/Database/Sqlserver.php in
public function enabled() {

return in_array('sqlsrv', PDO::getAvailableDrivers());

}

There is no sqlsrv in PDO drivers. If I understand correctly from varius documents,
sqlsrv is for Windows.
How can I use it for linux?
Thanks

A: I was getting this error too, it's pretty misleading. I eventually found out that the user ["username" in your case] did not have the sufficient privileges to access the database ["DB" in your case]

A: There's a "Community Technology Preview" for running the Microsoft SQL Server ODBC Driver, but I don't think it provides the functionality you need. This doesn't seem to integrate with PHP and therefore not with CakePHP.
In fact, I'm pretty certain you need the SQLSRV PHP extension, which is Windows only. You could run the MS SQL database on a Windows machine and make the data available through a script interfacing with the database and hosted on the same machine returning some form of structured output (XML, JSON, etc.). For more complex queries that approach probably won't cut it, so you would likely be looking at a simple REST API implementation.
Have a look at this question as well, there are only two answers, but they contain some interesting links detailing the problem.


text:
Q: Is there priority queue data structure implementation in Ruby's standard library? Does Ruby's standard library have a priority queue implementation?

A: There is also https://rubygems.org/gems/PriorityQueue, which still works 1.9 even though it wasn't changed from 2005.
It works well from what I tried, there is a benchmark, and it is well documented. I might not say that for algorithms's PriorityQueue and Heap (which does not seems to allow to change the key for a given value easily).

A: Just published a ruby extension (in C++) implementing priority queues, it's order of magnitudes faster than ruby based implementations. See https://rubygems.org/gems/priority_queue_cxx.

A: Nope, but there's one in Kanwei Li's Algorithms and Containers GSoC 2008 project.

A: There is a skewheap implementation in RubyGems, if you're interested.

A: There is the long standing rubygem rbtree which provides this type of functionality. It is an implementation of Red-Black Tree.
Additionally, there is a pure ruby implementation rbtree-pure.


text:
Q: What is the best way to upload heavy(around 180mb) XML data to MySQL? My XML format is this
`
<?xml version='1.0' encoding='UTF-8'?>
<XMLResponse>
    <ResponseType>HotelListResponse</ResponseType>
    <RequestInfo>
        <AffiliateCode>JD3622</AffiliateCode>
        <AffRequestId>6</AffRequestId>
        <AffRequestTime>2014-11-04T10:57:31</AffRequestTime>
    </RequestInfo>
    <TotalNumber>148703</TotalNumber>
    <Hotels>
        <Hotel>
            <HotelCode>AD06PQ</HotelCode>
            <OldHotelId>0</OldHotelId>
            <DestinationId>AF6Z</DestinationId>
            <Destination>Andorra La Vella</Destination>
            <Country>Andorra</Country>
            <HotelName>Domus Selecta Hotel Niunit</HotelName>
            <StarRating>4</StarRating>
            <HotelAddress>Ctra General Del Serrat S/n ANDORRA</HotelAddress>
            <HotelPostalCode>AD300</HotelPostalCode>
            <HotelPhoneNumber>+376 735735</HotelPhoneNumber>
            <HotelArea></HotelArea>
            <Chain></Chain>
            <Coordinates>
                <Latitude>42.616516</Latitude>
                <Longitude>1.538348</Longitude>
            </Coordinates>
            <HotelImages>
                <ImageURL>http://image.metglobal.com/hotelimages/AD06PQ/6229360_0x0.jpg</ImageURL>
                <ImageURL>http://image.metglobal.com/hotelimages/AD06PQ/6229381_0x0.JPG</ImageURL>
                <ImageURL>http://image.metglobal.com/hotelimages/AD06PQ/6229348_0x0.jpg</ImageURL>
                <ImageURL>http://image.metglobal.com/hotelimages/AD06PQ/6229349_0x0.jpg</ImageURL>
                <ImageURL>http://image.metglobal.com/hotelimages/AD06PQ/6229351_0x0.jpg</ImageURL>
                <ImageURL>http://image.metglobal.com/hotelimages/AD06PQ/6229352_0x0.JPG</ImageURL>
                <ImageURL>http://image.metglobal.com/hotelimages/AD06PQ/6229353_0x0.JPG</ImageURL>
                <ImageURL>http://image.metglobal.com/hotelimages/AD06PQ/6229354_0x0.jpg</ImageURL>
                <ImageURL>http://image.metglobal.com/hotelimages/AD06PQ/6229355_0x0.jpg</ImageURL>
                <ImageURL>http://image.metglobal.com/hotelimages/AD06PQ/6229356_0x0.JPG</ImageURL>
            </HotelImages>
        </Hotel>
        <Hotel>
            <HotelCode>AD0AT3</HotelCode>
            <OldHotelId>0</OldHotelId>
            <DestinationId>AF6Z</DestinationId>
            <Destination>Andorra La Vella</Destination>
            <Country>Andorra</Country>
            <HotelName>HUSA MOLA PARK</HotelName>
            <StarRating>3</StarRating>
            <HotelAddress>Josep Viladomat, 22 - AD700 Andorra</HotelAddress>
            <HotelPostalCode></HotelPostalCode>
            <HotelPhoneNumber>00376 882000</HotelPhoneNumber>
            <HotelArea></HotelArea>
            <Chain></Chain>
            <Coordinates>
                <Latitude>42.511145</Latitude>
                <Longitude>1.539706</Longitude>
            </Coordinates>
            <HotelImages>
                <ImageURL>http://image.metglobal.com/hotelimages/AD0AT3/5864892_0x0.jpg</ImageURL>
                <ImageURL>http://image.metglobal.com/hotelimages/AD0AT3/5864893_0x0.jpg</ImageURL>
                <ImageURL>http://image.metglobal.com/hotelimages/AD0AT3/5864894_0x0.jpg</ImageURL>
                <ImageURL>http://image.metglobal.com/hotelimages/AD0AT3/5864895_0x0.jpg</ImageURL>
            </HotelImages>
        </Hotel>

And currently I am using the following approach to do this in codeigniter
 function _getXML_Hotellist($fname) {

        $filename = $fname.'.xml';
        $xmlfile='xml/'.$filename;
        $xmlRaw = file_get_contents($xmlfile);
        $xmlData = $this->simplexml->xml_parse($xmlRaw);

        /* database for XMLResponse */

        $result0['ResponseType'] = $xmlData['ResponseType'];
        $result0['AffiliateCode'] = $xmlData['RequestInfo']['AffiliateCode'];
        $result0['AffRequestId'] = $xmlData['RequestInfo']['AffRequestId'];
        $result0['AffRequestTime'] = $xmlData['RequestInfo']['AffRequestTime'];
        $result0['TotalNumber'] = $xmlData['TotalNumber'];

        /* database for Hotel List */

        foreach($xmlData['Hotel'] as $row) {

            $result1['HotelCode']=$this->check_empty($row['HotelCode']);
            $result1['OldHotelId']= $this->check_empty($row['OldHotelId']);

            if(is_array($result1['OldHotelId'])) {
                $result1['OldHotelId']= $result1['OldHotelId'][0];;
            } else {
                $result1['OldHotelId']= $result1['OldHotelId'];
            }

            $result1['DestinationId']= $this->check_empty($row['DestinationId']);
            $result1['Destination']= $this->check_empty($row['Destination']);
            $result1['Country']= $this->check_empty($row['Country']);
            $result1['HotelName']= $this->check_empty($row['HotelName']);
            $result1['StarRating']= $this->check_empty($row['StarRating']);
            $result1['HotelAddress']= $this->check_empty($row['HotelAddress']);
            $result1['HotelPostalCode']= $this->check_empty($row['HotelPostalCode']);
            $result1['HotelPhoneNumber']= $this->check_empty($row['HotelPhoneNumber']);
            $result1['HotelArea']=$this->check_empty($row['HotelArea']);
            $result1['Chain']=$this->check_empty($row['Chain']);

            /* database for Hotels Location */

            $result2['Latitude']=$this->check_empty($row['Coordinates']['Latitude']);
            $result2['Longitude']=$this->check_empty($row['Coordinates']['Longitude']);
            $result2['HotelCode']= $this->check_empty($row['HotelCode']);

            /* database for Hotels Images */

            $result4['HotelCode']= $this->check_empty($row['HotelCode']);
            $result3['ImageURL']=$row['HotelImages']['ImageURL'];

            if(empty($result3['ImageURL'])) {
                $result4['ImageURL']="";
                $this->db->insert('cf_hotel_images',$result4);
            } else {
                if(is_array($result3['ImageURL'])) {
                    foreach($result3['ImageURL'] as $row) {
                        $result4['ImageURL']=$row;
                        $this->db->insert('cf_hotel_images',$result4);
                    }
                 } else {
                     $result4['ImageURL']= $result3['ImageURL'];
                     $this->db->insert('cf_hotel_images',$result4);
                 }
             }

            /* database Queries */

            $this->db->insert('cf_hotel_list',$result1);
            $this->db->insert('cf_coordinates',$result2);
            }

            //$this->db->insert('cf_xml_response',$result0);
    }

This is working but, this is very slow and expires every time and also taking too many hours. so please suggest me some another solution.

A: Insert multiply rows like this:
function _getXML_Hotellist($fname) {
   $resToInsert1 = $resToInsert2 = array();
   $rowsCounter = 0;
   foreach($xmlData['Hotel'] as $row) {
      // fill your $result1 and $result2 arrays
      $resToInsert1[] = $result1;
      $resToInsert2[] = $result2;
      $rowsCounter++;
      if ($rowsCounter == 1000) { // for example, you can choose another number
         // insert to db like a
         //  INSERT INTO table (col1, col2)
         //  VALUES (...),
         //  VALUES (...),
         //  VALUES (...);
         // all data from $resToInsert1 and $resToInsert2
         // and refresh vars
         $resToInsert1 = $resToInsert2 = array();
         $rowsCounter = 0;
      }
   }
}

UPD. Also, if you don't are afraid of losing your data you can use INSERT DELAYED

A: You should convert the data to a file and the upload it to a location . Then , instead of inserting data into the database , insert the url to the file .
Uploading large files is not a good practice . It can cause heavy traffic in your MySQL database


text:
Q: React-Redux: Could not find "store" in the context of "Connect(UploadInternal)" Duplicated Code Sandbox
https://ndg6d.csb.app/
Full Error
Uncaught Error: Could not find "store" in the context of "Connect(UploadInternal)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(UploadInternal) in connect opt.
Situation
Everything was working correctly, then updated react 15.x to 16.13.x, and react-redux from 5.x to 7.2.x, and now the error above occurs on a component several levels deep.
I've checked the ReactRedux Docs and verified I've followed their recommended steps. And I've read all the other similar cases listed here on StackOverflow, but have not resolved the issue. Specifically, a store is passed to a provider that wraps the root app <Provider store={store}><App/></Provider>, and the intermediary components are connected with connect via ReactRedux, so I'm not sure why one of the nested children doesn't have access to the store.
index.js
   const store = configureStore(preloadedState);

    ReactDOM.render((
        <Provider store={store}>
          <MuiThemeProvider muiTheme={getMuiTheme()}>
            <ConnectedRouter history={history}>
              <Route component={App} />
            </ConnectedRouter>
          </MuiThemeProvider>
        </Provider>
      ), document.getElementById('root')
    );

configureStore.js
import {createStore, combineReducers, applyMiddleware, compose} from 'redux';
import rootReducer from '../components/app/reducers';
import thunk from 'redux-thunk';
import { connectRouter, routerMiddleware } from 'connected-react-router'
import createHistory from 'history/createBrowserHistory'
import history from '../history/history'

export default function configureStore(initialState) {

  var middleware;
  var storeEnhancer;
  var store;

  if(initialState){
    middleware = [thunk, routerMiddleware(history)];

    storeEnhancer = compose(
      applyMiddleware(...middleware)
    );

    store =   createStore(
      combineReducers({
        root: rootReducer,
        router: connectRouter(history)
      }),
      initialState,
      applyMiddleware(...middleware)););
  }else{
    middleware = [thunk];
    storeEnhancer = compose(
      applyMiddleware(...middleware)
    );

    store = createStore(
      combineReducers({
        root: rootReducer,
        router: connectRouter(history)
      }),
      applyMiddleware(...middleware)););
  }

    if (module.hot) {
        // Enable Webpack hot module replacement for reducers
        module.hot.accept('../reducers', () => {
            const nextRootReducer = require('../reducers');
            store.replaceReducer(nextRootReducer);
        });
    }

    return store;
}

Child.jsx & NestedChild.jsx (Inside Child.jsx) -- Just the bottom of the files to show the Components are connected:
const mapStateToProps = (state, ownProps) => {

  const {root, ...rest} = state;
  const reduxState = {...root};

  return {
    reduxState
  };
};

const mapDispatchToProps = (dispatch)=>{
  return {dispatch};
};

const mergeProps = (stateProps, dispatchProps, ownProps) => {
  return Object.assign({}, ownProps, stateProps, dispatchProps);
};

const options = {

};

Child_or_NestedChild = connect(mapStateToProps, mapDispatchToProps, mergeProps, options)(Child_or_NestedChild);

export default muiThemeable()(Child_or_NestedChild);


text:
Q: How to know when to tune up a digital multimeter? I have bought the multimeter with temperature measurement from the following website:
http://futurlec.com/Multimeters.shtml
Currently I use the voltage, resistance, and short circuit detection functions on it.
The short circuit detection function works fine. but now when I measure high resistance values over 100K, the results are inaccurate. For example, the 560K resistor was measured at 408 instead of 560 on the meter (I turned the knob to the 2000K setting). When I measured a 1K resistor, the meter reported 0.8 instead of 1.0 on the 200K setting.
All resistors measured were carbon film 1/4 watt with 5% tolerance.
One time when I opened up a multimeter to replace the battery, I noticed it had a fuse and a potentiometer as part of its circuit.
Would adjusting the potentiometer fix this issue? I mean the low battery symbol never appeared on the meter so I don't know if battery is an issue. Could I hack the meter somehow and measure something that could give me an indication if the battery is dying?

A: For the 560k resistor reading, if you had your fingers touching both probes, you body resistance would be in parallel with the resistor, so would lower the meter reading. This effect would be insignificant with a 1k resistor, however.

A:
When I measured a 1K resistor, the meter reported 0.8 instead of 1.0 on the 200K setting.

That's an error of \$ \frac {0.2}{200} = 0.1\% \$ of full scale on that range. That's much better than might be expected on such an instrument.
For accuracy you should always make your measurements on the lowest range that will accommodate the value being measured. If unsure what to expect then start on the highest range and work down so that you minimise the chance of applying an over-voltage to the electronics. (This isn't important on the resistance measurement ranges as the meter itself is the voltage source.)
You don't know what the potentiometer is for so don't mess with it. You don't have any reference to measure from anyway.

A: If all of the other ranges are reading correctly, you have a bad resistor which sets the gain for that particular range. Without a schematic, there is no way to tell which it is, and I'm assuming it's a SMD part anyways. So, no, the pot won't fix the problem - or if it does it will cause all the OTHER ranges to be wrong. The problem is probably fixable, but not without both knowing what you're doing and having access to documentation.
Generally, unless you're just in it for the experience, you're better off either just not using that scale or trashing the meter - DMMs are dirt cheap these days, so why put up with the hassle?


text:
Q: Index pdf documents in Solr from C# client Basically I'm trying to index word or pdf documents in Solr and found the ExtractingRequestHandler, but can't figure out how to write code in c# that performs the HTTP POST request like in the Solr wiki: http://wiki.apache.org/solr/ExtractingRequestHandler.
I've installed Solr 3.4 on Tomcat 7 (7.0.22) using the files from the example/solr directory in the Solr zip and I haven't altered anything. The ExtractingRequestHandler should be configured out of the box in the solrconfig.xml and ready to use, right?
Can some of you give an C# (HttpWebRequest) example of how you make the HTTP POST request and upload a PDF file like it is done using curl in the Solr wiki?
I've look all over this site and many others trying to find an example or a tutorial on how this is done, but haven't found anything.
EDIT:
I finally managed to get it to work using SolrNet!
In order for it to work you need to copy this to a lib-folder in your Solr installation directory from the Solr zip:

*

*apache-solr-cell-3.4.0.jar file from the dist folder

*content of contrib\extraction\lib directory

With SolrNet 0.4.0 beta 2, this code does the job:
Startup.Init<IndexDocument>("YOUR-SOLR-SERVICE-PATH");
var solr = ServiceLocator.Current.GetInstance<ISolrOperations<IndexDocument>>();

using (FileStream fileStream = File.OpenRead("FILE-PATH-FOR-THE-FILE-TO-BE-INDEXED"))
{
    var response =
        solr.Extract(
            new ExtractParameters(fileStream, "doc1")
            {
                ExtractFormat = ExtractFormat.Text,
                ExtractOnly = false
            });
}

solr.Commit();

Sorry for the trouble. I hope however that others will find this useful.

A: I would recommend using the SolrNet client. It supports the ExtractingRequestHandler.


text:
Q: jQuery UI Sortable events - click and send to the end I need help with jQuery UI Sortable script.
How can i send an item to the last item on the list?

        First

x

        Second

x

        Third

x

        Fourth

x

My JS:
$(document).on('click', '#drag div', function(e) {

    var item = $(this).closest('li');

    // Send `item` to the end of list...

});

How can I do that ?

A: This should do the trick
$('#drag').sortable();

$(document).on('click', '#drag div', function (e) {
    $(this).parent().appendTo('#drag');
});

http://jsfiddle.net/7PDav/
You basically take and re-append the clicked item. The append will put it at the end.


text:
Q: Carregar imagem aleatória no background-image usando css É possível usando apenas css, fazer o carregamento de imagens aleatórias na propriedade background-image de um elemento qualquer?
Por exemplo tenho uma section
<section id="slide">

</section>

E tenho uma pasta chamada img que contém 5 arquivos
background-1-img.png
background-2-img.png
background-3-img.png
background-4-img.png
background-5-img.png

Toda vez que fosse carregada a página que contém essa section, uma das imagens desse diretório deveria ser setada na propriedade background-image da section de maneira aleatória.
A minha dúvida é, posso fazer isso só com CSS, ou precisarei do JavaScript para isso?


text:
Q: How do I seed Identity roles in ASP.NET Core 2.2 using Script-Migration? I'm using migrations to create and seed my database. Since my database is running on a separate server from my web application, I'm using Script-Migration to generate a script that I can run on the database server.
According to the official EF Core Docs, we can use HasData to configure seed data for our entities. Is there a way to do this with Identity roles or users?

A: For seeding data by HasData, it is usually used for your own defined model.
For seeding data for IdentityUser or IdentityRole, it is recommended to use UserManager<IdentityUser> and RoleManager<IdentityRole>. This is due to that there are many properties may not set correctly by HasData like PasswordHash and ConcurrencyStamp.
Check this issue How to seed the ASP.NET Identity model, and related seeding questions #736

A: You can do it in OnModelCreating() method. Note that keys have to be predefined to avoid seeding new roles everytime the method is executed. Below code will create a new user and a new role, and associate the role to the user:
protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        base.OnModelCreating(modelBuilder);

        //Seeding a  'Administrator' role to AspNetRoles table
        modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole {Id = "2c5e174e-3b0e-446f-86af-483d56fd7210", Name = "Administrator", NormalizedName = "ADMINISTRATOR".ToUpper() });

        //a hasher to hash the password before seeding the user to the db
        var hasher = new PasswordHasher<IdentityUser>();

        //Seeding the User to AspNetUsers table
        modelBuilder.Entity<IdentityUser>().HasData(
            new IdentityUser
            {
                Id = "8e445865-a24d-4543-a6c6-9443d048cdb9", // primary key
                UserName = "myuser",
                NormalizedUserName = "MYUSER",
                PasswordHash = hasher.HashPassword(null, "Pa$$w0rd")
            }
        );

        //Seeding the relation between our user and role to AspNetUserRoles table
        modelBuilder.Entity<IdentityUserRole<string>>().HasData(
            new IdentityUserRole<string>
            {
                RoleId = "2c5e174e-3b0e-446f-86af-483d56fd7210",
                UserId = "8e445865-a24d-4543-a6c6-9443d048cdb9"
            }
        );

    }


text:
Q: Flutter DropdownButtonFormField does not show in Row I am adding a DropdownFormField and TextFormField side by side inside a Row. This is what the build function looks like
Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                DropdownButton(
                  hint: new Text('Select Gender'),
                  items: _salutations,
                  value: client.salutation,
                ),
                SizedBox(width: 20),
                new Expanded(
                  child: TextFormField(
                    decoration: InputDecoration(labelText: 'Name'),
                    validator: (value) {
                      return value.isEmpty ? 'Empty name.' : '';
                    },
                  ),
                ),
              ]
            )
          ],
        )
      ),
    );
  }

That code currently shows because it is DropdownButton. But if I change it to DropdownButtonFormField it won't show, as long as it is in the Row(). Why is this?
I wish to use DropdownButtonFormField so that the height of the Dropdown will be the same as the TextFormField since the current code shows the dropdown with a smaller height.

A: Try out like this,
List<String> valueList = ['A', 'B', 'C', 'D'];

  String _value = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Container(
                    height: 50.0,
                    width: 100.0,
                    child: new DropdownButtonFormField<String>(
                      hint: new Text('Select'),
                      items: valueList.map((String value) {
                        return new DropdownMenuItem<String>(
                          value: value,
                          child: new Text(value),
                        );
                      }).toList(),
                    ),
                  ),
                  SizedBox(width: 20),
                  new Expanded(
                    child: Container(
                      height: 50.0,
                      child: TextFormField(
                        decoration: InputDecoration(labelText: 'Name'),
                        validator: (value) {
                          return value.isEmpty ? 'Empty name.' : '';
                        },
                      ),
                    ),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

DropdownButtonFormField must have a width inside Row so wrap it inside a Container and set width for that Container
Hope this could help..


text:
Q: JavaFX application won't compile in NetBeans IDE 8.1 I am trying to run this application in which I used event-handling and it won't compile and won't show anything. I am currently using NetBeans 8.1. What is that I did wrong. Also it is not showing any errors.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class event extends Application {

public void start(Stage primaryStage)
{
   HBox pane = new HBox();
   pane.setAlignment(Pos.CENTER);
   Button btOk = new Button("OK");
   Button btCancel = new Button("Cancel");
   OkHandlerClass handler1 = new OkHandlerClass();
   btOk.setOnAction(handler1);
   CancelHandlerClass handler2 = new CancelHandlerClass();
   pane.getChildren().addAll(btOk, btCancel);

   Scene scene = new Scene(pane);
   primaryStage.setTitle("Handle the fucking event");
   primaryStage.setScene(scene);
   primaryStage.show();
 }

 class OkHandlerClass implements EventHandler<ActionEvent>{
    public void handle(ActionEvent e) {
        System.out.println("OK button clicked");
    }
 }
 class CancelHandlerClass implements EventHandler<ActionEvent>{

    public void handle(ActionEvent event) {
       System.out.println("Cancel button clicked");
    }

 }

 public static void main(String[] args) {
    launch(args);
 }

 }


text:
Q: Please explain the definition of cyclic groups etc. From my teacher's notes: "We say that a subset $S\subseteq G$ generates $G$ is any element $a\in G$ is the result of finite compositions of elements in $S$ or their inverses. A group $G$ is called cyclic if there exists an element $a\in G$ that generates $G$."
I still don't quite understand the definition of "generate", "finite compositions" and "cyclic" after reading the paragraphs. please help.

A: Perhaps a few examples will clarify. Let $S = \{a,b,c\} \subseteq G$.
$abac$ is a finite composition of elements of $S$. Here, "composition" is just another word for the group operation, maybe you also call it "multiplication. Finite means exactly what you think it does. This is a finite composition because it is a composition of finite things. Other examples include $a$, $bbb$, $abcbabbaca$.
We're not just using elements of $S$, we're including "...elements in $S$ or their inverses." So we also allow $\{a^{-1},b^{-1},c^{-1}\}$ in our finite compositions. So now we are allowed for instance $ab^{-1}cb^{-1}abb^{-1}aca^{-1}$.
Thus, $S \subseteq G$ generates $G$ if every element of $G$ can be written in the way just described.
A special case of this is when $S = \{a\}$, in which case $G$ is just all powers of $a$: $G = \{\ldots, a^{-2},a^{-1},e=a^0,a^1,a^2,\ldots\}$ (note that $a$ might have finite order, so $G$ might still be finite.) In this case, we say $G$ is cyclic.
Edit: As mentioned by a comment, "$a$ has finite order" means that there is some $n \in \mathbb{N}$ so that $a^n=e$. In particular, this mean $a^{n+1}=a$. Then $G$ (from above) can be written as
\begin{align}
G &= \{\ldots,a^{-2}, a^{-1},e=a^0,a^1,a^2,\ldots, a^{n-1},a^n=e,a^{n+1}=a,\ldots\} \\
&=\{\ldots,a^{-2},a^{-1},e,a,a^2,\ldots,a^{n-2},a^{n-1},e,a,a^2,\ldots \}
\end{align}
After $n$ elements, the list repeats, or "cycles." Because sets don't see repitition, we may rewrite as
$$G = \{e,a,a^2,\ldots, a^{n-2},a^{n-1}\}$$
Hence, $G$ is finite.

A: As explained in another answer, a subset $S$ of a group $G$ generates $G$ if every element of $G$ is a finite product of elements of $S$ or their inverses. Let me elaborate on why that is the definition, since this idea of "generation" appears in many other contexts.
If $S \subseteq G$, we can define the subgroup of $G$ generated by $S$, denoted $\langle S \rangle$; once we define this, then $G$ is generated by $S$ precisely if the subgroup of $G$ generated by $S$ is in fact all of $G$ (i.e. if $\langle S \rangle = G$). So how do we define the subgroup of $G$ generated by $S$? It's the smallest subgroup of $G$ which contains every element of $S$. That is, it contains $S$, along with the minimum amount of other stuff we need to include in order to have a subgroup of $G$. It is a subgroup of $G$ containing $S$, and there is no other subgroup $H$ such that $S \subseteq H \trianglelefteq \langle S \rangle$.
So what is the "minimum amount of other stuff" we need to add to $S$ in order to make it into a subgroup of $G$? Well, subgroups are closed under taking inverses, so had better include the inverse of every element of $S$. Subgroups are also closed under multiplication (i.e. the group operation of $G$), so along with elements of $S$ and their inverses, we also need to include all finite products of elements of $S$ and their inverses. This is enough though; we have obtained a subgroup. Notice that it's closed under multiplication; using the example $S = \{a, b, c\}$, if $abcca^{-1}b$ and $cb^{-1}a^{-1}b$ are two finite products of elements of $S$ and their inverses, their product $abcca^{-1}bcb^{-1}a^{-1}b$ is also a finite product of elements of $S$ and their inverses! It's also closed under taking inverses; for example, the inverse of $cb^{-1}a^{-1}b$ is $b^{-1}abc^{-1}$ (which again is a finite product of elements of $S$ and their inverses). In summary, we have produced $\langle S \rangle$ by adding to $S$ only the things we need to make it a subgroup.
Lastly, let me briefly describe how this idea generalizes to other contexts. In linear algebra, the subspace $\langle S \rangle$ of a vector space $V$ spanned by $S$ of vectors is the smallest subspace of $V$ containing $S$. The details are different here, since vector spaces are different than groups ($\langle S \rangle$ comprises all linear combinations of finite subsets of $S$), but the core idea is the same. In ring theory, the ideal generated by a subset of a ring is the smallest ideal containing the subset. In topology (or in the study of metric spaces), the closure of a set $A$ is the smallest closed set containing $A$; it is, if you like, the "closed set generated by $A$."