text:
Q: why cant i return multiple values here?
Basically the code shows the difference between Alicepoints and BobPoints.But when i am returning them it just doesnt run.

But when i run the code this error is shown.
"Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Solution.solve(Solution.java:12)
at Solution.main(Solution.java:33)"

which  is unexpected.the code is shown below
    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;
    import java.math.*;
    import java.util.regex.*;

    public class Solution {

    static int[] solve(){
    // Complete this function
    Scanner in = new Scanner(System.in);
    int a0 = in.nextInt();
    int a1 = in.nextInt();
    int a2 = in.nextInt();
    int b0 = in.nextInt();
    int b1 = in.nextInt();
    int b2 = in.nextInt();
    int pointsAlice,pointsBob;
    pointsAlice = ((a0>b0)?1:0)+ ((a1>b1)?1:0)+ ((a2>b2)?1:0) ;
    pointsBob = ((a0<b0)?1:0)+ ((a1<b1)?1:0)+ ((a2<b2)?1:0) ;
    int ar[] = new int[2];
    ar[0]=pointsAlice;
    ar[1]=pointsBob;
    return ar;

}

public static void main(String[] args) {

    Solution m=new Solution();
    int rr[] = new int[2];
      rr = m.solve();

    System.out.println(rr[0] +" " + rr[1]);

    }
}

A: The code is working fine, Nevertheless couple of points.

*

*You don't really need to create an object of Solution to call the solve() method. you can do it as shown below, since it is static.

*You don't need to create a new int[] to store the result returned by solve();
int rr[] = Solution.solve(); //note that I didn't create a new array.

A: The problem is nothing to do with returning values.  The problem is that the input you are trying to read is not in the form that the program can handle.
The code as written will work if you run it with input that starts with 6 integers with white-space between them.  If you give it something else, one of those nextInt calls will throw InputMismatchException (if a token isn't an integer) or NoSuchElementException (if you get to the end of the stream).  Then it will crash because you are not handling these exceptions.


text:
Q: Spring Web Security Config - Ignore CSRF Validation for either or I have certain conditions to ignore csrf validations but I am not sure how to put this in config. Following are my conditions to ignore the validation:

*

*Has a Bearer token in the authorization.

Or

*

*Particular URL

Here is the config I have now:
security.csrf().ignoringRequestMatchers(new RequestHeaderRequestMatcher("Authorization")).ignoringAntMatchers("/test").and();

But with this config, I guess it is treating it like an AND operation or something. How can I change this?

A: Try the OrRequestMatcher.
security.csrf()
       .ignoringRequestMatchers(new OrRequestMatcher(new RequestHeaderRequestMatcher("Authorization"), new AntPathRequestMatcher("/test")));

redpajama_set_name: RedPajamaStackExchange


text:
Q: homebrew check binary package availability Is there a brew command to check if the formula I want to install is available as binary or I have to install it from source.
As corollary, if I need to install a particular formula by recompiling it with brew install --build-from-source XXXX all the packages on which that particular formula depend will be rebuilt from source too?
Thanks

A: brew info <formula> will tell you if a given formula is bottled (= compiled) for your system, e.g.:
$ brew info postgresql | head -n 1
postgresql: stable 9.5.1 (bottled)

You can get more info by using --json=v1:
# bottled formula
$ brew info --json=v1 postgresql | jq '.[0].bottle'
{
  "stable": {
    "revision": 0,
    ...
  }
}

# non-bottled formula
$ brew info --json=v1 docker-machine-nfs | jq '.[0].bottle'
{}

if I need to install a particular formula by recompiling it with brew install --build-from-source XXXX all the packages on which that particular formula depend will be rebuilt from source too?

Only the dependencies you don't already have will be built from source.


text:
Q: strange marker info messages from maven dependency plugin how I can get rid of these messages?

[INFO] --- maven-dependency-plugin:2.3:unpack-dependencies (jetty-classpath) @ scmapi ---
  isMarkerOlder:
    artifact1 = .../.m2/repository/org/eclipse/jetty/jetty-io/9.1.1.v20140108/jetty-io-9.1.1.v20140108.jar
    marker    = .../src/maven-intermediate/scmapi/dependency-maven-plugin-markers/org.eclipse.jetty-jetty-io-jar-9.1.1.v20140108.marker
      artifact1 lastModified: 1398992691000
      marker lastModified: 1398992691000
  < false = marker older than artifact?
  isMarkerOlder:
    artifact1 = .../.m2/repository/org/eclipse/jetty/jetty-webapp/9.1.1.v20140108/jetty-webapp-9.1.1.v20140108.jar
    marker    = .../src/maven-intermediate/scmapi/dependency-maven-plugin-markers/org.eclipse.jetty-jetty-webapp-jar-9.1.1.v20140108.marker
      artifact1 lastModified: 1398992692000
      marker lastModified: 1398992692000
  < false = marker older than artifact?

Note that the artifact1 lastModified: 1398992692000 value and the marker lastModified: 1398992692000 are exactly the same. Which contradicts the error message marker older than artifact.
Note also that if you google: "marker older than artifact" you could find that a lot of people have the same "[info]" messages reported in their builds.

A: I think you have checked in your marker files in Perforce by mistake. It says that, for an artifact like this one
 artifact1 = .../.m2/repository/org/eclipse/jetty/jetty-io/9.1.1.v20140108/jetty-io-9.1.1.v20140108.jar

It has a marker file here
 marker = .../Perforce/scmapi/src/maven-intermediate/scmapi/dependency-maven-plugin-markers/org.eclipse.jetty-jetty-io-jar-9.1.1.v20140108.marker

The artifact is in a .m2 repository directory, which looks normal, but the reference to Perforce on the marker path makes me a bit anxious.
Check to see if you may have marker files under revision control by mistake and subsequently get rid of it.
Then you should be able to clear and update dependencies, for example like:
mvn -U dependency:go-offline

And the problem should subsequently go away.

A: I had the same problem, what I did was remove the content which was under /target in my project and the recompile all, the issue was gone with that, hope that helps.
I suspicious that the problem in my case was because I was using maven to solve dependencies but also the IDE tool, probably that affected my dependencies


text:
Q: Passportjs sessions fail when JSON response is set first I'm using express + passport to handle authentication for a react app. Because I'm using react, I don't want to automatically redirect the login request via express, instead I want to return JSON.
However, I've noticed that simply returning JSON and then calling next(null, user) seems to prevent passport from running the serializeUser method. By calling next passport should automatically call the req.login function, which doesn't appear to happen when I've sent json.
It appears that if I manually call req.login and then send the JSON, it works (the serialize method is called, the user has a session).
Is there a way to send a json response and call next without having to manually invoke req.login? Feels like I'm just not doing things the correct way.
module.exports = function(app) {
    app.post('/login', (req, res, next) => {
        passport.authenticate('local', (err, user) => {
            if (err) {
                res.json({ errorMessage: err.message });

                return next(err);
            }

            if (!user) {
                res.json({ errorMessage: 'Invalid user.' });

                return next(err);
            }

            // This fails to invoke the session serialization:
            // res.json({
            //     success: true,
            //     username: user.username
            // });

            // return next(null, user);

            // This works:
            req.logIn(user, loginErr => {
                if (loginErr) {
                    return next(loginErr);
                }

                res.json({
                    success: true,
                    username: user.username
                });

                return;
            });
        })(req, res, next);
    });
};


text:
Q: Improve performance of SurfaceView-dervied custom view? I have written a simple Android application that draws a maze using a custom view derived from SurfaceView.  It follows the model of the LunarLander sample application and performs all calculation and drawing using a background thread directly into the SurfaceHolder object.
All well and good and it's running well for small/medium mazes, however if I set the maze cell size to be 8 pixels there are lots of cells in the maze the application crawls along.
The code is doing something I don't like in that is draws every cell even if it hasn't changed and this is required to avoid screen flickering from the SurfaceView double buffer (in previous iterations of the application I was drawing just what changed and that resulted in a jumpy mess).
What I want then is the ability to use SurfaceView but be more selective about what gets drawn.  Is this possible?  If not, what are the alternatives?  How about keeping an offscreen bitmap, and selectively drawing into that first?
EDIT: I implemented an offscreen Bitmap and Canvas combination, written to by my timer-driven state machine, drawing only those areas affected during carving/solution.  I then simply draw the whole offscreen bitmap onto the SurfaceView within the run() method and this has solved my problem; I am able to drop the cell size to 5 pixels and performance is fine.

A: About double-buffering issues:
Take a look at this tutorial series. Do you see any difference in the way you handle drawing?
https://web.archive.org/web/20121109162356/http://www.droidnova.com/playing-with-graphics-in-android-part-iii,176.html
About optimizing your drawing:
The following link, explains some approaches:
http://developer.android.com/guide/topics/graphics/opengl.html
http://developer.android.com/reference/android/opengl/GLSurfaceView.html

Continuous rendering versus
render-when-dirty
Most 3D
applications, such as games or
simulations, are continuously
animated. But some 3D applications are
more reactive: they wait passively
until the user does something, and
then react to it. For those types of
applications, the default
GLSurfaceView behavior of continuously
redrawing the screen is a waste of
time. If you are developing a reactive
application, you can call
GLSurfaceView.setRenderMode(RENDERMODE_WHEN_DIRTY),
which turns off the continuous
animation. Then you call
GLSurfaceView.requestRender() whenever
you want to re-render.

Also, in 2D games it's particulary easy to calculate what is being seen by the user so refrain from drawing objects out of the visible scene.
One final note:
You said

All well and good and it's running well for small/medium mazes, however if I set the maze cell size to be 8 pixels there are lots of cells in the maze the application crawls along.

Does this means that you are computing the maze's solution? If so, you shouldn't do it in the same thread where you draw it. You should solve it in another thread. (I might have understood you wrong)


text:
Q: Generate alter syntax for column I've found a way to find missing tables between two databases, and missing columns from intersect tables. I can get "create" syntax for missing tables, but how do I generate "alter" syntax for missing columns?
Is there something like SHOW CREATE TABLE $table for column?
@Edit
I get:
CREATE TABLE `table` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(225) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
)

by SHOW CREATE TABLE $table
-> I figure out the second database's "table" misses "name" column. How do I "parse" (?) this create to generate alter to add column "name" to the second database's table?

A: If you want individual columns, then use ( change users to your table name )
show columns from users

If this is done on both tables, you can check the differences.  This may include having to alter columns if the definition has changed.
To add a new column, use something like
alter table users add column email varchar(255) after name

The after bit allows you to position the new column at the same place as in your other table (makes it look consistent in query tools).


text:
Q: How to minimize this function difference Sorry about this somewhat lengthy introduction to my question. I thought it might be useful to know what I'm trying to do.
I decided that I would like to have sequence of polynomials in $\mathbb{P}_n (x)$ defined in domain $x\in[0,1]$ which gradually learn a function. So, given an initial polynomial $P_{\alpha_0}(x)=\sum_{i=1}^n a_i x^{i-1}$ where $\alpha_0 = (a_1,\ldots,a_n) \in \mathbb{R}^n$, I would introduce a new point $(x_0,y_0) \in [0,1]\times\mathbb{R}$ and try to find all $\beta \in\mathbb{R}^n$ such that
$$
P_{\alpha_0 + \beta}(x_0)=y_0
$$
If the solution space to that is $S$, then the next step would be to find optimal solution which somehow minimises the non-local difference. Define a norm which penalizes non-local difference:
$$
{\lVert P_{\alpha} \rVert}_{(x_0)} = \int_0^1 {(x-x_0)}^2{(P_{\alpha}(x))^2} dx
$$
The objective would be to find such $\beta \in S$ that it minimises
$$
{\lVert P_{\alpha_0} -P_{\alpha_0+\beta}\rVert}_{(x_0)}
$$
and then have for the next round $\alpha_1 = \alpha_0 + \beta$.
Looking at solutions for the standard basis $\beta_i=(0,\ldots,0,b_{i,i},0,\ldots,0)$ (i.e. all but the $i$:th element are zero) one finds easily that
$$
P_{\alpha_0+\beta_i}(x_0)=y_0
$$
when
$$
b_{i,i} = \frac{y_0 - P_{\alpha_0}(x_0)}{x_0^{i-1}}
$$
Let's use $b_i = b_{i,i}$ for short.
The solution space $S$ is linear combination $\sum t_i \beta_i$ with the requirement that $\sum t_i = 1$.
Now, do you have any elegant ways to find the minimum for
$$
{\lVert P_{\alpha_0} -P_{\alpha_0+\beta}\rVert}_{(x_0)} =
\sum_{i,j}^n t_i t_j b_i b_j g_{x_0}(i,j)
$$
where
$$
g_{x_0}(i,j) = (\frac{1}{i+j+1} -\frac{2 x_0}{i+j} + \frac{x_0^2}{i+j-1})
$$
from the solution hyperplane $\sum t_i = 1$?
It's rather easy to find the equation for the null space of the partial differentials
$$
\frac{d{\lVert P_{\alpha_0} -P_{\alpha_0+\beta}\rVert}_{(x_0)}}{d t_k} =
\sum_i t_i b_i g_{x_0}(k,j)
$$
This is a linear mapping of the form $M t = 0 $ where $M_{i,j} = b_i g_{x_0}(i,j)$. Testing numerically with some functions seems to indicate that $M$ is mostly of full rank and in those cases the solution would be $t=0$ which does not fulfill the requirement that $\sum t_i = 1$.
Adding this requirement to the mapping gives overdetermined equation
$$
\left(
\begin{matrix}
M \\
1
\end{matrix}
\right) t =
\left(
\begin{matrix}
0 \\
1
\end{matrix}
\right)
$$

A: So the problem I had was to find such $t\in S \subset \mathbb{R}^n$ that it minimises the function (1)
$$
d(t,b,x_0)=\sum_{i,j=1}^n t_i t_j b_i b_j g_{ij}(x_0)
$$
within the hyperplane
$$
S = \{t:\sum_1^n t_i = 1\}
$$
From the original integral form of the function it is easy to see that it is positive for all $t$ and from the sum form that it grows with $\lVert t \rVert$ .
I chose the rather elaborate way of substituting $t_n$ with $1-\sum_1^{n-1} t_i$ in (1) and trying to find the zero of the partial differentials of the difference. For simplicity, I also denote $g_{ij}(x_0)$ with just $g_{ij}$ and the reduced vector ${(t_i)}_{i=1}^{n-1}$ with $t^*$.
With the substitution  the equation (1) can be (after several steps) written as
$$
f(t^*)=\sum_{i,j=1}^{n-1} t_i^* t_j^* A_{ij} + \sum_{i=1}^{n-1} t_i^* b_n B_i + b_n^2 g_{nn}
$$
where $A_{ij}=b_i b_j g_{ij} - 2 b_i b_n g_{in} + b_n^2 g_{nn}$ and $B_i = 2 b_i g_{in}-2b_n g_{nn}$.
The partial differentials (finally) have the form
$$
\frac{d f}{d t_k^*} = (\sum_{i=1}^{n-1} t_i (A_{ik}+A_{ki})) + B_k
$$
and from this finding the zeros of the differentials can be written in matrix form as
$$
C t + B = 0
$$
where $C_{ij}=A_{ij}+A_{ji}$ is a symmetric matrix. Finding solution to this is rather easy.
Testing numerically the solution shows that $C$ is easily ill-conditioned and the whole idea perhaps rather useless. Nevertheless, watching the polynomials twist and wiggle as new points are added is very entertaining.


text:
Q: Is "items[]size" a valid array declaration? I have a foreach and inside it there's an input that has a name of items[]size and another input that has a name of items[]price. When I try to fetch their value it just returns an array of items[]. How do I get only the items[]size value or items[]price value?
@foreach($sizes as $size)
                <input type="checkbox" name="items[]size" value="{{ $size->id }}">
                <x-label>{{ $size->value }}</x-label>
                <input type="text" name="items[]prize">

@endforeach

A: Try something like:
@foreach($sizes as $size)
    <input type="checkbox" name="items[{{ $loop->index }}][size]" value="{{ $size->id }}">
    <x-label>{{ $size->value }}</x-label>
    <input type="text" name="items[{{ $loop->index }}][prize]">

@endforeach


text:
Q: php What is the correct way to execute a WebSocket server? I'm trying to execute server.php which is a server for websocket to work (Rachet websocket),
I tried this code below, but the problem is script always hangs at that line when calling shell_exec(),
I also tried using exec() same problem
Code:
$result = shell_exec('php ../bin/server.php > chat_logs.txt &');
    if ( empty($result) )
    {
        echo 'Error, not executed!';
        return;
    }


text:
Q: True or false question. Single variable calculus. I'm looking through an old exam and this question popped up:

Determine if the assertions below are true or false.

*

*If $f$ is differentiable over $(a,\infty)$, and $\lim_{x\rightarrow\infty}f'(x)=\infty,$ then it follows that $\lim_{x\rightarrow\infty}f(x)=\infty$

*If $f$ is differentiable over $(a,\infty),$ and $\lim_{x\rightarrow\infty}f(x)=\infty$, then it follows that $\lim_{x\rightarrow\infty}f'(x)=\infty$

*If $f$ is two times differentiable over $(a,\infty),$ and $\lim_{x\rightarrow\infty}f''(x)=\infty,$ then it follows that $\lim_{x\rightarrow\infty}f(x)=\infty.$

My attempt:

*

*So if the derivative is constantly increasing, it implies that the slope of the function is constantly increasing. This can only happen if also the function gets bigger and bigger. Also, if a function is differentiable over an interval, then it is also continous.

*This one is false for because the function can get bigger and bigger, but it's slope remains constant. Take the function $f(x)=2x+1$ for example.

*If the second derivative is getting bigger and bigger, it means that the slope of the derivative is increasing, but if the slope is increasing, we are back to problem 1 above, so it is true as well.

Any constructive critique?


text:
Q: c++ and portaudio, horribly distorted output I have written a small piece of code which intents to read a wav file and play it through portaudio.
I restrained myself to some particular wav files : linear pcm (no compression) , no more than 2 channels. As i can see, the wav file decoding works just fine, i believe i'm in trouble later when playing it through portaudio.
For my tests i choosed an overly simple wav file (short : 8 bits bitdepth, 11025 sample rate, mono and about 3 sec long).
So, once i got all my samples ready i did give them to portaudio (scalling them so they're between -1.0f and 1.0f as in the tutorial example) and i could recognize the sound but it was horribly distorted...
I thought it could be because of the sample rate (altough 11025 hz is quite standard) and re-sampled it to the rate given by Pa_getDeviceInfo->getDefaultSampleRate (44100hz).
But i just get the same result. I also tried selecting another device bt still it doesn't get better.
I read in some slides from Bjorn Roche (http://blog.bjornroche.com/2011/11/slides-from-fundamentals-of-audio.html) that my scaling approach wasn't good but i found no alternative.
Could it be a configuration problem? Or did i miss something important about sampling and audio playback? (this is my first shot at audio programming)
By the way i'm using linux and alsa with portaudio and i get these error message when initializing portaudio :
    ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
    ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
    ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
    bt_audio_service_open: connect() failed: Connection refused (111)
    bt_audio_service_open: connect() failed: Connection refused (111)
    bt_audio_service_open: connect() failed: Connection refused (111)
    bt_audio_service_open: connect() failed: Connection refused (111)

I defined my callback function as follow : (only to play this particular file)
    unsigned int actualSample;

    static int patestCallback( const void *inputBuffer, void *outputBuffer,
                       unsigned long framesPerBuffer,
                       const PaStreamCallbackTimeInfo* timeInfo,
                       PaStreamCallbackFlags statusFlags,
                       void *userData )
    {
        /* Cast data passed through stream to my wav file. */
        WavSound *data = (WavSound*)userData;
        float *out = (float*)outputBuffer;
        unsigned int i;
        (void) inputBuffer; /* Prevent unused variable warning. */

        for( i=0; i<framesPerBuffer; i++ )
        {
             *out++ = (float) ((data->getSample(::actualSample)-127)/128);
             ::actualSample = ::actualSample + 1;
             if(::actualSample >= data->getSamplesSize())
                 ::actualSample = 0;
        }
        return 0;
    }

Thanks for reading!

A: The reason the sound was distorted is the following : the samples were stored in unsigned 8 bits format, but silence was defined with the sample value beign 255 as i would consider it to be 0. the whole scaling is in reverse order.
I changed the line :
*out++ = (float) ((data->getSample(::actualSample)-127)/128);

with
*out++ = (float) (((-1)*data->getSample(::actualSample)+127)/128);

and it all went good.
just In case it could help someone.


text:
Q: How to calculate the number of days (difference) between two dates in PHP? I've one mysql table in that I store two dates say 2015-03-13 and 2015-03-20 and I displays these dates on form with no. of days between these two dates.
In this I want PHP code for calculating days.

A: Try with this (Object oriented style):
<?php
$datetime1 = new DateTime('2015-03-13');
$datetime2 = new DateTime('2015-03-20');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a días');
?>

Procedural Style:
<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a días');
?>

You can read more at:

http://php.net/manual/en/datetime.diff.php

A: $start = strtotime('2015-03-13');
$end = strtotime('2015-03-20');

$diff = $end - $start;

$days = floor($diff / (3600 * 24));

A: Try This.
$date1=date_create("2013-03-15");

$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);

echo $diff->format("%R%a days");

Source: http://www.w3schools.com/php/showphp.asp?filename=demo_func_date_diff

A: Try this code:
<?php
     $first_date = strtotime("2015-03-10");
     $last_date = strtotime("2015-03-01");
     $datediff = $first_date - $last_date;
     echo "Days : ". floor($datediff/(60*60*24));
?>

A: Use this
   $daylen = 60*60*24;
   $date1 = '2015-03-13';
   $date2 = '2015-03-20';
   echo (strtotime($date1)-strtotime($date2))/$daylen;


text:
Q: SonarQube starting Failed I installed SonarQube Version 7.9.1 on CentOS 7 and the service set to start with non root user. My vm.max_map_count is set to 262144.
sysctl vm.max_map_count
vm.max_map_count = 262144

Because of My SonarQube version I set the JDK in Wrapper.conf to
wrapper.java.command=/usr/lib/jvm/java-11-openjdk/bin/java

My sonar.log is:
--> Wrapper Started as Daemon
Launching a JVM...
Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
  Copyright 1999-2006 Tanuki Software, Inc.  All Rights Reserved.

2019.07.29 13:31:51 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory /opt/sonarqube/temp
2019.07.29 13:31:51 INFO  app[][o.s.a.es.EsSettings] Elasticsearch listening on /127.0.0.1:9001
2019.07.29 13:31:51 INFO  app[][o.s.a.ProcessLauncherImpl] Launch process[[key='es', ipcIndex=1, logFilenamePrefix=es]] from [/opt/sonarqube/elasticsearch]: /opt/sonarqube/elasticsearch/bin/elasticsearch
2019.07.29 13:31:51 INFO  app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running
OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.
2019.07.29 13:31:51 INFO  app[][o.e.p.PluginsService] no modules loaded
2019.07.29 13:31:51 INFO  app[][o.e.p.PluginsService] loaded plugin [org.elasticsearch.transport.Netty4Plugin]
ERROR: [1] bootstrap checks failed
[1]: max file descriptors [4096] for elasticsearch process is too low, increase to at least [65535]
2019.07.29 13:31:56 WARN  app[][o.s.a.p.AbstractManagedProcess] Process exited with exit value [es]: 78
2019.07.29 13:31:56 INFO  app[][o.s.a.SchedulerImpl] Process[es] is stopped
2019.07.29 13:31:56 INFO  app[][o.s.a.SchedulerImpl] SonarQube is stopped
<-- Wrapper Stopped

My es.log is:
2019.07.29 13:31:53 INFO  es[][o.e.e.NodeEnvironment] using [1] data paths, mounts [[/ (rootfs)]], net usable_space [31.1gb], net total_space [49.9gb], types [rootfs]
2019.07.29 13:31:53 INFO  es[][o.e.e.NodeEnvironment] heap size [494.9mb], compressed ordinary object pointers [true]
2019.07.29 13:31:53 INFO  es[][o.e.n.Node] node name [sonarqube], node ID [XhVUvjLfTS-JwFuXmFVL4Q]
2019.07.29 13:31:53 INFO  es[][o.e.n.Node] version[6.8.0], pid[60694], build[default/tar/65b6179/2019-05-15T20:06:13.172855Z], OS[Linux/3.10.0-957.21.3.el7.x86_64/amd64], JVM[Oracle Corporation/OpenJDK 64-Bit Server VM/11.0.4/11.0.4+11-LTS]
2019.07.29 13:31:53 INFO  es[][o.e.n.Node] JVM arguments [-XX:+UseConcMarkSweepGC, -XX:CMSInitiatingOccupancyFraction=75, -XX:+UseCMSInitiatingOccupancyOnly, -Des.networkaddress.cache.ttl=60, -Des.networkaddress.cache.negative.ttl=10, -XX:+AlwaysPreTouch, -Xss1m, -Djava.awt.headless=true, -Dfile.encoding=UTF-8, -Djna.nosys=true, -XX:-OmitStackTraceInFastThrow, -Dio.netty.noUnsafe=true, -Dio.netty.noKeySetOptimization=true, -Dio.netty.recycler.maxCapacityPerThread=0, -Dlog4j.shutdownHookEnabled=false, -Dlog4j2.disable.jmx=true, -Djava.io.tmpdir=/opt/sonarqube/temp, -XX:ErrorFile=../logs/es_hs_err_pid%p.log, -Des.enforce.bootstrap.checks=true, -Xms512m, -Xmx512m, -XX:+HeapDumpOnOutOfMemoryError, -Des.path.home=/opt/sonarqube/elasticsearch, -Des.path.conf=/opt/sonarqube/temp/conf/es, -Des.distribution.flavor=default, -Des.distribution.type=tar]
2019.07.29 13:31:53 INFO  es[][o.e.p.PluginsService] loaded module [analysis-common]
2019.07.29 13:31:53 INFO  es[][o.e.p.PluginsService] loaded module [lang-painless]
2019.07.29 13:31:53 INFO  es[][o.e.p.PluginsService] loaded module [mapper-extras]
2019.07.29 13:31:53 INFO  es[][o.e.p.PluginsService] loaded module [parent-join]
2019.07.29 13:31:53 INFO  es[][o.e.p.PluginsService] loaded module [percolator]
2019.07.29 13:31:53 INFO  es[][o.e.p.PluginsService] loaded module [reindex]
2019.07.29 13:31:53 INFO  es[][o.e.p.PluginsService] loaded module [repository-url]
2019.07.29 13:31:53 INFO  es[][o.e.p.PluginsService] loaded module [transport-netty4]
2019.07.29 13:31:53 INFO  es[][o.e.p.PluginsService] no plugins loaded
2019.07.29 13:31:54 WARN  es[][o.e.d.c.s.Settings] [http.enabled] setting was deprecated in Elasticsearch and will be removed in a future release! See the breaking changes documentation for the next major version.
2019.07.29 13:31:55 INFO  es[][o.e.d.DiscoveryModule] using discovery type [zen] and host providers [settings]
2019.07.29 13:31:55 INFO  es[][o.e.n.Node] initialized
2019.07.29 13:31:55 INFO  es[][o.e.n.Node] starting ...
2019.07.29 13:31:56 INFO  es[][o.e.t.TransportService] publish_address {127.0.0.1:9001}, bound_addresses {127.0.0.1:9001}
2019.07.29 13:31:56 INFO  es[][o.e.b.BootstrapChecks] explicitly enforcing bootstrap checks
2019.07.29 13:31:56 ERROR es[][o.e.b.Bootstrap] node validation exception
[1] bootstrap checks failed
[1]: max file descriptors [4096] for elasticsearch process is too low, increase to at least [65535]
2019.07.29 13:31:56 INFO  es[][o.e.n.Node] stopping ...
2019.07.29 13:31:56 INFO  es[][o.e.n.Node] stopped
2019.07.29 13:31:56 INFO  es[][o.e.n.Node] closing ...
2019.07.29 13:31:56 INFO  es[][o.e.n.Node] closed

A: I had the exact same error yesterday and resolved it by following a short chain of resources.

*

*Googling the max file descriptors [4096] issue identified this top post . The solution highlighted the fact that it wasn't that vm.max_map_count variable wasn't being picked up correctly, but instead the LimitNOFILE and LimitNPROC. This post points the solution as updating variables in the "unit file".

*After Googling around more for the commenter's mentioned "unit file", systemd, and updated documentation, I found it here in the "Running SonarQube as a Service on Linux with SystemD" section.

*By creating and running SonarQube via SystemD, it ensured the max file descriptor variables were actually being set. Following those exact directions allowed SonarQube to start without a problem.

A: To apply these configuration permanently, edit /etc/sysctl.d/99-sonarqube.conf or /etc/sysctl.conf and add:
sysctl -w vm.max_map_count=262144
sysctl -w fs.file-max=65536
ulimit -n 65536
ulimit -u 2048`

vm.max_map_count is greater or equals to 262144
fs.file-max is greater or equals to 65536
the user running SonarQube can open at least 65536 file descriptors
the user running SonarQube can open at least 2048 threads
Or if you want to apply these settings on current session, just enter each command in terminal:
sysctl -w vm.max_map_count=262144
sysctl -w fs.file-max=65536
ulimit -n 65536
ulimit -u 2048

Hope this helps!


text:
Q: Toggle and animate height of a ul within a li I have a list inside a li which needs to slide into view when the parent li is clicked.
My code works nicely but if i click any li all of the sub lists show where as i want it only to apply to the one that was clicked...
$("#offering li").click(function() {
        $("#offering li ul").animate({height: "toggle"}, 1000);
    });

sage solutions

50

200

CRM

solutions

50

200

CRM

third party additions

A: $(this).find("ul").animate({height: "toggle"}, 1000);

A: Here you are applying the animation to all elements that match the selector #offering ul li, when infact you just need to apply it to the child ul of the li clicked.
Instead of the following
$("#offering li").click(function() {
        $("#offering li ul").animate({height: "toggle"}, 1000);
    });

Try this
$("#offering li").click(function() {
        this.childNodes[0].animate({height:"toggle"},1000);
    });

I'm not as familiar with jQuery as I am with Mootools, so there may be a more appropriate way to get the child ul element than using the childNodes array - but you get the idea.


text:
Q: Ajax.BeginForm UpdateTargetId doesn't work with DropDownList Code:
<% using (Ajax.BeginForm("GetResourcesByProject", "CreateRequest", new AjaxOptions { UpdateTargetId = "ResourceListDiv"}))
{
 Response.Write(Html.DropDownList("SelectProject", Model.ProjectList, "Select Project", new { onchange = "this.form.submit();" }));
} %>

When I run the page I get the correct controller action to trigger with the right data in the form collection:
public ActionResult GetResourcesByProject(FormCollection formCollection)
{
    var resourceModels = (from project in POTSModel.ProjectList
                          where project.Id == Convert.ToInt32(formCollection["SelectProject"])
                          select project).First().Resources;

    return PartialView("ResourceList", resourceModels);
 }

It works fine from an Ajax.ActionLink like this:
<%= Ajax.ActionLink("Select", "GetResourcesByProject", "CreateRequest", new { projectId = item.Id }, new AjaxOptions { UpdateTargetId = "ResourceListDiv" })%>

When the post happens I'm navigated to a new page instead of staying on the existing page and updating the contents of the div.
Thanks.

A: submit() probably don't trigger Ajax.BeginForm, and so it is processed as usual post. See this for example: Additional jQuery events submitting my Ajax.BeginForm.
Alternatively add submit button (maybe hidden) and call its .click().

A: The using(Ajax.BeginForm(...)) doesn't work when it contains a Html.RenderPartial.

A: Does it works with Internet explorer 7. I have some issue with IE7 in cascading DropDownList.
The Ajax.BeginForm doesn't retrieve form (Request.Form["myIdForm"] is blank) Value in IE7, in all others web browser it works (including IE8)!
            <% using (Ajax.BeginForm("profileChanged", "profiles", new AjaxOptions() { UpdateTargetId = "customer", OnComplete = "SetHiddenProfile" }, new { @class = "filtersForm" }))
          {   %>
        <p id="customer">
            <% Html.RenderPartial("FilterContracts"); %>
        </p>
        <%} %>

I call the database to populate dropDown in profileChanged action and return a partial view ("FilterContracts").


text:
Q: Laravel query with temporary table How to convert this query to laravel db query.
    SELECT * FROM {
      Select * from organizers
      Order by organizers.rank
} Group by t.department

This is simplified version of query. In real the inner query has more where clause and built using laravel db query.
Edit: I am aware of raw query. But that's not what I am looking for. Inner query is complex and has lots of conditional where clause. I would like to retain the db query object I used there.

A: You can have 2 different query builders and merge their binding like below :
$innerQuery = DB::table('organizers')->orderBy('organizers.rank');

$mainQuery = DB::table(DB::raw('(' . $innerQuery->toSql() . ') as t'))
    ->mergeBindings($innerQuery->getQuery())
    ->groupBy('t.department')
    ->get();

This will also help you retail the $innerQuery builder instance for your later use as you have mentioned in the question.

A: I think you will have to execute a raw query.
$result = DB::select("SELECT * FROM (
      Select * from organizers
      Order by organizers.rank
) Group by t.department");

reference: https://laravel.com/docs/5.7/queries#raw-expressions


text:
Q: Keep timestamp label updated in UITableView I have a UIViewController that has a UITableView which presents comments fetched form a live Firebase database.
Every time a new comment arrives, I call
tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: self.liveComments.count-1, section: 0)], with: .fade)
tableView.endUpdates()

to insert the latest comment with a fade animation. This works fine.
However, each cell has a label that shows when it was posted, in the form of "seconds, minutes or hours ago". The problem is that when many comments arrive, the age label does not get updated, since the existing cells are not updated, and it looks to the user like the comment ages are wrong.
I've tried calling
tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows ?? [], with: .none)

inside my tableView updated block, but the animation is all messed up, since all of the visible cells seem to get animated in a weird, "jumpy" way.
I've also tried getting all of the visible cells, and calling a method on them to update their timestamp labels manually, but I get a crash when I do this, so I guess it's not recommended:
if let visibleCells = self.tableView.visibleCells as? [LiveCommentTableViewCell] {
    visibleCells.forEach { cell in
    cell.updateCommentAgeLabel()
}

How can I approach this? I just need to reload all visible cells without an animation, and the last cell with a fade in animation. Thank you!

A: I would just reload all the data, as long the cellForRowAt sets the timestamp label correctly it should work fine:
// still do your nice animation
tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: self.liveComments.count-1, section: 0)], with: .fade)
tableView.endUpdates()
// now just refresh the entire table
tableView.reloadData()

of course you're going to want to make sure that whatever collection feeds the numberOfItemsInSection is also updated before calling reloadData() im assuming you're already doing this as well or you'd be running into a lot of bugs and crashes
make sure that code that edits UI is on the main thread too, obviously.
That being said what does your cell.updateCommentAgeLabel() function look like bc that would work in theory as well unless potentially its not being called on the main thread again or the cast isn't working.
Perhaps try telling the system you want it to do a layout pass:
if let visibleCells = self.tableView.visibleCells as? [LiveCommentTableViewCell] {
    visibleCells.forEach { cell in
    cell.updateCommentAgeLabel()
    cell.layoutIfNeeded() // either this
}
tableView.layoutIfNeeded() // OR this at the end, I dont expect you'll need to do both but not sure if both work


text:
Q: Stop Thread right after one Minute I have a JButton to invoke my thread. But what I actually want to do is to stop the thread just after the one minute!
My actionListener Method is:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    new Frame2().setVisible(true);
    Thread t=new Thread(new Frame2());

    t.start();
    }

My thread to run for only one minute is as follow:
    public void run(){
    int i;
    while(!Thread.currentThread().isInterrupted()){
        for(i=0;i<=100;i++){

            if(i==100){
            Thread.currentThread().interrupt();
             }
        try {
            Thread.currentThread().sleep(600);
        } catch (InterruptedException ex) {
            System.out.print("THREAD CLOSED");
           return;
        }

    }
        System.out.print("DOING THINGS BLA BLA");
    }

}

The Problem:
I have stopped the thread after one minute successfully, but I was not able to do anything desired in it. I just want to know that how can I achieve this in order to run the thread for only one minute and inside the thread I want to do my things! But how? Am I wrong with this approach? If, yes then what should be the right approach?

A: The simplest way to do what you want is to have something like the following:
public void run() {
    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < startTime + 60000) {
        // do something useful
    }
}

"do something useful" should be a fast operation, and your thread will always last slightly longer than 1 minute (1 minute + the time of "do something useful").
Note about your original code: to stop a thread from the thread itself, no need for an interrupt: you just need to return from the run() method.

A: To be sure that your thread will work 1 minute you need to create separate thread for that.
 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
   new Frame2().setVisible(true);
   final Thread t=new Thread(new Frame2());

   t.start();
   new Thread(new Runnable() {
     @Override
     public void run() {
       TimeUnit.SECONDS.sleep(1);
       t.interrupt();
     }
   }).start();
 }

Now regardles of what your "t" thread is doing, it will be killed after 1 minute.


text:
Q: Timelike and spacelike projections in General Relativity and associated conservation laws For any timelike curve $p_\mu$ in General Relativity (section 3 of this review), we can project this into its timelike and spacelike components. Further, these projections are associated with conservation laws.
The projection along the timelike component is obtained by projecting $p_\mu$ onto $u^\mu$, where $u^\mu$ is the 4-velocity. This projection captures what occurs in the rest frame of the observer as he moves along with the fluid.
The projection along the spacelike component is obtained by defining a 'projection tensor' as follows: $$h_{\mu\nu}=g_{\mu\nu}+u_\mu u_\nu$$ where the projection is taken onto the spacelike components.
Then, energy and momentum conservation can be obtained from the covariant energy-momentum conservation equation $\nabla_\mu T^{\mu\nu}=0$ as follows:

*

*Energy conservation (timelike projection): $u_\nu\nabla_\mu T^{\mu\nu}=0$

*Momentum conservation (spacelike projection): $h_{\mu\nu}\nabla_\mu T^{\mu\nu}=(g_{\mu\nu}+u_\mu u_\nu)\nabla_\mu T^{\mu\nu}=0$
My questions:
1. Why is energy conservation associated with timelike projection and momentum conservation associated with spacelike projection?
2. How do we derive the expression for the projection tensor? Any suggestions to suitable references would be sufficient.

A: First of all, do note that the momentum conservation equations should read $h_{\rho\nu} \nabla_\mu T^{\mu\nu}=0$, otherwise you would have a single equation.
The strict distinction between energy and momentum conservation is only valid in the Local Rest Frame, the frame of the fluid element with velocity $u^\mu$: for some other observer with velocity $v^\mu \neq u^\mu$ the equation $u_\nu \nabla_\mu T^{\mu\nu}$ will not represent only energy conservation.
Now, to answer question 1: the $\mu\nu$ component of the stress-energy tensor is the flow of the $\mu$-th component of four-momentum through a surface of constant $x^\nu$, so if we project using the vector $u_\nu$ we are getting something which, in the LRF, is conservation of four-momentum through surfaces of constant time. This, coupled with the fact that the time component of the four-momentum is the energy is the motivation for the name.
The reasoning for the momentum conservation equations is similar.
To convince yourself that this makes sense, you can look at the nonrelativistic limit of these equations: see the Theoretical Physics Reference. There, they use the fact that in the LRF $u^\mu = (1, 0,0,0)$ to write the energy conservation equation as $\nabla_\mu T^{\mu 0}$ and similarly for the others.
There they derive Euler's equations for a perfect fluid, but a very similar line of reasoning applies to the general case.
As for question 2, very loosely following section 3 in Taub (1978): to see that $h_{\mu}^{\nu} = \delta_\mu^\nu + u_\nu u^\mu$ is an orthogonal projector onto the subspace orthogonal to $u^\mu$ we need to check that it is idempotent ($h^\mu_\rho h^\rho_\nu = h^\mu _\nu$), that it is orthogonal, and that its $\ker$ is just the span of $u^\mu$:
$$
h^\mu_\rho h^\rho_\nu =
(\delta^\mu_\rho + u^\mu u_\rho)(\delta^\rho_\nu + u^\rho u_\nu) =
\delta^\mu_\nu + 2 u^\mu u_\nu + u^\mu u_\rho u^\rho u_\nu
= h^\mu _\nu
$$
since $u^\rho u_\rho = -1$. Orthogonality can be seen immediately from the definition.
Also, $(\delta^\mu_\nu + u^\mu u_\nu) u^\nu = 0$ but for a vector $k^\mu$ with $k^\mu u_\mu = 0$ we have $ (\delta^\mu_\nu + u^\mu u_\nu) k^\nu = k^\mu$.
This proves the statement. To get the (0,2)-tensor it is just necessary to lower an index.
To see why one might define $h_{\mu\nu}$ this way you can start by looking at the projection tensor onto the time-like subspace, which will be proportional to $u_\mu u^\nu$: $\pi_\mu^\nu = \alpha u_\mu u^\nu$, and since we want it to leave $u^\nu$ unchanged it will have to be $\alpha = -1$.
Then, the way to find $h_{\mu\nu}$ is to write the equation
$$
\delta_\mu^\nu = h_\mu^\nu + \pi_\mu^\nu
$$


text:
Q: Ruby on Rails Tuto <% if signed_in? %> error I'm following this tutorial but I don't understand why i'm having an error on <% if signed_in? %> (app/views/layouts/application.html.erb)
Here is my application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  include SessionsHelper
end

And my sessions_helper.rb
module SessionsHelper

  def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.digest(remember_token))
    self.current_user = user
  end

  def signed_in?
    !current_user.nil?
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user
    remember_token  = User.digest(cookies[:remember_token])
    @current_user ||= User.find_by(remember_token: remember_token)
  end
end

Am I missing something obvious ? I get those errors :
app/helpers/sessions_helper.rb:20:in `current_user'
app/helpers/sessions_helper.rb:11:in `signed_in?'
app/views/layouts/application.html.erb:29:in `_app_views_layouts_application_html_erb___1005071352_28922208'

EDIT :
SQLite3::SQLException: no such column: users.remember_token: SELECT  "users".* FROM "users"  WHERE "users"."remember_token" = 'da39a3ee5e6b4b0d3255bfef95601890afd80709' LIMIT 1

Thanks

A: It turns out that I missed one step of the tutorial. I did not realized that my migration what empty when I performed rails generate migration add_remember_token_to_users :
class AddRememberTokenToUsers < ActiveRecord::Migration
  def change
  end
end

I just follow the advice and perform a new migration (because of the timestamp) :
class AddRememberTokenToUsers < ActiveRecord::Migration
  def change
    add_column :users, :remember_token, :string
    add_index  :users, :remember_token
  end
end

Thanks all for your help


text:
Q: Initialize modal with object, make changes to intermediary object, save/revert to parent component I'm trying to get a modal to be initialized with an object('s properties). Then be able to make changes within the modal, and then either cancel (don't save changes) or save (setting the temporary values to the bound object, thus giving the parent its data)
I have found this question on stackoverflow:
binded object with temp editing in svelte
Which voices some of the same issues I've had. Though the accepted answer is flawed and doesn't consider nested properties, besides any update in the parent sets its value to be that of the child (even when the child value has not been set to be saved).
I've reproduced the issue in this small demo on repl:
https://svelte.dev/repl/7ee93070005a4dd38d9fd3261816f3f1?version=3.23.2
My actual code looks a bit like this:
<Modal isOpen={isSavingModalShown} onRequestClose={() => isSavingModalShown = false}>
  <SaveVenueForm bind:venue onSaved={() => isSavingModalShown = false} />
</Modal>

<!-- SaveVenueForm.svelte -->
<script lang="ts">
  export let onSaved: () => void
  export let venue = {}

  let tempVenue: Venue

  const populate = () => {
    tempVenue = { ...venue } as Venue
  }

  $: venue, populate()

  const handleSubmit = async () => {
    venue = tempVenue
    onSaved()
  }
</script>

<input type="text" bind:value={tempVenue.name} />
<input type="text" bind:value={tempVenue.location.city} />
<button variant="contained" size="lg" on:click={handleSubmit}>Save venue</button>

A: Just get one of the many deep cloning libraries and use that instead of a simple spread when setting the temporary value. In modern browsers you can also use the native structuredClone function.
Currently, as soon as you change the city, the source object (the location) is modified, even if that is not shown in the UI right away. (REPL that forces the UI update)


text:
Q: PDF needs dynamic data I have a PDF document that is taking in dynamic data. I want to write some conditionals to edit how some of the data is displayed. I obviously can not do this with javascript because by the time the PDF loads the data, is it not on the client side anymore. I have tried inline visualforce conditionals but no luck.
Is there a way around this?
My goal is to have a phone list with each person sorted by department with the department name as the header. Also, if there is a department with no users, then do not display the header for that department.

Public phoneListController(){
    allPeople = [SELECT Name,Title, Department, Extension, Phone FROM User ORDER BY Department ASC];
    system.debug('this is the list: ' + allPeople);
}

    <apex:repeat value="{!allPeople}" var="person">
        {!person.Department}

            {!person.Name}
            {!person.Title}
            {!person.Extension}
            {!person.Phone}

    </apex:repeat>

What I am getting caught up on is how to display the department name so it is just listed once on top of the group of users WITHOUT having to put a filter on the query. Right now with this code, the department is listed on top of every user listed.
What I want it to look like:

What it does look like:

A: Its all about the data...
Use a Map:
Class
Public phoneListController(){}

public Map<String,User[]> allPeople{
    get{
         Map<String,User[]> tmp = new Map<String,User[]>();
         for(User u : [SELECT Name,Title, Department, Extension, Phone FROM User ORDER BY Department ASC]){
              //A while ago we had a discussion on performance and this was found to be better of a if..then.. block with contains key
              User[] uList = tmp.get(u.Department);
              if(uList == null) uList = New User[]{};
              uList.add(u);
              //Add mack to the map
              tmp.put(u.Department,uList);
         }
         return tmp;
    }
    set;
}

VF
<apex:repeat value="{!allPeople}" var="depts">
     {!depts}
<apex:repeat value="{!allPeople[depts]}" var="person">

        {!person.Name}
        {!person.Title}
        {!person.Extension}
        {!person.Phone}

</apex:repeat>
</apex:repeat>

Basically get a Map of Departments to Users and structure the repeats to user the Keys and then the values


text:
Q: Global sections of a line bundle on a hypersurface in complex projective space. Let  $X \subset \mathbb{P}^n $ be a complex hypersurface of degree $d$. I'm trying to calculate the global sections of $\mathcal{O}(r)_{|X}$ for $r \in \mathbb{Z}$. This is what (I think) I have so far:
By the long exact sequence in cohomology and Kodaira Vanishing theorem we have a short exact sequence:
$$ 0 \to H^0(\mathbb{P}^n,\mathcal{O}(r-d)) \to H^0(\mathbb{P}^n,\mathcal{O}(r)) \to H^0(X,\mathcal{O}(r)_{|X}) \to 0$$
I can identify $H^0(\mathbb{P}^n,\mathcal{O}(r)) $ with homogeneous polynomials  of degree $r$.
As I understand it, the second map in the above sequence is induced by tensoring the map $ j^\sharp: \mathcal{O}_{\mathbb{P}^n} \to j_* \mathcal{O}_X $, where $j:X \subset \mathbb{P}^n$, with $\mathcal{O}(r)$, and then applying the projection formula.
1) does what I've written make sense?
2) If so, how does $H^0(\mathbb{P}^n, \mathcal{O}(r-d))$ get identified with the kernel here? Do I need to look at the first map given by the inclusion of the ideal sheaf $\mathcal{I}_X \cong \mathcal{O}(-d)$?
Apologies if I'm being real stupid here.


text:
Q: Can't load static library in Java - UnsatisfiedLinkError : invalid ELF header (Possible cause: endianness mismatch) This is how I load the library.
static {
        try {
            System.load("/usr/lib/libname.a");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

When I choose .so (shared-library) application loads library without any error.
But there is a problem with loading static library.
While running the application exception happens :
Caused by: java.lang.UnsatisfiedLinkError: /usr/lib/libname.a: /usr/lib/libname.a: invalid ELF header (Possible cause: endianness mismatch)
    at java.lang.ClassLoader$NativeLibrary.load(Native Method) ~[na:1.8.0_242]
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1946) ~[na:1.8.0_242]
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1828) ~[na:1.8.0_242]
    at java.lang.Runtime.load0(Runtime.java:810) ~[na:1.8.0_242]
    at java.lang.System.load(System.java:1088) ~[na:1.8.0_242]

Codes runs on Linux machine.


text:
Q: Scroll Rect scrolls simply due to mouse movement. How to fix it? Unity 2019.1.0f2
Input System 1.0.2

*

*I create an empty 3D project, then import the Input System into it.

*I add EventSystem to the scene.

*Then I write a simple script and add it to scene:

    using UnityEngine;
    using UnityEngine.InputSystem;

    public class TestScroll : MonoBehaviour
    {
        void Update()
        {
            Debug.Log(Mouse.current.scroll.ReadValue());
        }
    }

*Then I run the scene and just move my mouse (don't spin the mouse wheel) and see this in the console:

Also in the documentation for the Input System I found this:

Because of this feature Scroll Rect starts to scroll simply because I move the mouse pointer over it.
How can this be avoided and why is this happening?

A: It turns out this is a Unity bug: topic


text:
Q: How do i Include 2 lines of Text (a title, and sub title), and box shadow on the images in html How do i add text (a title and a subtitle), to the images and a box shadow behind the boxes. I have tried inserting it under the container in css, but it doesn't work.

More on this

More on this

More on this

More on this

.product-box {
  width: 100%;
  float: left;
  display: block;
  max-height: auto;
  margin-bottom: 80px;
  overflow: hidden;
  border-bottom: 100px solid #fff;
  border-radius: 3px;
  cursor: pointer;
  box-shadow: 20px #404040;
  font-size: 90%;
  margin-top: 30px;
  box-sizing: border-box;
}

.img_wrap {
  list-style: none;
  position: relative;
  box-shadow: #bcbcbc;
  overflow: hidden;
  margin: 0px;
  width: 100%;
  background-color: #000;
}

.img_description {
  text-align: center;
  margin-top: 30px;
  font-weight: 400;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -80%);
  opacity: 0;
  visibility: hidden;
  color: #fff;
  border: 2px solid #fff;
  border-spacing: 5px;
  font-size: 100%;
  padding: 10px;
  transition: opacity 0.2s, visibility 0.2s;
}

.img_img {
  width: 100%;
  opacity: 1;
  display: block;
  height: auto;
  transform: scale(1.03);
  transition: transform 0.2s;
  text-decoration-style: solid;
  backface-visibility: hidden;
  overflow: hidden;
}

.img_img:hover {
  transform: scale(1.15);
  opacity: 0.4;
}

.img_wrap:hover .img_description {
  visibility: visible;
  opacity: 1;
}

How do i add text (a title and a subtitle), to the images and a box shadow behind the boxes. I have tried inserting it under the container in css, but it doesn't work.

A: Do you need such a result? In the css I added rules for the .row class to line up using flex.

.row {
  display: flex;
  justify-content: center;
}

.product-box {
  width: 100%;
  float: left;
  display: block;
  max-height: auto;
  margin-bottom: 80px;
  overflow: hidden;
  border-bottom: 100px solid #fff;
  border-radius: 3px;
  cursor: pointer;
  box-shadow: 20px #404040;
  font-size: 90%;
  margin-top: 30px;
  box-sizing: border-box;
}

.img_wrap {
  list-style: none;
  position: relative;
  box-shadow: #bcbcbc;
  overflow: hidden;
  margin: 0px;
  width: 100%;
  background-color: #000;
}

.img_description {
  text-align: center;
  margin-top: 30px;
  font-weight: 400;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -80%);
  opacity: 0;
  visibility: hidden;
  color: #fff;
  border: 2px solid #fff;
  border-spacing: 5px;
  font-size: 100%;
  padding: 10px;
  transition: opacity 0.2s, visibility 0.2s;
}

.img_img {
  width: 100%;
  opacity: 1;
  display: block;
  height: auto;
  transform: scale(1.03);
  transition: transform 0.2s;
  text-decoration-style: solid;
  backface-visibility: hidden;
  overflow: hidden;
}

.img_img:hover {
  transform: scale(1.15);
  opacity: 0.4;
}

.img_wrap:hover .img_description {
  visibility: visible;
  opacity: 1;
}

Name1

More on this

Description1

Name2

More on this

Description2

Name3

More on this

Description3

Name4

More on this

Description4

This answer is where the name and description are under the block.

.row {
  display: flex;
  justify-content: center;
}

.product-box {
  width: 100%;
  float: left;
  display: block;
  max-height: auto;
  margin-bottom: 80px;
  overflow: hidden;
  border-bottom: 100px solid #fff;
  border-radius: 3px;
  cursor: pointer;
  box-shadow: 20px #404040;
  font-size: 90%;
  margin-top: 30px;
  box-sizing: border-box;
}

.img_wrap {
  list-style: none;
  position: relative;
  box-shadow: #bcbcbc;
  overflow: hidden;
  margin: 0px;
  width: 100%;
  background-color: #000;
}

.img_description {
  text-align: center;
  margin-top: 30px;
  font-weight: 400;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -80%);
  opacity: 0;
  visibility: hidden;
  color: #fff;
  border: 2px solid #fff;
  border-spacing: 5px;
  font-size: 100%;
  padding: 10px;
  transition: opacity 0.2s, visibility 0.2s;
}

.img_img {
  width: 100%;
  opacity: 1;
  display: block;
  height: auto;
  transform: scale(1.03);
  transition: transform 0.2s;
  text-decoration-style: solid;
  backface-visibility: hidden;
  overflow: hidden;
}

.img_img:hover {
  transform: scale(1.15);
  opacity: 0.4;
}

.img_wrap:hover .img_description {
  visibility: visible;
  opacity: 1;
}

More on this

Name1

Description1

More on this

Name2

Description2

More on this

Name3

Description3

More on this

Name4

Description4


text:
Q: MVC - RegisterRoutes I would like to rewrite the url from
http://localhost:51639/home/index?id=123

to
http://localhost:51639/home/product

Here is my code in Global.asax.cs
public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }

What can I do? Thanks a lot

A: Important is the order, because MVC searchs first a fit with RouteCollection and return a url.
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(null, "home/product/{id}", new {
            controller = "Home", action = "Index",
            id = UrlParameter.Optional}
    );
    routes.MapRoute("Default",  // Route name
            "{controller}/{action}/{id}",   // URL with parameters
            new {
                controller = "Home", action = "Index",
                id = UrlParameter.Optional }    // Parameter defaults
    );
}

A: If you're using MVC 5, you can use a custom route parameter, i.e.  [Route("home/product/{id:int}")]. It's really useful for one off routes, and since you can specify a type in the parameter that's passed, it doesn't conflict with other deep routes you might need.
http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx


text:
Q: Using Categories in Swift and Using them in different class I am new to swift. I am working on creating the categories in swift. I have created one category for UIColor. I need to call this in some other class. Currently I am calling this by
messageview.backgroundColor = UIColor(hexaString: "31D433")

but it gives an error.
class Colorextension: UIColor {
    convenience init(hexaString:String) {
        self.init(
            red:   CGFloat( strtoul( String(Array(hexaString.characters)[1...2]), nil, 16) ) / 255.0,
            green: CGFloat( strtoul( String(Array(hexaString.characters)[3...4]), nil, 16) ) / 255.0,
            blue:  CGFloat( strtoul( String(Array(hexaString.characters)[5...6]), nil, 16) ) / 255.0, alpha: 1 )
    }
}

A: In swift you use extensions, placed in global scope:
extension UIColor {
    convenience init?(hexaString:String) {
        if hexaString.characters.count < 6 {return nil}
        self.init(
            red:   CGFloat( strtoul( String(Array(hexaString.characters)[0...1]), nil, 16) ) / 255.0,
            green: CGFloat( strtoul( String(Array(hexaString.characters)[2...3]), nil, 16) ) / 255.0,
            blue:  CGFloat( strtoul( String(Array(hexaString.characters)[4...5]), nil, 16) ) / 255.0, alpha: 1 )
    }
}

Now messageview.backgroundColor = UIColor(hexaString: "31D433") should work.
Update
Note you used wrong ranges (I corrected them), and you probably need to write failable initializer for case when input string have wrong format.


text:
Q: Behaviours in wpf apps Microsoft expression blend 4 I am using Microsoft expression blend 4 and i want to add a simple button,in a wpf application, which by clicking it(on "Run Project" mode) navigates the user to another existing wpf application in expression blend 4.This can be done by using a method but maybe I used the wrong method or i used the right method the wrong way.To be more specific i dragged on the button(that i want to make the task i mentioned) the "Launch UriOrFile Action" method but i realised(by making experiments with various files on desktop and using internet url's) that i can only link the running wpf application with random files or internet sites and not to another wpf application as i wanted(when i put the path of the wpf application it pops up a window saying"windows explorer has stopped working",something that didnt occured when i put random file's paths or internet sites url's).If anyone understands my problem let me know!thanks!!

A: Check out Process.Start. Create a command that fires code that calls that method.


text:
Q: For Mysql, how can "boxing" of output be suppressed when using -e? I want to make a quick query that'll return one record from a mysql DB from the linux command line.  I am planning on using "mysql -e".  Works fine except that it returns hyphens, vert bars and plus signs to "box" the output.  Example...
% mysql -h whatever -u whatever -p<whatever> mydb -N -e "select finish from
the_table where status like 'PASS%' order by start desc limit 1"
+---------------------+
| 2018-02-13 19:57:30 |
+---------------------+

Is there a way to suppress all the hyphens, very bars and "+" signs and just get...
2018-02-13 19:57:30

I found -N suppressing the header (that was good) but didn't see anything obvious to suppress the "boxing".
I suppose I could awk and sed it into submission, but I was looking for something simpler.
Thanks in advance


text:
Q: How to find the correct surface area of rotation Hi I am trying to find the surface area that is traced when the curve $8y^2=x^2-x^4$ is revolved about the $x$-axis. But I am having some trouble with it.
I know that for this in general I will want to use that about the x axis,
$$S= 2\pi \int_{C} y dS $$
I graphed the curve so I see what it looks like; a figure eight type shape with $x$ going from $-1$ to $1$.
But my issue is how I should find $y(t)$.
 I think I could probably use symmetry to simplify as well. Can anyone help with this please?
It seems that there are some discrepancies with different answers from different users, leaving me feeling quite confused. I am still wondering, can no one answer this??

A: Using symmetry as you suggest, and using $y=\frac{1}{\sqrt{8}}x\sqrt{1-x^2}$ in the first quadrant,
$\displaystyle S=2\int_0^12\pi r(x)\sqrt{1+\left(\frac{dy}{dx}\right)^2}dx=2\int_0^1 2\pi\cdot\frac{1}{\sqrt{8}}x\sqrt{1-x^2}\cdot\sqrt{1+\frac{1}{8}\frac{(1-2x^2)^2}{1-x^2}}dx$
$\hspace{.2 in}\displaystyle=\frac{4\pi}{\sqrt{8}}\int_0^1 x\sqrt{1-x^2+\frac{1}{8}(1-2x^2)^2}dx$
$\hspace{.2 in}\displaystyle=\frac{4\pi}{8}\int_0^1 x\sqrt{8-8x^2+1-4x^2+4x^4}\;dx=\frac{\pi}{2}\int_0^1x\sqrt{4x^4-12x^2+9}\;dx$
$\hspace{.2 in}\displaystyle=\frac{\pi}{2}\int_0^1x\big|2x^2-3\big|dx$.  $\;\;\;$(Now simplify and integrate.)

Alternate solution:  $\;\;$Using symmetry, and the parametrization
$x=\cos t, \;y=\frac{1}{\sqrt{8}}\sin t\cos t,\; 0\le t\le\frac{\pi}{2},$ for the part of the curve in Quadrant I gives
$\displaystyle S=2\int_0^\frac{\pi}{2}2\pi r(t)\sqrt{\left(\frac{dx}{dt}\right)^2+\left(\frac{dy}{dt}\right)^2}dt=2\int_0^\frac{\pi}{2} 2\pi\left(\frac{1}{\sqrt{8}}\sin t\cos t\right)\sqrt{\sin^2 t+\frac{1}{8}(\cos^2 t-\sin^2 t)^2} dt$
$\hspace{.2 in}\displaystyle=\frac{4\pi}{8}\int_0^\frac{\pi}{2}(\sin t\cos t)\sqrt{8\sin^2t+(1-2\sin^2 t)^2}dt=\frac{\pi}{2}\int_0^\frac{\pi}{2}(\sin t\cos t)\sqrt{(1+2\sin^2 t)^2}dt$
$\hspace{.2 in}\displaystyle=\frac{\pi}{2}\int_0^\frac{\pi}{2}(\sin t\cos t)(1+2\sin^2 t)dt$.  $\hspace{.2 in}$ (Now use $u=1+2\sin^2t, du=4\sin t\cos t dt$.)

A: Notice, consider an elementary right triangle with hypotenuse $dS$ & legs $dx$ & $dy$ then one should have,
$$dS=\sqrt{1+\left(\frac{dy}{dx}\right)^2}\ dx=\sqrt{1+\left(\frac{x-2x^3}{8y}\right)^2}\ dx$$
$$=\frac{x\sqrt{7-4x^2-4x^4}}{8y}\ dx$$
hence, the surface area of the solid $$2\pi\int_Cy\ dS=2\pi\int y\cdot \frac{x\sqrt{7-4x^2-4x^4}}{8y}\ dx$$
$$=\frac\pi4\int x\sqrt{7-4x^2-4x^4}\ dx$$
$$=\frac\pi4\int 2 x\sqrt{2-\left(x^2-\frac 12\right)^2}\ dx$$
let, $x^2-\frac 12=t\implies 2x\ dx=dt$,
$$=\frac\pi4\int\sqrt{2-t^2}\ dt$$


text:
Q: WooCommerce: Get custom post type IDs or specific order status email notification Attempting to receive and display custom post type wcfa_attachment ID to only be displayed on a order status change notification email with the id of wc_order_status_email_731.
For example:
$attachments = get_posts( array( 'numberposts' => -1, 'post_parent' => $order_id, 'post_type'=> 'wcfa_attachment', 'order' => 'ASC', 'orderby' => 'ID', 'suppress_filters' => false/*,  'meta_key' => 'wcaf_is_active', 'meta_value' => true */ ));

I am able to target wc_order_status_email_731 and pull the order_id then display if for testing but not the custom post type post id's for wcfa_attachment associated with the order.
function add_content_specific_email( $order, $sent_to_admin, $plain_text, $email ) {
    if ( $email->id == 'wc_order_status_email_731' ) {

        $order_id = $order->get_id();

        /// works to print the order id so we know its being received
        print_r ($order_id);

        function get_attachments($order_id)
        {
            $result = array();

            $attachments = get_posts( array( 'numberposts' => -1, 'post_parent' => $order_id, 'post_type'=> 'wcfa_attachment', 'order' => 'ASC', 'orderby' => 'ID', 'suppress_filters' => false/*,  'meta_key' => 'wcaf_is_active', 'meta_value' => true */ ));
            foreach((array)$attachments as $attachment)
            {
                $result[$attachment->ID] = $this->get_attachment($attachment->ID);
            }
            return $result;
            print_r ($result);
        }
    }
}

A: The post ID  that you are looking for your custom post type, is simply $attachment->ID.
Now you should never embed a function in another function. Just add them apart.
Then you can call your function in the other function like:
function get_attachments( $order_id ) {
    $result = array();

    $attachments = get_posts( array( 'numberposts' => -1, 'post_parent' => $order_id, 'post_type'=> 'wcfa_attachment', 'order' => 'ASC', 'orderby' => 'ID', 'suppress_filters' => false/*,  'meta_key' => 'wcaf_is_active', 'meta_value' => true */ ));
    foreach((array)$attachments as $attachment){
        $result[$attachment->ID] = $this->get_attachment($attachment->ID);
    }
    return $result;
}

function add_content_specific_email( $order, $sent_to_admin, $plain_text, $email ) {
    if ( $email->id == 'wc_order_status_email_731' ) {

       $order_id = $order->get_id();

        /// works to print the order id so we know its being received
        print_r ($order_id);

        $attachments = get_attachments( $order_id ); // Call the function

        print_r ($attachments);
    }
}

It should better work.


text:
Q: How to make a splitscreen with a listview on one side I want the right side of the activity to show different items depending which item of the listview on the left is selected. I was able to follow the Android ListView example where the listview  takes up the whole activity screen, but was unable to expand that to split screen. Here is my xml with the list view on the left and a simple button on the right for now. I'm having trouble figuring out the code that will populate my listview.
system_status.xml:
<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/activity_system_status"
       android:title="@string/system_status"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:orientation="horizontal">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="1">

        <ListView
        android:id="@+id/my_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        </ListView>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:layout_weight="1">
        <ToggleButton android:text="ToggleButton" android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></ToggleButton>
    </LinearLayout>
    </LinearLayout>

UPDATE:
I figured it out with the help of Scythe's post. Here is the code that got it working. The xml above works as is.
public class SystemStatusActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ListView lv = (ListView) findViewById(R.id.my_list);
    String[] stats = getResources().getStringArray(R.array.array_system_status);
    lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, stats));
}
}

list_item.xml:
     <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>

A: You have to set up and adapter for that ListView. Search for tutorials on creating custom Adapter classes, you can find dozens of those. You absolutely must understand custom adapters if you plan to develop for this platform.
But anyways, you can get away with the standard ArrayAdapter to get this to work:
String[] countries = <put your strings here>
yourList.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, countries));

After this, set up an ItemClickListener for the list, and handle the content change on the right pane as needed.

A: Try something like
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal">
The above block was new
<LinearLayout
    android:layout_width="0dp" <--BIG CHANGE HERE
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_weight="1">

    <ListView
    android:id="@+id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    </ListView>

</LinearLayout>

<LinearLayout
    android:layout_width="0dp" Big change here
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_weight="1">
    <ToggleButton android:text="ToggleButton" android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></ToggleButton>
</LinearLayout>

</Linearlayout> NEW

The big changes here were to change the layout_width for the linearlayouts you had, so they evenly share the space, and I also put them both in a horizontal linear layout.

A: From http://www.anddev.org/view-layout-resource-problems-f27/two-listviews-side-by-side-t11199.html
Pretty much just need to wrap what you have in a LinearLayout with android:orientation="horizonal".
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              >
    <LinearLayout android:orientation="vertical"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:layout_weight="1"
                  >
        <ListView android:id="@+id/list"
                  android:layout_width="wrap_content"
                  android:layout_height="fill_parent"
                  android:entries="@array/colors"
                  />
    </LinearLayout>
    <LinearLayout android:orientation="vertical"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:layout_weight="1"
                  >
        <TextView android:id="@+id/text"
                  android:layout_width="wrap_content"
                  android:layout_height="fill_parent"
                  android:text="Hello World, AndroidTest"
                  />
    </LinearLayout>
</LinearLayout>


text:
Q: Scrolling to reach a Dom Object Position and then do something i was working on a galery where when the user scrolls and reaches a thumb certain background action occurs.
Now  did this coding and i am able to get the result but somehow i am confused as it only works one time and then when i again scroll to that position it does nothing.
I am using alert boxes to reach 5th and 7th thumb and it only shows message once.
I am using something like this
    $(document).ready(function () {

        // Thumb 1
        var thumb4Target = $("#myImg1").offset().top;
        var interval = setInterval(function () {
            if ($(window).scrollTop() >= thumb4Target) {
                alert('1nd Image Position Obtained');
                clearInterval(interval);
            }
        }, 0);

        //Thumb 2
        var thumb4Target2 = $("#myImg2").offset().top;

        var interval2 = setInterval(function () {
            if ($(window).scrollTop() >= thumb4Target2) {
                alert('2nd Image Position Obtained');
                clearInterval(interval2);
            }
        }, 0);

    });

check this Fiddle
LINK
Please tell me where i am doing wrong.Thanks.

A: Use scroll event instead of interval. LIVE DEMO 1 Or LIVE DEMO 2
$(window).scroll(function()
{
   var thumb4Target = $("#myImg1").offset().top;
   var thumb4Target2 = $("#myImg2").offset().top;

   if ($(window).scrollTop() >= thumb4Target) {
       alert('1nd Image Position Obtained');
   }
   if ($(window).scrollTop() >= thumb4Target2) {
       alert('2nd Image Position Obtained');
   }
});


text:
Q: Log In to page automatically by filling in HTML elements with VB.NET I'm attempting to migrate a script written in VBA inside a database into an application that I've written in VB.NET, as an added feature.
I understand that the VBA and VB.NET languages are very different and I've been having a hard time trying to migrate the section of code that I need.
I need to open an Internet Explorer page, fill in two textboxes that would be used for a username and password, and press the submit / login button automatically.
In VBA, I was able to do this using the below code.
Dim HTMLDoc As HTMLDocument
Dim MyBrowser As InternetExplorer

Dim MyHTML_Element As IHTMLElement
Dim MyURL As String

    'Ignore errors
    On Error GoTo Err_Clear

    MyURL = Address

    Set MyBrowser = New InternetExplorer 'Open Internet Explorer
    MyBrowser.Silent = True 'Silence popups & Errors
    MyBrowser.Navigate MyURL 'Browse
    MyBrowser.Visible = True 'Obvious

    Do
    'Wait till finished
    Loop Until MyBrowser.ReadyState = READYSTATE_COMPLETE
    Set HTMLDoc = MyBrowser.Document

    'Enter user / password
    For Each MyHTML_Element In HTMLDoc.getElementsByTagName("input")
        If MyHTML_Element.Name = ("username") Then
            MyHTML_Element.Value = Username 'Variable to be passed to sub

        ElseIf MyHTML_Element.Name = ("password") Then
            MyHTML_Element.Value = Password 'Variable to be passed to sub

        ElseIf MyHTML_Element.Type = "submit" Then
            MyHTML_Element.Click: Exit For

        End If

    Next

Err_Clear:
        If Err <> 0 Then
        'Debug.Assert Err = 0
        Err.Clear
        Resume Next

        End If

When moving this to VB.NET, even after adding the references I'd used for Microsoft Internet Controls, and Microsoft HTML Object library, I receive several errors such as:
 Dim MyHTML_Element As IHTMLElement '"ITHMLElement" is ambiguous in the namespace 'mshtml'

 Loop Until MyBrowser.Readystate = READYSTATE_COMPLETE 'Not declared

I've used Visual Basic before, but haven't used it to manipulate values of HTML pages within a web browser, and haven't been able to find much regarding this in VB.NET online.
I'm hoping someone can provide some insight into this for me, or point me in the right direction, thanks in advance!

A: I found an answer today on another site.
I was able to use the following vb.net code to identify each element, fill in it's value with a username and password, and then click a submit button (assuming the submit button's Element ID is known)
Dim theElementCollection As HtmlElementCollection = Me.WebBrowser1.Document.GetElementsByTagName("input")

        For Each curElement As HtmlElement In theElementCollection

            Dim controlName As String = curElement.GetAttribute("name").ToString.ToUpper

            If controlName.ToUpper = "USERNAME" Then

                curElement.SetAttribute("Value", Username)

            ElseIf controlName.ToUpper = "PASSWORD" Then

                curElement.SetAttribute("Value", Password)

WebBrowser1.Document.GetElementById("submitButton").InvokeMember("click") 'click button


text:
Q: Seleccionar id dinamicos Tengo un formulario que voy llenando con datos de un producto.necesito saber como puedo trabajar con id dinámicos,buscando en Internet aprendí que se deben agregar corchetes al final del id de esta forma: name="id[]" pero mi problema es que no sé como llamarlos en el selector de jquery.
Al momento de seleccionar un botón del producto deseado se solicita la información de ese producto y lleno mis td e input correspondientes de la siguiente forma:
var cant = prompt("Ingresar Cantidad:");

if(cant>0){
$('#cod[]').val(data.ID); //probé con esto pero no me dio resultado

Los antes de enfrentarme al problema de agregar los datos a la tabla correspondiente los trabajaba de esta forma incrementando una variable en 1
var $cant = $('#qty'+idqty).text(cant);
idqty ++;
$('#producto'+idprod).text(data.DESC);
idprod ++;
$('#precio'+idpre).val(data.PRECIO);
idpre ++;
agrega_fila();
calcular_valores(cant,data.PRECIO);

}else{
    alert ("La cantidad debe ser mayor a 0");
}

El problema es que no tengo idea de como insertar los datos de la forma que me funciona (incrementado la variable con cada iteración)
Código del formulario:

Detalle

                        <form id="detalle-form" method="post" class="form-horizontal style-form" >
                            <input id="n-mesa" name="n-mesa" hidden="" type="number">

                             Codigo
                              Qty
                              Descripción
                              Peso
                              Precio

<input id="cod[]" class="form-control input-md"  type="text">

Kg
<input id="peso0" class="form-control input-md"  type="text" value="0">

$
<input id="precio0" class="form-control input-md"  type="text" value="0">

                                  Total :

$
<input id="total" class="form-control input-md"  type="text" value="0">

                              <button title="Guardar registro" id="save" name="save" class="btn btn-success"></button>
                                                    <button class="btn btn-success "></button>

                                  Propina Sugerida 10%

$
<input id="propina" class="form-control input-md"  type="text" value="0">

                  </form>


text:
Q: Javascript add class I have this line in javascript document.getElementById("load").classList.add("active"); but not working. Where is problem and what I must change?
In html I have

And I need with javascript add class active to this div.

A: Your code looks fine, just make sure your JS code executed after building the DOM, the below code will ensure that:
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("load").classList.add("active");
});


text:
Q: Expirable links to profile pages I'm working on a project in core php with mysql for a tutor agency in which i have send mail to people with links to the tutor profile pages matching their required criteria. I want these links to be temporary links and want them to expire in say 72 hours, I'm not sure how to go about it. Any ideas?
originally link is something like this
"http://mysite.com/mysubdirectory/index.php?action=view_credentials&tutorid=".$tutor_id;

Thanks for help.
For anyone looking for the same answer as I was, I followed shadyyx and with a bit of effort i was done!! thanx everyone!

A: Use a table to store the TIMESTAMP when sending the link and redirect to an error if the link is accessed after TIMESTAMP+<72 hours>

A: Some solution that bumped into my mind:
Create a DB table for these links where You would save the link, unique identifier (some hash), date it was created and date when it will expire.
Then create a page (script) that will get that link (containing not the full URL but the URL of that script and a unique identifier of the link stored in the DB). This script will try to search for the link identified by the unique hash while conditioning current date and time to the link expiry date.
If the link is found and not expired then You would redirect user to that page otherwise You will end up with a message that the link is expired or not found.
Should be pretty easy to implement.
Hope this idea will help You.

A: Your tutor_id shall be stored in database before you send it. This would help sending unique id (just in case :), and do some checks if i.e. ID used come with is valid. So when anyone enters the link, your index.php should check if all parameters are valid, query DB agains value of $_GET['tutorid'] and see if it is not expired. And you'd know this because your DB record shall hold TIMESTAMP with creation date. Having creation date you can check how old it is and accept or reject the tutor_id

A: Protected Links is a PHP Script from codecanyon, it expires links after a fixed time and much more..
It can be used to expire a tutorial link or any other link in 72 hours or any number of hours, by IP address, for single user or mutiple users. A php coder can integrate this in their application with some effort.
http://codecanyon.net/item/protected-links-expiring-download-links/2556861


text:
Q: How to parse a url and convert the url contents into string for Android? How to parse and convert the contents of url into string?
whether this can be done for Android programming?

A: Use UrlQuerySanitizer class.
EDIT
Here is an article which will show you how to download images/files from a specific URL to your device.
Second Edit
See this answer.
You can take a look at this tutorial also.

A: What should I do to connect to Server from eclipse - Android?
Check This URL here i posted a complete code to connect to a url and read the entire content . at present it getting in the Log cat you can store it in Strings or anywhere you want


text:
Q: is winrt code better protected against reverse engineering? My application is being developed in silverlight. Plan to launch it later this year. I am worried against my xaps getting reverse-engineered. I do have a fare amount of intelligence in my wcf service but you cant put everything in the service. Now winrt is anothe option. Fact that both silverlight and winrt use xaml, it seems possible to move my client code to winrt but only if that code is protected against reverse engineering. Opinions?

A: No.
http://JustinAngel.net/ReverseEngineerWin8Apps

A: There is little that can protect your code against reverse engineering. Running on server hides the code making it most secure, obfuscation still protects it quite well, but not completely and it has some other risks. WinRT allows you to write native code, which is a bit harder to reverse engineer than .NET code, but only marginally. On the other hand - if your application is written in non-minified javascript - you are basically shipping your source code and you don't even have a xap file to decompress - just look in C:\Program Files\WindowsApps and there is a folder for your app where all the files you see in Visual Studio are stored.
You can look at these options then and decide what would work best for you. Ultimately though - the choice between WinRT and Silverlight is a choice of platform - WinRT applications will only run on Windows 8 and (we can speculate) possibly on the next version of Windows Phone, which at least initially - limits your target audience. I have not heard of the option to sell Silverlight apps through Windows Store, unless you are targeting Windows Phone, where that is the only option (that and XNA - both being .NET based).
If your client-side code is indeed a unique intellectual property - you are better off protecting it with patents and copyright law than with obfuscation and compilation.


text:
Q: Specifying dimensions of text For a submission requirement I need that my document exactly fills a box of m x n inches.
Does anybody know how I can specify this in LaTeX?

A: In your document preamble, use
\usepackage[includeheadfoot,width=<m>in,height=<n>in]{geometry}

where you specify <m> and <n> (or use text={<m>in,<n>in}). Add the showframe option to see the boundaries.


text:
Q: html with many similar selects that react when changed My html contains many similar selects which I thought I could do all as
<form name="form">
<select name="site" size="1" onChange="formHandler()">
  <option value="$site?i=$i&j=$2">ABC</option>
  ...
</select>
</form>

Contained in the html header is
function formHandler() {
  var URL = "";
  URL = document.form.site.options[document.form.site.selectedIndex].value;
  if ( (URL != "") && (URL != "0") ) {
    window.location.href = URL;
  }
}

But I get TypeError: document.form.site is undefined. I presume this is because the forms and their selects all have the same name. This is because I only want one formHandler() in the header.
Very thankful for help!

A: Pass the element as parameter to the handler function:
onchange="formHandler(this)"

and then in the handler:
function formHandler(el) {
    var url = el.options[el.selectedIndex].value;
    // and the rest...
}


text:
Q: C#: How to create a window like this? I need to create a window similar to this:

a window similar to the types of dialog boxes that have been included with windows vista.

but I could not find exactly the same dialog boxes. very similar - it's Credential dialog and Input dialog. In the first case there are differences in the UI, in the second - the number of input fields and the absence of label. How can I make exactly the same window? Sorry for bad English.

A: You want to create a dialog exactly like the first dialog you've shown, the one used by FluffyApp?
You'll have to create it yourself, by hand. It's not a standard Windows dialog; it's a custom dialog resource provided by the FluffyApp application. It's obviously modeled to look a lot like the standard Windows authentication dialog, which is a good idea—users are already familiar with the native UI and will find your application to be much easier to use if it strongly resembles what they're already accustomed to. I recommend that if you decide to create your own custom dialog that you follow Windows's example as well.
But it's not entirely clear why you need your dialog to look exactly like the one that FluffyApp uses. I'm not really even sure why FluffyApp needed to create a custom dialog! It seems like the standard Windows authentication dialog would be perfectly sufficient. They have the same number of input fields, the UI designers at Microsoft have just replaced labels with cue banners. Not anything to worry about.

A: Those are standard windows dialogs, but instead of letting the dialog manager draw the text, they use DrawThemeText to draw the text, using one of the themed elements (not sure what, because you have several examples).  You can play around with the various parameters to DrawThemeText to come up with something that works.


text:
Q: Symfony classNotFoundInNamespaces exception I am working with a bundle called rss-atom-bundle. Through this bundle I should be able to fetch the RSS feeds and save them to the database.
I can get the bundle to work up till getting the feeds from the URL but when I try to presist I get the following error and I just cant figure it out why I am getting it.
The class 'Debril\RssAtomBundle\Protocol\Parser\Item' was not found in the chain configured namespaces Symfony\Bundle\AsseticBundle\Entity, AppBundle\Entity`

Looking online and at stackoverflow i came across questions that were related to this but all of them are talking about by default the Entity should be inside the Entity folder of the Bundle and if they are not then this error appears but my Entity files are inside Entity folder and I followed the instructions given by the bundle author but still i cant get passed this error
This is what my Controller looks like
        $em = $this->getDoctrine()->getManager();
        // fetch the FeedReader
        $reader = $this->container->get('debril.reader');

        // this date is used to fetch only the latest items
        $unmodifiedSince = '01/01/2000';
        $date = new \DateTime($unmodifiedSince);

        // the feed you want to read
        $url = 'http://example.com/feed/';

        $feeds = $reader->getFeedContent($url, $date);
        $items = $feeds->getItems();

        dump($items);
        foreach ( $items as $item ) {
            $em->persist($item);
        }
        $em->flush();

As per bundle instructions I did implement FeedInterface to my Feed Entity and ItemInInterface, ItemOutInterface to my Item Entity
This is what my orm.yml looks like for Feed and Item Entity
Feed
AppBundle\Entity\Feed:
    type: entity
    table: null
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
    fields:
        title:
            type: string
            length: 255
        description:
            type: text
        link:
            type: text
        publicId:
            type: text
        lastModified:
            type: datetime
        lastViewed:
            type: datetime
    oneToMany:
        items:
            targetEntity: AppBundle\Entity\Item
            mappedBy: feed
            cascade: ["persist"]
    lifecycleCallbacks: {  }

Item
AppBundle\Entity\Item:
    type: entity
    table: null
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
    fields:
        title:
            type: string
            length: 255
        title:
            type: text
            nullable: true
        summary:
            type: text
            nullable: true
        description:
            type: text
            nullable: true
        medias:
            type: text
            nullable: true
        updated:
            type: string
            nullable: true
        publicId:
            type: string
            nullable: true
        link:
            type: string
            nullable: true
        comment:
            type: string
            nullable: true
        author:
            type: string
            nullable: true
    manyToOne:
        feed:
            targetEntity: AppBundle\Entity\Feed
            inversedBy: items
            joinColumn:
                name: feed_id
                referencedColumnName: id

Any help will be really appreciated as I am clueless why i am getting the error?

A: Try to add RssAtomBundle to the list with mappings in app/config/config.yml
orm:
    entity_managers:
        default:
            connection: default
            mappings:
                AppBundle: ~
                AsseticBundle: ~
                RssAtomBundle: ~


text:
Q: Sound output configuration option missing in settings on 22.04 When connecting an audio device over bluetooth the audio quality is very poor and it gets interrupted a lot. It seems that I have the same problem as this asker.
The solution would be easy, but I'm missing the 'Configuration' option as it appears in other answers referring to older versions.
Where did the option move in 22.04? What am I missing?


text:
Q: Content or measure zero of a graph of a continuous function? I'm starting to learn some basic definitions that are presented on Spivak's Calculus on Manifolds, mainly Measure ant content zero. The definition for measure zero is that, for every $\varepsilon >0$, we have a set of closed rectangles such that $E \subset\bigcup_{k \in \Bbb{N}} R_k$ and $\sum_{k=1}^\infty \mu (R_k) < \varepsilon$. Content zero is the same but with finitely many rectangles.
Now, my question is, does the graph of a continuous function has content zero? I'm aware that the graph of real continuous function has measure zero. I completely understand the OP solution with the correction gave there. But the solution implies that it has content zero as well? Indeed, in a part of the proof, we get that $$G(f) \subset \bigcup_{i=1}^n [x_{i-1},x_i]\times[m_i,M_i],$$ i.e., we can cover $G(f)$ by a finite amount of closed rectangles, mainly, $\{[x_{i-1},x_i]\times[m_i,M_i]:1\le i\le n\}$. Which, by definition, it implies that it has content zero as well. Am I correct or am I making a dumb mistake?


text:
Q: Use of previous not null state of data I am trying to carry forward the previous state of data wherever data is not available.
For example, I have this data:
Month   Order   Amount
----------------------
   1    Item1   100
   1    Item2   200
   1    Item3   300
   2    NULL    NULL
   3    Item4   100
   4    NULL    NULL
   5    NULL    NULL
   6    Item1   100

So in the above example I want to use 1st month's information to be carry forwarded as it is for 2nd month. Also since 3rd month's information is available then use it for the month 4 and 5.
Hence the output will be the following:
Month   Order   Amount
----------------------
   1    Item1   100
   1    Item2   200
   1    Item3   300
   2    Item1   100
   2    Item2   200
   2    Item3   300
   3    Item4   100
   4    Item4   100
   5    Item4   100
   6    Item1   100

A: You can do this using a LEFT JOIN. If you join on "Month", you can ensure that the joined "Month" has the higest value (so far) and also has a non-NULL "Order".
SELECT *
  FROM      myTable t1
  LEFT JOIN myTable t2 ON t2.Month = (SELECT MAX(Month)
                                        FROM myTable
                                       WHERE Month <= t1.Month
                                         AND [Order] IS NOT NULL)

You'll get too many rows at first, since "Month" 1 will give 9 rows. You can remove those by also ensuring that the joined "Month" is strictly lower:
SELECT *
  FROM      myTable t1
  LEFT JOIN myTable t2 ON t2.Month = (SELECT MAX(Month)
                                        FROM myTable
                                       WHERE Month <= t1.Month
                                         AND [Order] IS NOT NULL)
                      AND t1.Month > t2.Month

Then you only need to SELECT the right columns:
SELECT t1.Month,
       COALESCE(t1.[Order],t2.[Order]) as [Order],
       COALESCE(t1.Amount,t2.Amount) as Amount
  FROM      myTable t1
  LEFT JOIN myTable t2 ON t2.Month = (SELECT MAX(Month)
                                        FROM myTable
                                       WHERE Month <= t1.Month
                                         AND [Order] IS NOT NULL)
                      AND t1.Month > t2.Month

dbfiddle


text:
Q: Share same key with multiple taskmanagers I have a flink application running on 400 taskmanagers. Within 1hour window time i get same keys more frequently, let's say out of 1500 unique keys 50 keys will occurs more often. This is making like few taskmangers alone process more amount than other. If 390 taskmanagers are processing 50MB per minute other 10 are processing 10GB per minute. This is making the system very slow.
Can we share same key with multiple taskmanagers if the load is high. How can i solve my issue here.

A: If you want finer grained partitioning of your data, you'll need to find a way to sub-divide the current keys. Depending on what you're doing, it might make sense to add a preprocessing layer before aggregating at the level of the current keys (for example).


text:
Q: I am having trouble getting data returned from a post request in angular/typscript frontnend and asp.net backend I have a web application I am developing that depends on back end processing. I am sending a post request from my Angular(v14)/Typescript front end to an ASP.NET back end.
Back end code
[HttpPost]
public async Task<string> ProcessExcelFile(IFormFile fileData, IFormCollection data)
{
      string guid = await processor.ProcessFile(fileData, data) //Imp not important for question.

      return guid;
}

Front end code
var guid: string = "";
this.http.post<string>('/api', formData).subscribe(result => {guid = result;});

I have confirmed the backend is being hit correctly through debugging and returns the correct data.
But the front end "guid" is empty after I call the post request. What I am doing wrong here?
The back end processing could take a few seconds, is that the problem? What can I do about this?

A: In case it's a JSON response you should be able to do it like this:
// Backend response
{
  "guid": "randomId123",
}

let guid: string;
this.http.post<any>('/api', formData).subscribe(result => {
    guid = result.guid;
});

If it's not JSON Response, could please share how the response look alike?
Update in case the response is just text:
let guid: string;
this.http.post<string>('/api', formData,{ responseType:'text'}).subscribe(result => {
    guid = result;
});

A: Just by going through the code snippets, not returning an IActionResult stands out to me so you could give this is a shot and check if it solves the issue
[HttpPost]
public async Task<IActionResult> ProcessExcelFile(IFormFile fileData, IFormCollection data)
{
  string guid = await
  processor.ProcessFile(fileData, data) //Imp not important for question.

  return ok(guid);
}

This basically sends an OK API response with the guid as the content

A: It looks like the post request would not finalize until the function it lived in that started from a button click on the web page finished.
Instead of creating the guid variable in the same function as the post request, I changed it to a global variable. I am now getting the correct data in the guid variable but only after the button press function finishes.
this.http.post<string>('/api', formData).subscribe(result => {this.guid = result;});