text:
Q: How to pass params from one action to another I need to pass all the params of one action to another, is this possibe?
def action1
  billing_id = params["billing_id"]
  # many more param values here....

  perform_transaction(billing_id)
end

def action2
  if params["hello"].nil?
    return action1
  end
  ...
end

Is it possible for me to somehow pass all the params when I call
return action1

I am calling the 1st action from the 2nd action, and I need all the param values passes also.

A: The params will be available to all the actions in your controller by default.
Update:
You can learn more about how params end up in controller actions from the following link:
https://medium.com/launch-school/params-in-rails-where-do-they-come-from-b172cdb46eb4

A: All action methods in a Rails controller have access to all the params.


text:
Q: the differences of install software in linux For me, I know three ways to install software in ubuntu.
First is "apt-get install",
next is "dpkg",
the last is "./configure, sudo make ,sudo make install".
But could anyone tell me the differences of these three ways?

A: apt-get
apt-get install will download and install software from the repositories you currently have enabled.  These, by default, usually include your distro's (Ubuntu in this case) online software repositories.
However, you may have various third-party repos added to your list of repositories that it will also check.
The advantages to this method is that it is easy to upgrade and remove software packages with a single command and all of your software comes from trusted sources.
The major disadvantage is that certain software you may want to install may not be available through your distro's repositories.
dpkg
dpkg -i is similar to apt-get install except that instead of looking for software online, it requires the DEB package you wish to install to already be located in an accessible location in the file system.
The advantage to this method is that once the package is installed, it can be removed via apt-get, just like a package that you used apt-get to install.  Also, DEB files for software you want may be available online via downloadable DEB files, but not in any repository.
The disadvantages are that most software installed via this method cannot be updated automatically, you must download and install any updated manually the same way you installed the initial package, and packages downloaded as individual DEB files can be dangerous and are inherently less trustworthy compared to those downloaded via a trusted repository.
sudo make install
sudo make install is often the last recourse for people who want software that is unavailable in a prepackaged format for their system.  This is the most dangerous way to install software.  When you run this command, the Make script has access to your entire file system and can add or remove files anywhere it thinks is necessary.  This might just work, but there's also a chance that files will end up in places that are inappropriate for your distro.
When the maintainers of your distro package software for use via your distro's repositories, they will often tweak the build scripts to place files in different places or look for dependencies in different places.
sudo make install is recommended for experts only.  The only time you'd want to do this is when you absolutely need the bleeding edge version of a software package or when you have no other choice.
The disadvantages are numerous.  This is an inherently unsafe operation, so make sure you trust the software package.  Whereas apt-get and dpkg will check for dependencies, you need to make sure you have the dependencies for software when you're building it yourself.  Also, if the software you're trying to install conflicts with an installed package, you will get no warning, whereas apt-get and dpkg will warn you of conflicts.  Finally, you can't use apt-get or dpkg to uninstall programs installed via sudo make install.  If you want to uninstall one of these programs, you'd better hope the person who made it included an uninstall target in their build script.  If not, you'll have to manually hunt for and remove all the files the build script added to your system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to "extend" factory methods when extending class with companion object with factory methods Say you have a class Foo, which is an abstraction over some kind of text file, and a companion object with factory methods that simplifies creation of Foo:
class Foo(val lines : Seq[String], filePath : String) { ... }

object Foo {
  def apply(file : File) : Foo = { new Foo(scala.io.Source.fromFile(file, "ISO-8859-1").mkString.split("\n").toList, file.getPath }
  def apply(file : String) : Foo = { apply(new File(file) }
}

What happens when you want to extend Foo as Bar and Baz, if both subclasses need to have the same factory methods?  You don't want to copy the companion object Foo as companion object Bar and companion object Baz, so what is the right way of making the factory methods "generic"?

A: You could do the following:
trait FooFactory[T <: Foo] {
   def apply(file : File) : T = //to be implement in your Baz and Bar class
   def apply(file : String) : T = { apply(new File(file) }   //shared method, no need to implement in subclassing classes

}

//example for Bar implementation------------------------------

class Bar extends Foo {
     // any specific Bar code here
}

object Bar extends FooFactory[Bar] {
  def apply(file : File) : Bar = { new Bar(scala.io.Source.fromFile(file, "ISO-8859-1").mkString.split("\n").toList, file.getPath }
}


text:
Q: UIReferenceLibraryViewController with Japanese-English dictionary causes app to freeze for certain words On an iPhone X running iOS 11.4.1, built with Xcode 9.4.1, the following code causes the app to become completely unresponsive:
let dictionaryVC = UIReferenceLibraryViewController(term: "mundane")
self.present(dictionaryVC, animated: true, completion: nil)

This occurs when the Japanese-English dictionary is installed.
If the Japanese-English dictionary is the only dictionary installed, the initial definition screen is shown, but pressing the back 'Dictionary' button on that screen causes the app to become unresponsive.
If the Japanese-English dictionary plus one or more other dictionaries are installed, the definition screen is not shown at all, and the app becomes unresponsive.
I have created a project to illustrate the problem: https://github.com/Paludis/A-Mundane-Problem
Unless I'm missing something this seems to be a bug on Apple's end?

A: Looks like this was fixed in iOS 12.


text:
Q: Loading a dll with LoadLibraryA and then reading variables inside of it I've looked around, and gotten to the point where I can load a DLL and use GetProcAddress() to find the address of an exported function. The part I'm stuck on is when I print out the address of the function, I get a ton of 0s (this many to be exact: 0000000000000000). In the end, I'm trying to read the name of a char that's in there.
.hpp file:
typedef char* (*t_Username)();

extern t_Username GetUsername;

I'm not really sure what this does since I got it from a "base", if you will.
.cpp file:
t_Username GetUsername;

std::string test = "";

int main()
{
    auto dll = LoadLibraryA("DLL.dll");

    GetUsername = (t_Username)GetProcAddress(ORACLE, "GetUsername");

    std::cout << GetUsername;

    test = "Hello " + std::string(GetUsername());

    std::cout << test;
}

My DLL:
#include "pch.h"
#include <iostream>

void onAttach() {
    const char* GetUsername = "whatever.f";
    std::cout << GetUsername << std::endl;
    Sleep(100000000000);
}

BOOL WINAPI DllMain(
    HINSTANCE hInstDll,
    DWORD dwReason,
    LPVOID lpReserved)
{
    switch (dwReason) {
    case DLL_PROCESS_ATTACH:
        DisableThreadLibraryCalls(hInstDll);
        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)onAttach, 0, 0, 0);
        break;
    default:
        return FALSE;
        break;
    }
    return TRUE;
}

Before I added the char to the void, I had it print a word, and that worked fine.


text:
Q: How to find index for time, lat, lon for particular variable point in xarray I have the following netcdf file opened as an xarray dataset, which contains monthly values of precipitation. Here is what the dataset (ds3) looks like:

I would like to isolate values above a certain threshold and return the indices for each value. For example:
outliers = ds3.where(ds3.tp > 0.08, drop=True)

for x in outliers.tp:
    print(x)

When I loop through the outliers, it gives me the information for each 'tp' value, but I need the associated indices.
For example, taking the one tp value of 0.08361223 (in the image above) I would like to return the time_index (index for 1981-03-01), lat_index (index for 8.25) and lon_index (index for 38.25).
I am new to netcdf files and python and would appreciate any guidance.

A: You could write something like :
ds3['tp'].where(ds3['tp'] > 0.08, drop=True).to_dataframe().dropna().reset_index()

It would give a pandas DataFrame with the values you want with its associated coordinates. In order to have the integer indexes associated, you may write :
df = ds3['tp'].where(ds3['tp'] > 0.08, drop=True).to_dataframe().dropna().reset_index()
for c in ds3.indexes:
    df[c] = df[c].apply(lambda v: list(ds3[c].values).index(v))

It's not very elegant, but works.


text:
Q: Delete lines of text until new blank line reached I'm looking for a way of removing all text in a file up until a new blank line is reached.  For example:
Line 1
Line 2

Line 3
Line 4
Line 5

Should end up looking like:
Line 3
Line 4
Line 5

Thanks in advance.

A: You can use awk and test for 0 fields. (it will also work if line has just spaces or tab, count as blank)
awk 't;NF==0 {t=1}' file
Line 3
Line 4
Line 5

t; print line if its true
NF==0 test for number of fields=0
If 0 fields, set t=1
Can be shorten some:
awk 't;!NF{t=1}' file

A: This might work for you (GNU sed):
sed '0,/^$/d' file

Delete all lines from line 1 until an empty line. This is GNU specific n.b. 1,/^$/d fill not include line 1 and so if line 1 were empty and the remainder of the file had non-empty lines, the whole of the file would be deleted.
Alternative, for all seds:
sed -n '/^$/{:a;n;p;ba}' file

Turn off automatic printing -n option. Only print lines following the first empty line to the end of file.


text:
Q: Named pipes, file descriptors and EOF Two windows, same user, with bash prompts.  In window-1 type:
$ mkfifo f; exec <f

So bash is now attempting to read from file descriptor 0, which is mapped to named pipe f. In window-2 type:
$ echo ls > f

Now window-1 prints an ls and then the shell dies.  Why?
Next experiment: open window-1 again with exec <f.  In window-2 type:
$ exec 3>f
$ echo ls >&3

After the first line above, window-1 wakes up and prints a prompt.  Why?  After the second line above, window-1 prints the ls output and the shell stays alive.  Why?  In fact, now in window-2, echo ls > f does not close the window-1 shell.
The answer must have to do with the existence of the file descriptor 3 from window-2 referencing the named pipe?!

A: There's not much to it: when there are no writers to the pipe, it looks closed to readers, i.e. returns EOF when read and blocks when opened.
From the Linux man page (pipe(7), but see also fifo(7)):

If all file descriptors referring to the write end of a pipe have
         been closed, then an attempt to read(2) from the pipe will see end-
         of-file (read(2) will return 0).

Closing the write end is what implicitly happens at the end of the the echo ls >f, and as you say, in the other case, the file descriptor is kept open.

A: After reading the two answers from @Kusalananda and @ikkachu, I think I understand.  In window-1, the shell is waiting for something to both open the write end of the pipe and then close it.  Once the write end is opened, the shell in window-1 prints a prompt.  Once the write end is closed, the shell gets EOF and dies.
On the window-2 side we have the two situations described in my question: in the first situation with echo ls > f, there is no file descriptor 3, so we have echo spawning, and its stdin and stdout look like this:
0 --> tty
1 --> f

Then echo terminates and the shell closes both descriptors. Since file descriptor 1 is closed and references f, the write end of f is closed and that causes an EOF to window-1.
In the second situation, we run exec 3>f in our shell, causing the shell to take this environment:
bash:
0 --> tty
1 --> tty
2 --> tty
3 --> f

Now we run echo ls >& 3 and the shell allocates file descriptors for echo as follows:
echo:
0 --> tty
1 --> f     # because 3 points to f
2 --> tty

Then the shell closes the three descriptors above, including f, but f still has a reference to it from the shell itself.  This is the important difference.  Closing descriptor 3 with exec 3>&- would close the last open reference and cause an EOF to window-1, as @Kusalananda noted.

A: It has to do with the closing of the file descriptor.
In your first example, echo writes to its standard output stream which the shell opens to connect it with f, and when it terminates, its descriptor is closed (by the shell).  On the receiving end, the shell, which reads input from its standard input stream (connected to f) reads ls, runs ls and then terminates due to the end-of-file condition on its standard input.
The end-of-file condition occurs because all writers to the named pipe (only one in this example) have closed their end of the pipe.
In your second example, exec 3>f opens file descriptor 3 for writing to f, then echo writes ls to it. It's the shell that now has the file descriptor opened, not the echo command. The descriptor remains open until you do exec 3>&-.  On the receiving end, the shell, which reads input from its standard input stream (connected to f) reads ls, runs ls and then waits for more input (since the stream is still open).
The stream remains open because all writers to it (the shell, via exec 3>f, and echo) have not closed their end of the pipe (exec 3>f is still in effect).

I have written about echo above as if it was an external command. It's most likely is built into the shell. The effect is the same nonetheless.


text:
Q: Force return with a specific value while debugging in Eclipse CDT I'm debugging some C++ code in Eclipse configured with a MinGW gdb configuration.
When running gdb directly in a shell, I can return from a function immediately, and tell it what value the function should return, with for example return 3.
How do I do that while debugging in Eclipse rather than running gdb outside of Eclipse in a shell window?

A: Eclipse CDT does not provide that feature in the UI with a button or similar. Feel free to enter a feature request, or even better a patch.
However, you can of type return 3 in the GDB input console in CDT without having to leave the Eclipse environment. Here are some instructions I wrote for a related (but not duplicate) question that shows you how to use the console.
Console
The console view allows you to enter GDB commands in standard GDB syntax.
To use the Console:

*

*Select the gdb item in the Debug View

*The Console view will now display the interface to GDB:

*Type commands to GDB, e.g. print i + j or p i - j (p is short for print):

Other Hints when using the Console

*

*You can "pin" the console so that it stays the selected console top with this button on the toolbar:

*You can switch console with this drop-down:

*

*You can open a second console, e.g. one for GDB interaction and one for output of your program with this button:


text:
Q: Can someone explain this source code for balanced partitioning? Can someone please explain this code in detail? I've tried debugging it but i can't figure out how it produces the result. I've been searching for a solution for the problem and this is the code that I stumbled upon, it produces accurate solutions and I would like to know how it works. Many thanks.
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
using namespace std;

int BalancedPartition ( int a[] , int n ){

int sum = 0;
for( int i = 0 ; i < n ; i++)
    sum += a[i];

int *s = new int[sum+1];

s[0] = 1;
for(int i = 1 ; i < sum+1 ; i++)    s[i] = 0;

int diff = INT_MAX , ans;

for(int i = 0 ; i < n ; i++)
{
    for(int j = sum ; j >= a[i] ; j--)
    {
        s[j] = s[j] | s[j-a[i]];
        if( s[j] == 1 )
        {
            if( diff > abs( sum/2 - j) )
            {
                diff = abs( sum/2 - j );
                ans = j;
            }

        }
    }
}
return sum-ans-ans;
}

int main()
{
    int n,result, arr[300];
    cin >>n;
    for(int i = 0; i < n; i++)
    {
        cin>>arr[i];
}
result = BalancedPartition(arr,n);
cout <<abs(result); // The difference between the sums of the two subsets

return 0;
}

A: The function BalancedPartition first computes the summation of the elements of the array a and stores it in sum. It then allocates an array s that is indexed by possible subset summation values. It serves as a bookkeeping structure that tracks the progress of the inner for loop. If s[j] is 1, it means the value j has been processed, where the value j represents the summation of some subset of elements in the array a. Initially, only s[0] is set to 1, which corresponds to the sum of no elements (the empty subset). diff is used to compute the subset with the summation closest to one half the value of sum, and this subset summation value is stored in ans. Once ans is correctly computed, the value returned is the difference between the summation of the elements not used in ans and ans itself, that is, (sum - ans) - ans. So, what's left is the double for loop, to see how it correctly arrives at diff and ans.
The outer for loop iterates i through all the indexes of the array a. The inner loop iterates j through all possible subset summation values, starting with sum. However, it only recognizes a subset summation value if the value is derivable from a previously recognized subset sum. That is, for any given iteration of j, s[j] becomes 1 only if s[j - a[i]] is 1. Since initially only the empty subset is recognized, the first iteration only recognizes s[a[0]]. The second iteration recognizes s[a[1]] and s[a[0]+a[1]]. The third iteration recognizes s[a[2]], s[a[0]+a[2]], s[a[1]+a[2]] and s[a[0]+a[1]+a[2]]. If you recognize the pattern, you can formulate an inductive argument for the correctness of the algorithm.


text:
Q: python time complexity quick sort algorithm def partition(A, l, r):
    p = A[l]
    stack = A[l]
    A[l] = A[r]
    A[r] = stack
    s = l

    for i in range(l, r):

        if A[i] <= p:

            stack2 = A[i]
            A[i] = A[s]
            A[s] = stack2
            s += 1

    stack3 = A[s]
    A[s] = A[r]
    A[r] = stack3

    return s

def quicksort(A, l, r):

    if l < r:

        q = partition(A, l, r)
        quicksort(A, l, q - 1)
        quicksort(A, q + 1, r)
    return A

I've written "maybe" quicksort algorithm, as I've noticed here the time complexity of partition was O(n) because of the for loop, Also the complexity in quicksort seems to be at least O(n). The question: how is it possible for the entire code to have total time complexity of O(nlogn).

A: Your sorting function isn't O(nlogn). In the worst case, you are making O(n) recursive calls.
As a simple test:
def test(n):
    nums = list(reversed(range(n)))
    return sum(quicksort(nums,0,n-1))

Then, for example, test(1100) triggers:
RecursionError: maximum recursion depth exceeded in comparison

Which wouldn't happen if you were calling partition just log(n) times.
On the other hand,
import random

def test2(n):
    nums = list(range(n))
    random.shuffle(nums)
    return sum(quicksort(nums,0,n-1))

works well even for calls like test2(100000), so you do have average case O(nlogn) complexity. This is easy to confirm numerically but difficult to prove. See https://en.wikipedia.org/wiki/Quicksort for a proof.

A: You partition by 2 each level till you get individual elements. Partitioning and comparison what makes the time complexity. You make n comparisons in each level and you will be partioning log2(n) times.

In the worst case, your array is already sorted and you will be partitioning n times and still make n comparisons in each level.


text:
Q: Prove that if $T \in \mathcal{L}(X,Y)$ and $X$ is reflexive, then $T$ is weakly compact Let be $X,Y$ Banach spaces and we denote $B_X, B_Y$ the respective closed balls. Let be
\begin{equation*}
\mathcal{L}(X,Y) = \{T: X \rightarrow Y : \text{linear and continuous in norm}\}
\end{equation*}
We say $T\in \mathcal{L}(X,Y)$ is compact if the clausure of $T(B_X)$ is compact (in norm) in $Y$. We say $T$ is weakly compact if the clausure of $T(B_X)$ is weakly compact in $Y$. I have to prove that if $T\in \mathcal{L}(X,Y)$ and $X$ is a reflexive space, then $T$ is weakly compact. I have just proved that in this hypothesis for all bounded sequence $x_n \in X$, there exists a subsequence $x_{n_k}$ such that $T(x_{n_k})$ is weakly convergent in $Y$.
¿Could anyone help me?


text:
Q: Android Maps gives blank (black screen) with device plugged in via usb I worked all day yesterday on getting Maps v2 to work on my setup so that I can do a project I want to do that will require maps, but no matter what I did I got an immediate message of "Unfortunately the app has stopped" when I emailed the apk to myself and installed it by clicking it on my phone itself.
Today I tried to use the method of installing the usb driver Samsung provides for using your phone to connect via usb while debugging in Eclipse.  The device shows up correctly in the DDMS list and I am able to select it and it shows connected with no warnings or errors.  But when I try to run the map test project I put together it just gives a black screen and I can't see any hint of errors or warnings in the console or logcat. I thought it might be my device not showing up correctly in Eclipse, so I tested another simple app project that is basically just a "hellow world" level project and it showed up on my phone correctly.
Just to demonstrate that I have been researching the project I have tried several versions of the following:
 1) I have been through the process of generating api key several times
 2) I have added the required permissions to my manifest
 3) I have added the  tag just above the  tag with the maps info and my api key
 4) I have tried 3 or 4 different example map apps from textbooks and online tutorials I found and all give the same result.
The most I have gotten to happen so far was to get a screen for the google map to show up but it just had a grid and no map (I thought that was due to bad key so I created a new one but it then went back to sorry app stopped message).  But now when I try the debug with device plugged in via usb approach I get just a black screen.
(added as ps.)
I do have a related question that involves the keystores in Eclipse.  When I first started yesterday I would use the manifest xml page's Export Wizard to export an apk file using a keystore I have previously created.  It caught my attention that in the file screen when it has you pick a file name for the apk file it would display the key value connected with the apk's certificate.  This was different then the debug key value that shows up when you use the keytool tool or when you look under Window/Preferences/Android.  I took this additional key value and added it to the allowed devices for the apikey in my google api console.  But it did not help.  Any thoughts on this?  thanks.  (Since I am now using my device directly connected via usb to debug this should not now be a factor but was curious to understand this).
(addes as ps.)
One thing I have noticed in the different examples I have tried is that one of them had me add  to the manifest inside  tag but none of the other examples did. curious to hear thoughts on that
Any help would be appreciated.  I feel like I have exhausted my ability to figure this out.
Thanks

A: I was able to figure out my issue by doing something similar to Chris Stratton's comment.  I added the following code that I found on the google android pages and it prints out in the logcat the correct key value and I was then able to figure out my issues from there:
    // Add code to print out the key hash
    try {
        PackageInfo info = getPackageManager().getPackageInfo("com.mycompany.mypackage",
PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }


text:
Q: Why did the dependencies override not work as expect in flutter? I want to force my project to use hooks_riverpod version 1.0.0-dev.6, so I specify the dependency in pubspect.yaml like this:
dependencies:
  hooks_riverpod: 1.0.0-dev.6
dependency_overrides:
  hooks_riverpod: 1.0.0-dev.6

but when I compile the project, the dependencies still using another version 1.0.0-dev.10:
../../../.pub-cache/hosted/pub.dartlang.org/riverpod-1.0.0-dev.10/lib/src/async_value_converters.dart:223:39: Error: The method 'ignore' isn't defined for the class 'Future<State>'.
 - 'Future' is from 'dart:async'.
Try correcting the name to the name of an existing method, or defining a method named 'ignore'.
            loadingCompleter!.future..ignore(),

am I missing something? what should I do to force the flutter dependencies using version 1.0.0-dev.6? BTW, I already running flutter update/upgrade/outdate for many times. I also tried to delete pub-cache folder and redownload the dependencies package. I found the .packages file always auto generate this line :
riverpod:file:///Users/dolphin/.pub-cache/hosted/pub.dartlang.org/riverpod-1.0.0-dev.10/lib/

this is my flutter version info:
$ ~/apps/flutter/bin/flutter doctor                                                                                ‹ruby-2.7.2›
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.2.3, on macOS 11.2.3 20D91 darwin-x64, locale en-CN)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[!] Android Studio (version 2020.3)
    ✗ Unable to find bundled Java version.
[✓] IntelliJ IDEA Ultimate Edition (version 2021.2.2)
[✓] VS Code (version 1.60.2)
[✓] Connected device (3 available)
    ! Error: xiaoqiang 的 iPhone is not connected. Xcode will continue when xiaoqiang 的 iPhone is connected. (code -13)

! Doctor found issues in 1 category.
(base)


text:
Q: Is it possible to get the URL of the closed browser tab using c#? i've tried manipulating it using Process.GetProcessesByName("firefox"). But i can only detect the opening and closing of the browser.
-can somebody help me to detect the when the tabs in the browser are closed.

A: No, it's not possible to do that from separate application, in C# or anything else.
You have to make browser addin and separate for every browser. Even for IE it's not recommended to make addin in .NET (see https://stackoverflow.com/a/1161529/351383).
For IE here is a excelent post about making addins :
How to get started with developing Internet Explorer extensions?
For firefox you have to make firefox addon, see this link :
https://addons.mozilla.org/en-us/developers/
Chrome :
http://developer.chrome.com/extensions/getstarted.html


text:
Q: Positioning a div underneath a table whose height can vary I would like to know how to position a div underneath a table whose height can vary.
This is for a shopping cart backend page: I have a table with the shopping cart items which can be a list of anything between 1 and 15 items, and can therefore have 1 through 15 rows. About 100px underneath this I would like to have a div containing input fields to collect the billing and shipping address. I don't want to have to set the height of the table to anything specific, just the height of the number of rows it requires, with the address div right below it.
I've looked into and experimented with all of the CSS positioning possibilities but found nothing helpful. Please help?
Thanks!

A: just put the div right after the table, and give it a css style that includes margin-top:100px;


text:
Q: React Table 7 - How to change the state of an individual button created dynamically by the React-Table API I am using React Table 7 to create a table with the first cell of each row being a ChecOut/CheckIn Button. My goal is to create a tool where people can CheckOut and CheckIn equipment. My React Table CodeSandbox
The idea is that when a user clicks the button, it will change from "CheckOut" to "CheckIn" and vise versa. It will also change the color of the row when Checked out. I was able to accomplish this with JQuery (code is in the sandbox under the App() functional component) but want to avoid that and am sure it's easily doable in react.
My issue is changing the state of an individual button and which functional component to define it in. The <Button> elements are created dynamically by the React-Table, defined in the columns object under the App functional component.
      {
        Header: "CheckIn/Out",
        Cell: ({ row }) => (
          <Button
            key={row.id}
            id={row.id}
            onClick={e => checkClick(e)}
            value={checkButton.value}
          >
            {checkButton.value}
          </Button>
        )
      }

I tried passing a function to onChnage attribute on the <Button> element. In that function I updated the state of the <Button> to change the string value from "CheckOut" to "CheckIn" but that does not work. At first, that changed the name (state) of All the <Button> elements.  Not sure if the state will live in the App() component or the TableRe() functional component. Or do I need to use state at all?
I basically built this on top of the editable table code available on the React-Table website React-Table Editable Data CodeSandbox , examples section React-Table Examples .
Any help is much appreciated!

data.js
import React from "react";

// export default random => {
//   let arr = [];
//   for (let i = 0; i < random; i++) {
//     arr.push({
//       first: chance.name(),
//       last: chance.last(),
//       birthday: chance.birthday({ string: true }),
//       zip: chance.zip()
//     });
//   }
//   return arr;
// };

const temp_data = [
  {
    firstName: "johny",
    lastName: "Bravo",
    age: "23",
    visits: "45",
    progress: "complete",
    status: "all done"
  },
  {
    firstName: "johny",
    lastName: "Bravo",
    age: "23",
    visits: "45",
    progress: "complete",
    status: "all done"
  }
];

const ArrayData = () => {
  const data = temp_data.map(item => {
    return {
      firstName: item.firstName,
      lastName: item.lastName,
      age: item.age,
      visits: item.visits,
      progress: item.progress,
      status: item.status
    };
  });
  return data;
};

// Do not think there is any need to memoize this data since the headers
// function TempData() {
//   const data = React.useMemo(ArrayData, []);
//   return data;
// }

export default ArrayData;


text:
Q: Issue with mangopay php sdk I'm using mangopay with the official sdk 3.11, i get following error :
Call to undefined method MangoPay\MangoPayApi::getLogger()

Here how i use the API :
namespace App\Services;

use MangoPay\MangoPayApi;

class MangopayServices
{
    private $api;

    public function __construct()
    {
        $this->api = new MangoPayApi();
        $this->api->Config->ClientId = 'MY_CLIENT_ID';
        $this->api->Config->ClientPassword = 'MY_API_KEY';
        $this->api->Config->TemporaryFolder = '/home/site/mgpy';
    }
    public function get_users()
    {
        return $this->api->Users->GetAll();
    }
}

When call this service :
$s = new App\Services\MangopayServices();
dump($s->get_users())

i get fatal error : Fatal error:  Uncaught Error: Call to undefined method MangoPay\MangoPayApi::getLogger()
Have you any idea please ?
Thank you


text:
Q: How to upload and retrieve file in mongodb in spring boot application without using GridFSTemplate? I want to upload files and retrieve them from mongodb in spring boot application. But I don't want to use GridFSTemplate because my file size will not be greater than 16 MB. I am not choosing GridFSTemplate because none of the requirements mentioned in link https://docs.mongodb.com/manual/core/gridfs/#faq-developers-when-to-use-gridfs do not meet my requirements.
Is working with Document to save files and retrieve them using MongoTemplate a good approach?
MyDocument definition will look like
@Document
public class MyDocument {
    @Id
    private String id;
    private String emailId;
    private String docType;
    @CreatedDate
    private DateTime created;
    @LastModifiedDate
    private DateTime modified;
    private File document;
}

Storing file
MyDocument document = new MyDocument();
document.setEmailId("abc@gmail.com");
document.setDocType("passport");
document.setDocument(file);
mongoTemplate.insert(document);

I want to store file along with some information like email. Later I will retrieve this file based on email parameter.
Please suggest if this approach is good or any other better solution is appreciated.

A: I could finally figure out the way to store files without using GridFS in mongodb. First thing you have to note that we have to store byte[] representation of file.
import org.bson.types.Binary;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document
public class DemoDocument {
    @Id
    @Field
    private String id;

    @Field
    private String emailId;

    @Field
    private String docType;

    @Field
    private Binary file;
}

Make sure your file object is org.bson.types.Binary.
Following is my controller code to save object in monogodb.
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile multipart, @RequestParam("email") String email) {
    try {
        DemoDocument demoDocument = new DemoDocument();
        demoDocument.setEmailId(email);
        demoDocument.setDocType("pictures");
        demoDocument.setDocument(new Binary(BsonBinarySubType.BINARY, multipart.getBytes()));
        mongoTemplate.insert(demoDocument);
        System.out.println(demoDocument);
    } catch (Exception e) {
        e.printStackTrace();
        return "failure";
    }
    return "success";
}

You can retrieve this object from mongodb as following.
@PostMapping("/retrieve")
public String retrieveFile(@RequestParam("email") String email){
    DemoDocument demoDocument = mongoTemplate.findOne(new BasicQuery("{emailId : \""+email+"\", docType : \"pictures\"}"), DemoDocument.class);
    System.out.println(demoDocument);
    Binary document = demoDocument.getDocument();
    if(document != null) {
        FileOutputStream fileOuputStream = null;
        try {
            fileOuputStream = new FileOutputStream(RETRIEVE_FOLDER + "prof_pic.jpg");
            fileOuputStream.write(document.getData());
        } catch (Exception e) {
            e.printStackTrace();
            return "failure";
        } finally {
            if (fileOuputStream != null) {
                try {
                    fileOuputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return "failure";
                }
            }
        }
    }
    return "success";
}

Please note this is just sample working code for understanding. It can be written in fully object oriented way keeping design principles in mind.


text: Q: Need to use lasers,mirrors and prisms for a project.How to make the light visible and presentable at the same time? Alright so I really want to put some art into science for my project.project. I'm thinking of creating a beautiful image,preferably in air.I read about the visible lime-green lasers but i still want to be able to use other colors,and I need to make it visible.How can i make "fog" for it so that a pretty image is seen yet at the same time the inspectors won't be suffocating.Any ideas on how should I make it and what other things I can use to create pretty images?Please explain in details as I might not know some terms in optics.Thanks in advance!


text:
Q: Enviar spreadsheets como archivo adjunto con google app scripts Soy nuevo en Google Apps Scripts y requiero adjuntar el archivo spreadsheets y enviarlo por correo. He visto como realizar el envió y se envía el email con el archivo adjunto, pero en formato pdf y lo requiero en su formato original xls o xlsx. ¿Alguien me puede ayudar?
function enviarEmail(){
var file = DriveApp.getFileById(id del archivo);
var destino = 'email de destino';
var asunto = 'Archivo XXXXX ';
var msg = 'xxxxxxxxxxxxxxxx xxxxxxxxxxxx'
GmailApp.sendEmail(destino,asunto,msg,{attachments:[file]});
}

A: Puedes especificar el formato en el que se enviará tu attachment de la siguiente forma
// Send an email with a file from Google Drive attached as a PDF.
var file = DriveApp.getFileById('1234567890abcdefghijklmnopqrstuvwxyz');
GmailApp.sendEmail('mike@example.com', 'Attachment example', 'Please see the attached file.', {
    attachments: [file.getAs(MimeType.PDF)],
    name: 'Automatic Emailer Script'
});

En tu caso en lugar de file.getAs(MimeType.PDF) intenta con  file.getAs(MimeType.MICROSOFT_EXCEL)
Referencias

*

*https://developers.google.com/apps-script/reference/gmail/gmail-app#sendemailrecipient,-subject,-body,-options

*https://developers.google.com/apps-script/reference/base/mime-type
Relacionado

*

*No se puede recuperar el siguiente objeto: el iterador alcanzó el final

A: Gracias por responder Rubén, al usar file.getAs(MimeType.MICROSOFT_EXCEL) me decía que no es posible realizar la conversión una solución que encontré es la siguiente:
// convierte archivo en xlsx y envía adjunto
function Enviar_xlsx() { var name = "Nombre del archivo"; var sheetId = "Id del archivo google spreadsheets"; var url = "https://docs.google.com/spreadsheets/d/" + sheetId + "/export?format=xlsx&access_token=" + ScriptApp.getOAuthToken(); var blob = UrlFetchApp.fetch(url).getBlob().setName(name + ".xlsx"); GmailApp.sendEmail('Email destino', 'Attachment example', 'Please see the attached  file.', {attachments: [blob]}); }


text:
Q: Cyclic groups and Unit groups So I wanted to find the the subgroup $3 \in U(20)$ where $U(20)$ is the unit group of $\mathbb Z_{20}$ (i.e. all integers in $\mathbb Z_{20}$ that are relatively prime to $20$). I thought that this is a cyclic subgroup where $3$ is the generator and $U(20) = \lbrace 1,3,7,9,11,13,17\rbrace$. Now $3$ is a generator for $\mathbb Z_{20}$, so the subgroup is going to be the whole $U(20)$. However, I got confused when the answer said $\lbrace 1,3,7,9\rbrace$. What am I misunderstanding here?

A: $U(20)$ is a multiplicative group whereas $\mathbb{Z}_{20}$ is an additive group. That is, the group operation on $U(20)$ is multiplication $\mod 20$, while the group operation on $\mathbb{Z}_{20}$ is addition $\mod 20$.
So, the subgroup of $U(20)$ generated by $3$ is: $\{3,3^2=9,3^3=7,3^4=1\}$.

A: $3$ does not generate $U(20)$.
$$3^2=9\\
3^3=27\equiv 7\pmod {20}\\
3^4\equiv 3\cdot 7\pmod {20}\equiv 1\pmod {20}$$

A: You were wrong to think $3$ is a generator of $U(20)$; just check $$3\cdot3\equiv9\pmod{20};\quad 3\cdot9\equiv7\pmod{20};\quad 3\cdot7\equiv1\pmod{20}.$$ Thus, we clearly see that $\langle 3\rangle=\{1,3,7,9\}$.


text:
Q: iOS6 XCode4.6.2 Passing Row Number via a Segue If I pass data via a Seque to another View Controller, e.g.
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
     if ([segue.identifier isEqualToString:@"mySequeIdentifier"]) {
         NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
         RecipientViewController *destViewController = segue.destinationViewController;
         destViewController.intPassedRow = indexPath.row;
    }
 }

THis passes the correct row number but...
I get an error saying "Incompatible integer to pointer conversion assigning to 'int' from 'int'."
If they are both Ints then what have I done wrong?


text:
Q: Css file images are not showing  I uploaded css files in the blob storage. Now I am trying to access that files in the browser directly
through the blob URI. But my problem is the images which are referenced in the css file. These images
are referenced by the relative address. There are lots of images in my css file. So that`s why is there
any alternative for this so that without upload those images in the blob we can show it in the browser ?

A: When you insert relative path in your CSS, the relative path will use the location of CSS as it root and then create the path. In your case, because your CSS is located at Azure Blob storage the relative path in your your CSS will all look for your Azure Blob storage as root. You hit the problem because your images are located at Azure VM and your CSS is located at Azure Blob storage. This is a by design behavior for CSS as described multiple places i.e.:
Is a relative path in a CSS file relative to the CSS file?
The bottom line if that if you are using CSS and referencing any content to it, it should reference to same web server. The folder/containers could be changed and then you can reference them correctly in your relative path.
To solve this problem you would need to copy all your images to same container at Windows Azure Blob storage and then you can just use "imagename.imageextension" any where in CSS.


text:
Q: How to fix 130 react error in react heroku? When i deploy my react to heroku, i have the following error:
p listening on port 3000!
{ Invariant Violation: Minified React error #130; visit https://reactjs.org/docs/error-decoder.html?invariant=130&args[]=undefined&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at ba (/Users/alexei.mairyn/opensense-admin/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:10:312)
    at r (/Users/alexei.mairyn/opensense-admin/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:11:166)
    at a.render (/Users/alexei.mairyn/opensense-admin/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:44:191)
    at a.read (/Users/alexei.mairyn/opensense-admin/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:41:58)
    at renderToString (/Users/alexei.mairyn/opensense-admin/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:53:83)
    at /Users/alexei.mairyn/opensense-admin/build/server.js:1:23661 name: 'Invariant Violation', framesToPop: 1 }

Also, when i start command yarn start:production - i have the same error.
  <Switch>
        <DefaultLayout
          isAuth={isAuth}
          path="/meetings"
          component={ConferenceContainer}
        />
        <DefaultLayout
          isAuth={isAuth}
          path="/domains"
          exact
          component={Domains}
        />
        <AuthLayout
          path="/login"
          exact
          component={Login}
        />
        <ConferenceLayout
          isAuth={isAuth}
          path="/:id/menu"
          component={Menu}
        />

    </Switch>


text:
Q: Using external library classes in CUDA project I am trying to enhance a small C++ project with CUDA.
My project is using a custom library's classes and functions for example Matrix3d, Vector3d, Plane2d etc. They are mostly geometric objects.
When I try to use my code in the device (either __host__ __device__ functions or a kernel) all the library functions/objects are considered as host code and I get multiple warnings and errors for example error: identifier "Plane3d::~Plane3d" is undefined in device code
Is there a way to use my library on device as well? How is it done?
I don't have experience on CUDA and C++ (I have only used CUDA with simple C code without classes) so I don't get the strategy very well.
Is there a method to avoid changing the library source code? It is possible to change the library's code but it would be better if I could avoid it.
Thanks a lot.

A: There is no particular problem with using C++ classes in CUDA. The object model is only slightly different to standard C++.
Any structure or class data members are automatically defined in whichever memory space (so host or device) the class or structure is instantiated in. What is not automatic is the code generation for function members and operators within classes and structure. The programmer must explicitly define and compile those for whichever memory space the object will be instantiated in. This latter requirement means you must have both __device__ and __host__ definitions of each function you call within the object. This includes the constructor and destructor, the latter being the error you show in your question.

A: You don't need to change the source code - what you need is to write an adapter.
CUDA kernels work with low level structures e.g. double*, double*, double** or float*, float*, float** as well as with the built in CUDA types.
CUDA can not work directly on memory allocated outside CUDA anyway (only with memory allocated on the Graphics card, not regular RAM), so you will have to copy your data into the graphics memory.
If you provide methods which have access to the buffers used by your types, you can copy them, continuously if your types have continuous memory, or in chunks if not, into the graphics card (using the CUDA memory copy function), then you can process them with kernels as double*** using simple indexing.


text:
Q: What would you call an item for task list? That terminology would you call something that is under SharePoint's Task List? I don't want to call it an Item.

A: Fundamentally these are items, because that's what we have to work with at the lowest level in SharePoint, files and items. Specifically, it is a Task, as a Tasks list would aggregate tasks. Looking at the content type in the list, you should see Task if you enable the content types in the advanced settings.


text:
Q: how to get kml file geometry data click event in android? I want to get Kml Geometry data.
Because I want to get an event when I click on the geometry for the geometry data.
When I import the container, I also want to read the  schema.
I looked at another code, but my kml file is unreadable, and an error is displayed when I touch it.
Here is my kml file.

<?xml version="1.0" encoding="utf-8" ?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document id="root_doc">
<Schema name="taprip" id="test">
 <SimpleField name="PNU" type="string"></SimpleField>
 <SimpleField name="JIBUN" type="string"></SimpleField>
 <SimpleField name="BCHK" type="string"></SimpleField>
 <SimpleField name="SGG_OID" type="float"></SimpleField>
 <SimpleField name="COL_ADM_SE" type="string"></SimpleField>
</Schema>
 <Folder>
  <name>taprip</name>
   <Placemark>
    <Style><LineStyle><color>ff0000ff</color></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
   <ExtendedData><SchemaData schemaUrl="#test">
    <SimpleData name="PNU">0102030405060708</SimpleData>
    <SimpleData name="JIBUN">1234</SimpleData>
    <SimpleData name="BCHK">5</SimpleData>
    <SimpleData name="SGG_OID">56789</SimpleData>
    <SimpleData name="COL_ADM_SE">30000</SimpleData>
   </SchemaData></ExtendedData>
        <MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>127.411442609279,36.4117774724474 127.411430639867,36.4117591928369 127.411388698287,36.4116954982216 127.411313907152,36.4115819196492 127.411299780584,36.4115604663116 127.411184250909,36.4113850092162 127.411177991161,36.4113754963568 127.411156029814,36.4113865565459 127.411147445404,36.411390875402 127.411239476374,36.4115307720544 127.411438060696,36.4118328822137 127.411444229354,36.4118398901497 127.411446675965,36.4118387102752 127.411442609279,36.4117774724474</coordinates></LinearRing></outerBoundaryIs></Polygon></MultiGeometry>
     </Placemark>
    <Placemark>
     <Placemark>
 <Style><LineStyle><color>ff0000ff</color></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
 <ExtendedData><SchemaData schemaUrl="#test">
  <SimpleData name="PNU">3020014300104450001</SimpleData>
  <SimpleData name="JIBUN">445-1 전</SimpleData>
  <SimpleData name="BCHK">9</SimpleData>
  <SimpleData name="SGG_OID">537137</SimpleData>
  <SimpleData name="COL_ADM_SE">30200</SimpleData>
 </SchemaData></ExtendedData>
      <MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>127.406330898793,36.4126478120527 127.406656845623,36.4126114483288 127.406607792592,36.4123793315293 127.406591051422,36.4123263819704 127.406574956391,36.4122754848661 127.406537905743,36.4122987698551 127.406490416308,36.412338680434 127.406410796489,36.4124198284199 127.406355694086,36.4124709119944 127.406302101173,36.4125185390081 127.406239762676,36.4125890038521 127.406271600953,36.4126141738274 127.40628509083,36.4126248430429 127.406323878118,36.412648448554 127.406340386208,36.4126584947809 127.40637242019,36.4126913149031 127.406653944943,36.4126692584376 127.406665011355,36.4126597318297 127.406664887663,36.4126509099066 127.406664741813,36.4126421150931 127.406664712427,36.4126407454316 127.406656845716,36.4126114663517 127.406330898793,36.4126478120527</coordinates></LinearRing></outerBoundaryIs></Polygon></MultiGeometry>
  </Placemark>
  <Placemark>
 <Style><LineStyle><color>ff0000ff</color></LineStyle><PolyStyle><fill>0</fill></PolyStyle></Style>
 <ExtendedData><SchemaData schemaUrl="#test">
  <SimpleData name="PNU">3020014300104990000</SimpleData>
  <SimpleData name="JIBUN">499 도</SimpleData>
  <SimpleData name="BCHK">9</SimpleData>
  <SimpleData name="SGG_OID">535830</SimpleData>
  <SimpleData name="COL_ADM_SE">30200</SimpleData>
 </SchemaData></ExtendedData>
      <MultiGeometry><Polygon><outerBoundaryIs><LinearRing><coordinates>127.406804360591,36.4124370980833 127.406707221773,36.4123494374184 127.406660737998,36.412241095079 127.406662908718,36.4121176290232 127.406566543667,36.4119983980378 127.406405693485,36.4119094745232 127.406330540255,36.4118366354167 127.40625847788,36.4118052481307 127.406224121009,36.4118147362003 127.406232095194,36.4118368146933 127.406268572928,36.4118515426019 127.406315737201,36.41189973047 127.406331868296,36.4119188346168 127.406470372054,36.4120717258792 127.406503919961,36.412123528265 127.406556798532,36.4122180703431 127.406574956391,36.4122754848661 127.406591051422,36.4123263819704 127.406607792592,36.4123793315293 127.406656845623,36.4126114483288 127.406709818172,36.4126055559029 127.407065604896,36.4125658820516 127.407002372494,36.4125346545848 127.406804360591,36.4124370980833</coordinates></LinearRing></outerBoundaryIs></Polygon></MultiGeometry>
  </Placemark>
 </Folder>
</Document></kml>

thank you!


text:
Q: What does this piece of AJAX code mean? I searched the internet for information but I cant seem to get any information about this AJAX piece of code i'm using:
function getEmployeeFilterOptions(){
    var opts = [];
    $checkboxes.each(function(){
        if(this.checked){
            opts.push(this.name);
        }
    });

Also what is the difference between this code since they are both ways to call of AJAX ?
function updateEmployees(opts){
    $.ajax({
        type: "POST",
        url: "submit.php",
        dataType : 'json',
        cache: false,
        data: {filterOpts: opts},
        success: function(records){
            $('#employees tbody').html(makeTable(records));
        }
    });

It would be nice if someone could explain in detail what everything stands for.

A: The First Code
The first code is just a pseudo code, or what you say an algorithm code to check for the checkness of a checkbox input element.
function getEmployeeFilterOptions(){
    var opts = [];
    $checkboxes.each(function(){
        if(this.checked){
            opts.push(this.name);
        }
    });
});

This would check for each of the checkbox, note the .each() method. It would execute a function for each element. And will check for a condition. But note, checkboxes won't do anything. You're morelikely to check it as:
$('input[type=checkbox]').each(function () {
  /* here if else statement */
}

The Second Code
The second code is the real code to do an ajax request execution.
function updateEmployees(opts) {
    $.ajax({
        type: 'POST',
        url: 'submit.php',
        dataType : 'json',
        cache: false,
        data: {
          filterOpts: opts
        },
        success: function(records) {
          $('#employees tbody').html(makeTable(records));
        }
    });
});

This code will send an AJAX request, just like a form submission with method="post", for this you can see the type: 'POST' part of the code. Next is the URL of the page, where the page is found to capture the request. The datatype is also the mime of the page, which is set to json. Server would know that the request is in json format. You can handle it on the server side too. Such as:
if(request_type == 'json') {
  /* note, it is also a pseudo code */
}

Then, the cache is set to false, so that the browser and the server must not and must never save the session of this request.
Data is some other response or QueryString added to the HttpRequest. For example, if the request were GET (type: 'GET'). Then you can add the data of your name or anyother as:
data: 'user_name=yourname&password=password'

This would be added to the url.
Next is a function to be executed if the response was a success. If there was no error found, then this function would execute and the table would be updated!


text:
Q: How to get PHP 64 Bit working and enabled on 64 Bit Apache in Windows 7 64? I have installed PHP 5.5 64 Bit, as well as Apache 2.4 64Bit on my Windows 7 64 bit PC, bit MAX_INT is still displaying a 32 bit number (2147483647). The whole point of me doing these installations was to increase MAX_INT.
I cannot seem to find any info on this, so any help with getting PHP running as 64 Bit would be much appreceated.

A: Could I suggest, say, WAMP Server 64 bit? The problem you might be having is the build of Apache. I don't think there's an official build of Apache 64 bit for Windows.

A: Seems only solution is to bypass Windows. Install VirtualBox with a 64 bit version of Linux, Apache and PHP 64 Bits, then at least it works.
I had Ubuntu 64Bit installed and get a MAX_INT of 9223372036854775807. Not ideal, as moving servers is a schlep, but it's much better and worth it in the end.

A: Now you've a chance to test upcoming PHP7 - http://windows.php.net/downloads/snaps/master/ with full 64-bit support.


text:
Q: new Jsch() no exception I'm ruunning this code but don't get error:
   JSch jsch = null ;
    try {
      logger.debug("rla new jsch");
      jsch = new JSch();
    }
    catch (Exception e){
        logger.debug("rla catch: {}",e.getClass());
    }
    logger.debug("rla end new jsch");

Execute stop after new Jsch() but don't catch exception why ?
After catch logger.debug never execute why ?
thanks


text:
Q: Create and import mysql database on shared host in php I'm trying to write php script that would:

*

*connect to mysql

*create database

*create user and password

*add user to database

*import prepared sql file to database

The thing is that it'll be on shared host (and I'm trying to make it universal and work with different hosts). I guess database and db user will be prefixed with my account name (what I use for ftp, to login to control panel, etc) on shared hosts? Something like mylogin_dbname and mylogin_dbuser. It's visible for example in cpanel - when I add database I enter its name and after it's created cpanel shows it as mylogin_somedb. How do I make my script work with this on multiple different shared hosts - add my prefix automatically depending on my main login?
Now working with such code (don't have a clue if it works, that's just what came to my mind):
<?php
mysql_connect("host", "user", "password"); // Connection to MySQL

$query = "CREATE DATABASE somedb;
USE somedb;
SOURCE path/to/sqlfile.sql;
CREATE USER someuser IDENTIFIED BY PASSWORD 'somepass';
GRANT SELECT,INSERT,UPDATE,DELETE ON somedb.* TO 'someuser'@'host';";

$arr= explode( ';', $query );
foreach( $arr as $command )
{
mysql_query( $command );
}
mysql_close(); // Disconnection from MySQL
?>

A: The fact that this is on a shared host shouldn't make that much of a difference in my opinion. Whatever your environment, you'll have to use your username and either the database name gets prefixed with that or it doesn't according to hosting setup. That said it is probably smart to adopt a naming convention with your username as a prefix or some other prefix naming convention.
As to what you're trying to do I have some suggestions:

*

*You should run each statement separately (as you do) but add error checking between each step so you don't attempt to source the file if the database wasn't created for instance.

*Maybe create separate functions for each kind of operation and send in parameters for the values. This would clean up the code in the longer run.

*If you have a situation where something is automatically prefixed to the name you provide and you have to detect the final name, you can probably do a "show databases;" query and search for the name you gave in the results. Then use the complete name for the resulting queries.

A: Use mysql_error()
http://us3.php.net/manual/en/function.mysql-error.php
So you can see what went wrong.
eg:
if (mysql_query( $command ) === false) {
  echo mysql_error();
  die;
}

The same for mysql_connect()
if (($link = mysql_connect("host", "user", "password")) === false) {
  echo mysql_error();
  die;
}

You have to make sure the user you are using has privileges to create databases.
For CPanel I believe you have to use your account username and pass. Then like you said prefix your db name with your username, or it will fail to create.

A: KISS principle: just use phpMyAdmin? It's almost certainly installed. If it's not, install it.
Its import capability is magnificent. If your database is by any chance too big, gzip it. If it's still to big, try splitting it up in a few pieces. I doubt you need to transfer it as a single big transaction. Do you?

After the explanation in first comment, well, here goes. This is my very simplistic script which does what you want. Except it doesn't take a look at the separators: one query == one line.
<link rel="stylesheet" href="style/contents.css"/>
<?

function timesanitize($v) {
    if ($v > 0)
        return round($v, 4);
    else
        return 0;
}

$startmt = microtime();
include_once 'include/db.php';
$f = fopen("db.sql","r");
echo dbGetEngine() . "
";
echo "
";
do {
    $l = rtrim(fgets($f));
    if (strlen($l) == 0)
        continue;
    if (substr($l, 0, 1) == '#')
        continue;
    $l = str_replace(
        array("\\n"),
        array("\n"),
        $l);
    if (dbGetEngine() == "pgsql")
        $l = str_replace(
            array("IF NOT EXISTS", "LONGBLOB"),
            array("", "TEXT"),
             $l);
    try {
        echo "
".nl2br(htmlspecialchars($l));
        $mt = microtime();
        $db->query($l);
        echo "

ok - " . timesanitize(microtime() - $mt) . "
";
    } catch (PDOException $e) {
        echo "

".$e->getMessage() . "
";
    }
} while (!feof($f));
fclose($f);

echo 'total: ' . timesanitize(microtime() - $startmt);
?>

It also outputs a small statistic of how long each query took. It's based around PDO; I believe PDO was introduced in PHP5.1 or PHP5.2. I think it should be trivial to modify it to work directly with mysql_*() functions, if for some reason you prefer that.
And once again: yes, I know it sucks. But as long as it Works For Me (tm), and possibly You... :-)

To complete the code, here are include/db.php and a sample include/config.php:
include/db.php:
<?
include_once 'include/config.php';

try {

        $attribs =
                array(
                        PDO::ATTR_PERSISTENT => $config['db']['persistent'],
                        PDO::ATTR_ERRMODE => $config['db']['errormode']
                );

        $db = new PDO(
                $config['db']['uri'],
                $config['db']['user'],
                $config['db']['pass'],
                $attribs
        );
        $db->query("SET NAMES 'utf8'");
        $db->query("SET CHARACTER SET 'utf8'");

} catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "
";
        die();
}

function dbGetEngine() {
        global $config;
        return substr($config['db']['uri'], 0, strpos($config['db']['uri'], ':'));
}
?>

include/config.php:
<?

//$config['db']['uri'] = 'sqlite:' . realpath('.') . '/site.db'; // PDO's database access URI
$config['db']['uri'] = 'mysql:host=localhost;dbname=sitedb'; // server should be : 195.78.32.7
//$config['db']['uri'] = 'pgsql:host=localhost;dbname=sitedb';
$config['db']['user'] = 'user_goes_here'; // database username
$config['db']['pass'] = 'pass_goes_here'; // database password
$config['db']['persistent'] = false; // should the connection be persistent
$config['db']['errormode'] = PDO::ERRMODE_EXCEPTION; // PDO's error mode

?>

Included are sample connection strings for SQLite, MySQL and PostgreSQL.

A: Regarding import, if upload limit is an issue, there are at least one alternative to phpMyAdmin that allows you to select a file on the webserver instead of uploading it. For example adminer (adminer.org) allows that. In adminer, click "SQL command" and then click "from server"


text:
Q: Ubuntu 20.10 upgrade from 20.04 - Black Screen with only mouse pointer after auto-login Ok, I can see there are loads of similar questions regarding many distro upgrades but none of the solutions or suggestions have worked for me.
Problem
I upgraded my Dell XPS laptop from Ubuntu 20.04 to 20.10 via the distro upgrade option.  Since doing so, I am having problems with my desktop whereby after auto-login, I end up with a black screen with only the mouse cursor and no window decorations, taskbar etc.
Comments

*

*My auto-login flashes the new standard Ubuntu background for about 5 seconds then the screen goes black.

*The mouse pointer is visible

*I can right click the black screen and start a terminal session, from where I can run applications from the command line

*Any windowed application I run has no title bar, appears in the top left corner of the screen and cannot be moved nor resized

*I created a new user and it logs in with a normal desktop in its initial state

*I have tried dconf reset -f /

*I have tried unity-tweak-tool --reset-unity

*I have tried renaming my entire .config folder and rebooting

*If I change the scale with xrandr to 0.9x0.9, I can see a little bit of the "standard" background / wallpaper along the right side of the screen and the bottom of the screen

*If I open display settings with gnome-control-center display for my usual account there are options for multiple screens, even though I only have the laptop screen enabled.  In addition, there are no scale buttons on the scale settings section

*If I do the same for the test account I created, I get a single desktop settings screen and 100% & 200% buttons in the scale section

*I have tried completely removing the installed NVIDIA drivers (460), with no effect

I am now out of ideas, I'm not sure which config file in my user home is driving this.  I do have a backup that I took prior to the upgrade so I could roll back, but I'd rather solve the problem if possible.
Thanks for any advice. Obviously if I've missed detail or can provide further information, please advise.

A: Ok, so in this case the fix was to replace the core.pb file in the ~/.cache/compizconfig-1 folder.
Diagnostic route was

*

*rename ~/.cache folder & reboot.  Problem solved

*rename ~/.cache/compizconfig-1 folder & reboot. Problem solved

*work through the recently changed (i.e. not old) files, renaming and rebooting.

core.pb was the culprit. The Desktop displays correctly when this file is replaced with the auto-created one. However, desktop configuration is lost (taskbar icons etc.) although this might be because of the resetting I did initially.
Posted in case this is helpful for anybody else.


text:
Q: Python pyqt5 QProcess how can I do it         def Start(self):
                txt = self.main.lneIslenecekTxt.text()
                ciktiDosyasi = self.main.lneCiktiDosyasi.text()
                txtCiktiAdi = self.main.lneCiktiAdi.text()
                eklenecekeMetin = self.main.lneEklenecekMetin.text()

                if txt:
                        if eklenecekeMetin:
                                txtOku = open(txt, 'r')
                                txtMetinOlustur = ''
                                for t in txtOku:
                                        metinEkle = str(eklenecekeMetin) + str(t)
                                        self.main.plainLog.insertPlainText(metinEkle)
                                        print(metinEkle.strip())
                                        txtMetinOlustur+=metinEkle

                                if ciktiDosyasi:
                                        if txtCiktiAdi:
                                                txtCiktiAdi = txtCiktiAdi + '.txt'
                                                yeniTxtYolu = os.path.join(ciktiDosyasi,txtCiktiAdi)
                                                txtYaz = open(yeniTxtYolu, 'w')
                                                txtYaz.write(txtMetinOlustur)
                                        else:
                                                self.main.statusbar.showMessage('Çıktı Dosya Adı Girilmedi.', 5000)
                                else:
                                        self.main.statusbar.showMessage('Çıktı Dosyası Seçilmedi.', 5000)
                        else:
                                self.main.statusbar.showMessage('Eklenecek Metin Girilmedi.', 5000)
                else:
                        self.main.statusbar.showMessage('TXT seçilmedi.', 5000)

I run the above function and print a log output to "self.main.plainLog".
But this happens when the program runs and finishes.
While the program is running, I want the log section to be recorded instantly.
How can I do it?
self.main.plainLog.insertPlainText(metinEkle)


text:
Q: How to increase the size of SingleChildScrollView in flutter? I am making an app in which one of the pages is scrollable. I used a SingleChildScrollView to scroll over the page. I need to add more stuff to it and when I do, it gives an error because of the limited height.
Can anyone help me in expanding the size of SingleChildScrollView so that I can complete my app?
This is the whole code:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:xdflutter/Component61.dart';
import './Component31.dart';
import './Component22.dart';
import './Component21.dart';
import './start.dart';
import 'package:adobe_xd/page_link.dart';
import 'package:flutter_svg/flutter_svg.dart';

class tester extends StatelessWidget {
  tester({
    Key key,
  }) : super(key: key);
  @override
  Widget build(BuildContext context) {
      // ignore: unnecessary_statements
      (context, constraint) {
        return SingleChildScrollView(
          child: ConstrainedBox(
            constraints: BoxConstraints(
                minHeight: constraint.maxHeight),
            child: IntrinsicHeight(
              child: Column(
                children: <Widget>[
                  Transform.translate(
                    offset: Offset(0.0, 290.0),
                    child:
                    // Adobe XD layer: 'right' (shape)
                    Container(
                      width: 315.0,
                      height: 287.0,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50.0),
                        image: DecorationImage(
                          image: const AssetImage('assets/images/right.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, -275.0),
                    child: SizedBox(
                      width: 434.0,
                      child: Text(
                        'What you should know \nbefore you begin? ',
                        style: TextStyle(
                          fontFamily: 'Corbel',
                          fontSize: 36,
                          color: const Color(0xff000000),
                          fontWeight: FontWeight.w700,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, -260.0),
                    child: SizedBox(
                      width: 348.0,
                      height: 108.0,
                      child: Component31(),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(-0.5, -376.5),
                    child: SvgPicture.string(
                      _svg_kr65u6,
                      allowDrawingOutsideViewBox: true,
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, -370.0),
                    child: SizedBox(
                      width: 166.0,
                      child: Text(
                        'R:Right',
                        style: TextStyle(
                          fontFamily: 'Corbel',
                          fontSize: 42,
                          color: const Color(0xff000000),
                          fontWeight: FontWeight.w700,
                          decoration: TextDecoration.underline,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, 15.0),
                    child:
                    // Adobe XD layer: 'left' (shape)
                    Container(
                      width: 307.0,
                      height: 278.0,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50.0),
                        image: DecorationImage(
                          image: const AssetImage('assets/images/left.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, -320.0),
                    child: SizedBox(
                      width: 130.0,
                      child: Text(
                        'L:Left',
                        style: TextStyle(
                          fontFamily: 'Corbel',
                          fontSize: 42,
                          color: const Color(0xff000000),
                          fontWeight: FontWeight.w700,
                          decoration: TextDecoration.underline,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, 50.0),
                    child:
                    // Adobe XD layer: 'face' (shape)
                    Container(
                      width: 312.0,
                      height: 289.0,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(54.0),
                        image: DecorationImage(
                          image: const AssetImage('assets/images/face.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, -300.0),
                    child: SizedBox(
                      width: 142.0,
                      child: Text(
                        'F:Face',
                        style: TextStyle(
                          fontFamily: 'Corbel',
                          fontSize: 42,
                          color: const Color(0xff000000),
                          fontWeight: FontWeight.w700,
                          decoration: TextDecoration.underline,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, 90.0),
                    child: Container(
                      width: 314.0,
                      height: 298.0,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50.0),
                        image: DecorationImage(
                          image: const AssetImage('assets/images/back.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, -270.0),
                    child: SizedBox(
                      width: 173.0,
                      child: Text(
                        'B: Back ',
                        style: TextStyle(
                          fontFamily: 'Corbel',
                          fontSize: 42,
                          color: const Color(0xff000000),
                          fontWeight: FontWeight.w700,
                          decoration: TextDecoration.underline,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, 130.0),
                    child: Container(
                      width: 314.0,
                      height: 300.0,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50.0),
                        image: DecorationImage(
                          image: const AssetImage('assets/images/upper.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, -230.0),
                    child: SizedBox(
                      width: 192.0,
                      child: Text(
                        'U: Upper',
                        style: TextStyle(
                          fontFamily: 'Corbel',
                          fontSize: 42,
                          color: const Color(0xff000000),
                          fontWeight: FontWeight.w700,
                          decoration: TextDecoration.underline,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, 165.0),
                    child: Container(
                      width: 310.0,
                      height: 296.0,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50.0),
                        image: DecorationImage(
                          image: const AssetImage('assets/images/down.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, -190.0),
                    child: SizedBox(
                      width: 187.0,
                      child: Text(
                        'D: Down',
                        style: TextStyle(
                          fontFamily: 'Corbel',
                          fontSize: 42,
                          color: const Color(0xff000000),
                          fontWeight: FontWeight.w700,
                          decoration: TextDecoration.underline,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, 145.0),
                    child: SizedBox(
                      width: 329.0,
                      child: Text(
                        'R2: Right twice',
                        style: TextStyle(
                          fontFamily: 'Corbel',
                          fontSize: 42,
                          color: const Color(0xff000000),
                          fontWeight: FontWeight.w700,
                          decoration: TextDecoration.underline,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, 160.0),
                    child: Container(
                      width: 312.0,
                      height: 294.0,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50.0),
                        image: DecorationImage(
                          image: const AssetImage('assets/images/r2.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.5, 170.0),
                    child: SizedBox(
                      width: 442.0,
                      height: 0.0,
                      child: Component22(),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, 185.0),
                    child: SizedBox(
                      width: 408.0,
                      child: Text(
                        'Counter-clockwise \nrotations',
                        style: TextStyle(
                          fontFamily: 'Corbel',
                          fontSize: 42,
                          color: const Color(0xff000000),
                          fontWeight: FontWeight.w700,
                          decoration: TextDecoration.underline,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.5, 380.0),
                    child: SizedBox(
                      width: 442.0,
                      height: 0.0,
                      child: Component22(),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, 200.0),
                    child: SizedBox(
                      width: 500.0,
                      height: 200.0,
                      child: Component61(),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.5, 260.0),
                    child: SizedBox(
                      width: 442.0,
                      height: 0.0,
                      child: Component22(),
//        THIS IS IF I NEED TO ADD LINE BELOW SLICE TURNS
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, 190.0),
                    child: SizedBox(
                      width: 238.0,
                      child: Text(
                        'Slice turns ',
                        style: TextStyle(
                          fontFamily: 'Corbel',
                          fontSize: 42,
                          color: const Color(0xff000000),
                          fontWeight: FontWeight.w700,
                          decoration: TextDecoration.underline,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, 280.0),
                    child: Container(
                      width: 312.0,
                      height: 303.0,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50.0),
                        image: DecorationImage(
                          image: const AssetImage('assets/images/m_anti.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                    ),
                  ),
                  Transform.translate(
                    offset: Offset(0.0, -80.0),
                    child: SizedBox(
                      width: 226.0,
                      child: Text(
                        'M: Middle ',
                        style: TextStyle(
                          fontFamily: 'Corbel',
                          fontSize: 42,
                          color: const Color(0xff000000),
                          fontWeight: FontWeight.w700,
                          decoration: TextDecoration.underline,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ),
//              Expanded(
//              child: (SingleChildScrollView(
//                child: Column(
//                  children: <Widget>[
                    Transform.translate(
                      offset: Offset(0.0, 100.0),
                      child: Container(
                        width: 304.0,
                        height: 297.0,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(50.0),
                          image: DecorationImage(
                            image: const AssetImage('assets/images/m.png'),
                            fit: BoxFit.fill,
                          ),
                        ),
                      ),
                    ),
          Transform.translate(
            offset: Offset(0.0, 250.0),
            child: Container(
              width: 304.0,
              height: 297.0,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(50.0),
                image: DecorationImage(
                  image: const AssetImage('assets/images/m.png'),
                  fit: BoxFit.fill,
                ),
              ),
            ),
          ),
          Transform.translate(
            offset: Offset(18.8, 3751.0),
            child: SizedBox(
              width: 338.0,
              child: Text(
                'M\': Middle anti-\nclockwise ',
                style: TextStyle(
                  fontFamily: 'Corbel',
                  fontSize: 42,
                  color: const Color(0xff000000),
                  fontWeight: FontWeight.w700,
                  decoration: TextDecoration.underline,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ),
          Transform.translate(
            offset: Offset(-33.5, 4618.5),
            child: SizedBox(
              width: 442.0,
              height: 0.0,
              child: Component22(),
            ),
          ),
          Transform.translate(
            offset: Offset(35.5, 100.5),
            child: SizedBox(
              width: 305.0,
              height: 0.0,
              child: Component22(),
            ),
          ),
          Transform.translate(
            offset: Offset(35.5, 100.5),
            child: SizedBox(
              width: 305.0,
              height: 0.0,
              child: Component22(),
            ),
          ),
          Transform.translate(
            offset: Offset(51.0, 100.0),
            child: SizedBox(
              width: 273.0,
              height: 56.0,
              child: Component21(),
            ),
          ),
          Transform.translate(
            offset: Offset(91.0, 100.0),
            child: PageLink(
              links: [
                PageLinkInfo(
                  transition: LinkTransition.Fade,
                  ease: Curves.easeOut,
                  duration: 0.3,
                  pageBuilder: () => start(),
                ),
              ],
              child: SizedBox(
                width: 193.0,
                height: 43.0,
                child: Text(
                  'Begin learning! ',
                  style: TextStyle(
                    fontFamily: 'Corbel',
                    fontSize: 28,
                    color: const Color(0xffffffff),
                    fontWeight: FontWeight.w700,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
            ),
          ),
                ],
              ),
            ),
          ),
        );
      };
  }
}

const String _svg_kr65u6 =
    '<svg viewBox="-33.5 113.5 442.0 121.0" ><path transform="translate(-33.5, 113.5)" d="M 442 0 L 0 0" fill="none" stroke="#707070" stroke-width="3" stroke-miterlimit="4" stroke-linecap="butt" /><path transform="translate(-33.5, 234.5)" d="M 442 0 L 0 0" fill="none" stroke="#707070" stroke-width="3" stroke-miterlimit="4" stroke-linecap="butt" /></svg>';

Thanks in advance!

A: You can use the below code.
Container(
  height: MediaQuery.of(context).size.height * .5,
  child: SingleChildScrollView(
    //Your Codes go here
  ),
)

Here MediaQuery.of(context).size.height is your total screen's height and MediaQuery.of(context).size.height * .5 means the half of your screen. so scrolling will be happens between the half of your screen.

A: I didn't understand exactly but you can use column in singleChildScrollView without limited height.like this example you can add widgets:
`
SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Container(
                height: 100,
                color: Colors.yellow,
              ),
              Container(
                height: 100,
                color: Colors.orange,
              ),
              Container(
                height: 100,
                color: Colors.yellow,
              ),
              Container(
                height: 100,
                color: Colors.orange,
              ),
              Container(
                height: 100,
                color: Colors.yellow,
              ),
              Container(
                height: 100,
                color: Colors.orange,
              ),
              Container(
                height: 100,
                color: Colors.yellow,
              ),
              Container(
                height: 100,
                color: Colors.orange,
              ),
              Text('hello'),
              Container(
                height: 100,
                color: Colors.yellow,
              ),
              Container(
                height: 100,
                color: Colors.orange,
              ),
              Container(
                height: 100,
                color: Colors.yellow,
              ),
              Container(
                height: 100,
                color: Colors.orange,
              ),
              Column(
                children: <Widget>[
                  Text('hello'),
                  Text('hello'),
                ],
              )
            ],
          ),
        ),

`

A:
Make changes according to this

 class tester extends StatelessWidget {

  @override
  Widget build(BuildContext context) {

      return SafeArea(
        child: Scaffold(
          body: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Container(height: 100,
                color: Colors.green,),
                SizedBox(height: 20,),
                Container(height: 100, color: Colors.yellow,),
                SizedBox(height: 20,),
                Container(height: 100, color: Colors.orange,),

                SizedBox(height: 20,),
                Container(height: 100, color: Colors.pink,),

                SizedBox(height: 20,),
                Container(height: 100, color: Colors.black,),

                SizedBox(height: 20,),
                Container(height: 100, color: Colors.red,),

                SizedBox(height: 20,),
                Container(height: 100, color: Colors.yellow,),

              ],
            ),
          ),
        ),
      );

  }
}

A:
Just set the mainAxisSize property of the column child of SingleChildScrollView to min like this:

child: column(
mainAxisSize: MainAxissize.min,
),


text:
Q: ¿Cómo puedo utilizar los threads para mostrar animaciones al mismo tiempo? Estoy haciendo un programa en java que muestra la animación de cuatro algoritmos de ordenamiento, pero estoy tratando de encontrar la forma de que se muestren al mismo tiempo y no tengan que esperar a que termine un proceso para iniciar otro.
Lo siguiente es parte de mi código que maneja la ejecución en el cual traté de utilizar Threads, pero de esta forma no me da animación alguna.
@Override
    public void run(){
        String com= this.getName();
        if("quicksort".equals(com)){
            try {
                jpanel1.desordenar();
                Thread.sleep(20);
                jpanel1.reiniciarColores();
                Thread.sleep(20);
                jpanel1.quickSort(jpanel1.A, 0, jpanel1.A.length-1);
            } catch (InterruptedException ex){}
        }

        else if("heapsort".equals(com)){
            try {
                jpanel2.desordenar();
                Thread.sleep(20);
                jpanel2.reiniciarColores();
                Thread.sleep(20);
                jpanel2.heapSort(jpanel2.A);
            } catch (InterruptedException ex){}
        }

        else if("mergesortsl".equals(com)){
            try {
                jpanel3.desordenar();
                Thread.sleep(20);
                jpanel3.reiniciarColores();
                Thread.sleep(20);
                jpanel3.mergeSort(jpanel3.A, 0, jpanel3.A.length-1);
            } catch (InterruptedException ex){}
        }

        else if("mergesortcl".equals(com)){
            try {
                jpanel4.desordenar();
                Thread.sleep(20);
                jpanel4.reiniciarColores();
                Thread.sleep(20);
                jpanel4.mergeSortListas(jpanel4.A, 0, jpanel4.A.length-1);
            } catch (InterruptedException ex){}
        }
    }

    public static void main(String args[]){
        Runnable runnable= new Grafica();
        Thread t1= new Thread(runnable);
        Thread t2= new Thread(runnable);
        Thread t3= new Thread(runnable);
        Thread t4= new Thread(runnable);
        t1.setName("quicksort");
        t2.setName("heapsort");
        t3.setName("mergesortsl");
        t4.setName("mergesortcl");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }

El programa es funcional (sin hilos), pero necesito que las animaciones se muestren al mismo tiempo.
Les agradezco de antemano a todos. Saludos.

A: El siguiente código debería de funcionar bien
class Main implements Runnable{
    @Override
    public void run(){
        String com = Thread.currentThread().getName();
        if("quicksort".equals(com)){
            for (int i = 0; i < 10; ++i) {
                System.out.println("QuickSort");
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        else if("heapsort".equals(com)){
            for (int i = 0; i < 10; ++i) {
                System.out.println("HeapSort");
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        else if("mergesortsl".equals(com)){
            for (int i = 0; i < 10; ++i) {
                System.out.println("MergeSortSL");
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        else if("mergesortcl".equals(com)){
            for (int i = 0; i < 10; ++i) {
                System.out.println("MergeSortCL");
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args){
        Runnable runnable= new Main();
        Thread t1= new Thread(runnable);
        Thread t2= new Thread(runnable);
        Thread t3= new Thread(runnable);
        Thread t4= new Thread(runnable);
        t1.setName("quicksort");
        t2.setName("heapsort");
        t3.setName("mergesortsl");
        t4.setName("mergesortcl");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

La diferencia de el código anterior con el tuyo es que este código implementa la interfaz Runnable. Supongo (no lo sé exactamente) que el tuyo extiende de Thread porque al principio de tu método run() tienes el siguiente código

String com= this.getName();

Lo cual se me hizo raro, y por eso supuse que extiendes de Thread.
En fin, si extiendes de Thread y luego haces un nuevo thread de ese thread es algo extraño, y si luego seteas el nombre del thread, lo vas a setear pero en el nuevo thread que acabas de crear.
No está mal extender de thread, sólo que no es muy común y en ese caso hay que manejar de diferente forma los hilos.
En la solución que expuse mejor implementé Runnable y obtuve el nombre del hilo no con this.getName() (porque no hereda de Thread), sino con Thread.currentThread().getName().
El output del código anterior es
QuickSort
HeapSort
MergeSortSL
MergeSortCL
QuickSort
HeapSort
MergeSortSL
MergeSortCL
...
QuickSort
HeapSort
MergeSortSL
MergeSortCL

El cual asumo que es el comportamiento deseado, pues se ejecutan de forma concurrente y no secuencial.
Nota: Que algo se ejecute al mismo tiempo es casi imposible, pues para ello se requeriría que las acciones se ejecutaran en diferentes cores o CPU's, pero podemos hacer (mediante hardware) que el tiempo de ejecución entre cada acción sea extremadamente pequeño, tanto, que sea imperceptible para nosotros los humanos, y parezca que se ejecutan al mismo tiempo.
Si los hilos se ejecutan en cores o CPU's separados, se dice que son pararelos, de lo contrario son concurrentes.


text:
Q: Grep in multiple files prints matches line with file name I'm using grep to found matching lines from a file in two different files. It finds the matching files just fine from File1 into File2 and File3, but from the moment there is more than one file, it prints the file name in which it was found next to the line.
grep -w -f File1 File2 File3

Output:
File2: pattern
File2: pattern
File3: pattern
Is there an option to avoid the print of File2: and File3:?

A: grep --no-filename -w -f File1 File2 File3

A: If you're on a UNIX system, please refer to the man pages.  Whenever you encounter a problem, your first step should be man $programName.  In this case, man grep.  It appears that you want the "-h" option.  Here's an excerpt from the man page:
   -h, --no-filename
          Suppress the prefixing of file names on output.  This is the default when there is only one file (or only standard input) to search.


text:
Q: IsReadOnly = False with issue - WPF I have a problem, I need some editable column in my grid, I do what I need, but when I set the IsReadOnly property to False on the grid, when loading the ItemSource, I get a phantom row. I already checked and the collection has the correct amount of items, is it a visual mistake?
<DataGrid AlternationCount="2"
      SelectionMode="Single"
      SelectionUnit="FullRow"
      BorderThickness="0,3,0,3"
      AutoGenerateColumns="False"
      GridLinesVisibility="Horizontal"
      ItemsSource="{Binding Articles}"
      BorderBrush="{DynamicResource GrayBrush5}"
      AlternatingRowBackground="{DynamicResource GrayBrush5}"
      HorizontalGridLinesBrush="{StaticResource AccentColorBrush}">

      <DataGridTextColumn Width="100"
                          Header="Code"
                          IsReadOnly="True"
                          Binding="{Binding Code}" />

A: You should add the property CanUserAddRows="false" to delete the "phantom row".


text:
Q: Return result to previous activity that is not the last activity The startActivityForResult()and onActivityResult works perfect if there are only two activities are involved. But how can I handle this, if more than 2 activities exists?
Example:
Activity A starts a new activity B, that starts activity C, that starts activity D. I want to return the result of D to activity A along with finishing activities B and C. How can I do this? Can I loop through the activity stack and finish the wanted activities or must I start a new instance of activity A?
For short: A->B->C->D has to lead back to A with the result of D.

A: Going back closing each activity would be a good way of doing things, but if you need to jump from an activity to another and you're not using a TabHost, you could take a look at the APIDemo Reorder code
It jumps from an activity (4th) to a previous opened one (2nd) in this way:
Intent intent = new Intent(ReorderFour.this, ReorderTwo.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);

A: In my opinion the most logical way is have the Activities take responsibility for this.

*

*D returns d to C.

*C returns d and c to B.

*B returns b,c,d to A.

This will force you to consider the error conditions when the Activities don't happen in this cycle explicitly.