text:
Q: JSESSIONID cookie not stored I have a frontend written in angular which runs on localhost:3002.
I have a backend written with Spring-boot which runs on localhost:8080.
I added a filter to handle CORS (which I found on SO and adapted to my need) :
@Component
public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:3002");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(request, response);
    }

    public void destroy() {}
}

When I authenticate, I can see that the server sends a cookie :

This cookie is not sent with the following requests. This results in 401 responses :

I looked at the "resources" panel of the chrome console and found out that no cookie were stored.
Any ideas?

A: In the file where you configure your $httpProvider, add this line to specify you want to send credentials with cross-site requests:
$httpProvider.defaults.withCredentials = true;

Typically, AngularJS will automatically send these cookies with requests (for same-origin requests) but since your requests are cross-site then you have to manually configure this.


text:
Q: Issue in setting env Variable for Supervisor debian I am using supervisorctl for running a program and environment variables to store the common variables.
For setting Environment Variable I am using /etc/environment. I have added the following as environment variable:
Foo=Bar

Then I made sure the environment variable is set right by using the following command
echo $Foo
> Bar

This is a Sample Program Which I am trying to run using Supervisor:
echo $Foo
while :
    do
        sleep 10s
        echo "I have completed"
done

When I run the program directly its working variable properly:
sh /home/data/trial.sh
> Bar
  I have completed

I have added Trial.conf in my /etc/supervisor/conf.d/ directory. This is my Trial.conf:
[program:Trial]
command = sh /home/data/trial.sh

When I run the program using supervisorctl
supervisor> start Trial
Trial: started
supervisor> fg Trial

I have completed

I found some solutions for setting the local environment variable for supervisorctl
I tried the following:
[supervisord]
environment=Foo="%(ENV_Foo)s"

But when I rebooted the supervisor and started the supervisor I got this error:
unix:///var/run/supervisor.sock no such file

One behavior I noticed is that when I am using sudo Then I cannot access my environmental variables:
echo $Foo
> Bar
sudo echo $Foo
>

For that, I found a solution sudo -E su which will preserve $Foo for root.

Question: How can I make Supervisor access my local environmental variables?

A: You shouldn't be trying to get supervisord to read your user's environment variables. You should instead tell supervisord what to use for the environment variables in its config.
Environment variables won't persist a reboot, they need to be set each time on boot or launching of a shell.
Keep in mind that it's possible for users to see environment variables of other users so don't store anything sensitive in them (like passwords). Use a properly protected config file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel Runtime exception I am new to Laravel, while running  http://localhost:8000/ in my browser i'm getting the below error
RuntimeException in compiled.php line 13230:
The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.

My compiled.php line 13230 lies below :-
 public function __construct($key, $cipher = 'AES-128-CBC')
{
    $key = (string) $key;
    if (static::supported($key, $cipher)) {
        $this->key = $key;
        $this->cipher = $cipher;
    } else {
        throw new RuntimeException('The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.');
    }
}

I got this error after the command 'composer update'.How can i clear this?


text:
Q: How to get output of fixed pattern in oracle I had a column called TRAN_TYPE in my table and it has data as shown below.
TRAN_TYPE
----------
success
failed
123456-001
654321-001
098765-002
time out

My requirement is to get the column data which contains continuous 6 digits followed by - and 3 digits.
As per above data my output will be
123456-001
654321-001
098765-002

Please suggest query.

A: You could use a regular expression:
where regexp_like(tran_type, '^\d{6}-\d{3}$');

The \d represents a digit, {6} and {3} are how many times the previous pattern have to be repeated, and they must be separated by a dash. The ^ and $ are start and end anchors so there can't be anything before or after the digits. Read more about regular expression support.
Demo with your sample data in a CTE:
with your_table (tran_type) as (
            select 'success' from dual
  union all select 'failed' from dual
  union all select '123456-001' from dual
  union all select '654321-001' from dual
  union all select '098765-002' from dual
  union all select 'time out' from dual
)
select tran_type
from your_table
where regexp_like(tran_type, '^\d{6}-\d{3}$');

TRAN_TYPE
----------
123456-001
654321-001
098765-002

Or try this sqlfiddle


text:
Q: How to get all form errors as array? I have a simple form using only form types delivered by the form package and want to get all form errors.
->createBuilder('form', $preselects, array('error_bubbling' => false))
->add('wealth', 'integer', array(
    'constraints' => array(
        new Range(array(
            'min' => 1
        ))
    )
))
->add('group', 'choice', array('choices' => $groups))
->getForm();

Regarding the upgrade doc there are new parameters for getErrors($deep = false, $flatten = true).
I am confused why I need now to give the first parameter to get the errors of simple types.
If I do this I can retrieve the error of wealth or group, but I don't really understand how to get the name of the child.
I have an instance of FormError and want to get the child name. I can get the propertyPath over the cause but it would look like children[wealth].data. I just want to get wealth.
Do I really need to modify the string itself?
My expected result is to get an array containing the child name as key and the errors as value to that child. The problem is not to get the error message but the child name.
Thanks for any hints.


text:
Q: Web application performance and deployment architecture (java) I have two questions regarding Java web application deployment and its impact on performance.
We have an application deployed on serverA, with JSPs exploded in to one content directory (that means JSPs are not part of the WAR)
question 1: What I knew was this was an approach for development rather than any other environments. Does this exploded deployment slow down performance?
now, the content directory is cross mounted(NFS share) to another hardware, and there we run serverB, which also use the JSPs for its content.
When both serverA and serverB are running and utilizing the same content, can it slow down the performance?

A: The first time any jsp is needed, it would be compiled into a servlet and stored in the web container's cache(at-least tomcat does it). Since the cache folder is not over NFS, that shouldn't affect web sevrer performance. It might be a good idea to precompile your JSPs though.

A: Deploying JSPs in exploded form (rather than in a WAR file) won't make any difference from a performance perspective.  When a WAR file is deployed, it is unpacked anyway.
Putting content (including JSPs) in an NFS mounted file system will make access to the files, and can lead to operational issues if your NFS mounts go stale at the wrong time.  This will happen the first time a JSP is used, and can also happen at other times if your JSP engine is configured to periodically check for changed JSPs.

A: Exploding the WAR should slightly improve deploy time, but the server is going to explode the WAR file anyways when it's deployed.
As other replies pointed out, JSPs are translated into servlets and then compiled into .class bytecodes.  This happens the first time a user accesses that JSP, and this will produce lag-time for the users, especially if it's a complex page.  The best way around this is to precompile the JSPs.

A: If you application's JSPs are precompile and the compiliation feature is closed in Servlet container, it does not impacts your application's performance,because the JSPs were compiled to their .class file,and then they would be loaded by container.


text:
Q: JQuery FadeOut Not Working Properly Could anybody explain to me why the fade out is not working properly for the following code. When I say it doesn't work properly the image does disappear, but it doesn't fade out over a 800ms time period. however the Fade In works fine.
        $('.main-image').fadeOut(800);

        $('.main-image').hide();

        $('.main-image').attr('src',newUrl);

        $('.main-image').css('margin-left','-' + divWidth+'px');

        $('.main-image').fadeIn(800);

A: It's because you call hide() straight after, you want code to be executed after the fadeOut() in the complete callback, second parameter.
$('.main-image').fadeOut(800, function() { // do stuff when fade is done });
fadeIn() works fine because it is the last action.
$('.main-image').fadeOut(800, function() {

    // $('.main-image').hide(); // Can be removed as fadeOut will do that already

    $('.main-image')
        .attr('src',newUrl)
        .css('margin-left','-' + divWidth+'px')
        .fadeIn(800);
});

A: You are calling .hide() before the fadeout completes. .fadeOut() will hide this already, no need to call hide after.
Also, one of the great things about jquery is chaining. You can simplify this tremendously as follows:
$('.main-image')
    .fadeOut(800)
    .attr('src',newUrl)
    .css('margin-left','-' + divWidth+'px')
    .fadeIn(800);


text:
Q: Web services using java I have created simple web services to convert temperature.
i have deployed it on tomcat under webserivces folder but when i am trying to access it using url "http://localhost:8080/YoutubeExample/ConverterService" its giving me an error shown below
"HTTP Status 404 - /YoutubeExample/Converter type Status report
message /YoutubeExample/Converter
description The requested resource is not available."
Can you please let me know the reason for the same.


text:
Q: Show an isomorphism If $N,M$ are normal subgroups of $G$ then $\frac{NM}{M} \simeq \frac{N}{N\cap M}$
I have been trying to build a function from $N$ to $\frac{NM}{M}$ and looking at is kernel, but i'm.strugling at what $\frac{NM}{M}$ looks like

A: The idea is very good.
You can first observe that $NM=\{xy:x\in N, y\in M\}$. Clearly, the right-hand side is a subset of $NM$ and contains both $N$ and $M$. On the other hand, a product of the form $(x_1y_1)(x_2y_2)$, with $x_1,x_2\in N$ and $y_1,y_2\in M$, can be rewritten as
$$
\underbrace{x_1\underbrace{(y_1x_2y_1^{-1})}_{\in N}}_{\in N}
\underbrace{(y_1y_2)}_{\in M}
$$
from which it easily follows that the right-hand side is closed under products. It's also closed under inverses, because, for $x\in N$ and $y\in M$,
$$
(xy)^{-1}=y^{-1}x^{-1}=
\underbrace{y^{-1}xy}_{\in N}
y
$$
Hence the right-hand side is a subgroup of $G$ containing both $N$ and $M$, so it coincides with $NM$.
In particular an element of $NM/M$ is of the form $xyM=xM$, for $x\in N$ and $y\in M$.
Hence the surjective homomorphism $N\to NM/M$ you are looking for is
$$
x\mapsto xM
$$
whose kernel is
$$
\{x\in N:x\in M\}=N\cap M
$$
The homomorphism theorem now shows $N/(N\cap M)\cong NM/M$.
Note that it is not needed to assume $M$ is normal in $G$, but just a subgroup; only normality of $N$ is required.

A: In particular, $NM=\{nm \, | \, n \in N \text{ and } m \in M\}$, therefore the quotient set (in this case quotient group as things are given to be normal) $$NM/M=\{n\color{red}{mM} \, | \, n \in N \text{ and } m \in M\}=\{nM \, | \, n \in N\}$$
Now start with $N \longrightarrow NM/M$ by using the map $\phi(n)=nM$ (so you are sending an element of $N$ to the coset it belongs to). It is easy to see that this is a surjective homomorphism with kernel $N \cap M$ (check it yourself!!). Now apply the first isomorphism theorem.

A: Let $\pi: G \to G/M$ be the canonical projection with kernel exactly $M$. Since $\pi$ is surjective, $\pi\restriction_N: N \to \pi(N)$ is surjective. By the first isomorphism theorem,
$$
\pi(N) \simeq N/\ker{\pi\restriction_N} = N/(\ker \pi \cap N) = N/(M \cap N)
$$
On the other hand, we can restrict the codomain, giving another surjective morphism,
$$
\pi \restriction^{\pi(N)} : \pi^{-1}(\pi(N)) \to \pi(N)
$$
and since $M = \ker \pi \subseteq \pi^{-1}(\pi(N))$, then $\ker \pi\restriction^{\pi(N)} = M$. Moreover, we have that $\pi^{-1}(\pi(N)) = NM$. In effect, from
$$
\pi(NM) = \pi(N)\cdot \{1\} = \pi(N)
$$
we see that $NM \subseteq \pi^{-1}(\pi(N))$ and the other inclusion is given by the fact that, if $\pi(x) \in \pi(N)$, there exists $n \in N$ with $\pi(x) = \pi(n)$, and so $xn^{-1} \in \ker\pi = M$ which implies $x \in M\cdot n \subseteq MN$. Thus once again, by the first isomorphism theorem,
$$
NM/ M \simeq \pi(N)
$$
and so
$$
NM/M \simeq\pi(N) \simeq N/(M\cap N)
$$
as desired.


text:
Q: Declaring Variables/Executing Functions Without Names I couldn't really find anything on this, although I don't know exactly how to word it.
Are there drawbacks to writing something like this:
new Thread(new ParameterizedThreadStart(SomeFunction)).Start(SomeObject);

versus this:
ParameterizedThreadStart threadStart = new ParameterizedThreadStart(SomeFunction);
Thread thread = new Thread(threadStart);
thread.Start(SomeObject);

To me, if I don't ever need to call that thread again, then why do I have to even name it?

A: In your case, no, however some reasons why you would want to use variables instead of inlining are:

*

*(obviously) if you wanted to reuse the value

*If the result implemented IDisposable (in which case you'd encapsulate it in a using statement)

*If one part of the compound statement could throw an exception that you could handle versus letting it bubble up.

A: In my opinion it depends on whether the intermediary variables provide value to the future reader of the code.
In your case I don't see any trouble in keeping it compact because the intermediaries are only infrastructure code necessary to run SomeFunction on a worker thread.

A: You can do it for

*

*Better readability.

*Maintenance of the code will be easy (for other developers)

*and for exception handling (in some cases)
Otherwise both are equal.


text:
Q: 'playing in films' or 'acting in films', which is correct? For example, in this sentence:

Jodie Foster started __ in films when she was very young.

Looks like both are correct but it should be one.

A: Both "playing" and "acting" may be used for what an actor dfoes in a play, film, video or TV show. Indeed "player" is another term for "actor", and it normally has much the same meaning,
The word "acting" is generally used more frequently than "playing" for the general concept. "Playing" is more often used when indicating specific parts played by a given actor, as in:

*

*The role of Ophelia was played by Joan Sutherland.

*Fred Searls, playing Tom Sawyer, does a first rate job ...

But either term may be used, the choice is a matter of style.


text:
Q: Errors during Window resize for Viewer that isn't visible I am hosting an Autodesk Viewer inside a bootstrap div, and find that when the tab is not active, hiding the Viewer, there are errors thrown when the window is resized.
I would like avoid this by tearing down the Viewer and preventing it from handling any resize events when the tab is deactivated.
Is there a way to do this?

A: Yes you are correct, attach an handler to your tab hidden depending on your code and do something like below:
if (this.viewer) {

  if(this.viewer.impl.selector) {

    this.viewer.tearDown()
    this.viewer.finish()
    this.viewer = null
  }
}


text:
Q: Programmatically add filter for real time video for iphone How to add filter effect for iphone camera, such as video blur or old 8mm effect?

A: It looks like the current method to do this involves capturing frames from the camera as images using AVCaptureSession, also see this technical Q&A from Apple. After starting an image stream, you'd have to modify the images before displaying them.


text:
Q: Is there a way to merge multiple columns in react table I have a data array as:
data = [ {date: "16/05/2020", value: [ {column: "student", count: 10, value: "abcd" },
         {column: "teacher", count: 25, value: "pqrs" }] },
         {date: "17/05/2020", value: [ {column: "student", count: 19, value: "mno" },
         {column: "teacher", count: 7, value: "xyz" }] }
        ];

This is the column array:
columns = [{ Header: "Date", accessor: "date"},
           { Header: "Column", accessor: "column"},
           { Header: "Count", accessor: "count"},
           { Header: "Value", accessor: "value"}
           ]

I want to display the data as mentioned in the picture (table) in React Table.
Inside render(), I am doing this:
              <ReactTable
                data={data}
                columns={columns}
                minRows={0}
                defaultPageSize={25}
              />

Kindly, help.
Thanks in Advance!!

A: You need to use the accessor to get into the properties from data
and to custom the cells.
Try this:

const data = [
  {
    date: "16/05/2020",
    value: [
      { column: "student", count: 10, value: "abcd" },
      { column: "teacher", count: 25, value: "pqrs" }
    ]
  },
  {
    date: "17/05/2020",
    value: [
      { column: "student", count: 19, value: "mno" },
      { column: "teacher", count: 7, value: "xyz" }
    ]
  }
];

const columns = [
  {
    Header: "Date",
    id: "date",
    accessor: d => (

{d.date}

{d.date}

    )
  },
  {
    Header: "Column",
    id: "column",
    accessor: d => (

{d.value[0].column}

{d.value[1].column}

    )
  },
  {
    Header: "Count",
    id: "count",
    accessor: d => (

{d.value[0].count}

{d.value[1].count}

    )
  },
  {
    Header: "Value",
    id: "value",
    accessor: d => (

{d.value[0].value}

{d.value[1].value}

    )
  }
];

const App = () => {
  return <ReactTable data={data} columns={columns} />;
};

and here is a sandbox:


text:
Q: Dynamically running ClamAV's clamscan on file uploads with PHP Stack,
I want to scan each file that gets uploaded via my php upload script with clam anti-virus's clamscan tool.  I think I've got a good script written but I wanted to run it past you guys.
So assuming that the file I'm sending to this php upload script is named "uploadedfile" does the following code make sense?
<?php

$safe_path = escapeshellarg('/tmp/' . $_FILES['uploadedfile']['tmp_name']);
$command = 'clamscan ' . $safe_path;
$out = '';
$int = -1;
exec($command, $out, $int);

if ($int == 0) {
   // all good, code goes here uploads file as normal IE move to
permanent directory etc;
} else {
   unlink('/tmp/' . $_FILES['uploadedfile']['tmp_name']);
header(Location: http://www.domain.com/uploadform.php?error=your-file-was-infected-pal);
}

?>

Also, will clamscan find php shells as well as traditional good old malware?
Thanks!
Update - found the answer
I answered my own question but don't have the reputation to officially do so.  Here is the anser:
For those who come after.  I've tested this script using the EICAR test virus file http://eicar.org/86-0-Intended-use.html and after a few tweaks it works. The return variable $int is what tells you whether or not the file is safe or not. If $int is 0, no virus was found, if $int is 1, a virus was found.  However, there are some changes that I had to make the script work (I updated the $safe_path variable to be correct), here is the working script:
<?php

$safe_path = escapeshellarg($_FILES['uploadedfile']['tmp_name']);
$command = 'clamscan ' . $safe_path;
$out = '';
$int = -1;
exec($command, $out, $int);

if ($int == 0) {
   // all good, code goes here uploads file as normal IE move to
permanent directory etc;
} else {
  //whatever you need to do if a virus is found.
}

?>

A: Note that if your server runs a clamav daemon (clamd) it may be possible to use clamdscan instead of clamscan as proposed, this usage is faster since use virus signatures already loaded by clamd.

A: Just be careful. If your clamscan becomes outdated you'll get feedback in the output:
It will look like this:
LibClamAV Warning: ***********************************************************
LibClamAV Warning: ***  This version of the ClamAV engine is outdated.     ***
LibClamAV Warning: *** DON'T PANIC! Read http://www.clamav.net/support/faq ***
LibClamAV Warning: ***********************************************************

Also depending on the version of clamscan the "result" might look like this (and you'll need to parse it accordingly):
[filename]: OK

----------- SCAN SUMMARY -----------
Known viruses: x
Engine version: x.x.x
Scanned directories: 0
Scanned files: 1
Infected files: 0
Data scanned: x.xx MB
Data read: x.xx MB (ratio 0.00:1)
Time: x.xx sec (0 m x s)

A: I had a lot of trouble with permissions when trying to run this with clamdscan. I found a solution for the permissions problem here: https://wiki.archlinux.org/index.php/ClamAV
This changed this line:
$command = 'clamscan ' . $safe_path;

to:
$command = 'clamdscan  --fdpass ' . $safe_path;

Seemed to successfully pass a good file and flag an EICAR file.


text:
Q: Topological manifolds (dimension) I am taking an introductory course to topology and the professor defined a topological manifold of dimension $n$ if it is hausdorff and if for every point $x$ there exists an open set $U$ around $x$ such that $U$ is homeomorphic to $\mathbb{R}^n$. My question is: By the way she defined it, one could have (apriori) a topological space $X$ being a manifold of dimensions $n$ and $m$? Meaning I could find open sets $U$ and $V$ around every $x$ and $U$ is homeomorphic to $\mathbb{R}^n$ and $V$ is homeomorphic to $\mathbb{R}^m$, and this would make the notion of dimension not well defined. My guess is that since it is called "topological manifold of dimension $n$" what I described probably cant happen, but I dont see why not.

A: You can use local homology groups to solve this problem. If $X$ is a topological space and if $x\in X$, then the local homology groups of $X$ at $x$ are defined by the rule $H_i^{\text{local}}(X,x)=H_i(X,X-x)$, where the right hand side denotes the relative homology groups of $X$ relative to $X-x$.
Exercise 1: Prove that if $X$ is an $n$-manifold, then the local homology groups of $X$ agree with the homology of an $n$-sphere. (Hint: use excision to reduce to computing the homology of an $n$-ball relative to its boundary, an $(n-1)$-sphere.)
Exercise 2: Prove that the dimension of a connected topological manifold is an invariant.
Exercise 3: What can you say about manifolds with boundary?
Hope this helps! Of course, tomasz's answer and the comments are excellent and address the question in other ways.

A: You are correct.
There are several ways to show that it is impossible, and it basically boils down to the fact that no open subset of ${\bf R}^n$ is homeomorphic to an open subset of ${\bf R}^m$ if $n<m$ (as $U\cap V$ would be in your case). You can assume without loss of generality that the sets in question are connected.
One way to show it is to use the fact that you can find an $(n-1)$-dimensional sphere which disconnects any open subset of ${\bf R}^n$, but it is a general fact that if a compact set disconnects ${\bf R}^m$, then it must admit a non-nullhomotopic map onto $S^{m-1}$ (in fact, it is an equivalent condition), while on the other hand, no proper compact subset of $S^{m-1}$ admits such a map.
So, summing it all up, a set homeomorphic to $S^{n-1}$ can't disconnect an open subset of ${\bf R}^m$ if $m>n$ and we're done.
(The results used can be shown by combinatorial or algebraic topology, but are not simple enough to show here.)


text:
Q: XMLHttpRequest Access-Control-Allow-Origin Error Google Drive API I try to acces google drive in a wordpress theme and get the following error while downloading a selected file.

XMLHttpRequest cannot load https://drive.google.com/a/mobfish.net/file/d/0B5IETzPj-JCw832h9rdwk/view?usp=drive_web. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://wptest.dev' is therefore not allowed access.

(I modified the URL a little bit, this is not the real file ID)
Here is the JavaScript Code:
var developerKey = document.getElementById('key').innerHTML;
var clientId = document.getElementById('clientID').innerHTML;

// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/drive.readonly'];

var pickerApiLoaded = false;
var oauthToken;

// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
  gapi.load('auth', {'callback': onAuthApiLoad});
  gapi.load('picker', {'callback': onPickerApiLoad});
  gapi.load("client");
}

function onAuthApiLoad() {
  window.gapi.auth.authorize(
          {
            'client_id': clientId,
            'scope': scope,
            'immediate': false
          },
  handleAuthResult);
}

function onPickerApiLoad() {
  pickerApiLoaded = true;
  createPicker();
}

function handleAuthResult(authResult) {
  if (authResult && !authResult.error) {
    oauthToken = authResult.access_token;
    createPicker();
  }
}

// Create and render a Picker object for picking user Photos.
function createPicker() {
  if (pickerApiLoaded && oauthToken) {
    var view = new google.picker.DocsView(google.picker.ViewId.DOCS_IMAGES_AND_VIDEOS)
      .setIncludeFolders(true)
      .setSelectFolderEnabled(true);

    var picker = new google.picker.PickerBuilder().
            hideTitleBar().
            disableFeature(google.picker.Feature.NAV_HIDDEN).
            addView(view).
            setOAuthToken(oauthToken).
            setDeveloperKey(developerKey).
            setCallback(pickerCallback).
            build();
    picker.setVisible(true);
  }
}

// A simple callback implementation.
function pickerCallback(data) {
  var url = 'nothing';

  if (data.action == google.picker.Action.PICKED) {
    var file = data.docs[0];
    download(file);
  }
}

function download(file) {
  console.log("downloading " + file.id);
  console.log(file);
  var downloadUrl;

  if (file.url) {
    var accessToken = gapi.auth.getToken().access_token;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file.url);

    xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    xhr.onload = function() {
      callback(xhr.responseText);
    };
    xhr.onerror = function() {
      callback(null);
    };
    xhr.send();
  } else {
    callback(null);
  }
}

function callback(param) {
  console.log(param);
}

Maybe i just forget to add some settings at https://console.developers.google.com ?
Thanks in advance, regards.

A: Maybe the problem that you are running into is in Cross Origin Security. Basically, most web-browsers will not allow you to pull in content from servers outside your own, unless the server says it is ok. To do this, the server needs to see an acceptable Access-Control-Allow-Origin in the headers.
Found on this link the tutorial on how to enable CORS in WordPress. You only need to add the appropriate header to the headers file:
<?php /** @package WordPress @subpackage Default_Theme  **/
header("Access-Control-Allow-Origin: *");
?>
<!DOCTYPE html>

You may also check on these related threads:

*

*Access-Control-Allow-Origin Multiple Origin Domains?

*How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

*Cross-domain post to external site fails on wordpress
Hope this helps!


text:
Q: Multi select meta box I have added multi select meta box to custom post-type it appears good but save only one selection . How to change the code below to save all selected options.
add_action( 'add_meta_boxes', 'add_condition_metaboxes'); function add_scondition_metaboxes() {
add_meta_box('condition', 'Информация спикеров', 'wpt_condition_author', 'condition', 'side', 'default');} function wpt_scondition_author() {
global $post;

// Noncename needed to verify where the data originated
echo '<input type="hidden" name="conditionmeta_noncename" id="conditionmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

// Get the author data if its already been entered

$my_dropdown = get_post_meta($post->ID, '_dappcf_i_dropdown', true);
// Echo out the field

    $posts = get_posts(array('post_type'=> 'speakers', 'post_status'=> 'publish', 'suppress_filters' => false, 'posts_per_page'=>-1));

        //here you add the HTML of the dropdown you add something like

        echo '<p>Select the speaker: <select multiple="yes" name="_dappcf_i_dropdown" class="widefat"  style="width:170px">';
        foreach ($posts as $post) {
        echo '<option value="', $post->ID, '">'.$post->post_title.'</option>';          }
    echo '</select>'; } function wpt_save_condition_meta($post_id, $post) {

// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['conditionmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}

// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ))
    return $post->ID;

// OK, we're authenticated: we need to find and save the data
// We'll put it into an array to make it easier to loop though.

$condition_meta['_dappcf_i_dropdown'] = $_POST['_dappcf_i_dropdown'];
// Add values of $testimonial_meta as custom fields

foreach ($condition_meta as $key => $value) { // Cycle through the $testimonial_meta array!
    if( $post->post_type == 'revision' ) return; // Don't store custom data twice
    $value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
    if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
        update_post_meta($post->ID, $key, $value);
    } else { // If the custom field doesn't have a value
        add_post_meta($post->ID, $key, $value);
    }
    if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
} } add_action('save_post', 'wpt_save_condition_meta', 1, 2); // save the custom fields

The options are queried from other custom post-type and the number of post can be changed.


text:
Q: Set a defined security group as Owner on provided Communication sites I am quite new to Power Automate and need your assistance.
I have around 30 communication sites and would like to set an AAD security group "xyz" as owner of all 30 communication sites. Since this scenario will repeat pretty often in the future I would like to save some time and browsing trough all the sites one-by-one manually.
This is how my plan looks like:

*

*Have a custom list in my teamsite where me and my colleagues will add the URL of the communication site and the name of the AAD group/ID of that group.

*Have a Power Automate running every time a new item is created and set the permissions.

So far I found out that I need to use the action "Send an HTTP request to SharePoint".
My experience with Power Automate is very small and I hope to get some tips from you.

A: You could try to add site collection admin to multiple sites from a CSV file using PowerShell as a workaround.
PowerShell:
Import-Module Microsoft.Online.SharePoint.PowerShell

#Parameters
$TenantAdminURL = "https://crescent-admin.sharepoint.com"
$CSVFilePath = "C:\Temp\SiteCollectionAdmin.csv"

Try {
    #Connect to Admin Center
    Connect-SPOService -Url $TenantAdminURL

    #Get data from the CSV file
    $CSVData = Import-Csv $CSVFilePath

    #Iterate through each row in the CSV
    ForEach($Row in $CSVData)
    {
        Try{
            #Add Site collection Admin
            Set-SPOUser -site $Row.SiteURL -LoginName $Row.SiteCollectionAdmin -IsSiteCollectionAdmin $True | Out-Null
            Write-host "Added Site collection Administrator to $($Row.SiteURL)" -f Green
        }
        Catch {
            write-host -f Yellow "`tError Adding Site Collection Admin to $($Row.SiteURL) :" $_.Exception.Message
        }
    }
}
Catch {
    write-host -f Red "`tError:" $_.Exception.Message
}

CSV file:

For Reference: Add Site Collection Admin to Multiple Sites from a CSV File using PowerShell

A: This answer could certainly be more polished but I think it'll meet your needs

*

*Create a SP list that contains the site URL and ObjectID

*Create an automated workflow using the When an item is created trigger along with a Get Item action to get the actual metadata required.

*Create two string variables, one containing the Site URL field and one that concatenates c:0o.c|federateddirectoryclaimprovider| with the Group ObjectID field

*Send a http request to get the ID of the Owners SharePoint group. Method = GET, URI = _api/web/SiteGroups?$filter=substringof(%27Owners%27,LoginName)&$select=Id
this assumes there is only one group that contains the word "Owners" in the name.

*Parse the JSON from the previous action (do a test run of the flow before this step and copy the output to use as a template for the JSON schema)

*Send a HTTP request to add the AAD group to the owners SharePoint group of the site.
Method: POST
URI: _api/Web/SiteGroups/GetById(Id)/Users (Id is from the output of the Parse JSON action and is Id not id)
Headers: { "accept": "application/json;odata=nometadata", "content-type": "application/json;odata=verbose" }
Body: { "__metadata": { "type": "SP.User" },  "LoginName": varGroupIDClaim }


text:
Q: mod_rewrite redirect to URL with propietary protocol I'm using Apache 2.2 with mod_rewrite.
Is there a way to force mod_rewrite to rewrite the entire URL, including protocol? I know it will automatically rewrite the whole URL if the redirect contains http:// at the beginning but I'm trying to redirect to a URL that uses a proprietary protocol: fcp://
When I add it in as the redirect it just redirects to the URL of my server with the rewrite appended like so:
http://www.example.com/fcp://@mailstaff....

Can I configure the module to treat fcp:// as a full URL so I don't run in to this?
UPDATE: Here is the code I am using:
RewriteCond ${externals:$2|Unknown} !Unknown
RewriteRule ^(internal|external)/(.*)/? ${externals:$2} [R=301,NE,L,NS]

Inside the externals RewriteMap, I have a line like this:
firstclass-email        fcp://@mailstaff.example.com/

When I go to trigger the RewriteRule by going to:
http://example.com/internal/firstclass-email

It will incorrectly redirect me to here:
http://example.com/fcp://@mailstaff.example.com/

If I change the protocol part from fcp:// to http://, Apache will realize it's an absolute URL and work correctly. I want Apache to recognize fcp:// should also be absolute.

A: Apache can only handle the most common URL schemes like http, https, ftp, mailto, etc. Custom URL schemes are not recognized as such but handled as a URL path.
See the is_absolute_uri function in the source code of mod_rewrite.c for details on what schemes are supported.

A: You can use RedirectMatch instead of RewriteRule.
Check How to handle mod-rewrite with a custom url scheme? for the explanation...

A: Have you tried this?
RewriteRule ^/yourUrl$ fcp://otherUrl [RL]

A: Quite old question - but I can answer. I had the same problem. This can be solved with two redirects.
Redirect /restore1 fcp://example.com/restore

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (android|bb\d+|meego).+mobile.....
RewriteCond %{HTTP_USER_AGENT} ^(1207|6310|6590|3gso|.....
RewriteRule ^restore/(.*)$ http://example.com/restore1/$1


text:
Q: Function overloading in php Is function overloading possible in php.If yes, then how and if not then why?
Thanks in advance.
I have checked the php manual  which gives solution to overloading as mail() function can be overloaded by mb_mail() function .
But is this the proper way for overloading

A: No. Because it has not been implemented. There's a PECL extension that allows you to do this, but it makes your code not portable to environments where this extension is not available.
Don't ask why it has not been implemented.
Since PHP 5.3 you can use namespaces for 'kind of' overloading
namespace MyNamespace;

function mail() {
   return \mail();
}

A: This can only be done internally (through a PHP extension), unless you install the PECL runkit extension, which exposes function overloading functionality to userspace.
However, you probably don't want to use runkit in a production environment, so there's no good way to do this from userspace.

A: i'm new to php .. so dont know about these extensions mentions above .. but recently i saw a method to overload function in php (sort of) ..
traditional function overloading is not supported in php because you can not have multiple functions with same name in php .. but you can use one single function which can take multiple arguments .. known as Variadic Function (http://en.wikipedia.org/wiki/Variadic_function)
function show()
{
    $data = "";
    $arr = func_get_args();      //Returns an Array of arguments passed

    for($a = 0 ; $a < func_num_args() ; $a++ )  // func_num_args returns number of arguments passed .. you can also use count($arr) here
    {
        $data .= $arr[$a];
    }

    echo $data, "<br>";
}

show("Hey","Hii","Hello");
show("How Are You");

here .. i have passed variable arguments to a function and appended each of them in a string ..
ofcourse including a string is not necessary .. you can simply echo $arr array contents inside a loop ..   hope that helps .. !!


text:
Q: How to fix bound sparql query not working as expected? I have this sparql query that I need to modify. I have the example instance, which has the exampleID 12345. For this case, if the :hasRelatedExample connection exists, the ?test variable will become 2. If the :hasRelatedExample connection doesn't exist from the example instance, the ?test variable doesn't get assigned the 1 value as it should. How could I fix this query to reflect the needed behavior?
PREFIX : <http://www.example.com#>
Select distinct  ?test
  where
  {
?ex a :Example ;
     :exampleID "12345" ;
     :hasRelatedExample ?relatedExample .

BIND (IF(BOUND(?relatedExample),2,1) as ?test)
}


text:
Q: Jquery mobile data-theme attribute cannot use everywhere Using jquerymobie theme roller I found few issues and I'm not sure how get over with.
ISSUE 1:
   When I define the data-theme attribute to the beginning of the div eg
 then inside that if I want place a another theme to a div like the below example then it's not working. Eg :

                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard.

ISSUE 2:
   In my case I've to put radio buttons in grid view using class="ui-grid-a". I know there's already in jquerymobile <filedset> element has to wrap with radio buttons but In my case that design not suitable. However, my radio button need theme "e" colour to despite the default theme I've specified data-theme="e" in the wrapping grid div eg:

It Worked!

                <form>

<input  type="checkbox" name="checkbox-0" /> BLACK

<input type="checkbox" name="checkbox-0" /> BLACK

                </form>

But it doesn't seems to working check my online example I've tried http://jsfiddle.net/SmYZd/. However if I specify the theme to the speific form element it works eg
<input  type="checkbox" data-theme="e" name="checkbox-0" /> BLACK
 see the example form http://jsfiddle.net/EEFQR/.
Could anyone please let me know about this ? I know I can achieve my colour with simply adding similar colours to additional css but in jquerymobile css we already have lot of css inbuilt. I just need know why we can't use data-theme attribute as to our wish on any element ?

A: Issue 1:
You should specify data-role in order to call the data-theme.
Check this: http://jsfiddle.net/EEFQR/
Issue 2:
I am not sure what is your problem. The design of the ui-grid or calling data-theme?


text:
Q: Can i get the project build path programmatically? I want to a project build path (default is src...). Can I do it using some java API?

A: As i know you can get the project path as the following :
String projectPath = System.getProperty("user.dir");

A: The question poster is writing an Eclipse plugin.
You can find the JDT API in the Eclipse help. You should be able to get the information you want from IJavaProject. See this tutorial for one example of how to get this.

A: There is a set of Ant tasks for this purpose. You could, in theory, use the Ant tasks as a Java API, albeit a rather clumsy one (unless you're actually writing in Ant, that is)

A: The project default path is just a common used standard, most IDE's default to it but there are no Java API methods you can use.

A:
The project deault path is just a common used standard, most IDE's default to it but there > are no Java API methods you can use.

+1
The project path is a development convention, but the java application built is independant from this development path.
Most Java IDE allow you to change this path.
In Eclipse for example, this path can be changed with :
Right clic on project folder > Properties > Java build path
If you need this path in external programs for build, Eclipse has internal variables that can be used (for Ant, Maven, etc.). When configuring an "external tool", you can for example use {$project_loc}. This will be dynamically replaced by the project path.


text:
Q: How to disable XsrfProtection #streamlit I have a setup.sh file :
mkdir -p ~/.streamlit/
echo "\
[server]\n\
port=$PORT\n\
enableCORS=false\n\
headless=true\n\
\n\
" > ~/.streamlit/config.toml

When i deploy my app on Heroku : It gives Application error H14, while in my logs I can see a small overriding done:
2022-06-28T13:59:07.660953+00:00 heroku[wev.1]: Restarting
2022-06-28T13:59:07.663151+00:00 heroku[wev.1]: State changed from up to starting
2022-06-28T13:59:08.426158+00:00 heroku[wev.1]: Stopping all processes with SIGTERM
2022-06-28T13:59:08.470430+00:00 app[wev.1]:   Stopping...
2022-06-28T13:59:08.740844+00:00 heroku[wev.1]: Process exited with status 0
2022-06-28T13:59:17.236832+00:00 heroku[wev.1]: Starting process with command `sh setup.sh && streamlit run app.py`
2022-06-28T13:59:17.842753+00:00 heroku[wev.1]: State changed from starting to up
2022-06-28T13:59:19.208294+00:00 app[wev.1]: 2022-06-28 13:59:19.208
2022-06-28T13:59:19.208305+00:00 app[wev.1]: Warning: the config option 'server.enableCORS=false' is not compatible with 'server.enableXsrfProtection=true'.
2022-06-28T13:59:19.208305+00:00 app[wev.1]: As a result, 'server.enableCORS' is being overridden to 'true'.
2022-06-28T13:59:19.208306+00:00 app[wev.1]:
2022-06-28T13:59:19.208306+00:00 app[wev.1]: More information:
2022-06-28T13:59:19.208307+00:00 app[wev.1]: In order to protect against CSRF attacks, we send a cookie with each request.
2022-06-28T13:59:19.208308+00:00 app[wev.1]: To do so, we must specify allowable origins, which places a restriction on
2022-06-28T13:59:19.208308+00:00 app[wev.1]: cross-origin resource sharing.
2022-06-28T13:59:19.208308+00:00 app[wev.1]:
2022-06-28T13:59:19.208309+00:00 app[wev.1]: If cross origin resource sharing is required, please disable server.enableXsrfProtection.
2022-06-28T13:59:19.208309+00:00 app[wev.1]:
2022-06-28T13:59:19.414636+00:00 app[wev.1]:
2022-06-28T13:59:19.414646+00:00 app[wev.1]:   You can now view your Streamlit app in your browser.
2022-06-28T13:59:19.414656+00:00 app[wev.1]:
2022-06-28T13:59:19.414692+00:00 app[wev.1]:   Network URL: http://172.19.20.38:24743
2022-06-28T13:59:19.414722+00:00 app[wev.1]:   External URL: http://3.235.143.6:24743
2022-06-28T13:59:19.414734+00:00 app[wev.1]:

While running, it is overriding my enableCORS=false to true, I think which is causing my application error.
I have previously posted doubt related to "Application error" : Heroku app Application error even after successful deployment message
Do check it for setup.sh and Procfile details.
How can I disable the XsrfProtection??

A: Per the error, server.enableCORS=false is being overridden because server.enableXsrfProtection is set to true. The solution is to set server.enableXsrfProtection=false:
mkdir -p ~/.streamlit/
echo "
[server]
port=$PORT
enableXsrfProtection=false
enableCORS=false
headless=true
" > ~/.streamlit/config.toml

I am also obliged to note what this setting is protecting against, but assume you are familiar with the risks of toggling it off.


text:
Q: Inclination angle with respect to a plane I have performed some molecular dynamics simulation and outcome gives position of each atom in Cartesian coordinate system. The outcome looking like this,
where the yellow atoms some sort of liquid so they move around and red and blue atoms stick together and act as a solid body. Both solid bodies half submerged inside liquid and it can rotate around itself. My aim is to find the approximate angle of inclination that any solid body makes with respect to liquid plane. The angle can vary from 0 to 90 degree. How can I extract the angle from the position of all atoms?

A: The solid direction can be found either by a PCA on the columns as pointed out by @ad2004 or by a regression to a straight line.
To find the surface normal I propose 2 options:

*

*consider the surface to to be defined by a vector $N$ and a scalar $d$ such that the points $P$ that obey $N\cdot P+d=0$ are on the surface, and thus all the liquid points $L_i$ must obey $N\cdot L_i+d<0$. Find $N,d$ by optimizing a softened version of $\sum sign(N \cdot L_i +d)$.   $\,\,erf(x)$ or $\arctan(x)$ come to mind.

*Find the boundary layer by looking for sharp changes in the density ( by convolving with  a Canny filter or something similar and then thresholding), then take the points that were determined to be on the boundary $B_i$ and do a regression to minimize $\sum(n \cdot B_i +1)^2$ and determine $N,d$ by normalizing $n$ so that $|N|=1$


text:
Q: How to generate a testing report in Django using selenium and LiveServerTestCase? I have been using LiveServerTestCase to build test cases for my Django project for a month.
Now, I am creating more test cases using Selenium and LiveServerTestCase together to test how my project runs automatically.
I want to know how can I generate and export a testing report using Selenium and LiveServerTestCase. Is there an inbuilt solution from selenium that allows me to do so? Or I have to code the part of generating the file?
Sorry, I am new to Django and Selenium. Thanks in advance!


text:
Q: Is there a purely SwiftUI way to call registerForRemoteNotifications()? my app has a struct that implements App, and this struct uses a custom AppDelegate. This is my entire AppDelegate:
class AppDelegate: UIResponder, UIApplicationDelegate {
  func application(_ application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    application.registerForRemoteNotifications()
    return true
  }
}

I would like to get rid of this AppDelegate and call application.registerForRemoteNotifications() in the App implementation. Is this currently possible with SwiftUI 2.0 or later?


text:
Q: How to get data from grid How to see the content in hilightedline in data-grid?
put the dgHilitedLine of group "DataGrid"  into theLine
   answer dgLine[theLine]

if the value of "theLine" is 5 then, How to get the text in the highlighted field in the grid.

A: put the dgHilitedLines of group "Datagrid" into mylist
put the dgText of group "Datagrid" into myText
repeat for each item tItem in mylist
  put line tItem of myText & CR after myselctedlines
end repeat
answer myselctedlines

see http://livecode.wikia.com/wiki/Datagrid_API


text:
Q: Windows 8 adding images I'm trying to add images to my hello world app (HTML / JavaScript).
I am able to add the standard images (logo.png, smalllogo.png etc), but adding:
<img src="images/testImg.png"> won't show, when testing the app.
The image is located in the images folder, but won't show. What's wrong here?

A: Apparently the image needs to be added by clicking "add->existing item->image". Then it gets loaded and will be available in the app.


text:
Q: AWS MSK Cloud Formation Tags problems When creating AWS::MSK::Cluster with Cloud Formation I am not able to set Tags in the usual way:
      Tags:
        - Key: Name
          Value: !Ref Identifier

Because of this error:
Property validation failure: [Value of property {/Tags} does not match type {Map}]
As of the time of writing, the documentation states that, instead of the usual Type: List of Tag, I should use: Type: Json.
Also the same documentation states that:
You can specify tags in JSON or in YAML, depending on which format you use for your template

A: After further investigation (and AWS support help), the working (only on creation) example looks like this:
Tags:
  Name: !Ref Identifier

Additionally, tags cannot be modified (the docs actually state that tags change require replacement), when tried a slightly confusing error shows up:
CloudFormation cannot update a stack when a custom-named resource requires replacing. Rename kafka-eu-west-1-dev and update the stack again.


text:
Q: Translate Inline Assembler of Codewarrior to GCC Inline Assembler I am working on a task to move a big project from old Codewarrior IDE to S32DS from NXP, which use a compiler of GCC 4.9. Unluckily I have big troubles to compile the inline assembley code in S32DS, since the grammar of inline assembley are quite different from codewarrior to GCC. Any ideas to solve this problem without rewrite sentence by sentence? Any quick translate tools as shortcut?
Thanks!

A: Your choices include porting to pure C (often best for inline asm that was a performance optimization for old bad compilers but which modern compilers can do on their own.  Or which isn't relevant on another ISA).
Otherwise yes, you'd have to port to either standalone asm functions, or GNU C inline asm syntax.  Stand-alone asm functions avoids having to get all the constraints right, and might be a good option for larger blocks.

Asm to asm translation don't typically exist, especially not to GNU C inline asm.  (Or at least I've never seen anyone mention one on Stack Overflow).
BTW, GCC4.9 is pretty old.  GCC7 and 8 have some nice new optimization capabilities, e.g. load/store coalescing (multiple narrow struct or array members loaded/stored with one full-register width load or store).  I'd recommend starting with a current GCC version when you don't already have a working codebase so there's no risk of compiler changes introducing regressions.
Also, GCC6 introduced flag output operands from inline asm: a branch condition can be a boolean output from the asm.


text:
Q: Jenkins Test Result Analyzer doesn't display results I have been using jenkins' TRA plugin for a while and all of a sudden it stopped showing results for some of the jobs I'm running. The message, which I'm getting:

No build data retrieved. You may need to select a Module.

I've read this answer but I'm already using Publish JUnit test result report under Post-build Actions.
Job's workspace path is correct, all of the test report .xml files are there.
What am I missing?

A:
No build data retrieved. You may need to select a Module.

What this means depends somewhat on the kind of Jenkins project you're dealing with.  It also seems to be the only error message the plugin has, which makes deciphering it more difficult than it should be.
This question appears to be about about a Freestyle job (as opposed to a Maven job), since the Publish JUnit test result post-build action is mentioned.
Freestyle Job
With a freestyle job, this error typically means that the published XML file (or series of published XML files) isn't found.  "Selecting a Module" doesn't make any sense in this context.
When you publish JUnit results, the xml files in your workspace are processed into a single file, called junitResult.xml.  This is what I mean when I refer to the published XML file.  This file is stored outside of the workspace, in the build history:
D:.
└───jobs
    └───MavenFreestyle
        ├───builds
        │   ├───1
        │   │       build.xml
        │   │       changelog.xml
        │   │       junitResult.xml
        │   │       log
        │   │
        │   └───2
        │           build.xml
        │           changelog.xml
        │           junitResult.xml
        │           log
        │
        └───workspace
            │   pom.xml
            │
            ├───.mvn
            ├───src
            └───target

If these junitResult.xml files are missing, you'll get empty TRA results.  Of course, if no test results are found in the workspace, no junitResult.xml files will ever get created.  I suppose it's also at least possible that they're being created, but then modified or deleted by some process or person.
At any rate, these are the files whose existence (and contents) you want to verify, more than anything in the workspace.
If these junitResult.xml files appear to be in place for your jobs with empty results, updating the question with the contents of one of them would be helpful.

To verify files are found in the workspace to publish, make sure this check box is unchecked:

This way, if there is a mismatch between your Ant pattern and your actual file locations, the build will fail.  If this box is checked, and you fat finger your include pattern, the job will succeed but your TRA results will be empty.
Maven Job
For readers running into this using Maven Jobs:
Here, "select a Module" does make sense.  The Test Results Analyzer link works from a Module page, but shows blank results when accessed from a Project page.
I found this "documentation" of said behavior buried in the comments of the plugin wiki page.

Multi-configuration job
With a Multi-configuration project, you must access the results via a Configuration page.  Accessing them from the Project page always yields empty results.


text:
Q: Test failure with mockito when testing database I have an android app that needs to be unit tested. I am trying to use Mockito to mock the DBHelper class.
public class DBHelper {
    private static final String TAG = "DB Utility";

    FirebaseFirestore db;
    CollectionReference cityCollection;
    ArrayList<City> cityDataList;

    public DBHelper(){
        db = FirebaseFirestore.getInstance();
        cityCollection = db.collection("Cities");
        cityDataList = new ArrayList();
    }
    public ArrayList<City> refreshDataList(){
        cityCollection.addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {

                for (QueryDocumentSnapshot doc: value){
                    Log.d(TAG, String.valueOf(doc.getData().get("Province name")));
                    String city = doc.getId();
                    String province = (String) doc.getData().get("Province name");
                    cityDataList.add(new City(city, province));
                }
            }
        });
        return cityDataList;
    }

    public int getNumberOfCities(){
        return cityDataList.size();
    }
}

In my CityTest class, I am trying to mock this functionality with stubbs.
import java.util.ArrayList;

public class CityTest{

    @Test
    public void testCityList(){
        DBHelper dbHelper = mock(DBHelper.class);
        ArrayList<City> cityList = new ArrayList<>();
        cityList.add(new City("Edmonton", "Alberta"));
        cityList.add(new City("Vancouver", "British Columbia"));

        when(dbHelper.refreshDataList()).thenReturn(cityList);

        assertEquals(2, dbHelper.getNumberOfCities());
    }
}

But the assertion failed.
Expected <2> but was <0>. This is the first time that I am trying Mocking and Stubbing. I have a feeling that I didn't mock the class properly.
Any pointers are much appreciated.


text:
Q: opening various app windows within Remote Desktop session freezes said windows for several seconds I run Windows 10 Pro and have no problems when working locally at my machine. However, when I remote into my machine with stock RDP that comes with Windows 10 Pro the login now takes a lot longer (around 15-20 seconds) and when I open certain application windows (Google Chrome, see screenshot below) or any kind of settings windows (especially those with elevated command prompt) then the window of said app first freezes with a white or blue background and after around 5-10 seconds the window becomes again fully functional. My mouse and keyboard works perfectly fine during said freeze and I can even open other windows during that freeze.
Here couple more information:

*

*Windows 10 Pro Workstation

*Remote Desktop Connection / mstsc.exe 10.0.17134.112

*Tried a complete Windows OS re-install to no avail

*Updated Nvidia driver to newest version

*Updated Bios, Updated chipset drivers, ....


text:
Q: Read The Docs not working with automodule I've written some documentation for my project (in the Python docstrings), and tested everything with Sphinx on my local computer – everything works fine, all the import work correctly and so on.
So I set up a custom environment on Read The Docs (Python 3, numpydoc and my library), added the docs directory (and the docs/source subdirectory) to my Github repo, and the build on Read The Docs passes, however, nothing is created (the View Docs link just shows a Nginx 404 page).
The logs are as follows:
State: Finished

Outcome: Passed

Version: latest

Type: html
Sphinx Standard Output

html
-----

Making output directory...
Running Sphinx v1.2.2
loading translations [en]... done
building [readthedocs]: targets for 5 source files that are out of date
updating environment: 5 added, 0 changed, 0 removed
reading sources... [ 20%] contents
reading sources... [ 40%] source/contents
reading sources... [ 60%] source/index
reading sources... [ 80%] source/kineticlib
reading sources... [100%] source/modules

looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [ 20%] contents
writing output... [ 40%] source/contents
writing output... [ 60%] source/index
writing output... [ 80%] source/kineticlib
writing output... [100%] source/modules

writing additional files... genindex search
copying static files... done
copying extra files... done
dumping search index... done
dumping object inventory... done
build succeeded, 15 warnings.
Copying readthedocs-ext.js_t... done

Sphinx Standard Error

html
-----

/var/build/user_builds/kineticlib/checkouts/latest/docs/source/kineticlib.rst:11: ERROR: Unknown directive type "automodule".

.. automodule:: kineticlib.affinities
    :members:
    :undoc-members:
    :show-inheritance:
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/kineticlib.rst:19: ERROR: Unknown directive type "automodule".

.. automodule:: kineticlib.crosssection
    :members:
    :undoc-members:
    :show-inheritance:
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/kineticlib.rst:27: ERROR: Unknown directive type "automodule".

.. automodule:: kineticlib.errors
    :members:
    :undoc-members:
    :show-inheritance:
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/kineticlib.rst:35: ERROR: Unknown directive type "automodule".

.. automodule:: kineticlib.loaddata
    :members:
    :undoc-members:
    :show-inheritance:
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/kineticlib.rst:43: ERROR: Unknown directive type "automodule".

.. automodule:: kineticlib.omegaint
    :members:
    :undoc-members:
    :show-inheritance:
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/kineticlib.rst:51: ERROR: Unknown directive type "automodule".

.. automodule:: kineticlib.particles
    :members:
    :undoc-members:
    :show-inheritance:
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/kineticlib.rst:59: ERROR: Unknown directive type "automodule".

.. automodule:: kineticlib.probabilities
    :members:
    :undoc-members:
    :show-inheritance:
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/kineticlib.rst:67: ERROR: Unknown directive type "automodule".

.. automodule:: kineticlib.ratesdiss
    :members:
    :undoc-members:
    :show-inheritance:
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/kineticlib.rst:75: ERROR: Unknown directive type "automodule".

.. automodule:: kineticlib.ratesvibr
    :members:
    :undoc-members:
    :show-inheritance:
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/kineticlib.rst:83: ERROR: Unknown directive type "automodule".

.. automodule:: kineticlib.reltimes
    :members:
    :undoc-members:
    :show-inheritance:
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/kineticlib.rst:91: ERROR: Unknown directive type "automodule".

.. automodule:: kineticlib.wtpoly
    :members:
    :undoc-members:
    :show-inheritance:
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/contents.rst:: WARNING: document isn't included in any toctree
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/index.rst:: WARNING: document isn't included in any toctree
/var/build/user_builds/kineticlib/checkouts/latest/docs/source/modules.rst:: WARNING: document isn't included in any toctree
WARNING: html_static_path entry '/var/build/user_builds/kineticlib/checkouts/latest/docs/_static' does not exist

Setup Output

checkout
-----

venv
-----

Using base prefix '/usr'
New python executable in /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/bin/python3
Not overwriting existing python script /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/bin/python (you must use /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/bin/python3)
Installing setuptools, pip...done.
Running virtualenv with interpreter /usr/bin/python3

sphinx
-----

Requirement already up-to-date: sphinx==1.2.2 in /var/build/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages
Requirement already up-to-date: virtualenv==1.9.1 in /var/build/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages
Requirement already up-to-date: docutils==0.11 in /var/build/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages
Downloading/unpacking readthedocs-ext from git+git://github.com/ericholscher/readthedocs-sphinx-ext
  Cloning git://github.com/ericholscher/readthedocs-sphinx-ext to /var/build/user_builds/kineticlib/envs/latest/build/readthedocs-ext
  Running setup.py (path:/var/build/user_builds/kineticlib/envs/latest/build/readthedocs-ext/setup.py) egg_info for package readthedocs-ext

    warning: no files found matching '*.css' under directory 'readthedocs_ext'
Installing collected packages: readthedocs-ext
  Running setup.py install for readthedocs-ext

    warning: no files found matching '*.css' under directory 'readthedocs_ext'
Successfully installed readthedocs-ext
Cleaning up...

requirements
-----

Requirement already satisfied (use --upgrade to upgrade): numpydoc in /var/build/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages (from -r docs/requirements.txt (line 1))
Requirement already satisfied (use --upgrade to upgrade): kineticlib in /var/build/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages (from -r docs/requirements.txt (line 2))
Cleaning up...

install
-----

running install
running build
running build_py
creating build
creating build/lib
creating build/lib/kineticlib
copying src/kineticlib/wtpoly.py -> build/lib/kineticlib
copying src/kineticlib/ratesvibr.py -> build/lib/kineticlib
copying src/kineticlib/errors.py -> build/lib/kineticlib
copying src/kineticlib/probabilities.py -> build/lib/kineticlib
copying src/kineticlib/omegaint.py -> build/lib/kineticlib
copying src/kineticlib/__init__.py -> build/lib/kineticlib
copying src/kineticlib/loaddata.py -> build/lib/kineticlib
copying src/kineticlib/particles.py -> build/lib/kineticlib
copying src/kineticlib/ratesdiss.py -> build/lib/kineticlib
copying src/kineticlib/reltimes.py -> build/lib/kineticlib
copying src/kineticlib/affinities.py -> build/lib/kineticlib
copying src/kineticlib/crosssection.py -> build/lib/kineticlib
creating build/lib/kineticlib/data
creating build/lib/kineticlib/data/models
copying src/kineticlib/data/models/dissociation.csv -> build/lib/kineticlib/data/models
copying src/kineticlib/data/models/interactions.csv -> build/lib/kineticlib/data/models
creating build/lib/kineticlib/data/particles
copying src/kineticlib/data/particles/O2.dat -> build/lib/kineticlib/data/particles
copying src/kineticlib/data/particles/n2.dat -> build/lib/kineticlib/data/particles
copying src/kineticlib/data/particles/n.dat -> build/lib/kineticlib/data/particles
creating build/lib/kineticlib/data/spectra
copying src/kineticlib/data/spectra/n2.dat -> build/lib/kineticlib/data/spectra
running install_lib
copying build/lib/kineticlib/wtpoly.py -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib
copying build/lib/kineticlib/ratesvibr.py -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib
copying build/lib/kineticlib/errors.py -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib
copying build/lib/kineticlib/probabilities.py -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib
copying build/lib/kineticlib/omegaint.py -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib
copying build/lib/kineticlib/__init__.py -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib
copying build/lib/kineticlib/loaddata.py -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib
copying build/lib/kineticlib/particles.py -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib
copying build/lib/kineticlib/ratesdiss.py -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib
copying build/lib/kineticlib/data/spectra/n2.dat -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/data/spectra
copying build/lib/kineticlib/data/particles/O2.dat -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/data/particles
copying build/lib/kineticlib/data/particles/n2.dat -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/data/particles
copying build/lib/kineticlib/data/particles/n.dat -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/data/particles
copying build/lib/kineticlib/data/models/dissociation.csv -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/data/models
copying build/lib/kineticlib/data/models/interactions.csv -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/data/models
copying build/lib/kineticlib/reltimes.py -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib
copying build/lib/kineticlib/affinities.py -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib
copying build/lib/kineticlib/crosssection.py -> /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib
byte-compiling /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/wtpoly.py to wtpoly.cpython-34.pyc
byte-compiling /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/ratesvibr.py to ratesvibr.cpython-34.pyc
byte-compiling /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/errors.py to errors.cpython-34.pyc
byte-compiling /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/probabilities.py to probabilities.cpython-34.pyc
byte-compiling /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/omegaint.py to omegaint.cpython-34.pyc
byte-compiling /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/__init__.py to __init__.cpython-34.pyc
byte-compiling /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/loaddata.py to loaddata.cpython-34.pyc
byte-compiling /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/particles.py to particles.cpython-34.pyc
byte-compiling /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/ratesdiss.py to ratesdiss.cpython-34.pyc
byte-compiling /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/reltimes.py to reltimes.cpython-34.pyc
byte-compiling /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/affinities.py to affinities.cpython-34.pyc
byte-compiling /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib/crosssection.py to crosssection.cpython-34.pyc
running install_egg_info
Removing /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib-0.6.egg-info
Writing /home/docs/checkouts/readthedocs.org/user_builds/kineticlib/envs/latest/lib/python3.4/site-packages/kineticlib-0.6.egg-info

Environment Standard Error

checkout
-----

venv
-----

sphinx
-----

requirements
-----

install
-----

/usr/lib/python3.4/distutils/dist.py:260: UserWarning: Unknown distribution option: 'include_package_data'
  warnings.warn(msg)

My conf.py has
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.mathjax',
    'sphinx.ext.autosummary',
    'numpydoc',
]
numpydoc_show_class_members = False

So, I have no idea why automodule is listed as an unknown directive.

A: This is the first FAQ...

My project isn't building with autodoc First, you should check out the
  Builds tab of your project. That records all of the build attempts
  that RTD has made to build your project. If you see ImportError
  messages for custom Python modules, you should enable the virtualenv
feature in the Admin page of your project, which will install your
  project into a virtualenv, and allow you to specify a requirements.txt
  file for your project.

emphasis mine..

A: The other answers address the issue, but I thought I'd put together a summary for troubleshooting readthedocs+autodoc for other users with issues with autodoc commands (automodule, autoclass, autofunction) in RTD but not locally with make html —there are multiple Qs in SE with different issues. These can be resolved by:

*

*Inspect errors: In RTD Build page one can see the Errors that arose in view raw.

*

*A common issue is missing modules or the target module.

*Browser hard refresh: In a browser it is critical to do a hard refresh of the pages (Shift+refresh button). Silly but I'd say 90% of issues come from this.

*enable autodoc sphinx.ext.autodoc needs to be in extension.

Notes
sys.path.insert(0, os.path.abspath("../../")) is really ugly. The same can be achieved in .readthedocs.yml with path: .. The yaml may look like this:
version: 2

build:
  os: ubuntu-20.04
  tools:
    python: "3.8"

sphinx:
   configuration: docs/source/conf.py
   builder: html
   fail_on_warning: false

python:
   install:
     - method: pip
       path: .
     - requirements: requirements.txt
     - requirements: docs/requirements.txt

Notes about the yaml:

*

*file:

*

*If the name of the yaml file is wrong you'll get a suggestion in RTD to use one

*If the file is incorrect the build will fail.

*If the file is correct, nothing.

*Do specify python version

*build only html for now

*switch fail_on_warning for quicker troubleshooting —until the Sphinx5.0 deprecation warnings kick in

In the config.py, RTD will add readthedocs_ext.readthedocs it won't make a difference with make html locally —but it might in the future. sphinx_toolbox.more_autodoc might work best before sphinx.ext.autodoc:
extensions = [
    'readthedocs_ext.readthedocs',
    'sphinx.ext.viewcode',
    'sphinx.ext.todo',
    'sphinx_toolbox.more_autodoc',
    'sphinx.ext.autodoc']

If you get a missing _static for html_static_path error change:
html_static_path = []

Changing the theme will help in the formatting fixes when running make html.
html_theme = 'sphinx_rtd_theme'

The extension sphinx_toolbox.more_autodoc.typehints does not make Sphinx behave as a type checker, so if there are modules imported for typehinting only (typing.TYPE_CHECKING == True), the code needs to also check if 'sphinx':
if typing.TYPE_CHECKING or 'sphinx' in sys.modules:
    from foo import Foo

def to_foo(self) -> Foo:
    ...


text:
Q: found ' Failed: Implicit Wait timed out after 30000ms' this error after play the testcase My problem is that my code found a timed out error. This is my code:
{
  "id": "7cff5f0f-49a0-4099-a4b4-6e50d5f38a1c",
  "comment": "",
  "command": "click",
  "target": "name=OrderSearch[order_id]",
  "targets": [
    ["name=OrderSearch[order_id]", "name"],
    ["css=input[name=\"OrderSearch[order_id]\"]", "css"],
    ["css=td:nth-child(1) > .form-control", "css:finder"],
    ["xpath=//input[@name='OrderSearch[order_id]']", "xpath:attributes"],
    ["xpath=//tr[@id='w0-filters']/td/input", "xpath:idRelative"],
    ["xpath=//input", "xpath:position"]
  ],
  "value": ""
}


text:
Q: Dimension of vector space of sections of a vector bundle Let $X$ be a vector space and $E$ be a vector bundle over $X$ where each fiber is a vector space over $F$. Let $\Gamma(E)$ denotes the set of all sections of $E$. Generally $\Gamma(E)$ is infinite dimensional vector space. We want to form a necessary and sufficient conditions of $\Gamma(E)$ is finite dimensional.
Let $X$ be a compact Hausdorff and let $E$ be an $F$ vector bundle over $X$. Then by the result from Swan's paper Vector bundles and projective modules, the set of section denoted by $\Gamma(E)$ is a finite dimensional projective module over $C(X)$.
Then there exist a finite subset $\{s_{1},\cdots, s_{n} \}$ which spans $\Gamma(E)$. Thus if $s$ is a section on $E$ then
$$ s =\displaystyle \sum_{i=1}^{n} a_{i} s_{i}.$$
Now suppose $X$ be a finite set. Let $X=\{ x_{1},\cdots ,x_{m} \}$. Define $m$ functions $\{ e_{i} \}_{i=1}^{m}$ on $X$ as  $ e_{i}(x_{j})=\delta_{ij} $
 where  $\delta_{ij}$ is Kronecker delta. This collection forms a basis for $C(X)$.
Then any $a_{i} $ in $C(X)$ can be written as $a_{i}= \displaystyle \sum_{j=1}^{m} \lambda_{ij} e_{j}$. Hence we can write a section $s$ as
 $$ s =\displaystyle \sum_{i=1}^{n} \displaystyle \sum_{j=1}^{m} \lambda_{ij} e_{j} s_{i}.$$
Thus $\Gamma(E)$ is a vector space over $F$ which is spanned by the set  $\{e_{j}s_{i} \}_{i,j}$. Hence dimension of $ \Gamma(E)$ is less than or equal to $mn$.
Hence if $X$ is finite compact Hausdorff space then $\Gamma(E)$ is finite dimensional vector space over $F$.
Consider the trivial  bundle $E=I \times \mathbb{Z}_{2}$ over $I$  where $I=[0,1]$ and $\mathbb{Z}_{2}=\{0,1\}$ with discrete topology. Consider the section $s$ on $E$. Then $$s(x)=\left( x,f(x) \right)$$
where $f: I \to \mathbb{Z}_{2}$ is continuous, and hence constant.
Hence $\Gamma(E)=\{ s_{1},s_{2} \}$, where $s_{1}(x)=(x,0)$ and $s_{2}(x)=(x,1)$. Thus $\Gamma(E)$ is finite dimensional over the field  $\mathbb{Z}_{2}$ where base space $I$ is infinite.
Thus base space is infinite  need not imply that $\Gamma(E)$ is infinite dimensional.
But here the underlying field $\mathbb{Z}_{2}$is finite. We want to find a  proof for if base space is finite then $\Gamma(E)$ is finite dimensional vector space over a $\mathbb{C}$ or a counter example like the one above.


text:
Q: dnx-watch is not recognized as an internal or external command I've tried to install the command dnx-watch through the command prompt so that I don't need to restart my server when file changes occur in my project.
After running the following command dnu commands install Microsoft.Dnx.Watcher it runs and installs the packages. Notice the following line:
"The following commands were installed:" dnx-watch

Then when I'm trying to run it, it says it's not recognized as an internal or external command?
And when I try to uninstall the commands using
dnu commands uninstall Microsoft.Dnx.Watcher

it throws the following:

Edit:
When i run dnu list, it lists all the packages but the watcher package has a star before it? Like below:

Is it not installed correctly?
I'm using 1.0.0-rc1-update2 coreclr x64 btw.
The installation process looks like this:

As you can see, it adds the package to my \.dnx path.
When I runt the command dnx-watch inside the folder of the package's (Microsoft.Dnx.Watcher) project.json file, it works.
How do I install it globally?
Finally my Environment variables looks like this:

A: I know this is a bit confusing but uninstall takes the command name. So, it should be dnu commands uninstall dnx-watch.
Can you please make sure that %userprofile%/.dnx/bin is on the PATH and that is has dnx-watch in it?


text:
Q: Dotnet Core button redirect with parameters I'm making a Web API application that populates data into a datagrid. Currently, I'm wanting to have a button that will call my webapi endpoint with an additional parameter.
My datagrid, and the button code is below. This is the entirety of my razor page code:
@(Html.DevExtreme().DataGrid<Batch>().ID("gridContainer")
    .Columns(columns =>
    {
        columns.Add().CellTemplate(
        @<text>
        @(Html.DevExtreme().Button()
              .ID("sendButton")
              .Text("Select Batch")
            .OnClick("function () { onItemClick(data); }"))
        </text>);
        columns.AddFor(m => m.BatchId).Caption("BatchId");
        columns.AddFor(m => m.CobId).Caption("Cob Id");
        })
        .DataSource(d => d.WebApi().Controller("Batches").LoadAction("GetAllEntries").Key("BatchId"))
)

<script>

    var idValue;
    function onItemClick(data)
    {
        DevExpress.ui.notify(data.Id);
        console.log(data.BatchId);

        idValue = data.BatchId;

         window.location.href = '@Url.Action("SeanTest", "BatchDatagrid", new {@id = idValue })';
    }

</script>

In my script the variable idValue contains the value I want to pass into my URL, yet when I try to place it in the Url.Action it tells me that it doesn't exist in the current context
What is the best way to pass idValue into my redirect action?

A: The @Url.Action is processed at the server side. So passing a dynamic value from client side to it may not be possible. But as a work-around you can use the below code
window.location.href = '@Url.Action("SeanTest", "BatchDatagrid", new {@id = "ID"})'.replace("ID",idValue );

If you like it, credit should be given to the original poster here


text:
Q: how to avoid white screen while page is loading via ajax or normal request I have encountered this problem before and so far I have applied ajax beforeSend:function() parameter to display a loading image, though for normal form requests and page reload is there any alternative way to display a loader instead of just a plain white background as to prevent clients from thinking the pages has crashed.

A: I prefer to have a "loading" image as a background in the center of the body tag. The main wrapper of the app/site would be toggled for ajax calls and you only need to toggle a class on the main wrapper. While the wrapper is hidden you'll can see the loading imagen on the body until new content arrives. Pretty cheap way and looks nicely on mobile.
Demo


text:
Q: How can I divide my time series dataset into train and test based on a condition? Here is my task:

Split the data into two datasets: a training dataset and a test dataset. The training dataset should incude the first 7,111 observations (until the last observation of 2004). The aim will be to use the training dataset to forecast the value of NOx concentration at 9am in January 2005. Therefore, split the original dataset into a training and a test dataset. The test dataset should include the 31 observations at 9am every day in January 2005

These are the variables in my dataset and their are 9375 observations:

*

*Date Date (dd/mm/yyyy)

*Time Time (hh:mm:ss)

*NOx True hourly averaged NOx concentration in ppb

*NO2 True hourly averaged NO2 concentration in microg/m3 Temp Temperature in °C

*RH Relative Humidity (% )

*AH Absolute Humidity

I used:
airdata_train <- airdata[1:7111,]
airdata_test <- subset(airdata,Date > 31/01/2005 & Date <= 01/01/2005, select = airdata)

but I'm unable to figure how to put multiple conditions.


text:
Q: prevent select element from triggering hyperlink I have a select box within a hyperlink. Unfortunately, It has to be this way due to some formatting constraints.
My code is as follows...
<a id="<? echo $rows['itemname']; ?>" class="radio-picture-meats" href="javascript:set_radio('<? echo $rows['itemname']; ?>');">

<? echo $rows['displayname'];?>

Per Pound
$<? echo $rows['price'];?>

<img class="box" src="<? echo $rows['imagepath']; ?>" width="300px" height="215px"/>

<select class="weight">
<option disabled selected value> -- select an option -- </option>
<option value="1/2 Pound">1/2 Pound</option>
<option value="1 Pound">1 Pound</option>
</select>

Is there a way to prevent the select box from triggering the parent hyperlink?
Thank You
Here is a fiddle. You will notice when the dropdown select box is click, it triggers the HREF link. I would like to prevent that from happening.
FIDDLE
This is the solution that worked. If I click the google image, the hyperlink opens, if I click the dropdown box, it doesn't. Perfect
$('.weight').click(function(){ return false; });
Solution FIDDLE

A: Simply return false from link click event
$({selector_for_anchor}).click(function(){ return false; });

A: See this fiddle
Add a javascript as follows
$('#a-link').click(function(event) {
    event.preventDefault();
});

where a-link is the id of the .
Read more about preventDefault() in the docs
Alternatively, you can return false from the click event which does the same functionality as the preventDefault(). See the fiddle

A: you have to prevent only on above a tag then please try with php+jquery combine to prevent click on a tag.


text:
Q: Parse and Facebook Linker Error I am currently integrating Parse and Facebook into an iOS application I am making. I have followed all the steps on https://developers.facebook.com/docs/ios/getting-started and have also included all of the libraries needed:

But for some reason I am still getting this error:
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I am not sure why I am getting this. I first included Parse cleaned and built the project and everything succeeded. But then when I added the 3 Facebook frameworks ( FBSDKCoreKit.Framework, FBSDKLoginKit.Framework, FBSDKShareKit.Framework) from the SDK I downloaded from their website it kept giving me this error. I have also updated my .plist file. I saw other posts on this error but they were all outdated. Can anyone help me out with this problem? Thanks!


text:
Q: Насколько верна такая реализация многопоточности? Не знаю, корректно ли на этом сайте такие вопросы задавать... В общем я не уверен что код ниже верно написан. Свою задачу он выполняет, проверял неоднократно. Однако меня гложут сомнения в том, насколько эта реализация может считаться правильной. Быть может на C# такого рода задачу принято реализовывать иначе? Хотелось бы получить критику и разъяснения.
Сама программа - аудио конвертер. Ищет в папке подходящие файлы и запускает внешний, консольный конвертер для их преобразования в wav.
public partial class Form1 : Form
{
    static object locker = new object();
    string[] findFiles;
    int fifi = -1;

    public Form1()
    {
        InitializeComponent();
        Conv();
    {

    async void Conv()
    {
        findFiles = Directory.GetFiles(Application.StartupPath, "*.ape", SearchOption.AllDirectories).Union(Directory.GetFiles(Application.StartupPath, "*.ogg", SearchOption.AllDirectories)).ToArray();

        // Поддерживаем не более 8 ядер.
        int p;
        if (Environment.ProcessorCount < 8)
            p = Environment.ProcessorCount;
        else
            p = 8;

        int t;
        // Если количество файлов больше чем ядер, то устанавливаем столько потоков, сколько ядер.
        if(findFiles.Length > p)
            t = p;
        else // Если файлов меньше чем ядер, то потоков устанавливаем сколько файлов.
            t = findFiles.Length;

        // Устанавливаем количество потоков.
        Task[] tasks = new Task[t];

        // Запускаем потоки.
        for (int i = 0; i <= p - 1; i++)
        {
            if(i <= findFiles.Length - 1)
            {
                tasks[i] = new Task(() => ConvertDoWork(++fifi));
                tasks[i].Start();
            }
        }

        // Ждём выполнения всех задач.
        await TaskEx.WhenAll(tasks);

        Application.Exit();
    }

    int p, pc;
    public void ConvertDoWork(int num)
    {
        int n = num;

        if ((findFiles.Length == 0) || (n > findFiles.Length))
            return;

        string s = findFiles[n];

        ProcessStartInfo startInfo = new ProcessStartInfo();
        if (Path.GetExtension(s).Equals(".ogg"))
        {
            startInfo.FileName = "oggdec.exe";
            startInfo.Arguments = "-Q \"" + s + "\"";
        }
        else
            if (Path.GetExtension(s).Equals(".ape"))
        {
            startInfo.FileName = "MAC.exe";
            startInfo.Arguments = "\"" + s + "\" \"" + Path.ChangeExtension(s, ".wav") + "\" -d";
        }
        startInfo.WorkingDirectory = Application.StartupPath;
        startInfo.CreateNoWindow = true;

        Process processReg = new Process();
        processReg.StartInfo = startInfo;
        processReg.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        processReg.Start();
        processReg.WaitForExit();

        lock (locker)
        File.Delete(s);

        int percentComplete = (int)Math.Round((double)(100 * n) / findFiles.Length);
        pc = percentComplete / 10;

        try
        {
            this.Invoke((MethodInvoker)delegate
            {
                progressBar1.Value = percentComplete;

                // Если не выбрано не отображать прогресс, то отображаем всплывашку.
                if ((notifyIcon1.Visible) && (!chkNotNotify.Checked) && (!pc.Equals(p)))
                {
                    notifyIcon1.ShowBalloonTip(300, "Прогресс", "Выполнено " + percentComplete + "% работы", ToolTipIcon.Info);
                    p = pc;
                }

            });

        }
        catch (System.Exception ex)
        {

        }

        lock (locker)
        ++fifi;
        if (fifi < findFiles.Length)
            ConvertDoWork(fifi);
    }

A: Есть несколько замечаний/пожеланий. Без определенного порядка и не только о многопоточности:

*

*Методы с сигнатурой async void годятся только в случае событий или
методов с похожей семантикой. В таких методах обычно нужно делать
глобальный try/catch, поскольку если возникнет исключение, вы об этом
или не узнаете, или это исключение убьет процесс (в случае с .NET 4.0
будет именно так).

*Запуск "асинхронного метода" из конструктора -- не лучшая идея.
Конструктор не может быть помечен async, что видимо и заставило вас
метод Conv сделать async void. Сделайте этот метод публичным и
вызывайте его отдельно после создания формы (не забывая при этом await'ить
вызов). Если же необходимо при создании объекта выполнить какой-то код, который является асинхронным, то вместо конструктора нужно использовать фабричный метод, который в свою очередь тоже будет асинхронным.

*Как уже отметил @Qwertiy, инкремент не является потокобезопасной
операцией. Используйте Interlocked.Increment(). И тогда лок на удалении файла вам не нужен будет.

*Вы используете один и тот же объект (locker), чтобы синхронизировать доступ к не связанным между собой "ресурсам". Это не совсем корректно, поскольку если один поток займет первый "ресурс", а другому потоку нужен будет второй "ресурс", он не должен ждать. Каждому "ресурсу" -- свой объект для синхронизации.

*Метод ConvertDoWork не должен управлять запуском новых конвертаций.
Для этого в методе Conv д.б. следующая схема: главный цикл крутится, пока список файлов для конвертации не пуст (заведите List), далее вы шедулите p тасков, далее ждете await Task.WhenAny(), далее выкидываете из списка сконвертированный файл и шедулите таск для нового файла. При этом от счетчика fifi можно будет избавиться вообще.

*Для уведомления о прогрессе каноничнее воспользоваться IProgress. Как
-- почитайте по ссылке. Правда это только для .NET 4.5 и выше.

*Application.Exit() в бизнес-коде выглядит странным. Пусть пользователь крестиком закрывает приложение или кнопкой отдельной.

A: Вместо куска кода по вычислению количества ядер, количества создания потоков и т.п. я бы посоветовал для этих целей посмотреть в сторону класса Parallel, который предназначен для поддержки выполнения параллельных задач. Она сама решит, сколько задач создавать, в скольких потоках. Использую функцию ForEach ваш "большой" кусок кода можно переписать таким образом
Parallel.ForEach(findFiles, (currentFile) => ConvertDoWork(currentFile);

Тем самым, объявление функции ConvertDoWork нужно изменить, чтобы она принимала сразу же имя файла.
public void ConvertDoWork(string filename)
{
   /// ваш код по обработке файла
}

Тогда ни с каким fifi вам не придется возиться. Функция ForEach закончит свое выполнение, как обработает все файлы.

A: 1.
Слишком много переменных уровня класса. Каждую из них надо отдельно перепроверять - а мне лень. Куда безопаснее локальные переменные и параметры функции.
2.
Переменная fifi используется опасным образом. Лучше от нее вовсе отказаться, а распараллеливание делать другими методами.
Для распараллеливания через задачи я сам использую и всем рекомендую вот такую конструкцию:
await TaskEx.WhenAll(
   from file in findFiles
   select Task.Run(() => ConvertDoWork(file))
);

Вам, я так понимаю, нужно еще ограничить число число одновременно выполняемых задач числом ядер. Вручную это можно сделать вот так:
class LimitedConcurrencyGuard {
  private readonly object _lock = new object();
  private readonly Queue<TaskCompletionSource<object>> queue = new Queue<TaskCompletionSource<object>>();
  private int slots;

  public LimitedConcurrencyGuard (int slots) { this.slots = slots; }

  public async Task<IDisposable> AcquireSlot() {
    TaskCompletionSource<object> tcs;
    lock(_lock) {
      if (slots > 0) {
        slots--;
        return new Slot(this);
      }
      tcs = new TaskCompletionSource<object>();
      queue.Enqueue(tcs);
    }
    await tcs.Task;
    return new Slot(this);
  }

  private class Slot : IDisposable {
    private readonly LimitedConcurrencyGuard owner;
    public void Slot(LimitedConcurrencyGuard owner) { this.owner = owner; }

    public void Dispose() {
      TaskCompletionSource<object> tcs;
      lock(owner._lock) {
        if (owner.queue.Count > 0)
          tcs = owner.queue.Dequeue();
        else {
          owner.slots++;
          return;
        }
      }
      tcs.SetResult(null);
    }
  }
}

// ...

var guard = new LimitedConcurrencyGuard(Environment.ProcessorCount);
await TaskEx.WhenAll(
  from file in findFiles
  select Task.Run(async () => {
    using (await guard.AcquireSlot())
      ConvertDoWork(file);
  })
);

Если поискать в гугле по запросу "ограничение числа одновременно выполняемых задач" - наверняка найдутся и другие реализации. Например, реализующие ограничение на стороне планировщика задач.
Или же можно сначала побить исходную последовательность файлов на куски, а потом запустить их параллельно:
static IEnumerable<IEnumerable<T>> SplitAndBatch<T> (ICollection<T> items, int batches) {
  var count = items.Count;
  var it = items.GetEnumerator();
  while (count > 0) {
    var current = (count + batches - 1) / batches; // Это на самом деле частное, округленное вверх
    count -= current;

    var batch = new T[current];
    for (var i=0; i<current; i++)
    {
      it.MoveNext();
      batch[i] = it.Current;
    }
    yield return batch;
  }
}

// ...

await TaskEx.WhenAll(
   from batch in SplitAndBatch(findFiles, Environment.ProcessorCount)
   select Task.Run(() => {
     foreach (var file in batch)
       ConvertDoWork(file);
   })
);

В любом случае, логику разделения файлов по ядрам процессора лучше вынести за пределы метода ConvertDoWork - это называется "разделение ответственности".
А может быть, нужно вообще отказаться от использования задач и использовать Parallel API - где ограничение по числу ядер уже реализовано.
3.
Уведомление пользователя о текущем прогрессе - дело хорошее, но сделано оно на устаревшей технологии. Элементарно: если пользователь закроет окно - то метод Invoke вылетит с ошибкой.
Для уведомлений о прогрессе есть такие классы как IProgress<T>/Progress<T>:
public void ConvertDoWork(string file, IProgress<object> progress) {
  // ...
  progress.Report(null);
  // ...
}

// ...

progressBar1.Maximum = findFiles.Length;
var progress = new Progress<object>(_ => {
  progressBar1.Value = ++done;
});
await TaskEx.WhenAll(
   from file in findFiles
   select Task.Run(() => ConvertDoWork(file, progress))
);

Достоинство данного способа - в том, что

*

*у метода ConvertDoWork забирается лишняя ответственность (индикация хода выполнения);

*класс Progress берет задачу перехода обратно в поток UI на себя.

Кстати, как вам такая идея - считать файлы не по 1 каждый, а пропорционально их размеру?..
4.
Формирование Arguments лучше делать через string.Format - это куда проще в восприятии.
5.
Лучше не использовать Application.Exit просто так: если в дальнейшем понадобится использовать старый код как часть большего проекта, то придется больно и мучительно искать все места, где он может закрыть всю программу.
В данном случае достаточно просто закрыть форму.
PS по поводу net 4.0
Многие замечательные классы реализованы в проектах Mono и .NET Core.
Лицензии у них свободные, код открытый - так что 1-2 класса (тот же Progress) зачастую можно прямо оттуда скопировать к себе в проект. Только если проект будете распространять - то с лицензиями придется разобраться.

A:
tasks[i] = new Task(() => ConvertDoWork(++fifi));

Неверно. Инкремент не атомарен.
Если задачи выполняются параллельно, то они могут получить одинаковые числа.


text:
Q: Migrate Apache Authorization Header rule to Lighttpd My web server is running PHP applications with lighttpd and PHP-FPM for years.
Now, after a 3rd-Party software upgrade, I must include some rules in order to activate a REST API.
<IfModule mod_setenvif.c>
  SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
</IfModule>
<IfModule mod_rewrite.c>
  Options -MultiViews
  RewriteEngine On
  RewriteBase /api/
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule .* index.php [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</IfModule>

I would like to understand what is it doing, and rewrite it based on lighttpd configuration if it has the support.

A:
I would like to understand what is it doing

*

*It sets an environment variable called HTTP_AUTHORIZATION to the value of the Authorization HTTP request header (if any). This might not be necessary on your server config. PHP should set this automatically, however, depending on how PHP is installed on some Apache configs this does not happen - hence this bit of code. (Note that the above code tries to set this in two different ways - but the net result is "almost" the same.)

*Front controller - All requests that do not map to existing files (or directories) are internally rewritten to /api/index.php. This is a standard "front controller pattern".
So, basically, the above code is just a standard front-controller that directs all requests to /api/index.php.

and rewrite it based on lighttpd configuration

Unfortunately, I don't speak lighttpd, but Googling lighttpd front controller pulls up some possibilities. For example, from this page, providing the necessary modules are enabled, they suggest you can do something like:

url.rewrite-once = ( "^/(.*)\.(.*)" => "$0", "^/([^.]+)$" => "/index.php", "^/$" => "/index.php" )

Although, that doesn't look like it actually checks for the existence of a requested file, but rather assumes that requests for files will have a file extension (my interpretation).

A: Setting the HTTP_AUTHORIZATION ("CGI") environment variable should happen as part of the CGI setup (headers are passed as HTTP_...), and lighttpd does NOT exclude the "Authorization"-header from this, so nothing to do here in lighttpd.
The rewrite config rewrites all requests not targeting static files or directories in the /api/ sub-path. The closest in lighttpd (1.4.24+) without using mod_magnet would be:
url.rewrite-if-not-file = ( "^/api/" => "/api/index.php" )

This will also trigger for directories (only regular files are not rewritten), but I think it is unlikely that you actually need dirlistings within the /api/ path, so it is probably fine.