text:
Q: Docker /bin/sh not found with binary go file Served many pages and forums and didn't find a solution. I have the simple docker container with executable .sh file. When I build and run it from Windows - all is fine. Now trying to build it from Ubuntu 18.04 with Docker version 19.03.5.
For rebuild use .sh script that I execute as bash install.sh
go build -o main.sh ./main

docker stop stats
docker container rm stats
docker image rm stats
docker build -t stats .
docker run --name stats -p 8080:8080 stats

My Dockerfile is:
FROM alpine:3.10.1

ARG appPath="app"

RUN mkdir /app/
COPY main.sh /app/main.sh
RUN chmod +x /app/main.sh
COPY resources  /app/resources

RUN apk add --no-cache bash
WORKDIR /app

EXPOSE 8080
CMD /bin/bash -c 'ls' && /app/main.sh dev

The output 'install' call is the following:
bash install.sh
stats
stats
Untagged: stats:latest
Sending build context to Docker daemon  38.98MB
Step 1/10 : FROM alpine:3.10.1
 ---> b7b28af77ffe
Step 2/10 : ARG appPath="app"
 ---> Using cache
 ---> 08baa7336701
Step 3/10 : RUN mkdir /app/
 ---> Using cache
 ---> fb9870e78322
Step 4/10 : COPY main.sh /app/main.sh
 ---> Using cache
 ---> 79bf713855e3
Step 5/10 : RUN chmod +x /app/main.sh
 ---> Using cache
 ---> 88bf70f9c6ec
Step 6/10 : COPY resources  /app/resources
 ---> Using cache
 ---> 2ebf95627a9e
Step 7/10 : RUN apk add --no-cache bash
 ---> Using cache
 ---> 39cd823e7f2f
Step 8/10 : WORKDIR /app
 ---> Using cache
 ---> 37e6fcea2d65
Step 9/10 : EXPOSE 8080
 ---> Using cache
 ---> 4250094c65f6
Step 10/10 : CMD /bin/bash -c 'ls' && /app/main.sh dev
 ---> Using cache
 ---> ed41a1efb15b
Successfully built ed41a1efb15b
Successfully tagged stats:latest
main.sh
resources
/bin/sh: /app/main.sh: not found

I don't understand what is wrong. main.sh is there. If I try to execute CMD /bin/bash -c 'ls' && bash main.sh dev then receive main.sh: main.sh: cannot execute binary file.
What is wrong there and how can I fix it?
UPD:
Renamed file that this was binary and shouldn't have .sh in the end.
And tryed again wi the following:
install.sh
#!/bin/bash
go build -o myapp ./main

docker stop stats
docker container rm stats
docker image rm stats
docker build -t stats .
docker run --name stats -p 8080:8080 stats

Dockerfile
FROM alpine:3.10.1

RUN mkdir /app/
COPY myapp /app/myapp
RUN chmod +x /app/myapp
COPY resources  /app/resources

RUN apk add --no-cache bash
WORKDIR /app

EXPOSE 8080
CMD /bin/bash -c 'ls' && ./myapp dev

Output was the following:
....
Step 9/9 : CMD /bin/bash -c 'ls' && ./myapp dev
 ---> Running in 52fc24d26747
Removing intermediate container 52fc24d26747
 ---> 8d4f415e6dcd
Successfully built 8d4f415e6dcd
Successfully tagged stats:latest
myapp
resources
/bin/sh: ./myapp: not found

Tryed /app/myapp, ./myapp and it doesn't work.

A: I'm guessing the error message is misleading, and that the real problem is that some library or other Go runtime component is missing from inside your Docker image. Try building your app statically (which means all the things it needs will be bundled into the binary).
CGO_ENABLED=0 go build -o myapp ./main

(And yeah, don't call it main.sh if it's not a shell script. Unix doesn't care, but you are confusing the hell out of your human readers. And actually, don't call it that even if it is. You don't need to know whether grep is a binary, a shell script, or a Python program; the same convention makes sense for your own tools.)


text:
Q: Need to pass a string with single \ character in python I have looked at various solutions and am familiar with using the \ as an escape character. Im in a situation where I need to pass credentials over pyodbc and in making my connection string I need to pass credentials, unfortunately my username is in the format domain\username . I am continually getting errors because the literal string passed to SQL server is domain\username. I have seen a similar question on here trying to figure this out for url requests. I tried implementing it and I end up with the same error once the actual credentials are decoded. I've tried all kinds of string and raw string tricks best I can get is either '\ ' (with space behind it) or '\\' being literally passed to SQL Server. Any ideas?
#username and password is an argument passed from the console, lets just focus on username issue

username = bytes(sys.argv, 'utf8')
credentials = base64.b64encode(usename, altchars = bytes('\ ', 'utf8') )

cnxnstrng = f'''Driver={SQL Server};
Server=server;
Database=database};
UID={base64.b64decode(credentials)};
PWD=password'''

redpajama_set_name: RedPajamaStackExchange


text:
Q: /usr/bin/time of a bash script containing ampersands lets say we have a bash script containing commands, some of which can have ampersand (&) symbols.
I would like to measure the execution time of such a script using the /usr/bin/time, but because of the ampersands the actual work gets done in the background, while the script returns command to the shell, resulting in measurements equal to zero.
Is there a way to suppress the ampersand behaviour (i.e. not letting the commands be run in background)?
The reason why I'm trying to do this is because I want to do a large-scale benchmark (large amount of data sets, and more than several tools (some of which exhibit such behaviour)).
A concrete, very simple example would be as follows.
Create a script test.sh containing:
#! /bin/sh
sleep 2 &

And try running it with:
/usr/bin/time ./test.sh

The result is:
0.00user 0.00system 0:00.00elapsed 100%CPU (0avgtext+0avgdata 668maxresident)k
0inputs+0outputs (0major+219minor)pagefaults 0swaps

The expected result would be around 2 seconds (either cpu or elapsed time).
Please note that the script above is only a toy example. Also, suppose that it cannot be modified (look at it as a black box).

A: Yes. Add a wait statement at the end of your script. This will cause that script to "wait" for the background tasks to finish.

A: This is a combination of answers from Elliott Frisch and Gilles (in the comments), and is intended to sum things up.
The answer is to create a wrapper script wrapper.sh that looks like:
#! /bin/sh
. $*; wait

The . (source command) will force the job to be executed in the same shell and not in the background, and wait will wait for all subprocesses to finish.
This can now be run as:
/usr/bin/time ./wrapper.sh ./test.sh

Please note that using the source command prevents you from changing the interpreter in test.sh's shebang line.


text:
Q: Showing each quiz inquiry separately I am trying to make a quiz using PHP and Mysql. I have create my database and filled it. The database is construct as follows:  question_id(P.K),question, right answer, annswer1,answer2, answer3,level and test_id(F.K).
I have created a query that "draws" questions in a random order and I have shuffled the answers. The PHP script for showing the Qs and As to the user is the following:
while ($index <= (count($test)-1)){
 echo $test[$index]['question']. "
";
 $question_id=$test[$index]['question_id'];
 $s_ans=User_Model::shuffle_answers($question_id);
  foreach ($s_ans as $s_a){
      echo "<input type='radio' name='test_ans[$index][$s_a]' id='$question_id' />$s_a
";

      }

 echo "
";
      $index++;

  }

The above code shows all questions and their answers at once.
What I would like to do, and couldn't successfully get it done, is to show each question separately and when the user presses the "next" button, the next question accompanied by its answers will be shown to him.
So,
a)is there a way I can achieve that?
b)when I try to access user's answers I get the following output:
Array ( [0] => Array ( [I  like ice cream => on ) [1] => Array ( [i don't go to school] => on ) [2] => Array ( [i play basketball] => on ) [3] => Array ( [i like sailing] => on ) )

How can i access the user's answers as to compare them with the right answer?

A: Well, since you're using PHP you can use sessions or cookies. It's probably not the most elegant solution, but I'd generate a reference string that represents a sequence of questions and store it in one session or cookie variable, and then have another session or cookie variable that represents the current position in the quiz. Furthermore you could have additional variables to keep track of score and other tidbits. Then when they hit the next button you just update variables and display the next question, or the end of the quiz if you've reached it.
If you want to do it dynamically without having to load another page then you'll need to look into javascript.

A: Multipage quizzes are very easy to do.
A) This can be done by removing the while() loop, but leave the counter to pass through a hidden <input> OR increasing the $_SESSION variable
$index = $_POST['index'] // OR $_GET['index'] OR $_SESSION['index'] depending on your form method
echo $test[$index]['question']. "
";
$question_id=$test[$index]['question_id'];
$s_ans=User_Model::shuffle_answers($question_id);
foreach ($s_ans as $s_a){
  echo "<input type='radio' name='test_ans[$index][$s_a]' id='$question_id' />$s_a
";
}

if ($index < $total_questions){
$index++; // Increase var, and then use in hidden input
echo "<input type='hidden' name='index' value='$index' />";
echo "<input type='submit' name='submit_answer' value='Next' />";}
else {
echo "<input type='submit' name='submit_answer' value='You Are Done' />";}
//OR
$_SESSION['index'] = $index++;

B) Without your code, this is just an example -
if ($user[$index]['their answer'] == $test[$index]['right answer'])
   { echo "You were correct";}
else
   { echo "Sorry, your answer was incorrect";}


text:
Q: Scala doesn't cast Element inside loop to yield value I am fairly new to scala. I have this method to filter all Elements -from Jsoup library- that start with a given namespace.
def getElementsByNamespace(element: org.jsoup.nodes.Element, namespace: String) : org.jsoup.select.Elements = {
    val elements =
      for {
        el <- element.select("*")
        if el.tagName().startWith(namespace+":")
      } yield el
    elements
  }

In this example <root><server:cpu></server:cpu><server:ram></server:ram></root> the method will get all elements that start with server
The problem is that scala is casting el <- element.select("*") as Any and not as Element which is the type returned by the method select (It actually returns an Elements object or an ArrayList)
For that reason, when I call if el.tagName().startWith(namespace+":") tagName() is not found and therefore the code doesn't compile.
I have tried filter, withFilter, etc but still not working.
Why is this happening? How can I make this code better?

A: Short Answer (tl;dr)
The problem is you need to convert between Scala and Java collections:
def getElementsByNamespace(element: org.jsoup.nodes.Element, namespace: String): org.jsoup.select.Elements = {
    import collection.JavaConverters._
    val elements = for {
      el <- element.select("*").asScala
      if el.tagName().startsWith(s"$namespace:")
    } yield el
    new Elements(elements.asJava)
  }

Explanation
In order to iterate over a collection in Scala you can use flatMap, map, or for comprehensions. There is no other way (like the for and foreach loops in Java).
But the thing is Java collections are not directly supported because they would need a flatMap method defined on them. flatMap is the essence of iteration (the other two methods are also defined based on flatMap).
That's why you need to convert the the variable of Elements type to a Scala collection (import JavaConverters._ and call asScala method on Java collections).
At the end, you need to construct a new Elements but constructors of that class, understandably, just accept Java collections, so you need to convert the result of your for comprehension, which is a Scala collection, to a Java collection.

A: I think that you may want to add import scala.collenction.JavaConversions._
Thing is Elements class, the one returned by select method does not support for comprehensions - as it is extension of ArrayList and hence does not have map, flatMap and filter methods - unless you do implicit conversion to one of scala collections.


text:
Q: Extract the first 6 lines from nvarchar text and the rest I need to extract the first 6 lines from this text and then the rest with a select statment, im using SQL server 2016.
Hi,
this is an
example
text to
extract the
first 6 lines
and then extract
the rest,
thanks

SELECT '6 first lines', 'rest lines'
Result:
COLUMN 1:
Hi,
this is an
example
text to
extract the
first 6 lines

Column 2:
and then extract
the rest,
thanks

A: Assuming you have a recent version of SQL Server, you can use the built-in functions STRING_SPLIT and STRING_AGG. A TABLE variable is used with an INT IDENTITY(1,1) column to keep track of the line numbers.
SQL Code:
CREATE TABLE Report (id INT, LongText NVARCHAR(MAX))
GO

INSERT INTO Report VALUES (37, 'Hi,
this is an
example
text to
extract the
first 6 lines
and then extract
the rest,
thanks
')
GO

DECLARE @Splitted TABLE(id INT IDENTITY(1,1), value NVARCHAR(MAX))
INSERT INTO @Splitted
       SELECT value FROM STRING_SPLIT( (SELECT TOP 1 LongText FROM Report WHERE id=37), CHAR(13) )

SELECT (SELECT STRING_AGG(value, CHAR(13)) FROM @Splitted WHERE id <= 6) AS Column_1,
       (SELECT STRING_AGG(value, CHAR(13)) FROM @Splitted WHERE id  > 6) AS Column_2

GO
DROP TABLE Report

You can see it working in a SQL Fiddle
I had to use CHAR(10) in the Fiddle because of how linebreaks are represented there. Presumably caused by the Web interface or by Linux hosting.

You can also create a User Defined Function for it:
CREATE OR ALTER FUNCTION SplitAsColumns(@LongText NVARCHAR(MAX), @LineCount INT)
RETURNS @TABLE TABLE(Column_1 NVARCHAR(MAX), Column_2 NVARCHAR(MAX))
AS
BEGIN
    DECLARE @Splitted TABLE(id INT IDENTITY(1,1), value NVARCHAR(MAX))
    INSERT INTO @Splitted SELECT value FROM STRING_SPLIT( @LongText, CHAR(13) )
    INSERT @TABLE
        SELECT (SELECT STRING_AGG(value, CHAR(13)) FROM @Splitted WHERE id <= @LineCount) AS Column_1,
               (SELECT STRING_AGG(value, CHAR(13)) FROM @Splitted WHERE id  > @LineCount) AS Column_2
    RETURN
END
GO

SELECT * FROM SplitAsColumns('Hi,
this is an
example
text to
extract the
first 6 lines
and then extract
the rest,
thanks
', 6)

A: browse for  DelimitedSplit8K
This is a table function that can split up any string by it's delimiter (in this case likely to be CHR(10) and/or CHR(13) into a table with a position number and the contents.  You can then select position <= 6 or > 6 for the two queries


text:
Q: Java optimal default number of threads without blocking I/O Two of the most common defaults that I've seen when sizing a non-blocking thread pool are:
number of threads = number of cores

number of threads = number of cores + 1

but now I found another one in Vert.x, which is:
number of threads = 2 * number of cores

Apparently the logic behind this value is that, as Java has no way of pinning a particular thread to a particular core, if we set # threads == # cores, we might be wasting some of the available cores. Theoretically by setting the # threads to something like 2 * # cores the probability of using all the cores increases.
I'm not sure if I'm convinced by this argument, as I would expect the OS scheduler to try to find the best distribution of work across the cores. It might not be the optimal distribution, but I would expect it to be better than having a constant multiplier.
I know that it all depends on the kind of tasks being performed but, assuming there is no blocking IO (so no need to have inactive threads waiting lots of time for a resource), is 2 * # cores a better default approach than # cores? Why?

A: The definitive book to Java threads (Java Concurrency in Practice) says:

For compute-intensive tasks, an Ncpu-processor system usually achieves optimum utilization with a thread pool of Ncpu +1 threads. (Even compute-intensive threads occasionally take a page fault or pause for some other reason, so an "extra" runnable thread prevents CPU cycles from going unused when this happens.)

According to my experiments this is true (Ncpu +1 was slightly better than Ncpu even though there was no I/O, but further increasing the number of threads had no benefits).
Of course, in a concrete situation you should always measure :)

A: The only definitive answer is to profile each one, because the behavior depends on what's running on your target system as well as the code involved.
If all of the threads are getting equal time, having (2*cores) will cause more context switches which can incur a penalty.
Also slightly related, there is a thread affinity library for Java called OpenHFT - which uses native code - allowing you to bind threads to specific cores.


text:
Q: Shriek push-forward for parameterized spectra In May and Sigurdsson's Parameterized Homotopy Theory, Proposition 2.2.11, four isomorphisms of functors are given. For a pullback square of base spaces $C=holim(A\overset{f}\to B\overset{j}\leftarrow D)$, with induced maps $C\overset{g}\to D$ and $C\overset{i}\to A$, there are natural isomorphisms:
$$(1)~~j^\ast f_!\cong g_!i^\ast~~~(2)~~f^\ast j_\ast \cong i_\ast g^\ast~~(3)~~f^\ast j_!\cong i_!g^\ast~~~(4)~~ j^*f_\ast\cong g_*i^*$$
Where for a map $f$ of base spaces, $f^\ast$ is the usual pullback of a parameterized space, $f_\ast$ is its right adjoint, and $f_!$ is its left adjoint.
Do these same natural equivalences hold for parameterized spectra over a pullback diagram of spaces? In particular, I am interested in equivalence $(3)$ above. And even more specifically, I am interested in comparing the two sides when $A$ above is a contractible space. In other words, $C$ is the homotopy fiber of the map $D\to B$. In that case, for a bundle of sphere spectra over $B$, we have that $i_!g^\ast$ yields the Thom spectrum of the pullback. How then should we think of $f^\ast j_!$ of the same bundle of sphere spectra?

A: Yes, the Beck-Chevalley condition holds for parameterized spectra. A proof appears as prop.4.3.3 in

*

*Michael Hopkins, Jacob Lurie, Ambidexterity in K(n)-Local Stable Homotopy Theory (pdf, nLab).

Some chat related to this is also around example 5.6 in my note "Quantization via Linear homotopy types" (arXiv:1402.7041)


text:
Q: Make Visual Studio not to compile any projects Is it possible to tell VS not to recompile some projects every time and use already compiled dll-s instead?

A: You can exclude any project from building in Configuration manager. Just unselect desired projects in Build column. You still will be able to debug those projects.

A: Instead of project references, you can add the compiled DLLs as references.
Any such referenced project will not rebuild if not changed.
However, since the references will now be to DLLs, you need some strategy to keep them synchronized and up to date with your code.

A: As I understood your question, you have a solution with multiple projects and you seem to have dependency of some of them on some other.
VS will always compile all the "loaded" projects. But when you add a reference to a project, add it directly to a (preferred) DLL assembly file, and not to one of the projects. This way the other project will be compiled but you are referencing the same DLL assembly over and over. Since if you reference the project, the output of the project is always what you reference actually.


text:
Q: Check if application is going to background and close my dialog(if any) I need to check if my application is going to background due to Home,power or any other event causing the application to go into background. Based on this event I have to close all the dialogs(if shown). My app also support orientation change and I have to retain dialog(if shown) in case of orientation change.
Things I tried: I have tried methods mentioned on the below blogs but it's fails in orientation change.
http://vardhan-justlikethat.blogspot.in/2013/05/android-solution-to-detect-when-android.html
Most of the Stackoverflow suggestion fails on orientation change.
EDIT
More information about my app so that could help.
My activity has Tabs and a container, which get replace with Fragment on tab click. Every fragment has different layout for landscape and portrait. Even the activity layout is different for landscape and portrait.

A: override your onPause method to insure that any open dialog is closed before it goes to background
@Override
protected void onPause() {
    super.onPause();
    if (alertDialog != null) {
        alertDialog.dismiss();
    }
}

A: On onPause dismiss all your dialogs:
@Override
protected void onPause() {
    super.onPause();
    if (dialog!= null) {
        dialog.dismiss();
    }
}

also if you want to handle orientation change then add this line in your activity tag in manifest:
android:configChanges="keyboardHidden|orientation|screenSize"

this will override the default behavior of android's orientation change.


text:
Q: UINavigationItem rightButton position is different on iOS6 vs iOS7 and missing touches I am trying to make my uinavigationbar to align the same way as in the iOS6 version of my app.  What I am finding is that on the iOS7 the uinavigationbar items are pulled in a bit towards the title.  Also for example if you are hitting just a litle right of the uinavigationitem.rightButton, the hits are not registered, however if you hit left of it for atleast 20px you can get the hits.  Can anyone help me with moving that touch area to the right as well?
Here is the code that I used to setup the button:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];

UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
rightButton.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
rightButton.imageEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
rightButton.frame = view.bounds;
rightButton.bounds = CGRectMake(0,0,44,44);
[view addSubview:rightButton];

[rightButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
[rightButton setImage:[[UIImage imageNamed:imageName] imageWithOpacity:0.8] forState:UIControlStateHighlighted];

[rightButton addTarget:target action:sel forControlEvents:UIControlEventTouchUpInside];

navItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];

Thanks,
Rajan

A: Use below code
UIImage *faceImage1= [UIImage imageNamed:@"slideshowarrow"];
UIButton *face1 = [UIButton buttonWithType:UIButtonTypeCustom];
face1.bounds = CGRectMake( 10, 0, faceImage1.size.width, faceImage1.size.height );
[face1 addTarget:self action:@selector(Goto_nextView) forControlEvents:UIControlEventTouchUpInside];
[face1 setImage:faceImage1 forState:UIControlStateNormal];
UIBarButtonItem *backButton1 = [[UIBarButtonItem alloc] initWithCustomView:face1];
self.navigationItem.rightBarButtonItem = backButton1;


text:
Q: C++, Jumping Sprite, Collision I'm trying to implement very basic platform/sprite behaviour using C++.
So far I have successfully rendered 2 platforms and a sprite which can move and jump. Below is a snippet of code that simulates the jump and gravity.
If I comment out lines 2,3, & 6 from the snippet commented "//gravity", I can not jump through the platform from underneath perfectly, but I'm unable to land on it... If I leave them as they are below, (Using the check_collision function), I can successfully jump up and onto a platform and move along it left and right. Unfortunately, if I press jump again (key119), I fall through the platform and sometimes even stick to the underneath of it instead of doing another jump.
What am I forgetting to implement to allow the sprite to do another jump?
    if(keyDown[119]){                                               //While 'w' key is pressed and not colliding
        if(!check_collision(sprite,platform)                        //If not colliding...
            && !check_collision(sprite,platform2)){
            y_Pos += jumpHeight;                                    //Jump up
            if(keyDown[97] ){x_Pos -= velocity*jumpLength;}         //While 'w' and 'a' are pressed, simulate arc of jump/gravity
            if(keyDown[100]){x_Pos += velocity*jumpLength;}         //While 'w' and 'd' are pressed, simulate arc of jump/gravity
        }
        else                                                        //Else you must be colliding, bounce off
            y_Pos -= jumpHeight;
    }
    if(keyDown[115]){y_Pos -= velocity;}                            //While 's' key is pressed
    if(keyDown[97] ){x_Pos -= velocity;}                            //While 'a' key is pressed
    if(keyDown[100]){x_Pos += velocity;}                            //While 'd' key is pressed

    //gravity
    if(y_Pos>0){                                                    //If above ground
        if(!check_collision(sprite,platform)                        //And not colliding
            && !check_collision(sprite,platform2)){
            gravity-=5*delta;                                       //Calculate gravity force
            y_Pos+=gravity;                                         //Descend to ground
        }
        if(keyDown[97] ){x_Pos -= velocity*2;}                      //While off ground, whilst 'a' is pressed, move left
        if(keyDown[100]){x_Pos += velocity*2;}                      //While off ground, whilst 'd' is pressed, move right
    }
    else{gravity=0;}                                                //Else, on ground, so gravity force is zero

Please excuse my naivety and do be patient, I am self learning and we all have to start somewhere. Thanks.
There's too much code to post the whole program, but if you're interested, the full source code can be found here


text:
Q: Continuously differentiable implies Lipschitz in one variable? Let $f:[t_{0}-a,t_{0}+a] \times [y_{0}-b,y_{0}+b] \to \mathbb{R}$ be continuously differentiable. Consider the problem
$$\begin{align*} y' &= f(t,y),\\
y(t_{0})&=y_{0}.
\end{align*}$$
Assume that the solution to the initial value problem exists in the interval $[t_{0}-a,t_{0}+a]$. Prove that Euler's method converges.
I have a theorem that will give convergence if I can establish that
$$ |w_{i}-y(t_{i})| \le \frac{hM}{2L} \left(e^{L(t_{i}-a)}-1\right),$$
where $y_{i}$ is the true solution, $w_{i}$ is the approximation from Euler's method, $M$ is a bound on $|y''(t)|$ and $L$ is the Lipschitz constant for $f$ in the variable $y$.
I can obtain $M$ from the fact that $f$ has a continuous derivative on a compact set, but I am having trouble determining if $f$ is Lipschitz continuous in $y$.
How can I show that $f$ is Lipschitz in $y$?


text:
Q: Failed to Open source file while system call in C I am trying to create a call to system using custom parameters. However I think that I am incorrectly malloc-ing the size of the final char*.
So I instead get a Failed to Open source file error during the system call. Am I doing something wrong in terms of syntax?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
  char program_name[] = "/usr/local/bin/some_program";
  char argument_1[] = "foo";
  char argument_2[] = "foo2";
  char space[] = " ";
  char *runProgram = malloc( strlen(program_name) + strlen(argument_1)+
                             strlen(argument_2) + 2*strlen(space) + 1);

  strcpy(runProgram, program_name);
  strcat(runProgram, space);
  strcat(runProgram, argument_1);
  strcat(runProgram, space);
  strcat(runProgram, argument_2);

  system(runProgram);
  free(runProgram);
  exit(0);
}

A: When I run your code, your string appears to contain exactly what it needs to to be called.  I do have a suggestion to simplify building it though:
...
int ret=0;
int len = strlen(program_name) + strlen(argument_1)+ strlen(argument_2) + 2*strlen(space) + 1;
char *runProgram = malloc( len);

ret = snprintf(runProgram, len, "%s %s %s", program_name, argument_1, argument_2);
if(ret < 0)
{
    //handle if truncation occurred (returns -1 for truncation)
}
if(ret >= len)
{
    //use runProgram buffer
}
system(runProgram);
free(runProgram);
//exit(0);
return 0;
...

Have you verified the chmod settings on the file to be executed are correct?
chmod +x /usr/local/bin/some_program

EDIT:
To address concern in comments regarding variations in implementation/documentation for snprintf().  When discussing standard C functions, the hope would be that implementations of the same function would be equal across platforms, but for snprintf(), it appears that some implementations are more equal than others...
1) snprintf some have referred to this as Microsoft's broken implementation.
2) snprintf from skrenta.com
3) snprintf from opengroup.org.
4) snprintf from linux.die.net, (includes glibc references, macros and other comments)

A: Your code should work fine, printf("cmd is '%s'\n", runProgram); to check if generated command can be run in shell and produces expected results:

*

*command string is correct

*/usr/local/bin/some_program exists and has correct permissions

*some_program does not fail


text:
Q: Rails version different by folder If I'm just in my user folder and I do rails -v I get 5.0.2. However if I cd into the directory of my project I get 5.0.0.1.
Why is there a difference and how do I update my project to be the latest version of rails?

A: Bundler uses a Gemfile.lock to save the versions and names of gems. When this is checked into version control, it ensures that your set of gems are exactly same across all machines. This fosters stability in an ever changing world.
The Gemfile.lock is generated by bundler, and based on the syntax system of the Gemfile you can dictate version there.
If you'd like to update rails, you can run:
bundle update rails

You should be careful with updating gems. Make sure you have good test coverage and run your test suite after you update to ensure you haven't broken anything because of the update.
Here's a link to the Gemfile.lock page of the bundler documentation, it covers a lot of these topics.
And, here's a link to the Gemfile docs.


text:
Q: When logged into a Linux system, can I find the ip addresses which can be used to connect to the machine via ssh? In our lab, we have a Linux server that we can log onto locally or ssh into with a specific IP. When I am logged into the machine, I can see its internal IP with ifconfig or ip a and I can see its external IP through something like curl icanhazip.com. However, the external IP reported by that last command, is different from the one I type in when using ssh to connect to the machine, I believe the reported IP is the IP of our router.
When I am logged into the machine locally, is it possible for me to find out which IP addresses can be used to ssh into the system (not the IP addresses of the users that are logged in, but rather what IP addresses I can use with the ssh ###.###.###.### command). I would like to find this out without logging into the router admin panel to see what IP addresses and ports are being forwarded. Would the ssh IP addresses be stored in a file (I could not find anything in /etc/sshd_config), or is there a command that I can run to display it, like with the internal IP?

A: Many utilities will show the user's IP address, including who and w and last -ai.
Of course, if there is any form of redirection taking place, you may be looking at the machine that did the redirection.

A: If I understand you correctly, you want to know if you can be on a LAN node behind a router and from that machine see which ports your router is using to forward you the SSH traffic? If that's the question, there's not going to be a way to do that in your scenario. The router config will not be visible to you, however there are several ways to go about probing to find it.
If it's a private network and you have authorization you can run a standard network map (nmap) and/or leave netstat open in a terminal. Better yet, get a verbose output of (insert firewall solution like ufw or firewalld or just iptables) and start/stop the services and your firewall will tell you exactly which ports are being pinged/blocked/used by ssh from both sides (router in, you out). The easiest way with Deb/Ubuntu/Mint would be to just open gufw as sudo and watch the log after typing  sudo systemctl restart ssh
If the question is how to find your internal or external IP, I think that's been covered. But knowing those numbers is useless without the port (I'm sure you know the default for SSH is 22).

A: ip route get 8.8.8.8 | awk '{print $NF; exit}'

gives your local ip address
IP=$(curl -s http://www.whatsmyip.website); echo $IP

gives the ip address into the router


text:
Q: Issues with WebSite to WebApplication conversion I converted a website to a web application using visual studio 2017.After conversion the web application throws the following error.Is there any solution to this problem

Parser Error Message: The file '/Global.asax.vb' does not exist.

Source Error:

Line 1:  <%@ Application Inherits="WebApplication1.Test.Global"
  Language="VB" CodeFile="Global.asax.vb" %

A: Open NOTEPAD application with a blank document.
Paste the following code into it
Option Explicit On
Imports Microsoft.VisualBasic
Imports System.Web.SessionState

Public Class Global_asax
  Inherits System.Web.HttpApplication
  '
  Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
    ' Fires when the application is started
  End Sub

  Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
    ' Fires when the session is started
  End Sub

  Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
    ' Fires at the beginning of each request
  End Sub

  Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
    ' Fires upon attempting to authenticate the use
  End Sub

  Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    ' Fires when an error occurs
  End Sub

  Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
    ' Fires when the session ends
  End Sub

  Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
    ' Fires when the application ends
  End Sub

End Class

Save the file as GLOBAL.ASAX in the ROOT folder of your application where the code is.
Next which ever file has the error flagged it:
Line 1: <%@ Application Inherits="WebApplication1.Test.Global" Language="VB" CodeFile="Global.asax.vb" %>

Change that line to the below:
<%@ Application Inherits="WebApplication1.Test.Global" Language="VB" %>

Without seeing some of your code as there is no code posted, its difficult to nail it down straight away.
If you follow the above, it should get you past the error you displayed.


text:
Q: RelativeLayout gravity center not working I'm trying to horizontally center several views in a RelativeLayout that is a base.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
    android:background="@android:color/transparent" >

This isn't working. I have set centerInParent to true for one of the views and that did work. However, I can't use this solution because I have 2 views side by side that need to be centered together. Trying to optimize this so I want to avoid nesting layouts, especially Linear, inside of each other.
Is there something obvious that I'm missing? I thought this attribute is made for this situation.

A: Wrap the two views in a LinearLayout and then center the LinearLayout in the RelativeLayout like you did for the single TextView.

A: I answered a similar issue involving three views without using nested ViewGroups.
https://stackoverflow.com/a/13279846/1011746
This is tested in API 11.
For the two view horizontal case:
<RelativeLayout
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:gravity="center"
  android:background="@android:color/black"
  >
  <Button
    android:id="@+id/apply"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="APPLY"
    android:textSize="20sp"
    />
  <Button
    android:id="@+id/undo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="UNDO"
    android:textSize="20sp"
    android:layout_toRightOf="@id/apply"
    />
</RelativeLayout>

For the two view vertical case:
<RelativeLayout
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:gravity="center"
  android:background="@android:color/black"
  >
  <Button
    android:id="@+id/apply"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="APPLY"
    android:textSize="20sp"
    />
  <Button
    android:id="@+id/undo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:text="UNDO"
    android:textSize="20sp"
    android:layout_below="@id/apply"
    />
</RelativeLayout>

A: You'll need to nest several layouts together. To center something in a RelativeLayout, you use android:layout_centerInParent="true" on the child. If you try to center several childs, they'll end up under/over each other.
Therefore, for example, you could use a LinearLayout with two views as a child to the RelativeLayout, with the LinearLayout having android:orientation="horizontal" and android:layout_centerInParent="true". The LinearLayout should now be centered in the RelativeLayout, with the two children next to each other.

A: So my fix for this issue turn out just to leverage the compound drawable feature of textview. I just trashed the button and used drawableRight to show the search icon.


text:
Q: BlackBerry - Ant build script for more complex apps I am having trouble creating an Ant build script for our production apps.
I have been reading a lot about Ant, and bb-ant-tools. I have followed many stackoverflow questions on Ant & BB (referenced below in comments to "link" the questions). I would like help with a script more complex than the usual "Hello World!" style apps. My current build process is run entirely in Eclipse, and done manually.
For this question, I would like to ask how to use Ant to build a project that uses 2 (or more) different library projects (which also need to be built), without using Eclipse at all?
I have Ant, bb-ant-tools installed. I have built & deployed on device a basic Hello World, using these tools following basic examples. I have created a build script, and some property files; but when I run the scripts, the end product does not run on the phone (phone UI freezes on the launch screen).

I have 3 build scripts, one for each library, and one for the main app. These are identical, except for the project name (and could be combined into one common imported script at some point). Each of the 3 java projects has an Ant properties file related to it. I also use 3 common properties files for defining constants, storing info on the JDE & the code signing password.

*

*common.properties:
jde.home=C:/development/tools/bb-jde/jde4.5/components
sigtool.jde = ${jde.home}
sigtool.password = xxx_pass_xxx

*project.properties (for SOAP library):
output=MySOAP
type=midlet

*project.properties (for internal SDK library):
output=MySDK
type=midlet

Update 1: I have updated the library property files since initial post. Previously I set type=library (based on RIM documentation). Based on my research outlined in this post (BlackBerry - use own JAR file in own project), I tried changing to type=midlet. This gives better results (at least on my platform BB JDE 5.0).

*

*project.properties (for my app):
output=MyApp
title=App
type=cldc
vendor=Richard
version=1.0.7
description=A nice app
icon=icon.png

*build.xml (all the same except for the name at the top, and the 2 library scripts do not have filesets declared inside import.jars):
<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="MyApp" default="build">

    <!-- BLACKBERRY ANT TOOLS -->
    <property name="bb-ant-tools.home" location="C:/development/tools/bb-ant-tools" />
    <taskdef resource="bb-ant-defs.xml" classpath="${bb-ant-tools.home}/bb-ant-tools.jar" />

    <!-- CONFIG FILES -->
    <property file="${common.basedir}/common.properties" />
    <property prefix="project" file="project.properties" />

    <!-- FOLDERS -->
    <property name="dest.dir" location="build" />

    <!-- this is empty in the library scripts -->
    <path id="import.jars">
        <fileset dir="../MySDK/build" includes="*.jar" />
        <fileset dir="../MySOAP/build" includes="*.jar" />
    </path>

    <path id="src.files">
        <fileset dir="src" includes="**/*" />
        <fileset dir="res" includes="**/*" />
    </path>

    <!-- TARGET ACTIONS -->

    <target name="build" depends="">
        <mkdir dir="${dest.dir}" />

        <!-- work around a bug requiring app icons to be in the output folder -->
        <copy file="${basedir}/res/icon.png" tofile="${dest.dir}/icon.png" />

        <rapc
                jdehome="${jde.home}"
                output="${project.output}"
                destdir="${dest.dir}" >

            <import refid="import.jars" />
            <src refid="src.files" />
            <jdp file="${basedir}/project.properties" />
        </rapc>
    </target>

    <target name="sign" depends="build">
        <sigtool
                codfile="${dest.dir}/${project.output}.cod"
                jdehome="${sigtool.jde}"
                password="${sigtool.password}" />
    </target>

    <target name="clean">
        <delete dir="${dest.dir}" />
    </target>

</project>

Update 2: I have updated the build.xml since the initial post. Target build now copies the app icon into the build output folder (${dest.dir}) to work around a bug in bb-ant-tools / rapc.

So this is a very simple Ant script, except:

*

*I would like to know how to trigger the sub-builds off from the main
app build (my answer below deals with that).

*The big one, is that the resulting output from this does
not work.

FWIW I have found the following popular resources, and list them so that they need not be added as answers, and to help anyone in the future looking for info:

*

*Basic Ant Tutorial

*Automating Eclipse-Based BlackBerry Project With Ant

*How to use rapc from RIM

*jarjar tool

*and many answers here on stackoverflow - see my comments below

A: This is what I'm using across multiple projects.
<macrodef name="compile">
    <attribute name="buildversion" />
    <attribute name="description" />
    <sequential>
        <mkdir dir="${build.dir}" />

        <rapc output="${cod.name}_bbminterface"  destdir="${build.dir}" verbose="false" quiet="true" nowarn="true">
            <src>
                <fileset dir="${bbminterface.src.dir}"/>
            </src>
            <import location="./lib/net_rim_bb_qm_platform.jar" />
            <jdp type="library" title="${app.name}_bbminterface" vendor="my vendor" version="@{buildversion}">
                <entry title="${app.name}_bbminterface" description=""/>
            </jdp>
        </rapc>
        <rapc output="${cod.name}_bbmimpl" destdir="${build.dir}" verbose="false" quiet="true" nowarn="true">
            <src>
                <fileset dir="${bbmimpl.src.dir}"/>
            </src>
            <import location="./lib/net_rim_bb_qm_platform.jar" />
            <import location="${build.dir}/${cod.name}_bbminterface.jar" />
            <jdp type="library" title="${app.name}_bbmimpl" vendor="my vendor" version="@{buildversion}" runonstartup="true" startuptier="6">
                <entry title="${app.name}_bbmimpl" description="" runonstartup="true" startuptier="6"/>
            </jdp>
        </rapc>

        <rapc output="${cod.name}" destdir="${build.dir}" verbose="false">

            <src>
                <fileset dir="${tmpsrc.dir}" />
            </src>
            <src>
                <fileset dir="${res.dir}" />
            </src>
            <src>

                <fileset file="${lib.dir}/paymentapi.jar" />
            </src>
            <import location="./lib/net_rim_bb_qm_platform.jar" />
            <import location="${build.dir}/${cod.name}_bbminterface.jar"/>

            <jdp type="cldc" title="${app.name}" vendor="my vendor" icon="../res/icon.png" version="@{buildversion}" description="@{description}" startuptier="7" ribbonposition="0">
                <entry title="${app.name}" icon="../res/icon.png" description="@{description}" runonstartup="true" arguments="boot" systemmodule="true" startuptier="7" ribbonposition="0" />
                <entry title="${app.name}" icon="../res/icon.png" description="@{description}" arguments="daemon" runonstartup="true" systemmodule="true" startuptier="7" ribbonposition="0" />
            </jdp>
        </rapc>
    </sequential>
</macrodef>

This is the compilation code.  We're compiling a few libraries and then the application, linking the just created libraries.
Then for signing:
<target name="sign" description="Sign the cod file">
    <sigtool codfile="${build.dir}/${cod.name}_bbminterface.cod" password=""/>
    <sigtool codfile="${build.dir}/${cod.name}_bbmimpl.cod" password=""/>
    <sigtool codfile="${build.dir}/${cod.name}.cod" password="" />
</target>

And then uploading to our OTA server:

A: To answer my question about triggering builds for included projects, from my main build file, the solution is to use the subant task, which is a standard Ant command.
For example, the below code (I forget where I copied it from, but its not mine, and it does work) will trigger the build.xml file in each of the folders supplied, and will run the export-all target within that build file.
    <subant target="export-all">
        <dirset dir="${basedir}/.." includes="${project.deps}" />
        <property name="export.dir" location="build/lib" />
    </subant>

It requires a property called project.deps to be declared as a comma-separated list of folders. The dirset is defined by looking back one folder from the main build.xml, and looking for each of the subfolders in project.deps.
Ant will then find the build.xml file in each of these folders, and run it, looking for the export-all target.
Within each of the new export-all subtasks, the property export.dir will have been set, which is how you can pass info from the main build.xml into the subtasks.

A: In order to maintain the resource structure instead of adding the 'res' folder as a source folder do the following:

*

*Create a temporary jar file of all the resources using the ANT 'jar' command:
<jar destfile="temp/@{brand}/res.jar"
    basedir="../@{brand}/res"
    compress="false"
    filesonly="false"
    includes="**/*"/>

*Add the temporary jar as a source element inside the 'src' element of the rapc command:
<fileset dir="temp/@{brand}" includes="res.jar"/>

A: I hope you don't forget to ship your library cods with your app cod to the end user. Because otherwise app won't work.
About triggering library building - I prefer build libraries only when it's necessary - code or dependency changed.
About solution for you I would just have bat file where I will trigger ant three times with different build.xml files and proper current files (because you ant scripts have relative directories). So it would be like:
cd librarydir1
ant
cd librarydir2
ant
cd appfolder
ant

A: I saw question about how to save resource directory structure in Dhiral's comment to Joe's answer. Some days ago I found workaround here (Blackberry Development with Ant & Eclipse) in comments to post:
yuri wrote:
I found a way

You just need to copy the resources temporarily to the output folder, and delete them
after the build is over. The key is that the resources must be in the working folder
of the compiler.

Posted 18 Jan 2008 at 5:08 pm ¶


text:
Q: Dependency injection: Unable to inject Carbon class in custom-helper class in laravel application I created a app\lib folder to keep my custom helper class. I added it to autoload in composer.json and ran composer dump-autoload. For the test purpose I quickly created a class called MyHelper and tried to instantiate it and it did work as expected. The custom helper class was nicely loading.
In my application, I needed to work with dates. So I chose to work dates with the help of Carbon extension. I found that it was already in Laravel vendor folder. To make easy, I added an alias in app.php
'Carbon'          => 'Carbon\Carbon'
Below is my custom helper class. (Code below is working fine)
class MyHelper{

public $today;

public function __construct(){
    $this->today = Carbon::now();
}

In the above code, I am creating a carbon object by doing Carbon::now(). This seems ok and working fine but as far as I know, it is better to do dependency injection rather than instantiating within the construct method. This will make testing more easy.
So I modified above construct method as below:
public function __construct(Carbon $carbon){
    $this->today = $carbon->now();
}

But, the above code does not work. And the error reporting is telling me that argument of construct method must be instance of Carbon\Carbon.

Argument 1 passed to Date::__construct() must be an instance of
  Carbon\Carbon, none given

I also added use Carbon\Carbon as Carbon but no joy. I think I am misunderstanding some simple logic of Laravel. May be misunderstanding with dependency injection or IOC that resolves classes.
Enlighten me..

A: It seems like you are having problems in instantiating MyHelper. Make sure that you pass a Carbon to your constructor. I believe you have something like
$myHelper = new MyHelper();

However, your constructor expects a Carbon parameter. Assuming that $carbon is a Carbon instance, you could do something like:
$myHelper = new MyHelper($carbon);

EDIT:
Laravel has an Inversion of control, which is used like this:
class FooBar {

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

}

$fooBar = App::make('FooBar');

(taken from here)
The make method is needed to be used instead of the pure PHP constructor call. Laravel should call the constructor correctly under the hood.

A: Kindly remove the alias and try
Not sure if there is any need adding alias since u want to inject
use Carbon\Carbon;

    class MyClass{

        protected $today;

        public function __construct(Carbon $carbon){
            $this->today = $carbon->now();
        }

    }


text:
Q: Reverse for 'userprofile' not found. 'userprofile' is not a valid view function or pattern name When i write in urls.py app_name = 'user_homeview'  then occure error in header.html  how i solve this error can you tell me i couldn't solve error yet please  tell me..in below html file where  wrote href="{%url 'userprofile' i.user %}" in code occure error after write app_name='' in urls.py please tell me how i solve
head.html
 {% for i in userpofile %}

                  {{i.user}}&nbsp
            {% endfor %}

urls.py

app_name = 'user_homeview'

urlpatterns = [

    path('', views.user_home,name='e'),
    path("user/follow/<str:username>", views.follow, name="follow"),
    path('postWrite', views.postWrite ,name='post'),
    path('post', views.post ,name='post'),
    path('like_dislike', views.likePost ,name='like_dislike_post'),
    path('slug/comment', views.comment ,name='comment'),
    path("delete/<int:ID>",views.delpost,name="delpost" ),
    path("search/", Search_User.as_view(), name="search_user"),
    path("<str:username>",views.userProfile,name="userprofile" ),
    path("<str:username>/edit", EditProfile.as_view(), name="editprofile"),

A: Since you declared the app_name you need to use that to construct the URL. So the correct way would be:
{% url 'user_homeview:userprofile' i.user %}


text:
Q: Webrick server error in Rails
Possible Duplicate:
Ruby On Rails 3 and Webrick issue

$ rails server
/Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/ruby-debug-base19-0.11.25/lib/ruby-debug-base.rb:1:in `require': dlopen(/Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/ruby-debug-base19-0.11.25
/lib/ruby_debug.bundle, 9): Symbol not found: _ruby_current_thread (LoadError)
  Referenced from: /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/ruby-debug-base19-0.11.25/lib/ruby_debug.bundle
  Expected in: flat namespace
 in /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/ruby-debug-base19-0.11.25/lib/ruby_debug.bundle - /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/ruby-debug-base19-0.11.25/lib/ruby_debug.bu
ndle
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/ruby-debug-base19-0.11.25/lib/ruby-debug-base.rb:1:in `<top (required)>'
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/ruby-debug19-0.11.6/cli/ruby-debug.rb:5:in `require'
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/ruby-debug19-0.11.6/cli/ruby-debug.rb:5:in `<top (required)>'
Vineethsfrom /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/bundler-1.1.4/lib/bundler/runtime.rb:68:in `require'
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/bundler-1.1.4/lib/bundler/runtime.rb:68:in `block (2 levels) in require'
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/bundler-1.1.4/lib/bundler/runtime.rb:66:in `each'
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/bundler-1.1.4/lib/bundler/runtime.rb:66:in `block in require'
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/bundler-1.1.4/lib/bundler/runtime.rb:55:in `each'
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/bundler-1.1.4/lib/bundler/runtime.rb:55:in `require'
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/bundler-1.1.4/lib/bundler.rb:119:in `require'
        from /Users/Vineeth/QA4/config/application.rb:7:in `<top (required)>'
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.3/lib/rails/commands.rb:53:in `require'
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.3/lib/rails/commands.rb:53:in `block in <top (required)>'
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.3/lib/rails/commands.rb:50:in `tap'
        from /Users/Vineeth/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.3/lib/rails/commands.rb:50:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'

When i tried to start server from Aptana studio it shows like above........
please help me solve this error......thanks.

A: Change your debugger to
gem 'debugger'

in your Gemfile.
Remove
gem 'ruby-debug19'

don't forget to run bundle install again.


text:
Q: Name for this matrix operation? Suppose two matrices have the same number of rows. I want to perform an operation of element-wise product between all possible column pairs between the two matrices. For example, if
$A = \left[{\begin{array}{ccc}
1 & 2 \\
3 & 4
\end{array}}\right], B=\left[{\begin{array}{ccc}
5 & 6 & 7 \\
8 & 9 & 10
\end{array}}\right],
$
then the operation leads to a matrix of 6 columns,
$C = \left[{\begin{array}{ccc}
5 & 6 & 7 & 10 & 12 & 14\\
24 & 27 & 30 & 32 & 36 & 40
\end{array}}\right].
$
My question is: Is there a name (and notation) for this kind of matrix operation, similar to Hadamard product?
The background for the question is that such operation seems to be involved in constructing the interaction columns between two dummy-coded factors.

A: I am not sure what that matrix operator is called, but it is very close to being a  Kronecker product (i.e., $A\otimes B$ ) so maybe there is something similar to that?  In either case here is some fast code for getting it out of R using Kronecker products as well.
> kronecker(A,B)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    5    6    7   10   12   14
[2,]    8    9   10   16   18   20
[3,]   15   18   21   20   24   28
[4,]   24   27   30   32   36   40

> kronecker(A,B)[c(1,4),]
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    5    6    7   10   12   14
[2,]   24   27   30   32   36   40

A: No there is not a defined and studied compact matrix operation that does this - "this" being a combination of column-wise Hadamard multiplication and matrix augmentation, which uses the symbol "|".
Your operation requires conformable row dimensions. Using small letters to denote the columns of a matrix we have
$$A_{k\times n} = \begin{matrix} [a_1 & ...& a_n] \end{matrix}, \qquad B_{k\times m}=\begin{matrix}[b_1 & ...& b_m]\end{matrix}$$
$$ C_{k\times (n\times m)} = \Big [a_1*b_1|...|a_1*b_m|...|a_n*b_1|...|a_n*b_m\Big]$$

A: I don't know what you would call this, but here's a quick way you can do this in R:
a = t(matrix(c(1,2,3,4), nrow=2))
b = t(matrix(c(5,6,7,8,9,10), ncol=2))

matrix(apply(a,2, function(x) x * b)
       ,ncol(a)
       ,ncol(a)*ncol(b))


text:
Q: OrderedDict sorting incorrectly As I understand it, the following should result in an OrderedDict object with the items sorted by the key, which is a datetime object.
ledger = OrderedDict(
    sorted(ledger.items(), key=lambda x: datetime.strftime(x[0], '%d-%m-%Y'))
)

However, in my case, the objects are being sorted out of order:
OrderedDict([
    (datetime.date(2021, 10, 1), {'net': -33924, 'entries': [{'text': 'Applied to 102101', 'amount': -16962, 'mode': 'debit'}, {'text': 'Applied to 102104', 'amount': -16962, 'mode': 'debit'}]}),
    (datetime.date(2021, 11, 3), {'net': -96118, 'entries': [{'text': 'Applied to 102104', 'amount': -96118, 'mode': 'debit'}]}),
    (datetime.date(2021, 9, 24), {'net': 18000.0, 'entries': [{'text': 'Payment Received', 'amount': 18000.0, 'mode': 'credit'}]})
])

What are the caveats that I am missing here?

A: If you want to sort in some way that is not chronological, you can access the attributes you want to sort by and use tuple sorting:
sorted(datetimes, key=lambda d: (d.month, d.seconds))  # or some other weird sorting

If it's just a chronological sort however, then you don't need to bother with any of this:
In [3]: OrderedDict(sorted(ledger.items()))
Out[3]:
OrderedDict([(datetime.date(2021, 9, 24),
              {'net': 18000.0,
               'entries': [{'text': 'Payment Received',
                 'amount': 18000.0,
                 'mode': 'credit'}]}),
             (datetime.date(2021, 10, 1),
              {'net': -33924,
               'entries': [{'text': 'Applied to 102101',
                 'amount': -16962,
                 'mode': 'debit'},
                {'text': 'Applied to 102104',
                 'amount': -16962,
                 'mode': 'debit'}]}),
             (datetime.date(2021, 11, 3),
              {'net': -96118,
               'entries': [{'text': 'Applied to 102104',
                 'amount': -96118,
                 'mode': 'debit'}]})])


text:
Q: How do I exclude a list of keys when cloning a JavaScript object? I am working on an app with a normalized state in Redux. One of my entities is the 'parent' entity of another, so when I delete that parent entity I want to delete all of the children entities associated with that parent.
For deleting a single entity (1 ID), I have been using this pattern:
// ../reducers/entity.js
case DELETE_ENTITY: {
    const entityId = action.payload.entityId;
    const {[entityId]: ignore, ...stateWithoutEntity} = state;
    return stateWithoutEntity;
}

For context, the state in the above snippet is shaped as such:
{
    ID_1: {
        //entity 1 value
    },
    ID_2: {
        //entity 2 value
    },
    // etc...
}

Is there a similar patten for deleting a list of multiple entities (n IDs)?
In other words, is there a pattern for cloning a JavaScript object while excluding several keys?
// ../reducers/entity.js
case DELETE_PARENT_ENTITY: {
    const parentId = action.payload.parentId;
    const childrenIdsToRemove = action.payload.children;
    // How do I clone the state while excluding each ID in childrenIdsToRemove?
}

A: If you have lots of keys of an object you want to remove, you can use Object.entries and then filter, and then finally reduce to make the final object.
Below is a simple example, that basically remove all keys that start with entity.

Update, Thanks to comments changed to fromEntries instead of reduce

const x = {
  'entity1': 1,
  'something': 2,
  'entity2': 3,
  'another': 4
}

const y =
  Object.fromEntries(Object.entries(x)
  .filter(([k]) => !/^entity/.test(k)));

console.log(y);


text:
Q: Stuck setting up multiple network interfaces with one gateway using /etc/network/interfaces I'm an advanced noob and I'm running into the limitations of my understanding of how to set up my network. My gateway to the internet should be 10.0.1.1, and I have 2 PCI 10ge nic cards installed to communicate with other devices not on the internet.
I thought I had my /etc/network/interfaces set up correctly so I'm only using 10.0.1.1 as the gateway to the internet, but when I add the first 10ge network interface (192.168.1.100) it seems to throw it off.
I'm still able to ping 1.1.1.1, and devices on the 192.168.1.x network, but when I traceroute 1.1.1.1 it takes over a minute to execute and it's going from 10.0.1.1 to 192.168.1.254 before hopping outside.
I don't see why any outside request is being directed through 192.168.etc... I'm guessing there's another /etc/ doc that I'm not aware about that I need to edit.
Any insight would be greatly appreciated.
I'm on Debian 10, and Below is my /etc/network/interfaces
source /etc/network/interfaces.d/*

auto lo
iface lo inet loopback

#iface eno1 main connection to network
    allow-hotplug eno1
    auto eno1
    iface eno1 inet static
    address 10.0.1.101
    netmask 255.255.255.0
    network 10.0.1.0
    broadcast 10.0.1.255
    gateway 10.0.1.1

# iface enp1s (first 10gbe card)
    allow-hotplug enp1s0f0
    auto enp1s0f0
    iface enp1s0f0 inet static
    address 192.168.1.100
    netmask 255.255.255.0


text:
Q: How do I omit the assembly name from the type name while serializing and deserializing in JSON.Net? We have a single contract assembly which has all our data contracts. We are using JSON.net for serializing our data contracts to json.
JSON.Net adds both the type name and the assembly name in the $type attribute on serialization. Since all our data contracts are in the same assembly which is always loaded in the current app domain, we should be able to omit this.
How can we achieve this?
Thanks

A: You can use the Binder property in your JsonSerializerSettings.
This blog post (by the library author) describes the steps: http://james.newtonking.com/archive/2011/11/19/json-net-4-0-release-4-bug-fixes.aspx
In short, you create a custom class deriving from SerializationBinder and override two methods:

*

*BindToName(Type serializedType, out string assemblyName, out string typeName)

*BindToType(string assemblyName, string typeName)
The logic you place in those methods will give you direct control over how type names are converted to string representation in the $type field, and how types are located at run-time given values from $type.
In your case, wanting to omit the Assembly name, you can probably do:
public override void BindToName(
    Type serializedType, out string assemblyName, out string typeName)
{
    assemblyName = null;
    typeName = serializedType.FullName;
}

public override Type BindToType(string assemblyName, string typeName)
{
    return Type.GetType(typeName);
}

A: I think maybe tag the class with the JsonObjectAttribute
[DataContract]
[JsonObject("")]
public class MyContractClass { ... }

This should override the fact that it is also a DataContract.


text:
Q: Fix array of incomplete links I'm writing a bash script that will find links in a page. It downloads the source code from a page and finds links in a tags and stores them into an array, $links. The problem though is that some links will not include the entire URL, just the sub-page or file. Say the source code of a page looks like this:

Julian's crappy webpage

Page One
Page Two
Page Three
Page Four

After finding links, the array would look something like this:
http://one.com
https://two.com
/three
four

I also have a variable $URL which is a valid URL, e.g. "https://google.com"
I need a way to make all of the items in $links valid by doing different things based on the item. For every item in $links:

*

*If the item starts with a /, then combine: $URL + ${links[n]}

*If the item does not start with a "/" or "https://" or "http://", then combine: $URL + "/" + ${links[n]}
Expected response for example above:
http://one.com
https://two.com
https://google.com/three
https://google.com/four

A: Here is a sample script which you can use to implement this:
#!/bin/bash

shopt -s extglob
readonly URL="https://google.com"
links=($(grep -o -P '(?<=href=").*(?=")' source.html)) # read into array

for ((i=0; i<${#links[@]}; i++))
do
  case ${links[$i]} in
    http*)
      : # do nothing
      ;;
    /*)
      links[$i]="$URL"${links[$i]}; # update array
      ;;
    *)
      links[$i]="$URL/"${links[$i]}; # update array
      ;;
  esac
done

It assumes source.html is the downloaded source of the web page in the current directory.

A: There are countless ways that using a regex to parse HTML can go wrong.  Even for a seemingly simple task like extraction of URLs from a HTML file.
So, don't use a regex.  Use something like this instead:
#! /bin/bash

htmlfile='./file.html'
URL='https://google.com'

links=($(lynx -dump -listonly -nonumbers -force_html "$htmlfile" |
         sed -e "s=^file://=$URL="))

printf "%s\n" "${links[@]}"

This requires that lynx be installed.  lynx is an ncurses-based text-mode web browser.  It is being used here to just generate a list of links in the HTML file, because lynx has already solved the much harder than you might think problem of how to reliably find URLs in HTML content (that's an important part of a browser's job).  Other languages like perl or python have good library modules for parsing HTML to extract URLs.  For shell scripts, use lynx.
See man lynx for details.
lynx is almost certainly available pre-packaged for your Linux distro or other unix-like OS.  If not, you can get the source code from the link above.


text: Q: save the image taken from camera to SQLite database and display them on computer? my application have a requirement to save the image taken from camera to sqlite database locally on mobile, then transfer the data from database from mobile memory to computer. The problem is i am not able to display the real image back onto computer though it shows in DB that the file is saved in PNG format? ANy help would be great. :)


text:
Q: Refresh from DB keeps OneToOneField Relation I have a simple model relation:
class Foo(models.Model):
    bar = models.OneToOneField(Bar)

Say I do the following:
>>> bar = Bar.objects.create()
>>> foo = Foo.objects.create(bar=bar)
>>> Foo.objects.all().delete()
>>> bar.foo is None
False

This is expected because bar is still referencing the foo object. But now when I try to get a fresh copy of bar from the DB, i.e. without the related foo, I tried:
>>> bar.refresh_from_db()
>>> bar.foo is None
False

Why does foo not come back as None? I see that in the docs it says that only fields of the model are reloaded from the database when using refresh_from_db(). Does foo not count as a field of bar in this case?

A: Which Django version are you using?
Earlier versions of Django did not clear cache when relationship objects did not change it's id's. There is their ticket https://code.djangoproject.com/ticket/29076.
It's already fixed in the new versions of Django.


text:
Q: Expected 2D array, got scalar array instead error in pandas regression I'm taking an error when i try to calculate regression in pandas. Here is the code:
import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame({"haftalar":[1,2,3,4,5,6,7],
                 "degerler":[6.11,5.66,5.30,5.32,5.25,5.37,5.28]})
haftalar=df[['haftalar']]
degerler=df[['degerler']]

from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(
    haftalar, degerler, test_size=0.57, random_state=0)

from sklearn.linear_model import LinearRegression

lr=LinearRegression()

lr.fit(x_train,y_train)
tahmin=lr.predict(8)
print(tahmin)

when i try to run the code, I'm taking this error:
"if it contains a single sample.".format(array))

ValueError: Expected 2D array, got scalar array instead:
array=8.
Reshape your data either using array.reshape(-1, 1)
if your data has a single feature or array.reshape(1, -1)
if it contains a single sample.

I have an exam in 3 hours about that subject. Can you help me?

A: Try:
tahmin=lr.predict([[8]])

More often, you may have data in numpy arrays like so:
import numpy as np
x_test = np.array([8])

Now the error message tells you what to do:
tahmin=lr.predict(x_test.reshape(-1, 1))


text:
Q: How prefill/preload images in uppy.io library I have an article post service, which has an upload form with uppy.io
Everything works great, but I need to edit those articles and their linked images.
How can I prefill already uploaded images to the uppy.io DashBoard?
My actual code:

The form works great for publishing an article, I just want to edit them, even the linked images.

A: You can prefill images from url (first converting the remote image into blob):
fetch({{your_image_url}})
.then((response) => response.blob())
.then((blob) => {
  uppy.addFile({
    name: "image.jpg",
    type: blob.type,
    data: blob
  });
});

And then, set the state of the loaded images to "Completed" to avoid Uppy re upload them:
uppy.getFiles().forEach(file => {
  uppy.setFileState(file.id, {
    progress: { uploadComplete: true, uploadStarted: false }
  })
})

Also, the property "autoProceed" must be false in the Uppy object configuration.
Source: https://github.com/transloadit/uppy/issues/1112#issuecomment-432339569


text:
Q: A question about defining the structure sheaf of Spec $R$ Pg 76 of Gathmann's Algebraic Geometry notes says the following:

But in the case of a general affine scheme Spec $R$ the various local rings $R_p$ for $p\in$ Spec $R$ do not lie in some big space, so we cannot just take their intersection.

Don't all the local rings lie in the function field of $R$?

A: Any ring with a zero divisor cannot be a subring of a field.
Furthermore, localization at a prime ideal is not always monic. For example, if $R = \mathbb{Z}  / 6 \mathbb{Z}$ and $\mathfrak{p} = 3 R$, then $R_\mathfrak{p} \cong \mathbb{Z} / 3 \mathbb{Z}$; the element $3$ is in the kernel of $R \to R_\mathfrak{p}$. ($\frac{3}{1} = \frac{0}{1}$ because $2 \notin \mathfrak{p}$ and $2 (3 \cdot 1 - 1 \cdot 0) = 0$)


text:
Q: Cutting a JsonStr my code looks like this:
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                contacts = jsonObj.getJSONArray(TAG_CONTACTS);

....
so i want to get Data from a Json Obj. My ap fails on the "try" part because it tells me that

".../b> on line 3370{"bpactivities":[{"id":"160", ...... "
so i assume its because of tags like /b>

What i want to do now is to cut everything in the jsonStr until " {"bpactivities": .. " starts.
so for example the string is now " i dont want this stuff to be here {"bpactivities": ..,, "  " but i want it like this: "{"bpactivities": .. " "
so how can i cut everything before my actual jsonObj starts? Is there a way?
thx in advance

A: If you know how the part before your jsonObj starts you can go with:
    String jsonStr = " i dont want this stuff to be here {\"bpactivities\": ..,, \" ";

    System.out.println(jsonStr.split(" here ")[1]);
    //returns_ {"bpactivities": ..,, "

String.split(String regex) returns a String-Array. In this case the first element contains the part before the regex, the second element the last part.
Your solution with:
JSONObject jsonObj = new JSONObject(jsonStr.substring(jsonStr.indexOf('{')));

works as well, but if there is any '{' before your actual jsonObj it will cause problems.

A: ok i solved it like this:
JSONObject jsonObj = new JSONObject(jsonStr.substring(jsonStr.indexOf('{')));


text:
Q: how to pass .EXE and command line argument to cmd.exe from command button in visual basic I have .EXE file called (GPLCubist)that run using command line interface by passing argument like this
    GPLcubist  -f filesteamName
where filesteamName is  the input file to the GPLcubist.exe.
Know i am going to design Interface using C# in visual basic community edition 2015.i need to pass the .EXE and the input to cmd.exe
I tried
 private void button1_Click(object sender, EventArgs e)
        {
           ProcessStartInfo startInfo = new ProcessStartInfo("GPLcubist.exe");
           startInfo.WindowStyle = ProcessWindowStyle.Minimized;
           Process.Start(startInfo);
           startInfo.Arguments = " -f filesteam";
}

please Any body Help me how to pass the GPLcubis.exe and the input file to CMD.exe using command button in visual basic.
thank you very much

A: You have to first define the arguments and than to start the process
private void button1_Click(object sender, EventArgs e)
{
    ProcessStartInfo startInfo = new ProcessStartInfo("GPLcubist.exe");
    startInfo.WindowStyle = ProcessWindowStyle.Minimized;
    startInfo.Arguments = "-f filesteam"; // No need of the beginning space
    Process.Start(startInfo); // now start it with the startInfo
}

Edit:
Please note, that the last two lines were swapped.


text:
Q: Match content between curly braces than also can contain curly braces If I have a string:
s = aaa{bbb}ccc{ddd{eee}fff}ggg

is it possible to find all matches based on outer curly braces?
m = re.findall(r'\{.+?\}', s, re.DOTALL)

returns
['{bbb}', '{ddd{eee}']

but I need:
 ['{bbb}', '{ddd{eee}fff}']

Is it possible with python regex?

A: If you want it to work in any depth, but don't necessarily need to use regex, you can implement a simple stack based automaton:
s = "aaa{bbb}ccc{ddd{eee}fff}ggg"

def getStuffInBraces(text):
    stuff=""
    count=0
    for char in text:
        if char=="{":
            count += 1
        if count > 0:
            stuff += char
        if char=="}":
            count -= 1
        if count == 0 and stuff != "":
            yield stuff
            stuff=""

getStuffInBraces is an iterator, so if you want a list of results, you can use print(list(getStuffInBraces(s))).

A: {(?:[^{}]*{[^{]*})*[^{}]*}

Try this.See demo.
https://regex101.com/r/fA6wE2/28
P.S It will only work the {} is not more than 1 level deep.

A: You could use this regex also.
\{(?:{[^{}]*}|[^{}])*}

DEMO
>>> s = 'aaa{bbb}ccc{ddd{eee}fff}ggg'
>>> re.findall(r'\{(?:{[^{}]*}|[^{}])*}', s)
['{bbb}', '{ddd{eee}fff}']

Use recursive regex for 1 level deep.
\{(?:(?R)|[^{}])*}

Code:
>>> import regex
>>> regex.findall(r'\{(?:(?R)|[^{}])*}', s)
['{bbb}', '{ddd{eee}fff}']

But this would be supported by the external regex module.


text:
Q: trouble with frontpage server extensions when publishing a web service I'm creating a web service for my app to talk to. When I go to publish it (locally), VS tells me that the server doesn't appear to have frontpage server extensions installed. It was correct.
Specifically the message says: "The Web server does not appear to have FrontPage Server Extensions installed. If FrontPage Server Extensions are installed, this error can occur because the _vti_bin virtual directory is not marked as executable. To correct this problem, run Internet Information Services Manager, select the Web server that has the problem, and then use the Check Server Extensions command."
I installed the extensions via the xp pro cd. I registered them as instructed here.
I registered asp using "aspnet_regiis -i -enable".
I open IIS, showing only my machine and only the 'default web site' running. I also can't quite figure out how to run the "Check Server Extensions" command.
I'd like host this web service locally so that I can test it and then send it off to the server admin to install it on the production server.

A: How are you trying to publish the service? FrontPage Server Extensions are no longer required.


text:
Q: Rectifier circuit behavior - Need an intuitive understanding
Case1: OUT Series res = 10 ohm -> spiky input current reaching upto 15 A -> capacitor charging fast

After a long time:

Case 2: OUT series res = 100 ohm -> almost sinusoidal input current reaching up to 1.6 A-> capacitor charging slowly

After a long time:

Looks like the behavior is same  at steady state - whatever be the resistance.
Can the same approach (dynamically vary resistance to maintain constant current) be used to limit inrush current?

A: Thermistors (NTC Type) can be made to specifically solve inrush current issues. Initially at power on the thermistor is cold and the resistance high, this limits the inrush current. Inrush plus normal operating current causes the thermistor to heat and resistance decreases, reducing operational voltage drop.
One such manufacturer is below (there are others):
https://product.tdk.com/en/products/protection/current/ntc-limiter/index.html
Slightly more complex is to have a relay short the thermistor after a short period to reduce the power loss further.

A: Yes, a resistor can be used, and has been used in various circuits to limit inrush current.

A: A common approach to make a soft start circuit is to use a PFET as a series element, with an RC that feeds the gate.

simulate this circuit – Schematic created using CircuitLab
The FET acts as a variable resistor, that starts as a very high resistor value.  As the R2 C1 voltage increases the gate drive, the resistance lowers and allows more current to pass.  Eventually, the PFET is fully turned on, and its resistance is only a few milliohms.
This is one of many answers on this site that discusses this topology: https://electronics.stackexchange.com/a/344821/166672


text:
Q: How to wait till element changes it type I want to get the value of an element which changes it type based on some condition.
So, For checking the type of that element I am using the following code:-
wait(driver, 15).until(EC.presence_of_element_located((By.ID, "incident.state")))

if( element_type != "text" ):
        select = Select(driver.find_element_by_id('incident.state'))
        selectval=select.first_selected_option.text

    else:
        select=driver.find_element_by_id('incident.state')
        selectval=select.get_attribute('value')

Here the problem is I'm always getting the element as select and not text when sometimes the element is text.
So, I used
time.sleep(5)

And it's working.But i don't want to use time.sleep as it's not a good practise.
So, I tried with
driver.implicitly_wait(10)

But it's not waiting
Can you tell me what should i use......

A: If your type check generally works in conjunction with sleep, you can put the type check in a loop in which you reduce the sleeping to time.sleep(1) - for example - and wait for the desired type.
That way, you don't waste too much time.
If you want to avoid sleep at any cost you have to use another locating strategy. Instead of ID you could locate by type and then narrow down to ID. See these functions for a start:
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector

A: It may be easier to use more specific selectors for each different kind of element this ID can appear on.  The reasoning here is you should know in advance what state the element will be in at any point in a test.
E.g. individual methods that find a specific html element with the incident-state id on it. The get_incident_state_text_value and get_incident_state_select_value methods would contain these locators:
find_element_by_xpath("//text[@id='incident-state']")

find_element_by_xpath("//select[@id='incident-state']")

This way, when you ask it to wait for the presence of one of these more specific elements, it will always wait for the correct one to appear before the test continues.
If you can't predict which method you need to use at any given time, you may be writing your tests incorrectly and relying on unknown states.  Once you start trying to get your tests to handle 5 different page states in one method, it can quickly get out of hand and become difficult to maintain.


text:
Q: Define a Likert scale grid with multiple rows I am trying to create a survey and I was hoping to do this with the eqexam package, but I can't really figure out how to make a good Likert scale. There are only examples of exams in the documentation and not of surveys.
I am trying to make something like:
    Bad NotBad Neutral OK Good
Q1  []    []     []    []  []
Q2  []    []     []    []  []
Q3  []    []     []    []  []
Q4  []    []     []    []  []

Should I do this with latex anyway? I am just trying to get a printable survey.

A: Here's one possible solution using a longtable environment and the method described by Herbert in his answer to How to programmatically make tabular rows using `\whiledo` ? to iteratively build the rows. I defined a \CheckTable command with a mandatory argument which builds your table with the number of rows specified in the argument:
\documentclass{article}
\usepackage{amssymb}
\usepackage{array,longtable}

\newcounter{question}
\newcounter{row}

\makeatletter
\newtoks\@tabtoks
\newcommand\addtabtoks[1]{\@tabtoks\expandafter{\the\@tabtoks#1}}
\newcommand*\resettabtoks{\@tabtoks{}}
\newcommand*\printtabtoks{\the\@tabtoks}
\makeatother

\newcommand\CheckTable[1]{%
  \setcounter{question}{0}
  \setcounter{row}{0}
  \resettabtoks
  \loop\ifnum\therow<#1\relax
    \stepcounter{row}
    \addtabtoks{& $\square$ & $\square$ & $\square$ & $\square$ & $\square$ \\}%
  \repeat
  \begin{longtable}{>{\stepcounter{question}Q\thequestion}l*{5}{c}}
    \multicolumn{1}{c}{} & Bad & Not Bad & Neutral & OK & Good \\
    \printtabtoks
  \end{longtable}%
}

\begin{document}

\CheckTable{10}

\CheckTable{6}

\CheckTable{12}

\end{document}


text:
Q: When does mc api rest for journey respond with "The contact status should be Active" We are getting the error
HTTP/1.1 400
{
    "message": "The contact status should be Active.",
    "errorcode": 30000,
    "documentation": ""
}

when adding a contact into a journey with the REST call:
https://developer.salesforce.com/docs/marketing/marketing-cloud/guide/postEvent.html
I've tried with no luck to reproduce the error by using a subscriber with 'Unsubscribed' status with no luck, the response is 201 created.
Does anyone knows when and why the "The contact status should be Active" error appears?

A: This means the customer is in one of the following states:

*

*The customer has been deleted - Per deletion process in Contact Builder, see more details here

*OR, the customer is suppressed due to the exit criteria of the Journey you are attempted to post an event to.

*

*For example: Journey has an exit criteria to Exit on day 1, see image below.

*You trigger the postEvent on 2023-02-06 12:00:00 AM

*If you trigger the postEvent again, you will get this error from the API

*Once the Exit criteria has been met, and the contact has exited the Journey, you will be able to trigger the postEvent again without error


text:
Q: "If you've written a compiler test, you've written a call to main" Calling maininside your program violates the C++ Standard
void f()
{
    main(); // an endless loop calling main ? No that's not allowed
}

int main()
{
    static int = 0;
    std::cout << i++ << std::endl;
    f();
}

In a lecture Chandler Carruth, at about '22.40' says

if you've written a compiler test you've written a call to main

How is this relevant or how the fact that the Standard doesn't allow is overcome ?

A: The point here is that if you write compiler test-code, you probably will want to test calling main with a few different parameter sets and that it is possible to do this, with the understanding of the compiler you are going to test on.
The standard forbids calls to main so that main can have magical code (e.g. the code to construct global objects or to initialize some data structure, zero out global uninitialized POD data, etc.). But if you are writing test code for a compiler, you probably will have an understanding of whether the compiler does this - and if so, what it actually does in such a step, and take that into account in your testing - you could for example "dirty" some global variable, and then call main again and see that this variable is indeed set to zero again. Or it could be that main is indeed not callable in this particular compiler.
Since Chandler is talking about LLVM (and in C terms, Clang), he knows how that compiler produces code for main.
This clearly doesn't apply to "black box testing" of compilers. In such a test-suite, you could not rely on the compiler doing anything in particular, or NOT doing something that would harm your test.
Like ALL undefined behaviour, it is not guaranteed to work in any particular way, but SOMETIMES, if you know the actual implementation of the compiler, it will be possible to exploit that behaviour - just don't consider it good programming, and don't expect it to work in a portable way.
As an example, on a PC, you can write to the text-screen (before the MMU has been configured at least) by doing this:
 char *ptr = (char *)0xA0000;
 ptr[0] = 'a';
 ptr[1] = 7;   // Determines the colour.

This, by the standard, is undefined behaviour, because the standard does say that you can only use pointers to allocations made inside the C or C++ runtime. But clearly, you can't allocate memory in the graphics card... So technically, it's UB, but guess what Linux and Windows do during early boot? Write directly to the VGA memory... [Or at least they used to some time ago, when I last looked at it]. And if you know your hardware, this should work with every compiler I'm aware of - if it doesn't, you probably can't use it to write low-level driver code. But it is undefined by the standard, and "UB sanitizer" will probably moan at the code.


text:
Q: bartMachine (Bayesian Additive Regression Tree) in >1 million cases in R I want to use BART via the bartMachine package for a dataframe of just over 1 million cases. With a lot of optimisation in the java memory setting, I can get R on my MacBook to complete the BART model for about 5000 cases. Anything above that is aborted as the system runs out of memory space.
Is there any chance I can use bartMachine() with an input matrix of 1 mio numbers of rows (ca. 15 predictors)?
Otherwise are there any alternative packages that would allow my to at least run predictor selection using BART?
Thanks for your help!

A: have you tried to increase RAM option ?
options(java.parameters="-Xmx12g") # must be set initially

A: I'm the maintainer of this package. Have you tried "mem_cache_for_speed = FALSE" as an option?


text:
Q: Do Mac and Windows versions of Source games contain the exact same files? Basically what the title says.
I want to do this, because I want to copy my Mac game to my Windows PC, without re-downloading it.

A: The executables and libraries may be different between Mac and Windows, but I would expect the assets to be the same in most cases.  And the assets are what take up the most space.
I would copy the files over and then open Steam, go to the Library, right-click on the game and hit Properties, go to the Local files tab, and hit "Verify integrity of game cache".  That should verify the assets and allow you to download the platform-specific files.
I've only done this Windows -> Windows with partial backups of games, but hopefully this works!  Edit: David Freitas confirms in a comment on the question that you can actually do a regular Steam backup and restore without copying files manually, awesome.


text:
Q: How do I get the userdata string from the authentification ticket? I have added a string as user identity but can't find out how to retrieve it from a class.
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;

tkt = new FormsAuthenticationTicket(1, txtUser.Text, DateTime.Now,
//Amount of minutes for standard session
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, UserCompany);
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);

A: Got there in the end...
        HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

        CompanyID = ticket.UserData;


text:
Q: Converting two single dimensional arrays(each one made up with an arraylist) to a two dimensional array I wanted to know if it is possible to convert two single dimensional array into one two dimensional array using arraylists.
Here's my code:
String[] user = (String[])compList.toArray(new String[usersList.size()]);

String[] computer = (String[])compList.toArray(new String[compList.size()]);

A: I assume
String[] user = (String[])compList.toArray(new String[usersList.size()]);

should be
String[] user = (String[])usersList.toArray(new String[usersList.size()]);

I don't think this is possible, assuming you want something like
String comuterUser[][]

where computerUser[0] is the user and computerUser[1] is the computer.  You'll have to iterate through the lists and populate the array. Something like (assuming the two lists are of equal length):
String computerUser[][] = new String[usersList.size()][];
for (int i = 0; i < computerUser.lenth; i++) {
    computerUser[i] = new String[]{ usersList.get(i), compList.get(i) };
}

Best to have the two lists ArrayLists for speedy lookup.  I haven't tested the above, but it should work.

A: You can combine the arrays using System.arrayCopy.
private String[][] wideArray(String[] zero, String[] one) {
    String[][] combined=new String[2][Math.max(zero.length, one.length)];
    System.arraycopy(zero, 0, combined[0], 0, zero.length);
    System.arraycopy(one, 0, combined[1], 0, one.length);
    return combined;
}


text:
Q: User Field value is not assigned? I have created a trigger.. contact is lookup. and i am assigning contact obj user value to current object.debug logs showing the value existed. but it is not assigned in record field.?
trigger NIGO_update on NIGOs__c(before insert,before update){

     List<NIGOs__c> NgList = [select id,name,Contact_Name__c,Product_Type__c,Contact_Name__r.Annuity_Territory_Wholesaler__r.id,Contact_Name__r.Annuity_Territory_Wholesaler__c,Contact_Name__r.Forecare_Territory_Wholesaler__r.id from NIGOs__c  where id in:Trigger.new];

     for(NIGOs__c ng:NgList){
        if(ng.Product_Type__c != 'Forecare'){
            if(ng.Contact_Name__c != Null){

                **ng.External_Wholesaler__c** = ng.Contact_Name__r.Annuity_Territory_Wholesaler__r.id;

            }
        }
        **System.debug('Ext1'+ng.External_Wholesaler__c);**
    }

}

A: You are doing two things wrong:
Querying records that do not exist yet in the before insert
The query will never return any records when its a before insert because the NIGOs__c records have not yet been persisted to the database.
Updating the wrong record instances
When using before triggers you can update the records from Trigger.new without the need to do an update. This is not what you are doing. You are doing a SOQL query to get the NgList list and then updating those instances rather than the ones from Trigger.new. You could do something like the following to get the correct record to update
NIGOs__c nigoFromTrigger = Trigger.newMap.get(ng.Id);
nigoFromTrigger.External_Wholesaler__c = ...

but keep in mind that Id values are not populated in before insert triggers.


text:
Q: Как вернуть значение из корутины в c++ 20 Пытаюсь вернуть вектор из корутины, функция func1 успешно возвращает в func вектор из 3 элементов, но я не совсем понимаю для чего нужна функция return_value. При вызове co_return в нее передается тот самый вектор и он же возвращается, но из самой корутины возвращается пустой вектор.
Я не совсем понимаю, как работают функции ассоциированные с co_return, а именно
std::suspend_never final_suspend() const noexcept { return {}; }
std::vector<T> return_value(std::vector<T>&& value){
    return value;
}

Прочитал документацию и несколько статей, но все равно до конца не понимаю. Как правильно вернуть вектор из корутины?
Вот код
#include <chrono>
#include <coroutine>
#include <exception>
#include <future>
#include <iostream>
#include <thread>
#include <type_traits>
#include <vector>

template<typename T, typename... Args>
struct std::coroutine_traits<std::vector<T>, Args...> {
    struct promise_type {
        void get_return_object() noexcept {}

        std::suspend_never initial_suspend() const noexcept { return {}; }

        std::suspend_never final_suspend() const noexcept { return {}; }

        std::vector<T> return_value(std::vector<T> &&value) {
            return value;
        }
    };
};

auto func1() {
    struct Awaiter {
        bool await_ready() { return false; };

        void await_suspend(std::coroutine_handle<> coro) {
            coro.resume();
        }

        auto await_resume() { return std::vector<int>{1, 2, 3}; }
    };
    return Awaiter{};
}

std::vector<int> func() {
    int a = 5;
    auto v = co_await
    func1();
    co_return v;
}

int main() {
    auto a = func();
    for (size_t i = 0; i < a.size(); i++) {
        std::cout << a[i] << std::endl;
    }
    return 0;
}