text:
Q: How to setup multiple websites with Django nginx and uwsgi? I'm really having a tough time getting this to work properly
In my sites enabled folder I have the following two .conf files setup
Site A (this site I setup first and works properly):
# the upstream component nginx needs to connect to
upstream django {
    server 127.0.0.1:8001; # for a web port socket (we'll use this first)
    }

# configuration of the server
server {

    # the port your site will be served on
    listen  80;
    # the domain name it will serve for
    server_name databank.eaventures.co www.databank.eaventures.co ; # substitute your mac$
    charset     utf-8;
    access_log /srv/www/*****/logs/access.log;
    error_log /srv/www/*****/logs/error.log;

    # max upload size
    client_max_body_size 75M;   # adjust to taste

    # Django media
    location /media  {
        alias /srv/www/******/projectdatabank/media;  # your Django project's m$
    }

    location /static {
        alias /srv/www/******/projectdatabank/static; # your Django project's s$
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     /etc/nginx/uwsgi_params; # the uwsgi_params file you installed
        }
    }

Site B (the new site I am trying to add but not getting to work):
# the upstream component nginx needs to connect to
upstream django2 {
    server 127.0.0.1:8002; # for a web port socket (we'll use this first)
    }

# configuration of the server
server {
    # the port your site will be served on
    listen  80;
    # the domain name it will serve for
    server_name 50.116.47.120 ***.eaventures.co ; # substitute your machine's IP add$
    charset     utf-8;
    access_log /srv/www/***.capital.com/logs/access.log;
    error_log /srv/www/***capital.com/logs/error.log;

    # max upload size
    client_max_body_size 75M;   # adjust to taste

    # Django media
    location /media  {
        alias /srv/www/***capital.com/***/media;  # your Django project's media$
    }

    location /static {
        alias /srv/www/***capital.com/***/static; # your Django project's stati$
    }

    # Finally, send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     /etc/nginx/uwsgi_params; # the uwsgi_params file you installed
        }
    }

to start uwsgi I ran the following command (in actuality I run an emperor command however I'd like to tackle one issue at a time here), when I run this site A works completely fine
uwsgi --socket :8001 --chdir /srv/www/.com/projectdatabank/ --wsgi-file /srv/www/.com/projectdatabank/databank/wsgi.py

Now I run this to try and start site B
uwsgi --socket :8002 --chdir /srv/www/***capital.com/***/ --wsgi-file /srv/www/***capital.com/***/***/wsgi.py

When I go to the ip address (set on site B) it runs the site django app but does not pull in the css files
any thoughts??

A: I got this working, the problem was the uwsgi_pass
Instead of passing the django variable which I believe is connected to the upstream, i changed it to the following for each file respectively
uwsgi_pass  127.0.0.1:8001;
uwsgi_pass  127.0.0.1:8002;


text:
Q: Create a Facebook App that can post to a page I am an admin of As part of the website I am working on, I need to be able to post directly to the wall of my clients Facebook Page.
I have created an App and am successfully posting to my own dummy profile by simply using:
$request = new FacebookRequest(
    $session, 'POST', '/me/feed', array(
    'link' => 'my_url',
        'message' => 'my_message'
     );

Now I need to modify this to post to my clients page, im assuming I cant just change 'me' to by their page ID because that would be a massive security flaw so I need to get permission somehow to post to their page. I am an admin for the page, how can I do this? Or do I actually need to be logged in with the user account that created the page?
I have looked all around in the developer section at creating an app but there doesn't seem to be any way of creating an app for a different account.
Any advice would be greatly appreciated on this.
Many thanks

A: Please look into Application developer section. It will help you. Create on developer account and you will be able to access page.

A: In order to post to a Facebook page, you need to go through a two steps process -

*

*login as the user using the extended user token,

*get the user's token for the page

*post to the page using the page's token.

The following code should be able to post a  message to your page. I HAVEN'T DEBUGGED IT since it is simplified from my own web site :-) Don't forget to include the Facebook SDK files:
function extract_access_token_of_facebook_page_by_id($array_of_all_user_pages,$page_id){
    $num_of_pages=count($array_of_all_user_pages['data']);
    $the_page_token="";

    for ($i=0; $i<$num_of_pages; $i++){
        if ($array_of_all_user_pages['data'][$i]['id']==$page_id){
            $the_page_token=$array_of_all_user_pages['data'][$i]['access_token'];
            }
        }
    return $the_page_token;
    }

$facebook = new Facebook(array(
            'appId'     => $YOUR-APP-ID,
            'secret'    => $YOUR-APP-SECRET,
            ));

try
    {
    $facebook->setAccessToken($THE-USER-TOKEN);
    $page_id = YOUR-PAGE-ID;
    $fanpage_access_token=extract_access_token_of_facebook_page_by_id($facebook->api("/me/accounts"),$page_id);
    $args = array();
    $args['access_token'] = $fanpage_access_token;
    $args['message'] = "THE TEXT YOU WANT TO POST";
    $api_url="/".$page_id."/feed";
    $api_response = $facebook->api($api_url, 'post', $args);
    }
catch (FacebookApiException $e)
    {
echo 'Error facebookservice'.$e;
    }

A: you code is for old sdk version i think, it not work for me : Fatal error: Class 'Facebook' not found

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing pixel value using cv::Mat::at operator I'm using OpenCV 2.3.1 (c++ api) and when I try to get the pixel value of colored image, I'm getting very strange results, instead of value number, output is something like this: ?, *, | etc. For example, the code is as follows:
cv::Mat inputImage = cv::imread("Picture1.jpg");
std::cout << inputImage.at<cv::Vec3b>(x,y)[0] << std::endl; //print B component

where x and y are coordinates from mouse callback function. I assume that type is wrong, do you have any idea what else could I use instead of Vec3b?

A: I assume that the problem happening because you are using "at(x, y)". Documentation says that the first argument should be "The 0-based row index" and second "The 0-based column index". So, you should either call at(y, x) or at(cv::Point(x, y)).

A: Check http://opencv.willowgarage.com/documentation/cpp/basic_structures.html
Vec3b in OpenCV is typedef Vec<uchar, 3> Vec3b;. So, I guess you need to cast to integer in the cout process.
Something like std::cout << (int) inputImage.at<cv::Vec3b>(x,y)[0] << std::endl; //print B component


text:
Q: Randomly partition Mongodb database So i have a mongodb database and would like to partition it randomly.
By this i mean the database is of size $s$ and I would like to have it split so that I have $frac{s}{2}$ to train my classifier on and $frac{s}{2}$ to test it's accuracy on. ~~ Cross Fold validation. How can i do that? I was thinking assigning every entry an integer and then given a range from 0 to 1000 just choosing a random sampling. The problem is that I don't know when it updates and when it inserts. So I would only increment the value to insert if it was a new entry. So i'm thinking to use getLastError maybe to check that?
I feel like there's a better way to do this....
Any suggestions?
Thanks,


text:
Q: By using JQuery, how to play the video when the mouse enter once and pause the video when the mouse enter twice? I want to achieve the effect that when the user's mouse enters into the video frame, it will trigger the movie. Also, when the user's mouse leaves the video, it will still continue to play.
However, when the user's mouse enters into the video frame again, the video will be paused. Is there any way to achieve this? I am new to this field.
 Here is what I have so far
:

JQuery:
$(document).ready(function(){
   $('#video1').mouseover(
        function()
            {
                $(this).get(0).play();
            }
        );
    });

HTML:
<video id = "video1" width = "420">
    <source src = "lololol.mp4" type = "video/mp4">
</video>

A: Just check the state of the video. And use the mouseenter event instead.
$('#video1').mouseenter(
   function()
   {
      if($(this).get(0).paused)
          $(this).get(0).play();
      else
          $(this).get(0).pause();
   }
);

A: You'll probably want to create a variable, increment it on mouseenter, and check its value for even or odd:
var movieHoverCt = 0;

$('#video1').mouseenter(function () {
    if (movieHoverCt % 2 === 0) { // even
        $(this).get(0).play();
    } else { // odd
        $(this).get(0).stop();
    }
    movieHoverCt++;
});


text:
Q: I got an error using 'char' in matlab I need some help guys. Im new to matlab and i really dont know how to solve this problem. It gives me this error " Error using char
Cell elements must be character arrays. " I need to simulate a contest and input 10 participants, and for each one the number of likes and comments. And if the number of likes is 0 he/ she its excluded from this contest.
Error in data(line 40)
        fprintf('The third winner is %s \n',char(cv))
n=input('Number of people ');
cs=zeros(1,n);
id1=cell(1,n);
for i=1:n
    id=input('Name','s');
    l=input('Number of likes is ');
    c=input('Numarul  of comments is');
    if (l==1)
        id1{i}=id;
        cs(i)=c;
    end
end
ord=0;
while(ord~=1)
    ord=1;
    for i=1:n-1
        if (cs(i)<cs(i+1))
            ord=0;
            aux=cs(i);
            cs(i)=cs(i+1);
            cs(i+1)=aux;
            aux1=id1{i};
            id1{i}=id1{i+1};
            id1{i+1}=aux1;
        end
    end
end
ct=id1{randi(numel(id1))};
fprintf('the winner is %s \n',ct)
csn='roata';
cv='salam';
cpl='ciorba';
for i=1:4
    if (((strcmp(id1(i),ct))==0) && (strcmp(csn,'roata')))
        csn=id1(i);
        fprintf('The second winner is %s \n',char(csn))
    end
    if (((strcmp(id1(i),ct))==0) && ((strcmp(id1(i),csn))==0) && (strcmp(cv,'salam')))
        cv=id1(i);
        fprintf('The third winner is %s \n',char(cv))
    end
    if (((strcmp(id1(i),ct))==0) && ((strcmp(id1(i),csn))==0) && ((strcmp(id1(i),cpl))==0) && (strcmp(cv,'ciorba')))
        cv=id1(i);
        fprintf('the third winner is %s \n',char(cpl))
    end
end

A: Your code has countless of cases where it would error, as you don't take all the possibilities of inputs into account.
I managed to get your error by giving input('Number of likes is '); a value other than 1. Then, your if condition never happens, thus id1 doesn't get filled. If that id1 is then accessed later in fprintf('The third winner is %s \n',char(id(i))), you get an error, as id(i) is an empty {0x0} cell, that can not be converted to char.


text:
Q: Configure karma to fail test execution when skipped cases are found (xdescribe or xit)? When running unit tests with karma and jasmine (I'm using angular 6), in console it's printed how many tests were skipped. I would like to know, first, if it is possible to print in console which tests are being skipped, and second, I don't think it is possible but I have to know, if I can configure karma to fail the execution when they are found.
Thanks in advance for any help you can provide.


text:
Q: If the Moon had a large piece blown out would it remain tidally locked?
*

*I just saw this video on Sonic Adventure 2 trivia where it's mentioned that part of the Moon was blown up but in later games it's whole. It was explained away as the Moon simply rotating to show the unbroken side, but in the video it's pointed out that this would be impossible since the Moon is in synchronous rotation around the Earth. But is that true?

*With the explosion and a large piece of it missing would the Moon remain tidally locked to the Earth? Or is it plausible that the Moon would begin to revolve?

*If it did would it revolve quickly or slowly?

*How long would it take before the scarred face would no longer be visible from Earth?

*And how long would it take for the Moon to become tidally locked once again?
Here is a picture of the Moon in the game just after it's been blown up.

A: Ignoring the difficulty with blowing a sizable piece of the moon off, there's 2 primary factors to consider.   Distance and angular momentum.
Distance
The moon actually rotates.  All tidally locked objects rotate, they just rotate, they just rotate in sync with their orbit.    The Moon rotates once every 28 days, the same as it's orbital period.   If the chunk is blown away from the Moon and Earth, and every action having an equal but opposite reaction, the Moon should get blown closer to earth, and if the angular velocity doesn't change, then the Moon will continue to rotate once every 28 days but being closer to the Earth, it will now orbit in less than 28 days and it would demonstrate a slow rotation, which, over time, maybe ten of million years or so, would gradually return to being tidally locked due to the Earth's tidal forces.
Angular Momentum
Angular Momentum between the remaining Moon, the piece blown away and the explosion needs to remain constant.   If the piece is blown off at an angle, that could significantly change the remaining Moon's angular velocity.   The piece would in effect, carry a bunch of angular momentum with it and the remaining moon would need the same amount of angular momentum subtracted from (or added to) it's Angular Momentum, as it could be done in either direction.   Hence, the explosion could not only blow off a chunk of the moon but cause the remaining moon to spin.   Explosions tend to be mostly uniform, so a significant change in rate of rotation would probably need a specific set-up if you wanted to get the moon spinning quickly.
If this chunk was blown off by a large meteor impact, that kind of impact could certainly send the Moon spinning.


text:
Q: Why is `JSON.parse` returning a proxy object? Because Lightning Web Components so often wrap objects in proxy objects, we long ago created a deProxyObj in order to be able to log to the console while debugging.
const deProxyObj = (proxyObj) => {
    return JSON.parse(JSON.stringify(proxyObj));
};

It's simple and allowed us to investigate proxy object contents while building the component. But a few months ago (don't know exactly when) this started returning a proxy object back, and I don't understand why. Finally decided to try to fix it, and did this:
const deProxyObj = (proxyObj) => {
    const str = JSON.stringify(proxyObj);
    console.log('str', str);
    const res = JSON.parse(str);
    console.log("res", res);
    return res;
};

When this gets executed, the log looks something like this (for data returned by Apex):
str {"0":{"Id":"a048K000000oRbnQAE","Address__c":"789 Third ...
res Proxy {}

So I'm successfully getting the proxy's contents as a string but then when I parse that string instead of giving me a standard object, it's wraping the object in a proxy object again, defeating the entire purpose.
So first, why did this used to work and now doesn't. And second, how can I extract the proxy object so I can investigate its contents for debugging purposes?

A: LWS, the Lightning Web Security replacement for the Aura Locker Service is now enabled by default on scratch orgs. It appears that LWS proxifies the JSON.parse response, unlike the Locker Service.
You can explicitly turn off LWS on the org but this only takes effect for new sessions.
You can ensure new scratch orgs use the Locker Service by adding "lockerServiceNext": false to your scratch def JSON.


text:
Q: Fundamental lemma: why is the transfer factor a power of q Let $k$ be a finite field of sufficiently large characteristic, $F = k((t))$ and $\mathfrak{o} = k[[t]]$. Let $G$ be a reductive algebraic group defined over $\mathfrak{o}$. Roughly stated, for sake of brevity, the Lie algebra fundamental lemma of Ngô states there is an equality of the form
$$
\mathcal{O}^\kappa_a = q^r\mathcal{SO}_{a_H}
$$
where $\mathcal{O}^\kappa$ is a $\kappa$-orbital integral for $G$ and $\mathcal{SO}$ is a stable orbital integral for an endoscopic group $H$ associated to $\kappa$ (or more precisely and endoscopic datum). Here $\kappa$ is a character of a cohomology group associated to stable conjugacy class $a$ in $\mathrm{Lie}(G)(F)$, and $a_H$ is the corresponding conjugacy class in $\mathrm{Lie}(H)(F)$. A more detailed and precise formulation is in [1], but this should suffice for the question.
Consider transfer factor $q^r$ in front of the stable orbital integral: it is a simple power of $q$ and $r$ depends on $a$ and $a_H$ (the number $r$ is the difference in dimensions of the associated affine Springer fibers).

Is there a relatively simple, perhaps 'geometric' explanation or heuristic of why the transfer factor in the fundamental lemma is a simple power of $q$, as opposed to another polynomial in $q$ such as e.g. $q^{r_1} + 2q^{r_2}$ where $r_1$ and $r_2$ just depend on $a$ and $a_H$?

Hales' paper [2] is a good relatively nontechnical summary of the fundamental lemma that briefly discusses this transfer factor but doesn't quite answer this question.
[1] Ngô, Bao Châu. Le lemme fondamental pour les algèbres de Lie. Publ. Math. Inst. Hautes Études Sci. No. 111 (2010), 1-169
[2] Hales, Thomas C. The fundamental lemma and the Hitchin fibration [after Ngô Bao Châu]. Séminaire Bourbaki: Vol. 2010/2011. Exposés 1027–1042. Astérisque No. 348 (2012), Exp. No. 1035, ix, 233-263.

A: I was hoping an expert would have commented on this. In any case, from my understanding, it boils down to purity. One sees this by global considerations: look at the fiber over the Hitchin base $\mathcal A_G$; by the BBDG decomposition theorem the complex $f_*\bar{\mathbb Q}_\ell$ is a direct sum of simple perverse factors, and the purity theorem tells us that the eigenvalues of the Frobenius action of each summand is a power of $q$.
Ngô proves this 'by hand' for a 'good' open subset of the anisotropic locus, i.e., he verifies some special cases of this, then by a continuity argument is able to extend this over the entire locus.
Now the exact power of $q$, I believe, is coming from the choice of certain divisors denoted $\mathfrak D_H$ and $\mathfrak R^H_G$ related to the discriminant and resultants of the conjugacy class involved. But eventually the exponent measures the codimension of the endoscopic stratum $\mathcal A_H$ in $\mathcal A_G$, which locally is relates to the dimension of the affine springer fibers, as you know.
This is mentioned in part by the report by J.F. Dat and D.T. Ngô in Lemme Fondamental pour les Algèbres de Lie, pp. 20-21, but I haven't been able to track this down precisely in B.C. Ngô's original paper.
EDIT: Looking more closely, I'm not so certain that my first paragraph is the right answer. But if you feel so inclined, I believe the key is Lemme 8.5.7 in Ngô, where he makes the local calculations (point counting) for some simpler cases. If that is the case, then there doesn't quite seem to be a geometric reason for the power of $q$, except that it matches the expected form.

A: I am also not 100% sure, but my impression (if wrong, the error is mine)  from conversations with Hales was that the power-of-q part of the transfer factor is the easy part, simply the absolute value of a ratio of some  Weyl discriminant-style factors (which comes from the normalization of measures on the matching orbits).
This discriminant factor is written explicitly in the other excellent expository paper by Hales, https://arxiv.org/pdf/math/0312227.pdf (see formula (6.0.1)): the product over roots is what gives the power of q, simply because it is the absolute value. The ratio of volumes in the same formula
I think is not part of the transfer factor, it's just a constant that can be removed by choosing the measures on G and T  (and is not a power of q).


text:
Q: How to change column heading using xtable in R? I have the following piece of code:
tableData <- head(original_table[,c("column1",
                                    "column2",
                                    "column3")])
library(xtable)
xt <- xtable(tableData)
print(xt,type="html")

The 'original_table' object is a table where the columns have very awkward names which I do not want in the final output from printing the xtable.
I have a lot of code using the 'original_table' object which comes after the xtable is created. So I do not want to change the column headings in the original table.
How can I change the column headings using xtable so they can appear as something like 'Height','Width' and 'Breadth' in my table output?

A: xtable inherits data.frame.
So,
library(xtable)
xt <- xtable(tableData)

names(xt) <- c('Height','Width','Breadth' )

will work.


text:
Q: Angular +WebApi+Azure App Service No Authorization Header (code 401) My app is an Angular 14 + .Net 6 WebApi. It is running all good locally.
After deploying both onto respective Azure App Service, it gets 401 when Angular calls backend Api which has Authorize[role].
Found a difference which the angular webapp deployed on Azure App Service has no Authorization(with jwt token) in the request header. Not sure if this is the root cause.
The header from local running when triggering the call was as below.

And the one deployed on Azure App Service as below.

Any help or advice would be greatly appreciated.
I see there might be an approach by using Http inteceptor adding a custom header.
I would probably take that as last resort if cannot find the root cause or other solutions.

A: To benefit the community, the issue was resolved by
cooldadtx's answer on Microsoft Q&A.
Quoting the answer below:

The authorization header is what is injected when you have successfully authenticated. How does your app get the authentication token when it runs? You either have hard coded credentials in your code to talk to the back end API or you are prompting the user for credentials and then authenticating from there. Whatever that step is isn't happening.

One thing that I would start to suspect is that your environment settings aren't properly configured. When you deploy your app to Azure you should have set up the environment under your app service's settings. The ASP.NET environment determines what appsettings.json file to read. By default it would read appsettings.json + appsettings.<environment>.json. You should confirm that your app service is using the appropriate environment and that your JSON files have been properly copied to the server and that they are configured for authentication properly. My gut instinct is that your using the wrong credentials so authentication is failing.
"

KunLi added "Now I have resolved it by adding an interceptor under the hood for adding the header. "


text:
Q: Release Date of New version of WSO2 appmanager(1.2.0) I was working on App manager, while accessing the store from my device the User interface was not responsive. But I have heard that all these bugs are resolved in the latest version. So when could I expect the release of next version. Or alternatively, how can I customize the code so that I could make the store, responsive for accessing through mobile devices

A: released version of wso2 app manager use bootstrap 2.X version and you can use bootstrap 3.X versions to make it responsive.
Here is the bootstrap update guide: http://code.divshot.com/bootstrap3_upgrader/


text:
Q: What is the best way to use jquery ui themeroller themes I just for the first time downloaded jquery and jquery-ui to use/learn last night.
I figured out how to get it working, and now I am playing around with the downloadable/customizable themes on themeroller...(nice tool).
A question about best way of maximizing the use of these tools:
I am integrating jquery/jqueryUI into an existing asp.net that I have already "themed" with colors/fonts that I like using my own custom css, I used the "themeroller" app to get the jquery UI elements to more or less match with my existing css color/font schemes.
The real question is, am I doing it backwards? Would I be better of designing my themes in themeroller, and then using that generated CSS for the ALL of my app? as opposed to using themeroller to mimic the css I already have for the non-jquery UI elements?
I could see that it would be nice to be able to use themeroller, download the CSS, and then base the non-jqueryUI CSS around the generated CSS, but I don't want to try it if that is not a generally accepted approach that will end up causing me problems down the road.

A: What I typically do is generate a theme for jQuery using the ThemeRoller that uses the colours from my website's CSS. I don't use the ThemeRoller theme for my website though, I usually keep these 2 separate.

A: I personally use the full jquery theme for my whole site.  The ui-widget, ui-widget-content, ui-widget-header, ui-state-default, and ui-state-active, among others.  I create my menus with these tags.  I think its good to fit into that model, because if I want to swap themes on the fly or change a theme later on I won't have much resistence.
Of course theirs always exceptions.  So, I always put my global.css file after my ui.all.css file in my header.


text:
Q: How to write dynamic loader for bare-metal arm-application I'm working on a project based on arm9 processor. We use only bare-metal without any operating system, so unfortunately we have no support for shared libraries / dynamic loader yet.
I would like to be able to have libraries loaded for example from SD card, which can also call the functions from the main application.
My first try was to use linker overlay capability (placing the library in specific absolutely positioned sections), but here is a problem with calling main app functions as I mentioned earlier -> with each change of the main application the libraries has to be recompiled again to be able to callback.
According to this I thing I will have to write my own dynamic loader, but I'm newbie in this area. Could please someone give me any example how to deal with it or how to start with such project? We are using gcc for arm-elf target.
regards
Jan

A: Check this application note. It describes in some details how dynamic linking works and what you need to do to write your own dynamic loader. It also gives some alternatives to that. I think the jump tables one is quite easy to implement and will resolve your issue with changing API addresses.

Edit: Here's how to do a simple jump table. First, decide which functions you need exported from your main program. Then make a structure of function pointers:
typedef struct _MyAPI
{
  int    (*init)(int flags);
  int    (*exit)(int exitcode);
  void * (*getmem)(size_t size);
  void   (*freemem)(void *ptr);
} MyAPI;

In the main program, define an instance of this structure, fill in the pointers, and place it at some predefined address:
#include <jumptbl.h>
int    main_init(int flags)
{
  return 0;
}
//...
MyAPI main_API __attribute__((section(".jumptbl"))) =
{
  &main_init,
  &main_exit,
  &main_getmem,
  &main_freemem,
};

(if you use this approach, you will need to describe .jumptbl section in the linker file and make sure it gets a fixed address)
In the loaded module, get the pointer to the jumptable and use it to call the main program:
#include <jumptbl.h>

MyAPI *pAPI = (MyAPI*)(0x1000000); // there should be a better way to do this

int main()
{
  pAPI->init(0);
  void *block = pAPI->getmem(0x30);
  //...
}

Hope this helps!


text:
Q: Scala+Linux: Cannot find main class for jar I have a simple scala program:
main.scala:
object Program {
  def main(args: Array[String]) {
    println("Hello World");
  }
}

It compiles just fine:
$ scalac -nowarn -d bin/scala.jar code/main.scala

When I run it, I get the error:
$ scala bin/scala.jar
Exception in thread "main" java.lang.RuntimeException: Cannot find main class for jar: bin/scala.jar
    at scala.sys.package$.error(package.scala:27)
    at scala.tools.nsc.MainGenericRunner$$anonfun$runTarget$1$1.apply(MainGenericRunner.scala:62)
    at scala.tools.nsc.MainGenericRunner$$anonfun$runTarget$1$1.apply(MainGenericRunner.scala:62)
    at scala.Option.getOrElse(Option.scala:108)
    at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:62)
    at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:80)
    at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:89)
    at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)

If I follow this same procedure on Windows, the program executes just fine. How do I fix this?

A: Scala can't find the main class because scala.jar is not on the classpath which contains Program. Run it with scala -cp scala.jar Program to set up the classpath and call the main in Program.


text:
Q: Ubuntu SDK content window always on top Just getting started with the Ubuntu SDK, trying to get everything set up, and I'm running into a graphics bug that I can't find a resolution to, or even anyone else who seems to have the same problem. Basically, the main content window of the SDK (which I guess is actually Qt Creator) will not let ANYTHING draw over it, even when it does not have focus. It's even showing up on the lock screen. The closest I've found to the same problem is OpenGL windows always on top, but I'm not using Unity-2D, so I don't know where to go from here.
This is getting to the point of being unusable, as I can't even use things like the options menu for Qt Creator because it's drawing over those unless I move the window after opening the dialog so that it stops drawing over it.
I'm running 14.04 LTS 64-bit, freshly installed on a VM inside Virtualbox within Mac OS X 10.9.5, with 3d acceleration enabled and functional, if that's any help.

A: Unfortunatelly you should turn off 3d acceleration. Don't know why, but just do it. It's solved same problem with my installation.


text:
Q: Modified rollapply mean I have a data file which consists of daily xy locations and a logical vector denoting whether or not the location is an outlier. Here is some (poorly created, I know) sample data:
x=seq(3,10,length.out=30)
y=seq(42,45,length.out=30)
outlier=c(F,F,F,F,F,F,F,F,T,T,T,F,F,F,F,F,F,F,F,F,F,T,F,T,F,F,F,F,F,F)
data=cbind(x,y,outlier)
> data
             x           y outlier
 [1,]  3.000000000 42.00000000       0
 [2,]  3.241379310 42.10344828       0
 [3,]  3.482758621 42.20689655       0
 [4,]  3.724137931 42.31034483       0
 [5,]  3.965517241 42.41379310       0
 [6,]  4.206896552 42.51724138       0
 [7,]  4.448275862 42.62068966       0
 [8,]  4.689655172 42.72413793       0
 [9,]  4.931034483 42.82758621       1
[10,]  5.172413793 42.93103448       1
[11,]  5.413793103 43.03448276       1
[12,]  5.655172414 43.13793103       0
[13,]  5.896551724 43.24137931       0
[14,]  6.137931034 43.34482759       0
[15,]  6.379310345 43.44827586       0
[16,]  6.620689655 43.55172414       0
[17,]  6.862068966 43.65517241       0
[18,]  7.103448276 43.75862069       0
[19,]  7.344827586 43.86206897       0
[20,]  7.586206897 43.96551724       0
[21,]  7.827586207 44.06896552       0
[22,]  8.068965517 44.17241379       1
[23,]  8.310344828 44.27586207       0
[24,]  8.551724138 44.37931034       1
[25,]  8.793103448 44.48275862       0
[26,]  9.034482759 44.58620690       0
[27,]  9.275862069 44.68965517       0
[28,]  9.517241379 44.79310345       0
[29,]  9.758620690 44.89655172       0
[30,] 10.000000000 45.00000000       0

What I need is to take a non-overlapping 6-day mean of the x and y columns. This is easy enough with rollapply(). However, I do not want outlier=1 values to be included in the 6-day mean; nor do I want the 6-day window to 'span' the gap left behind by removing all rows where outlier=T. Instead, I want to make an exception to the 'non-overlapping rule'.
I think this is best explained using the sample data above: the first value should be the mean of rows 1:6, but rather than the second value being the mean of rows 7:12 (including outlier=1 values) or of rows c(7:8,12:15) (skipping over outlier=1 values) I want it to overlap with the first window and take the mean of rows 3:8.
So for the length 30 sample data above, the end result should be of length 5, showing the mean values of rows 1:6, 3:8, 12:17, 16:21 & 25:30 (ideally all values which result from overlapping windows should be labelled as such; i.e. values 1:4 overlap, whereas the final value is unique)

A: Here is a function that will give you the indices of the endpoints of the averages that you want:
findIndices<-function(outlier,window=6){
  r<-rle(outlier)
  rends<-cumsum(r$lengths)
  segs<-cbind(rends-r$lengths+1,rends)
  segs<-segs[with(r,lengths>=window & values==0),]

  indices<-unlist(apply(segs,1,function(x) seq(x[1]+window-1,x[2],by=window)))
  sort(unique(c(indices,segs[,2])))
}

findIndices(data[,3])
## [1]  6  8 17 21 30

You can then get the averages you want like this:
id<-findIndices(data[,3])
require(zoo)
cbind(index=id,rollmean(data[,1:2],6)[id-5,])
##     index        x        y
## [1,]     6 3.603448 42.25862
## [2,]     8 4.086207 42.46552
## [3,]    17 6.258621 43.39655
## [4,]    21 7.224138 43.81034
## [5,]    30 9.396552 44.74138

You can put it all together in a single function like this:
maWithOutliers<-function(x,outlier,window){
  id<-findIndices(outlier,window)
  cbind(index=id,rollmean(x,window)[id-window+1,])
}

> maWithOutliers(data[,1:2],data[,3],6)
     index        x        y
[1,]     6 3.603448 42.25862
[2,]     8 4.086207 42.46552
[3,]    17 6.258621 43.39655
[4,]    21 7.224138 43.81034
[5,]    30 9.396552 44.74138
> maWithOutliers(data[,1:2],data[,3],4)
     index        x        y
[1,]     4 3.362069 42.15517
[2,]     8 4.327586 42.56897
[3,]    15 6.017241 43.29310
[4,]    19 6.982759 43.70690
[5,]    21 7.465517 43.91379
[6,]    28 9.155172 44.63793
[7,]    30 9.637931 44.84483
>


text:
Q: How to write another field from a wizard Odoo 11 I want to change a field value from wizard. The field itself is not within wizard. Here is the code:
class TestMapWizard(models.TransientModel):
_name = 'test.testmapwizard'
_description = 'Map Wizard'

name = fields.Char(string='Coordinates', required=True)

@api.onchange("name")
def _change_coordinates(self):
    for record in self:
        if record.name:
            ids = self.env["test.map"].search([('name', '=', record.name)])
            if ids:
                ids.write({'name': self.name})

A: Pass your active_id from the button through context
Example: In your XML file
<button name="%(your_wizard_act_window_id)d" type="action" context="{'default_active_id':active_id}" string="Your String"/>

In your Python(wizard code):
@api.onchange("name")
def _change_coordinates(self):
    for record in self:
        if self.env.context.get('default_active_id'):
           active_id = self.env.context.get('default_active_id')
        if record.name:
            ids = self.env["test.map"].browse(active_id)
            for id in ids:
                id.write({'name': self.name})
    return True


text:
Q: Problema com forecast no R Estou tentando fazer uma previsão do PIB relativamente simples, mas estou encontrando o seguinte erro:
**Error in model.frame.default(formula = y ~ t2, drop.unused.levels = TRUE) :
  comprimentos das variáveis diferem (encontradas em 't2')**

Segue o script que estou fazendo:
scan=(~pib)

#Previsão

tspib = ts(pib[,2],start = c(2002,1), frequency = 12)

tspib

plot(tspib, xlab='Years', ylab = "Pib")

plot(forecast(tspib))

summary(forecast(tspib))

#Regressão

length(tspib)

t=(1:182)

t2=t^2

#Erro aqui

reg=lm(y~t+t2)

summary(reg)

O arquivo está em meu PC e é um CSV no seguinte formato (exemplo das 5 primeiras linhas):
Data    PIB
2002-01 112374,80
2002-02 111477,10
2002-03 118444,70
2002-04 120385,90
2002-05 123552,50

Data está importado como "character" PIB como "numeric".

A: O erro está dizendo o problema: as variáveis t e t2 possuem comprimentos diferentes da sua variável resposta.
Veja o erro que aparece nesse código bem simples em que as variáveis possuem comprimentos diferentes.
> y = 1:9
> x1 = 1:10
> x2 = 1:10
> lm(y ~ x1 + x2)
Error in model.frame.default(formula = y ~ x1 + x2, drop.unused.levels = TRUE) :
  O comprimentos das variáveis diferem (encontradas em 'x1')

Pelo seu código, t e t2 possuem com certeza o mesmo lenght, portanto o problema está entre t e a resposta.
Vi que você usa o lenght(tspib) e deve ter dado 182 porque você depois fez t <- 1:182. Verifique se o tspib não tem informações NA, que são excluidas automaticamente quando você ajusta o modelo de regressão.


text:
Q: is there an oauth2 provider who is essentially anonymous (but might store credit card information) Not sure if this is right place to ask but...
The title sums it up - we are looking for an oauth2 provider that doesn't have the baggage of a Facebook or Twitter but does provide oauth2. A bonus would be some form for credit card integration (although a distant requirement) Does paypal or stripe offer something like this?
thx in advance

A: PayPal Access is what you may be looking for https://www.x.com/developers/paypal/documentation-tools/getting-to-know-paypal-access.
Can you explain the credit card integration piece?


text:
Q: How to get displays myArray after X-value is true? I'm trying to create a program where if the user enters a X-number between 1-9, and it takes that X-number and creates X-number of rows and columns. For example, if the user enters "5", the output should be something like this:
....1
...2.
..3..
.4...
5....
I cannot get it to show the output right now with the code I have. I am still new to JavaScript so any help is appreciated.

function drawSquare() {
let myArray1 = ["1"];
let myArray2 = [".1", "2."];
let myArray3 = ["..1", ".2.", "3.."];
let myArray4 = ["...1", "..2.", ".3..", "4..."];
let myArray5 = ["....1", "...2.", "..3..", ".4...", "5...."];
let myArray6 = [".....1", "....2.", "...3..", "..4...", ".5....", "6....."];
let myArray7 = ["......1", ".....2.", "....3..", "...4...", "..5....", ".6.....", "7......"];
let myArray8 = [".......1", "......2.", ".....3..", "....4...", "...5....", "..6.....", ".7......", "8......."];
let myArray9 = ["........1", ".......2.", "......3..", ".....4...", "....5....", "...6.....", "..7......", ".8.......", "9........"];
let l1 = myArray1.length;
let l2 = myArray2.lenght;
let l3 = myArray3.length;
let l4 = myArray4.length;
let l5 = myArray5.length;
let l6 = myArray6.length;
let l7 = myArray7.length;
let l8 = myArray8.length;
let l9 = myArray9.length;
let number = document.getElementById("textbox3")
let getNumber = number.value
if (getNumber != 1 || getNumber > 9) {
 alert("You have entered an incorrect number");
 } else if (getNumber = 1){
  text = "
";
   for (i = 0; i < l1; i++) {
   text += "
" + myArray1[i] + "
";
   }
  }
 }

Enter a height for our square<input type="text" id="textbox3"><button id="drawSqaure" onclick="drawSquare()">Draw Square</button>

Output goes here

A: Little implementation using a textarea.  It uses the number of rows to draw to know how many dots to draw, depending upon which row you are drawing.

document.getElementById('rowCount').addEventListener('input', function(e){
  var rowCount = parseInt(e.target.value.trim() || '0', 10);
  var textarea = document.getElementsByTagName('textarea')[0];

  textarea.innerHTML = '';

  for (var i = 1; i <= rowCount; i++) {
    if (i > 1) textarea.innerHTML += "\n";

    textarea.innerHTML += '.'.repeat(rowCount - i);
    textarea.innerHTML += i;
    textarea.innerHTML += '.'.repeat(i - 1);
  }
});
<input type="number" id="rowCount" value="0" min="0">
<textarea></textarea>

A: To make it the way you clearly said on your question:
. . . . 1
. . . 2 .
. . 3 . .
. 4 . . .
5 . . . .

The solution is this:
$("#generate_square").click(function(){
    let number = $("#number").val();
  let square = $("#square_gen");
  let str = "";
  let number_shown = 1;
  for(var dcolumns = 1; dcolumns<=number; dcolumns++){
    for(var drows = 1; drows<=number; drows++){
        if( drows === number_shown ){
        str += number_shown+"  ";

      }else{
       str +="0  ";
      }
    }
    str += "
";
    number_shown++;
  }
  square.append(str);
});

Here is a fiddle of it working:
https://jsfiddle.net/ndpe671c/1/

A:

function drawSquare() {
  var n = document.getElementById("textbox3").value;
  n = parseInt(n);
  var str = '
';
  for (var i = 0; i < n; i++ ) {
    var x = n - 1;
    for (var j = x; j >= 0; j--) {
      if (j === i) {
        str += i;
      } else {
        str += '.';
      }
    }
    str += '
';
  }
//  console.log(str);
  $('#output2').html(str);
}

Enter a height for our square<input type="text" id="textbox3"><button id="drawSqaure" onclick="drawSquare()">Draw Square</button>

Output goes here

I make it simpler with jquery. Check it and tell me, if it's what you want.


text:
Q: How to add a small straight line (I mean like this: a̅ b̅ X̅) onto a character inside a string? I want to add small straight line onto some desired characters/numbers inside a string inside textview. I couldn't find a solution. Maybe using NSMutableAttributedString. Meanwhile, I mean doing this programmatically. There is strikethrough style, but not overstrike style. Or maybe adding the letters "a" and "_" with different .baseline values. But how to add both characters onto each other then?
Is it possible?
EDIT: Due to make a try for the helpful answers below, I think to make the line at a spesific height is needed. "A\u{0305}" makes the up line very close to the character, as if it sticks. Is there a way to make it at specific height? For example, if we assume that all the keyboard-inputted characters are written inside every single boxes, the ceiling side of these boxes could be lined?

A: So this (note: see edit below) appears to be an "a tilde ogonek" (it's Lithuanian).
You can write it for instance as follows using these two Unicode characters:
let atildeogonek = "\u{0105}\u{0303}"
let title = "How to add a small straight line (I mean like this: \(atildeogonek)) onto a character inside a string?"

The first character is the a with an ogonek, the second one is the tilde.
EDIT: The initial question specifically asked about the character ą̃ ("a tilde ogonek") in the title, and I used this code to demonstrate how to use Unicode characters in a Swift string. After posting this answer, the question was edited to be more general about "a line above a character".

A: Programmatically, you could use a function like this:
func overline(character: Character) -> Character? {
    return "\(character)\u{0305}".first
}

That will take a character as input and return a new character (glyph) that has had the Unicode combining overline character added to it. It will return nil if adding the combining overline character fails.
The code print(overline(character:"A")!), for example, returns "A̅"
Or, if you want to add an overline to every character in a string, you could use a function like this:
func overline(characters: String) -> [Character?] {
    return  Array(characters).map { return "\($0)\u{0305}".first
    }
}

(I'm not sure if there are any characters for which the above will fail, so I'm not sure if force-unwrapping the result is safe. Thus I left the result of both functions to be optional Character/Array of Character.)

A: You can easily find the unicodes of ā or ą̃ by using the xcode's own Character Viewer. Just follow the following steps :
hit : Control + Command + SpaceBar
If you get a compact one like this, click the upper right corner icon to expand it.

When expanded, Click the settings gear in the corner . Select customize list.

select Enclosed Characters

Go down to the bottom and open Code tables then add Unicode.

Now, just search for your required Character and you can check its unicode value. here i am searching ā

to print unicode's value :
print("\u{0101}")


text:
Q: Lightning: Importing "Tasks" from Outlook The Problem:
I am trying to migrate user from Outlook 2003 to Mozilla Thunderbird w/ Lighting extension.
User kept important data stored as Tasks. While I can easily export Tasks from Outlook 2003 to it's default CSV format, I found so far no way to import the CSV into Lightning.
The Research:
So far I have found no out-of-the-box solution.
In fact, the only solution I can actually think of would be to manually prepare and inject CSV data into the SQLite database storing Lighting data (<profile_dir>\calendar-data\local.sqlite).
That solution needs quite a lot of work, though. The single task data is stored among several tables, I'd have to manually match columns, find some solution to recalculate date values etc.
Attempted solutions:

*

*Tried to export data from Outlook to .ics using Outport as @Randolph West suggested. When ordered to import that file, Lightning did nothing.

*Attempted to build an .ics myself, basing on a template task exported from Lightning (so that I could be sure the format itself is not an issue). Same result as with attempt #1.

The Question:
I am looking for some out-of-the-box solution, or at least a near one. A solution that could be comfortably used by some less-than-skilled users.

A: I've been looking at this and can't find an easy solution.
However, I plan to try the following steps tomorrow, unless someone has a reason why it won't work:
PLAN:

*

*Export all Outlook TASKS to csv

*Edit the csv to look like Lightning EVENTS
(this will lose some data and looks like the most difficult step as Lightning is very fussy about importing csv's. I think all fields have to be quoted, and dates without centuries will appear in the 1900's if you aren't careful)

*Create a new calendar and import all the EVENTS

*Select all the EVENTS and convert them to TASKS
(this involves reviewing all the entries manually, but is better than having to retype them all!)

*Select all the TASKS and move them to another calendar (if you don't want them in a separate calendar)

Anyone who knows this won't work, please let me know. Otherwise I'll report back if it is successful.
Mark

A: One workaround is as follows:

*

*Install and run Outport

*It will parse through the pst file hierarchy and will display Tasks folders as well. Select the folders you want to export

*In the Tasks format options chose Evolution Tasks

*After you export is complete you can find all your tasks as one *.ics file per your Outlook folder

*Import ics files one by one to Thunderbird by right-clicking the required Calendar and selecting Export Calendar
One caveat - any attachements in Tasks will be lost. You will need to reattach them manually. Still it's better than the solution offered above.
Second caveat - you may or may not need to have outlook installed at the time to run Outport. I have Outlook installed on my machine, so it was not an issue.


text:
Q: In VBScript, can I raise an error to simulate Goto? If I were working in VBA, my current procedure would go something like this:
Do While MyFile.AtEndOfStream <> True
arrRecord = Split(MyFile.ReadLine, ",") ' Make an array of the values in this line

'There are certain records I don't want to process:
If arrRecord(1) <> "USA" then goto skip
If arrRecord(0) <= "12/31/2001" then goto skip

' Otherwise, run the rest of the code on this record

skip:
Loop

But I'm working in VBScript, which doesn't have this kind of Goto function.
I'm thinking of doing the same thing by delibaratly raising an error. For instance:
Do While MyFile.AtEndOfStream <> True
arrRecord = Split(MyFile.ReadLine, ",") ' Make an array of the values in this line

On Error Goto skip

'There are certain records I don't want to process:
If arrRecord(1) <> "USA" then Call NoSuchFunction
If arrRecord(0) <= "12/31/2001" then Call NoSuchFunction

' Otherwise, run the rest of the code on this record

skip:
Loop

Is there any potential problem with this? Should I use Err.Raise instead?

A: VBScript, unlike VBA, doesn't have On Error Goto. It only has On Error Resume Next.
However, the case that you're looking for, of exiting a control flow early, can be handled with the Exit statement. See this article from the Microsoft Scripting Guys for more details and examples.
If you're not currently in a control flow that you are looking to exit, you can hack it by creating one that will only execute once:
Do
    'Stuff
    If something Then Exit Do
    'More Stuff
Loop While False 'Execute once, can be left early by "Exit Do"

And while that's clearly a hack, I'm not sure it's any worse than trying to use a straight "Goto" in the first place. Usually one can restructure the logic to be clear as to what one is actually doing, without needing such inelegant constructs.

A: This is not possible in VBScript.  The only error handling you have is On Error Resume Next and, to disable that within a certain scope, On Error Goto 0.
There's no such think as a label in VBScript.


text: Q: Can we add only necessary ciphers for an Azure Redis Cache hosted in a Virtual Network I have hosted my Azure Redis Cache inside a Virtual Network and our penetration testing team has suggested to allow required Cipher suites as per the company norms. Is it possible to alter the cipher suites.


text:
Q: Run shell script which is on hdfs location from a pyspark script I have a requirement where i have to run call a shell script which is on hdfs location and run the shell script from a pyspark script.
My code is something like this,
bashcommand="hadoop fs -cat (0) |exec sh -s (1)". format (shell script, hqlfile)

subprocess.Popen (bashcommand.split 0),
stdout=subprocess.PIPE)

# hqlfile is my parameter for shellscript

The subprocess.Popen is not working here.
Any help is appreciated
Note : (I am running the pyspark script by firing spark-submit)
#####Update
bashCommand='hadoop fs -cat /bin/test/ingest.sh|exec sh -s /bin/test/hql/test.hql'

This is my command which I am trying to execute using
os.system(bashCommand)

The above code I have written in pyspark script and triggering pyspark script through spark-submit
My ingest.sh script contains
beeline -u "jdbc:hive2:************" -f $hql_file_path
My beeline command works perfectly fine when I run it on the edgenode and also when i run the shellscript ingest.sh on edgenode directly then also the beeline runs perfectly fine. The issue is only when I trigger it through a spark-Submit
code flow:
pyspark-->
bashCommand='hadoop fs -cat /bin/test/ingest.sh|exec sh -s /bin/test/hql/test.hql' os.system(bashCommand)
shell script(ingest.sh)--->
beeline -u "jdbc:hive2:************" -f $hql_file_path

Error when triggered the PySpark script:
22/04/23 17:37:26 WARN ipc.Client: Exception encountered while connecting to the server :

org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.ipc.StandbyException): Operation category READ is not supported in state standby
sh: line 9: beeline: command not found


text:
Q: How to visualize touches with android (Nexus One) Do you know if there is a tool/setting that allows me to visualize the touch events while using my phone? I would like to use it for a usabilty test.
There is a tool for the iPhone that does exactly what I need (It´s called DisplayRecorder)
In this video you can see what I mean: http://www.youtube.com/watch?v=WGOrkDxgMME
I didn´t find a similar tool for android. I´m not sure if it works with the dev tools setting "Pointer Location" - my Nexus One crashes when I try to set it.
Does anybody know if this works while using the phone as normal? In terms of a layer on top of the normal application?
Hope someone can help me! Thanks in advance!

A: I used a small "joke" application creating electrical sparks where one touched. That's probably not really what you want, but maybe you could craft your own app using the same principle: a transparent overlay, registering touches and displaying a haircross where they are detected (and possibly showing coordinates in a textbox or something).


text:
Q: Moving a Mega Menu Over I am new to jquery and css. I created a jquery mega menu but I am having problems with the Link menu item. It runs off the right side of the scren and I want to bring it over to match the right edge of the site. Can someone please explain how I can do this? I normally would post the code or put up a jsfiddle link but there are different css and js files to run this and I don't know of another way then to link you directly to the site.
This style I have linked to the UL of the list for Links
Located in the menu.css file.
/* Style the 3rd level links */
.dcjq-mega-menu ul.menu li .sub li ul li#links-layout {

}

I have tried float left and also margin-right:300px; and neither seem to effect moving it.
This is on the main page.

LINKS

Instruction: Roll your mouse over the "LINKS" menu bar item and notice how it runs off the right browser screen I want to fix this.
Here is the link: http://gdisinc.com/barker/default.php


text:
Q: Open CV + Visual Studio 2008 weird Debugging problem I've recently installed OpenCV2.0 under Visual Studio 2008 professional edition, built the libraries, dll-s and got everything working but when I run the first example program:
#include "highgui.h"
int main( int argc, char** argv ) {
IplImage* img = cvLoadImage( argv[1] );
cvNamedWindow( "Example1", CV_WINDOW_AUTOSIZE );
cvShowImage( "Example1", img );
cvWaitKey(0);
cvReleaseImage( &img );
cvDestroyWindow( "Example1" );
}

It goes straight into Debug mode with the following exception : Unhandled exception at 0x7855b9f0 in HelloOpenCV.exe: 0xC0000005: Access violation reading location 0x00000000.
It also switches to a "loadsave.cpp" file and it points to the line:
return (IplImage*)cv::imread_(filename, iscolor, cv::LOAD_IMAGE );

At the stack point : > highgui200.dll!cvLoadImage(const char * filename=0x00000000, int iscolor=1)  Line 474 + 0x13 bytes C++
I also made a printscreen with the visual studio debugging window link text
I presume it has something to do with misplaced dependencies , problems with the dll-s.
If anyone has an idea of what I could do to fix this please answer and I will be forever grateful.
Thanks,
Alex

A: Did you specify a valid file in your command-line parameters for argv[1], i.e. the filename of the image to be read?

A: You need to verify that you have enough command line arguments.  You should add something like this to the start of main():
if (argc < 2)
{
    fputs("Usage: prog filename\n", stderr);
    exit(1);
}
else if (argc > 2)
{
    fputs("ignoring extra parameters\n", stdout);
}

You could also modify your code to use each command line option in turn (if you do this, you would want to remove the warning about extra parameters in my above example):
int arg;
for (arg = 1; arg < argc; ++arg)
{
    IplImage* img = cvLoadImage( argv[arg] );

    ... the rest of your code ...
}

Finally, since it appears from your screen capture that you are starting your executable within the debugger, you will need to modify your properties in order to add the command line arguments.  Within your project's properties, you want to choose the Debugging tab and then add the file to "Command Arguments".

A: This isn't a direct answer, but I would try asking on the OpenCV Yahoo Group. It's quite active, and someone there is bound to know. Anytime I've ever asked a question there it's been replied to in a few hours.

A: i think your command line  argument is not proper
make sure for validity of command line arguments.

A: As other answers have indicated, the program is running with no command line arguments. You should do what R Samuel Klatchko said so your program works properly when run with out them.
But beyond that, to help you debug with proper arguments you can specify the command line arguments you want passed in to the program when the debugger is started in the VS project's Property Page on the "Debugging" 'tab'.  It's the "Command Arguments" setting.


text:
Q: How to run the other keyword if the test case fail in robot framework? While I'm running one of my test cases in my robot file, I want to send the file if this test case fail. Not just for one condition, it's like keep detecting the errors, if you find it, you send the file and RF will help you stop this test case. So I don't think Run keyword if is the best choice. It seems like it just can use only one time.
Also I want to ask that if the test case fail, could it keep executing the same test case? But I still want to know all the errors it has. I know there is Run Keyword And Ignore Error but I don't think it can let all the errors show on the screen. It just ignore the fail without printing the error.
Are there the keywords could do these questions? Thanks

A: You can try keyword Run Keyword And Warn On Failure. The keyword should not fail, but you should have warning in the log to make it more visible, unlike Run Keyword And Ignore Error.

A: There is also Run Keyword and Continue on Failure.
https://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Run%20Keyword%20And%20Continue%20On%20Failure
This will run the other keywords in test after the failure occurred. The test report will be showing all failures.


text:
Q: Fill formula right to end of row, without going to edge of worksheet In Excel, suppose I have a row with, say, 26 formulas horizontally from A1 to Z1, and then I move down to cell A2 and type a formula. Now I want to fill that formula to the right, through cell Z2. The issue is that if I just use Ctrl+R, it will fill this formula to the edge of the worksheet. Normally I get around this by going to cell A1, then Ctrl+→ (right arrow) to the end of the row (cell Z1), then drop down one row to cell Z2, put something (e.g., a 1) into that field, then Ctrl+← (left arrow) to select cell A2, and then finally I do Ctrl+R, which will fill my formula only through cell Z2.
Is there a much easier way to do this?

A: 1) If your used range is between columns A and Z, then you can press Shift+Ctrl+End to select cells Ax:Zx (x being your current row). If you accidentally paste something outside of this range and delete it, then you can restore that range by saving the workbook.
2) You could put all of the formulas in Column A and then select all of the formulas and fill right in one action.
3) You can use this sequence (starting on a cell containing a newly entered formula):

*

*Ctrl+C

*Up

*Ctrl+Right

*Down

*Shift+Ctrl+Left

*Ctrl+V

*Down (you are now ready to enter a new formula)

(While this seems like a lot, it can catch on relatively quickly)
4) Record a macro to accomplish the same steps as 3 with relative references. Assign that to a simple keystroke such as Shift+Ctrl+A.
5) Write a macro that does the same as 4, but only takes 2 lines of code.
6) Continue using Ctrl+R to fill all the way to the end of the sheet. Once you have finished building out the worksheet, delete columns after Z.

A: Its easier if you are working in rows you can just double click the little black box in the corner of a2 when it is selected.
For copying across columns I just

*

*navigate to Z2 from A1 (up, ctrl+right,down)

*select the range and copy (ctrl+shift+right, ctrl+right)

Fills the range, takes about a second, seems fast enough for me.


text:
Q: Showing convergence in probability for poisson distribution Given random variable X and N so that, N ∼ Poisson(λ), and X|N ∼ Bin(N,p) where p is a constant (Assume that X = 0 when N = 0 and 0 < p < 1). Note that the moment generating function of a Bernoulli random variable with parameter p is 1 − p + etp, and the moment generating function for Poisson(λ) distribution is exp[λ(et − 1)].
Show that X/λ → p, as λ → ∞
I believe I found the pmf of X not conditioned on N below
$ P(x=x) = \frac{e^{-\lambda p}(\lambda p)^x}{x!} $
Then used $ E(e^{tx}) $ to find the mgf
$ M_x(t) = e^{\lambda p(e^t-1) }  $
But I am no unsure of how to show convergence in distribution.

A: *

*You've shown $M_X(t) = e^{\lambda p (e^t-1)}$

*Show that consequently, $M_{X/\lambda}(t) = e^{\lambda p (e^{t/\lambda} - 1)}$.

*Note that $\lim_{\lambda \to \infty} \frac{e^{t/\lambda} - 1}{t/\lambda} = 1$ to conclude that $\lim_{\lambda \to \infty} M_{X/\lambda}(t) = e^{pt}$


text:
Q: Slow down Twilio's TwiML "Say" command for text-to-speech numbers I've created a Twilio application that involves using Twilio's TwimL <Say> command to read off a list of numbers that constitute an ID that the user has previously input (e.g., 3638194746219190 or something along those lines).  Since it's a long list of numbers, I have the application read back the list of numbers to confirm that the user has input them correctly.  Since it's dynamic, I can't pre-record it--it has to be with <Say>, but Twilio reads it back way too quickly.
I currently have the numbers played back with spaces and commas between them to slow them down, for example: '3, 6, 3, 8, 1, 9, 4, 7, 4, 6, 2, 1, 9, 1, 9, 0', and that has helped a little bit, but it still reads the list back way too quickly.
Do you know how to force Twilio's <Say> command to slow down its text-to-speech playback even further?

A: You can add multiple commas or periods and it'll increase the pause time. You may also consider adding longer breaks every X numbers so it has a more natural cadence to it.
3,,,6,,,3,,,8,,,,,,,1,,,9,,,4,,,7,,,,,,,4,,,6,,,2,,,1

A: You can add a <Pause> verb to pause execution for a number of seconds. The documentation is here: http://www.twilio.com/docs/api/twiml/pause
There's more information about generating pauses in TwiML at this question: How can I generate a half second pause in TwiML?

A: You could try using periods, e.g. 1. 2. 3. 4. 5. 6. 7. 8. 9.


text:
Q: WooCommerce - Display categories and its products on front page when the user visits my shop homepage he sees all the products which are in the shop. I want to change the view, so that the user sees:
- Category 1
Products of cat 1
- Category 2
Products of cat 2
How can I achieve this? I looked in woocommerce/templates/archive-product.php and found this:
<?php woocommerce_product_loop_start(); ?>

                <?php woocommerce_product_subcategories(); ?>

                <?php while ( have_posts() ) : the_post(); ?>

                    <?php wc_get_template_part( 'content', 'product' ); ?>

                <?php endwhile; // end of the loop. ?>

            <?php woocommerce_product_loop_end(); ?>

But how can I hook into this, to create two different loops for cat 1 and cat 2?
Does somebody knows that? Thanks!

A: First you'll need to query the products from a category:
$args = array(
    'posts_per_page' => -1,
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => 'category-slug1' //Your category goes here
        ),
    ),
    'post_type' => 'product',
    'orderby' => 'title',
);
$first_cat_query = new WP_Query( $args );

Then just do a loop to print each product:
while ( $first_cat_query->have_posts() ) {
    $first_cat_query->the_post();
    echo '' . get_the_title() . '

';
}
wp_reset_postdata();

And repeat the same to the next category, you'll need to adapt the template to make it compatible with the query.


text:
Q: filtering column values while using SELECT in MySQL I have a mysql table with a column Doc TEXT.
the column contains HTML as content.
I want to select the column with filtered to get only URLs from the content. column content contains A HREF="(.*)" .
I tried mysql's REGEXP, but it will return only true or false, not the filtered match.
highly appreciate your help.

A: If your HTML column text is well-defined XML (i.e. XHTML with proper closing tags) you can use MySQL's extractValue() function to parse it as XML using Xpath.
CREATE TABLE links (anchor VARCHAR(100) NOT NULL);

INSERT INTO links VALUES ('Stack Overflow');

SELECT extractValue(anchor, '/a/@href') FROM links; -- prints http://stackoverflow.com/

If the column contains other tags (like  etc.) just modify your Xpath (//body/a/@href) accordingly.
EDIT: For the column HTML shared in your comments below:
<TITLE>*******</TITLE>
GOOGLE

YAHOO

BING

The extractValue() xpath needs to be modifed to //A/@HREF (case-sensitive)
SELECT extractValue(anchor, '//A/@HREF') FROM links;
-- prints http://www.google.com http://www.yahoo.com http://www.bing.com

Also, notice that closing
 with
 is not proper XML but somehow MySQL ignored it.

A: As per the @Barmar suggestion, i searched in google and got 1 solution.
user defined functions for PREG.(Perl Compatible Regular Expressions)
http://www.mysqludf.org/
https://github.com/mysqludf/lib_mysqludf_preg#readme
All functions seems good and we can apply regular expression as like any other language (Perl, PHP etc)
NOTE: But it requires, c++ program compilation and installation to mysql


text:
Q: Order of negated comparison I want to form a sentence to describe this image.

In Russian the entire sentence is: "Мозги даны человеку не для истерики, а для того, чтобы смеяться". I want to say the same in English.
I've made a few variants but I don't know which of them is/are correct:

*

*Brain was given to man to laugh, not to get hysterical.

*Brain was given to man to laugh, instead to get hysterical.

*Brain was given to man not to get hysterical, but to laugh.

*Brain wasn't given to man to get hysterical, but to laugh.

I think the first one is correct. I think it is featuring obvious opposition of laugh and hysteria. In the second sentence, in my view, there is something negative (like it was said in a fight). I like the word order in the first sentence more than in the third.

A: Reference
http://www.dictionary.com
https://www.grammarly.com/blog/articles/
http://www.english-grammar-revolution.com/sentence-fragments.html
laugh (verb): to express mirth, pleasure, derision, or nervousness with an audible, vocal expulsion of air from the lungs
hysteria (noun): an uncontrollable outburst of emotion or fear, often characterized by irrationality, laughter, weeping
hysterical (adjective): of, relating to, or characterized by hysteria
Options
All are mostly grammatically correct but all differ significantly in meaning.  I take it that the original sentence is attempting to express the juxtaposition and contrast of laughter and the extreme expression of hysteria.  In which case:

*

*Brain was given to man to laugh, not to get hysterical.

The indefinite article indicates that a noun refers to a general idea rather than a particular thing.
"Brain was given to man" doesn't read right, "brain" should be used with an article and referred to as "a brain".
Also, the subject is missing, a human doesn't get "given" a brain like one would be given a birthday present, it reads better like "God gave man a brain" or "man biologically evolved a brain".  In this context the correct structure would be something like "A brain was bestowed upon man" or "Man was granted a brain".  You could say "man was given a brain (by a god or creation origin concept)".
Then with the second part, hysterical is an adjective that describes man, hysteria is a noun.  The tricky part is that the comparison needs to be made between a verb and an adjective so I think "to laugh" and "to get hysterical" is fine and works.

*Brain was given to man to laugh, instead to get hysterical.

Should be "instead of" and then the adjective becomes "instead of getting hysterical" or "instead of becoming hysterical" or even "instead of reaching hysteria". This suggests mutual exclusivity, that is, man can either laugh or "instead" get hysterical.  Laughter may lead to hysteria and hysteria may involve laughter so I don't think it is right to imply that man can do one OR the other.

*Brain was given to man not to get hysterical, but to laugh.

"A brain" was not solely given to man to laugh, this is how the sentence reads.

*Brain wasn't given to man to get hysterical, but to laugh.

"Was not given" and "not to get" has the same meaning, sentences 3 and 4 convey the same meaning.
Choice.
If I was writing this in English from scratch I would use something like:

*

*Man was given a brain to laugh, not to become hysterical

*Man was granted sentience for the purpose of laughter, not hysteria

*Man was not given a brain to become hysterical, but merely to laugh

*Man was granted consciousness to laugh and not to be plagued with hysteria

*A brain was not bestowed upon man for hysteria, but for laughter

*A brain was given to man for laughter, not hysteria

*A brain was given to man for laughter, not to become hysterical

*A brain was given to man to laugh, not to become hysterical

*A brain was not given to man to become hysterical, but simply to laugh

*Man has a brain so that excitement can be controlled


text:
Q: How to Enable Permissions on Discussions (Comments) in Custom Portlet in Liferay I realize this question has been asked before but there doesn't seem to be a complete answer so I'll ask with specifics and what has been tried. It has also been asked many times in other forums with either no answers or very incomplete with few details.
I have been able to add Comments (Discussions) to my custom portlet using the 'liferay-ui:discussion' taglib in Liferay 6.1.20 After searching around I have finally got it to work using the following setup:
JSP Page
<portlet:actionURL
            var="discussionURL"
            name="addDiscussion"/>

        <liferay-ui:discussion
            className="<%= Announcement.class.getName() %>"
            classPK="<%= announcement.getPrimaryKey() %>"
            formAction="<%= discussionURL %>"
            formName="fm2"
            ratingsEnabled="<%= false %>"
            redirect="<%= currentURL %>"
            subject="<%= announcement.getHeadline() %>"
            userId="<%= themeDisplay.getUserId() %>"
        />

Portlet Class
Note: Class extends MVCPortlet
public void addDiscussion(ActionRequest actionRequest, ActionResponse actionResponse){
    try {
        //invokeTaglibDiscussion(actionRequest, actionResponse);
        PortletActionInvoker.processAction("com.liferay.portlet.messageboards.action.EditDiscussionAction", null, actionRequest, actionResponse);
    } catch (Exception e) {
        _log.error("There was an Error adding a comment to the Announcement");
    }
}

Since class extends MVCPortlet I tried using the invokeTagLibDiscussion but no change in permission results. This came from the book Liferay In Action (which is a great source of information). So I tried using the PortletActionInvoker.processAction method as mentioned in a number of articles.
Question
So, now that I have a working Discussion added to my custom portlet, it turns out that anyone can edit any other individual's previous comments. Obviously I can't launch a portlet with that security issue. Again researching further, I found the following 'answers'...

*

*Add Permissions to the resource-actions file Add Permissions. This seemed the most promising since it made total sense that the Liferay code would utilize the permission system in this manner. What I find interesting is why no tutorials/boods on this topic mention using the DELETE_DISCUSSION and UPDATE_DISCUSSION permissions. (ie. Liferay Wiki Article) Either way, this didn't resolve my issue even when the owner of this question indicates it did for them.

*Another posted 'answer' indicated to 'just add the permission to the specific role' in the control panel. Not only did they not provide any details as how to accomplish this, but it didn't make any sense since those permission actions wouldn't be in the portlet.

Any assistance would be greatly appreciated as this is the final component to my custom portlet project that is hindering me getting it released to my user group.
Thanks in advance.


text:
Q: Convert bash script to Perl or Python I have a bash script which greps numeric values from the log files, but it consumes server resources and the server is becoming overloaded. I want to write the same script in Perl or Python. The log file size is approx 1GB and the script needs to run on a daily basis.
while read  i
do
egrep -h $i  /opt/logs/oc-resizer.log  >> /opt/logs/purge-resizer.tmp
done  < /opt/nasa/shahid/logo.csv

A: Just reduce your script to this:
#!/bin/bash
egrep -f /opt/nasa/shahid/logo.csv /opt/logs/oc-resizer.log \
              >> /opt/logs/purge-resizer.tmp

It will be a lot faster. It will be even faster – if you are searching fixed strings and not patterns – using fgrep instead of egrep:
fgrep -f /opt/nasa/shahid/logo.csv /opt/logs/oc-resizer.log \
              >> /opt/logs/purge-resizer.tmp

See man grep for details.
I don't think that perl or python can get faster that this.


text:
Q: Work with SQL Server accounts (2005 & 2008) I'm writing a MVC application which has to use SQL Server accounts to authenticate. I want to use MembershipProvider, RoleProvider and PrincipalProvider for doing that (that's here: MVC3 - Authenticate with SQL Server Accounts).
Now my question is: how do I work with SQL Server accounts to authenticate against via C#? I don't know where to start and how complicated that is (together with MVC3). Could someone provide an example?
Thanks in advance.

A: The way your ASP.NET application will talk to the database will be through database logins/users.  On SQL Server you will create a login as such:
create login YourWebLogin with password = 'p@ssw0rd'
go

That is a basic login that can really do nothing (research server permissions here).  Then you'd create a SQL Server user off of this login, like so:
use YourASPNETDb
go

create user YourWebUser for login YourWebLogin
go

Now you have the security context to access YourASPNETDb with a SQL Server user, through the context of a SQL Server login.  (research database permissions here)
Your ASP.NET MVC application will access the database through your login/user, and this connection information will be stored in a connection string.  This is a typical SQL Server connection string:
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Your Membership/Role Providers will utilize this connection string with your correct credentials to gain access to your database.
This is just a high-level view of how everything works together.  There are a few moving parts, but this should get you started.


text:
Q: MP4Box comparing to Qt-faststart Since I have no idea about qt-faststart (and a little with MP4Box) are there any online resources about them(haven't found much)? Which is better? What about their differences?
Especially if i want to create hinted video files for android devices, which one is the best?

A: One is a single purpose tool, one is a virtual tool chest of gadgets.

*

*qt-faststart: Single purpose: Move the MOOV atom.  That's it, nothing else.  Small (13kb executable on OSX) easy to compile.

*MP4Box: Larger (~2500 KB) and capable of oh-so-much-more.  From the documentation:

MP4Box is a multimedia packager, with
  a vast number of functionalities:
  conversion, splitting, hinting,
  dumping and others

A: Your question is a bit ambiguous:

*

*"hinted video files" refer to the notion of "hint tracks" used by streaming servers (such as Apple's old Darwin Streaming Servers) to form RTP packets from media tracks (audio, video ...). There is nothing specific to Android here. Anyway, MP4Box can be used for producing the hint tracks, using commands like:
MP4Box -hint file.mp4

*What qt-faststart does is reorder the boxes in the file to help progressive download and playback of the file. It is not at all related to hinting. MP4Box can also be used to change the order of the boxes and to control the interleaving of the payload of the different tracks (audio, video, subtitles ...) using:
MP4Box -inter 500 file.mp4

for an interleaving window of 500 ms.


text:
Q: Using hash function for fast image duplication prevention I develop website where people can upload images for using as textures.
I want to limit pressure on web-server by avoiding storing the same image twice.
As users can upload images very often I want to have a very fast technique to identify is uploaded image have a copy on web server and if it has when discard it and use already existing image.
Is it ok to use hash function for this task if I can accept possibility of different images having the same hash below 1e-5? What hash function is better suitable for my task?


text:
Q: Reading a file and passing parameters to other shell scripts line by line So, I am trying to automatize the creation of a user using bash script. I have the script below:
#!/bin/bash

cd /tmp/new/

cat autoid`date +%Y%m%d`.csv | grep "THING" | grep "4B"
while read -r line;
        do
                name=$(awk -F';' '{print $10}' | awk -F' ' '{print $1}')
                surname=$(awk -F';' '{print $10}'|awk '{for (i=2; i<NF; i++) printf $i " "; print $NF}')
                userid=$(awk -F';' '{print $8}')
                bash new_user.sh $userid $name $surname
                sleep 1
                bash basic_access.sh C $userid
                sleep 1
        done

The thing is I'm a bit confused here. I'm testing the command using echo in the place of calling the other bash scripts and it isn't returning me anything but the output of the "cat autoiddate +%Y%m%d.csv | grep "THING" | grep "4B"" line. Tried to pipeline the end of this line to while loop but it isn't working anyway.
What am I doing wrong here?

A: You need to pipe the output to the while loop. The variable line should be piped separately to each awk process (to fix your immediate problem; keep reading for a better solution):
#!/bin/bash

cd /tmp/new/

cat autoid`date +%Y%m%d`.csv | grep "THING" | grep "4B" |
  while read -r line;
        do
                name=$(echo "$line" | awk -F';' '{print $10}' | awk -F' ' '{print $1}')
                surname=$(echo "$line" | awk -F';' '{print $10}'|awk '{for (i=2; i<NF; i++) printf $i " "; print $NF}')
                userid=$(echo "$line" | awk -F';' '{print $8}')
                bash new_user.sh $userid $name $surname
                sleep 1
                bash basic_access.sh C $userid
                sleep 1
        done

However, repeatedly calling awk to get a single field is inefficient. Let read do the splitting. (Included are other miscellaneous fixes and improvements.)
grep "THING" "autoid$(date +%Y%m%d).csv" | grep "4B" |
  while IFS=";" read -ra fields; do
    read name surname <<< "${fields[9]}"
    userid=${fields[7]}
    bash new_user.sh "$userid" "$name" "$surname"
    sleep 1
    bash basic_access.sh C "$userid"
    sleep 1
 done


text:
Q: Comparator TLV3201 Output never goes high I've put together the circuit from the TI document Comparator with Hysteresis Reference Design using the same reference voltage to the noninverting input (Vth 2.3V - 2.7V).  The Inverting input is connected to a voltage divider that depends on a thermistor, but for testing just a potentiometer.
I can confirm that the initial threshold voltage is 2.3V, and that the Power(5V) and GND are correct at pins 5 & 2.  When I sweep the inverting input past the threshold voltages, the output never changes from GND.
Ultimately this output is driving the base of an NPN transistor to power a relay, but again, I never get 5V on the output.  I actually pulled the first TLV3201 off the board and replaced it, but same issue.
What stupidity have I done?

EDIT - Reference circuit included for clarity.
EDIT2 - There is a low impedance path from the U2.1 (comparator output) to GND.  Even on a number of blank boards.  The board was not designed as such, but I measure 0.1 Ohms between those two pins.  See the board image below. The output net is not directly grounded, the only way to GND is supposed to be via R2 + R3 (100K + 576K).

A: Assertions:

*

*There is a false assumption in your BJT calculation for hFE.

*

*The hFE applies in the linear region and not the saturated region as a switch. You should not choose a base current, Ib, less than 10% of this expected Ic/hFE min or use the rated Ic/Ib ratio for Vce(sat) which is 20:1 implied from the tables.  It is not coincidental, that the B rank hFE= 200 minimum but you must choose a base current of 70 mA/20 = 3.5 mA and thus Rb max= 4.3V/3.5mA = 1.23k max.

*There is a short on the board or both IC's you have tested have been damaged as all IC's are 100% tested.

*

*Exceeding the do not exceed by any method such as ESD handling damage or DO Not Exceed thresholds exceeded.

*There should also be an observable voltage change from 0V output as the curves for this CMOS Op Amp indicate an RdsOn at room temp (25'C) of 35 Ohms. Thus you can expect and IR drop from the push-pull CMOS drain  outputs.

*Re-read all the datasheet parameters until understood.
Suggested:

*

*check for a short on board.

*Measure Resistance with power off between gnd. and Output. It must not be low resistance.  The DMM current will not exceed the device tolerance of 10 mA for ESD diodes.

A: Measure the voltage at pin 4 and make sure it actually goes below the threshold.
If you just have a potentiometer connected between 5V and the input with no path to ground the input voltage will not change enough to trip the comparator.


text:
Q: Regex pattern to replace and disable href links I need to disable a link tags (whose href attribute value starts with log.html) in my html table. I am trying to use string replace to do.
The code line looks approximately like this, str.replace(/log.html...../g,'') where there must be a regex pattern in the place of dots.
All patterns like this,

must be made as,

A: You can use the following to match:
/log.html#[^"]*/g

And replace with #
Code:
str.replace(/log.html#[^"]*/g,'#')

See DEMO

A: What you are looking for is string.match(). This function returns an array of the match and any captured groups. You could test all your links with something like this:
$('a').each(function() {
    href = $(this).attr("href");
    if(href.match(/^log\.html/)) {
        $(this).attr("href", "#");
    }
});

Fiddle

A: This regex pattern seems to work given that the url is accessable as a string. This can easily be accomplished with jQuery.
 str.replace(/log\.html.*/g,'#')

A: Since href and ".." are always available in a link, i would use a simple
/href=".+"/g

DEMO


text:
Q: Converting from scala.collection.immutable.List to a java.util.List in java I'm currently working within a java runtime google cloud dataflow. The scala sdk I'm using shows the property I'm working with as an immutable list: https://github.com/snowplow/snowplow-scala-analytics-sdk/blob/master/src/main/scala/com.snowplowanalytics.snowplow.analytics.scalasdk/Event.scala#L91
final List<SelfDescribingData> contexts
Does anyone have any pointers on how to properly cast / convert this to a Java list? Most of the examples I have found are doing this in the Scala runtime vs the Java runtime.
I had thought the JavaConverters package would help me here, however these methods don't seem to be expecting an immutable scala list.
Where e in the example below is an instance of the Event in the linked sdk.
List<SelfDescribingData<Json>> list = JavaConverters.asScalaBufferConverter(e.contexts()).asScala().toList();
for (SelfDescribingData<Json> t : list) {
    LOG.info(t.toString());
}

A: JavaConverters.asScalaBufferConverter:

Adds an asScala method that implicitly converts a Java List to a Scala mutable Buffer

To convert a scala.collection.immutable.List, which is a subtype of scala.collection.immutable.Seq and scala.collection.Seq to a java.util.List you would call JavaConverters.asJava:
java.util.List<SelfDescribingData<Json>> list = JavaConverters.asJava(e.contexts().data())

The code I've posted is after the Scala 2.13 collection rewrite.  For older versions of Scala, the equivalent function is JavaConverters.seqAsJavaList


text:
Q: WordPress - functions.php causing WordPress error I have the following folder structure for my theme:
theme
   inc
      theme
         functions.php
      init.php
   functions.php

In inc/theme/functions.php, I'm placing all theme specific functions (i.e. removing taxonomies etc). In theme/functions.php, I have all my core functions.
With my current code, WordPress states "The site is experiencing technical difficulties.". If I delete everything in theme/functions.php, the content loads, but the code in inc/theme/functions.php is not being executed. For example, in inc/theme/functions.php, I have wp_enqueue_style( 'style', get_stylesheet_uri() ); and none of the styles are pulling through.
Can't seem to figure out:

*

*Why theme/functions.php is causing a WordPress error.

*Why inc/theme/functions.php is not being executed.

theme/functions.php
<?php

require_once trailingslashit( get_template_directory() ) . 'inc/init.php';

new theme_ThemeFunctions;
class theme_ThemeFunctions {

    function __construct() {
        load_theme_textdomain( 'theme' );
        add_action( 'init', array( $this, 'post_types_taxonomies' ) );
        add_action( 'init', array( $this, 'register_menus' ) );
    }

    public function post_types_taxonomies() {
        register_post_type(
            'case-studies',
            build_post_args(
                 'case-study', 'Case study', 'Case studies',
                 array(
                    'menu_icon'     => 'dashicons-book',
                    'menu_position' => 20,
                    'has_archive'   => true
                 )
            )
        );
    }

    public function register_menus() {
        register_nav_menus(
            array(
                'main'   => __( 'Main Menu', 'theme' ),
            )
        );
    }

}

?>

inc/theme/functions.php
<?php

function scriptAndStyles() {
    wp_enqueue_style( 'style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'scriptAndStyles' );

function remove_editor() {
  remove_post_type_support('page', 'editor');
}
add_action('admin_init', 'remove_editor');

// Remove featured image option from pages
function remove_thumbnail_box() {
    remove_meta_box( 'postimagediv','page', 'side' );
}
add_action('do_meta_boxes', 'remove_thumbnail_box');

// Remove posts type option
function post_remove () {
   remove_menu_page('edit.php');
}
add_action('admin_menu', 'post_remove');

?>

inc/init.php
<?php

$include_dir = trailingslashit( get_template_directory() ) . 'inc/';

// Load any custom functions
require_once $include_dir . 'theme/functions.php';

?>

A: You need use get_template_directory() for require your files.
And use new theme_ThemeFunctions below class itself.
Also use to view errors:
define('WP_DEBUG', 1);
define('WP_DEBUG_DISPLAY', 1);


text:
Q: Is GCC (Google Congestion Control) implemented in WebRTC? I was doing some reading on GCC (https://datatracker.ietf.org/doc/html/draft-ietf-rmcat-gcc-02) but was unable to find if this was actually implemented in WebRTC.
Would someone be able to verify or point me in the right direction?

A: It is implemented here:
https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/modules/congestion_controller/?q=congestion_controller
The details have changed a bit since the draft was written but you'll find many of the elements described here in the goog_cc directory.

A: AFAIK yes, it was used in WebRTC. Search for REMB in WebRTC.
Currently transport wide congestion control is considered a better approach. See please this blog post for details http://www.rtcbits.com/2017/01/bandwidth-estimation-in-webrtc-and-new.html


text:
Q: Trouble with responsivitizing my twentythirteen header I'm using the twentythirteen theme and trying to get the header to adapt to screen resolution.
I've uploaded several image files with the required resolutions, and changed my custom-header.php source code according to what is suggested here.
The website, www.ensemblepourviroflay.org/wp/ (can't link more than twice with newbie account), does not seem to be displaying any of the images, at whichever resolution. I have pasted the content of my custom-header.php file here.
I would appreciate it if a kind stranger would have a look.

A: I think the paths to your images specified in custom-header.php aren't correct. You can use home_url() to specify this path if necessary, eg


text:
Q: Availability of deprecated egrep and fgrep commands Quite often I've seen answers mentioning that egrep is grep -E or fgrep is grep -F and using egrep or fgrep in their answers, even though these are technically deprecated.
So I was wondering if there were particular examples of modern(ish) unix-like systems which don't provide this link between the sets of commands. For example, the GNU grep manual contains

In addition, two variant programs egrep and fgrep are available. egrep
  is the same as 'grep -E'. fgrep is the same as 'grep -F'. Direct
  invocation as either egrep or fgrep is deprecated, but is provided to
  allow historical applications that rely on them to run unmodified.

while FreeBSD has

In addition, two  variant programs egrep and fgrep are available.
  egrep is  the same  as grep -E.  fgrep is the same as grep -F.

It would be good to know that a script wouldn't necessarily work everywhere, even with the fact that egrep or fgrep could be removed tomorrow.

A: I don't think there are any systems that explicitly don't have them (but I don't have any modern comercial UNIX systems to look at right now, just open-source systems), but there are quite a few where they are just stubs that call regular grep with the appropriate option.
For example, on Gentoo Linux, /bin/egrep is this shell script:
#!/bin/sh
exec grep -E "$@"

And /bin/fgrep is essentially the same.  I've also seen some systems where egrep and fgrep are just symbolic links or hard links to grep, but I have never seen one where neither of them eisted.
Note however that while egrep and fgrep are deprecated, they're almost certainly not going away any time soon.  A quick scan of scripts in /usr on my laptop (which is running Gentoo Linux) finds a few dozen software packages that have scripts which use one or the other, including such ubiquitous things as Python and GCC.
Given all this, one can rather ironically conclude that code that uses the deprecated commands instead of the options is actually more portable than code which uses the options, since it will run on older systems that code using the options won't.


text:
Q: loading loose XAML drawing securely A C# Windows application would like to load vector drawings that are stored in loose XAML files without allowing arbitrary code execution.
I am already loading such drawings from resources in linked assemblies over which I have control. However, I would like to also support loading loose XAML files.  I imagine you can use XAML access control to limit the objects that can be instantiated in such XAML?  Ideally, I would limit the loader to instantiating only the drawing primitives that are in the files we know about.  It's ok that it would reject a file that has new drawing primitives in it that we have not whitelisted.
Is this a standard thing already supported by an API?  Because I could not find it.  Otherwise, does anyone have an example or beginnings of an example?  This is for a free open source project and any help getting started would probably cut down the research I need to do by a lot.

A: The following seems to do a pretty decent job of white listing specific types in a XAML load:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Controls;
using System.Windows.Media;
using System.Xaml;
using System.Xml;

namespace TestXamlLoading
{
    internal class SchemaContext : XamlSchemaContext
    {
        // map from XAML element name to required namespace (currently always the same)
        private static readonly Dictionary<string, string> AllowedTypes = new Dictionary<string, string>();

        static SchemaContext()
        {
            // questionable: <Image> is used in some drawing XAML, should review it
            foreach (string name in new[]
            {
                "Canvas", "Compound", "Ellipse", "GradientStop", "GradientStopCollection", "Group", "Line",
                "LinearGradientBrush", "MatrixTransform", "Path", "PathGeometry", "Polygon",
                "RadialGradientBrush", "Rectangle", "RotateTransform", "ScaleTransform", "SkewTransform", "TextBlock",
                "TransformGroup", "TranslateTransform"
            })
            {
                AllowedTypes[name] = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
            }
        }

        public SchemaContext(IEnumerable<Assembly> referenceAssemblies, XamlSchemaContextSettings settings) : base(
            referenceAssemblies, settings)
        {
            // no code
        }

        protected override XamlType GetXamlType(string xamlNamespace, string name, params XamlType[] typeArguments)
        {
            if (!AllowedTypes.TryGetValue(name, out string requiredNamespace) || xamlNamespace != requiredNamespace)
            {
                throw new Exception($"disallowed instantiation of '{xamlNamespace}' '{name}' from XAML");
            }

            return base.GetXamlType(xamlNamespace, name, typeArguments);
        }
    }

    internal class Program
    {
        [STAThreadAttribute]
        private static void Main(string[] args)
        {
            bool shouldFail = TestLoad("..\\..\\..\\badfile.xaml");
            Debug.Assert(!shouldFail);
            bool shouldSucceed = TestLoad("..\\..\\..\\goodfile.xaml");
            Debug.Assert(shouldSucceed);
        }

        private static bool TestLoad(string path)
        {
            Stream inputStream = new FileStream(path, FileMode.Open);
            XmlReader xmlReader = new XmlTextReader(inputStream);
            Assembly[] referenceAssemblies =
            {
                // these are two separate assemblies which contain all the types we allow
                Assembly.GetAssembly(typeof(Canvas)),
                Assembly.GetAssembly(typeof(TransformGroup))
            };
            XamlSchemaContextSettings settings = new XamlSchemaContextSettings();
            XamlSchemaContext schemaContext = new SchemaContext(referenceAssemblies, settings);
            try
            {
                XamlReader reader = new XamlXmlReader(xmlReader, schemaContext);
                Canvas canvas = (Canvas) System.Windows.Markup.XamlReader.Load(reader);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                return false;
            }

            return true;
        }
    }
}


text:
Q: Contractibility of the sphere and Stiefel manifolds of a separable Hilbert space Why are the sphere $$S=\lbrace |x|=1\rbrace$$ and the Stieffel manifolds of orthonormal $n$-frames $$V_n=\lbrace (x_1,\dots,x_n)\in S^n\mid i\neq j\Rightarrow\langle x_i|x_j\rangle=0\rbrace$$ of a infinite dimensional separable Hilbert space $\mathscr{H}$ contractible? I've read a proof of this about a year ago, but I can't find it, and I don't remember the argument.

A: Let $\mathscr H$ be an infinite dimensional Hilbert space. Let us write
$$\mathscr{V}_p=\{\text{all linearly independent }x_\bullet=(x_1,\dots,x_p)\in\mathscr{H}^p\}$$
and
$$\mathscr{V}_p^\perp=\{\text{all orthonormal }x_\bullet=(x_1,\dots,x_p)\in\mathscr{H}^p\}$$ The Gram-Schmidt orthonormalization process induces a retraction of $\mathscr{V}_p^\perp\hookrightarrow \mathscr{V}_p$. Affine interpolation between $x_\bullet$ and its Gram-Schmidtization $\widetilde{x_\bullet}=\mathrm{GS}(x_\bullet)$ produces for every $t\in[0,1]$ a linearly independent family $(1-t)x_\bullet+t\widetilde{x_\bullet}$. Thus, the inclusion $\mathscr{V}_p^\perp\hookrightarrow \mathscr{V}_p$ is a deformation retraction and it is enough to prove that $\mathscr{V}_p$ is contractible.

Let $(e_n)_{n \in \mathbb N}$ be an orthonormal family in $\mathscr{H}$. Define a linear isometry $T$ of $\mathscr H$ by setting
$$\begin{cases}
\forall n\in\mathbb N,&Te_n=e_{n+1}\\
\forall v\in V,& Tv=v
\end{cases}$$
where we put $V=\overline{\langle e_n\rangle}^\perp_{n\in\Bbb{N}}$.

Fact. Let $x_\bullet\in\mathscr{V}_p$ be free, $a,b\in \mathbb R$ with $a+b\neq0$, then $ax_\bullet +bT^px_\bullet$ is also free.

This follows immediately from the fact that $x$ and $T^p x$ are collinear iff $x\in V$ in which case $T^p x=x$.

We define a homotopy $H$ from $\mathrm{id}_{\mathscr{V}_p}$ to the constant map equal to $e_\bullet:=(e_1,\dots ,e_p)$.
$$
H:
\left\{
\begin{array}{ccc}
[0,2]\times \mathscr{V}_p & \longrightarrow & \mathscr{V}_p,\\
(t,x_\bullet) & \longmapsto &
\begin{cases}
0\leq t\leq 1:&
(1-t)x_\bullet+tT^px_\bullet\\
1\leq t\leq 2:&
(2-t)T^px_\bullet+(t-1)e_\bullet
\end{cases}
\end{array}
\right.$$
The fact quoted above means that $H$ is well-defined for $0\leq t\leq 1$. This map is still well-defined for $1 < t \leq 2$ since for $t>1$ the orthogonal projection of $(2-t)T^px_\bullet+(t-1)e_\bullet$ onto the span of $e_1,\dots,e_p$ is $(t-1)e_\bullet$ thus free.
Thus $\mathscr{V}_p$ is contractible and so is $\mathscr{V}_p^\perp$.