text:
Q: What is access control of an Amazon EC2 instance like if people purchase AMI from marketplace? I'm new to the Amazon EC2 platform and marketplace, so I need some help with the questions I have.
Currently our company is trying to create a customized Linux AMI to put into marketplace, and I'm responsible for setting up the whole thing. I'm not quite sure about the following things when customers load one new instance:

*

*Do they have the access to the Linux system that we pre-configured when they get the instance? I assume "no" because they need the private key to SSH but only I have the key. Please let me know otherwise.

*How is the security group applied for the new instance? Are the customers responsible for setting up the firewall rules or is the security group bound to the instance when I create the AMI?

*By default the instance does not have any public IP addresses, and currently I have to manually fetch an Elastic IP address and hook it to the instance. Is this the responsibility of the customer when they load an instance?

A:
Do they have the access to the Linux system that we pre-configured when they get the instance? I assume "no" because they need the private key to SSH but only I have the key. Please let me know otherwise.

Yes they do.  Amazon will reject your submission to the marketplace if you embed any SSH keys into the AMI so you cannot use your own.  The users' own keys will get added to the instance when it's launched.

How is the security group applied for the new instance? Are the customers responsible for setting up the firewall rules or is the security group bound to the instance when I create the AMI?

Security groups are applied to instances, not AMIs.  So the customer would be responsible for setting this up.  However, if your application requires a specific security group configuration, you may wish to distribute a CloudFormation template with your AMI that makes it easier for the customer to set everything up correctly.

By default the instance does not have any public IP addresses, and currently I have to manually fetch an Elastic IP address and hook it to the instance. Is this the responsibility of the customer when they load an instance?

Yes, it's the customers' responsibility.  However, a CloudFormation template could help here as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: No Recently Viewed Records In Lookup A custom object Payment_History__c has a Lookup field to the standard Order object.

There is no lookup filter for the field.

But when I click on the "magnifying glass" icon
I don't see any Recently Viewed Orders in the lookup search window despite the fact they exist and were viewed a few minutes earlier.

However, if I search by an Order number, it will return that Order.

I looked everywhere:
Lookup field filter does not work on record creation
Considerations for Lookup Filters
Lookup do not show records
But still I cannot figure out why it doesn't return Recently Viewed Orders. I am logged in as System Administrator and there is nothing wrong with sharing settings. There are other lookup fields on the custom object Payment_History__c which work just fine.
Also I checked Setup > Customize > Search > Search Settings and the Number of Search Results Displayed Per Object for Orders is 25, which is more than enough


text:
Q: PHPlot drawing only chosen records im doing a plot of my measured temperature. I thought it would be nice to use phplot to draw the plot for the temperature for example in last day. But phplot draws every single record from base. Is there any option to set something like phplot could every tenth record?
The code i use is simple:
<?php
//Include the code
require_once 'phplot/phplot.php';

//Define the object
$plot = new PHPlot(800,400);

//Set titles
$plot->SetTitle("Wykres temperatury od czasu");
$plot->SetXTitle('Data');
$plot->SetYTitle('Temperatura');

mysql_connect("", "", "");
mysql_select_db("");
$query = mysql_query("SELECT data,temperatura FROM arduino ORDER BY data DESC LIMIT 3");

$data = array();

while ($row = mysql_fetch_assoc($query)) {
    $data[] = $row;
}

$plot->SetDataValues($data);

//Turn off X axis ticks and labels because they get in the way:
$plot->SetXTickLabelPos('none');
$plot->SetXTickPos('none');

//Draw it
$plot->DrawGraph();
?>


text:
Q: Merging these files Having a sets of matched files in a folder, the name of each pair of files is like this with a basename, for instance
LP6005334-DNA_H01_vs_LP6005333-DNA_H01.passed.somatic.indels.vcf.parsed.txt

and
LP6005334-DNA_H01_vs_LP6005333-DNA_H01.passed.somatic.indels.vcf_fixed_vcf.txt.hg19_multianno.txt

How I can extract columns 5th and 6th from files with passed.somatic.indels.vcf.parsed in their file name and append these columns to the matched file (passed.somatic.indels.vcf_fixed_vcf.txt.hg19_multianno) returning an output .txt with the basename (LP6005334-DNA_H01_vs_LP6005333-DNA_H01)
For cutting the columns I done
[
fi1d18@cyan01 folder]$ for f in *.passed.somatic.indels.vcf.parsed.txt; do awk '{print $5,$6}' $f > $out
> done;
-bash: $out: ambiguous redirect

Hereafter I don't know how to find the matched find and append the cut columns to that
This is the link of a pair of these files
https://www.dropbox.com/s/y4jx1rznswqz6dq/LP6008460-DNA_G03_vs_LP6008340-DNA_C05__pv.1.7__rg.grch37_g1k__al.bwa_mem__.passed.somatic.indels.vcf_fixed_vcf.txt.hg19_multianno.txt?dl=0
and

A: It depends how your files are delimited, but you should be able to use something like
for f in *.vcf.parsed.txt; do
  cut -f3,4 "$f" | paste "${f%.parsed.txt}_fixed_vcf.txt.hg19_multianno.txt" - > "${f%%.*}.txt"
done

The expansions ${f%.parsed.txt} and ${f%%.*} remove, respectively, the shortest and longest "dot suffixes" from the looped filename.

For the file pair
LP6008336-DNA_H02_vs_LP6008333-DNA_H02.snp.pass.txt
LP6008336-DNA_H02_vs_LP6008333-DNA_H02.snp.pass.txt.hg19_multianno.txt

which don't conform to the naming convention in your original question, you will need to change the pattern matches accordingly
ex.
for f in *.pass.txt; do
    cut -f60,61 "$f" | paste "$f.hg19_multianno.txt" - > "${f%%.*}.txt";
done


text:
Q: How to redirect a page from a View to a Controller in ASP.NET MVC 3? I'm using mvc3 with Razor Engine and I have a condition that when it's true should redirect automaticaly to another page sending an object as parameter. What I want to do is:

@if (cond > 10)
  {

Url.Action("Edit", product); //redirect in this line automaticaly to the action Edit sending the object as parameter
    }

Somebody knows if exist a Html.Helper that do this for me?
I mean redirect to a page like this: someHtmlHelper("myAction", "myController", myObject).
I tried do this using JavaScript and almost works, I just find some problems in url parameter. The Url.Action returns the symbol code instead the caracter for the special caracters. Like "&" instead "&".

@if (cond > 10)
  {
  var url = Url.Action("Edit", product);

var Url = '@url';
    location.href = Url;

  <}

The url result is:
http://localhost:4772/Product/Edit?ProductId=2234&Code=0020582&Name...
I will be injured if MVC3 doesn't has a single page redirect implemented.
So I need help.
Thanks.

A: The view isn't the appropriate place for that sort of logic.
Depending on your solution you should either:
A)  Check the condition in yor Controller, prior to returning the View, and redirect there like so:
if (cond >= 10)
    return RedirectToAction("ADifferentResult");

B)  Use partial views to conditionally RenderAction like:
@{
    if (cond > 10)
        Html.RenderAction("ADifferentResult");
    else
        Html.RenderAction("DefaultResult");
}

A: @if (cond > 10){@Html.ActionLink("Edit", "Product", new { ProductId = 2234, Code = 0020582 })}


text:
Q: Get rid of warning in templated method due to unsignedness I have found some templated code which at some point performs the following check:
template<class IntegralType>
void randomFunction(IntegralType t)
{
    ...
    if (t < 0)
    ...
}

The idea of the code is that t is of an integral type (either signed or unsigned). The code works just fine regardless of signedness, but the compiler issues a warning because in the case of an unsigned integer the check will always be true.
Is there a way in C++03 of modifying the code to get rid of the warning without suppressing it? I was thinking of checking the signedness of T somehow, don't know it it's possible.
I am aware of C++11's is_signed but I am not sure how it could be implemented in C++03.

A: With Tag dispatching and traits:
template <typename T>
bool is_negative(T t, std::true_type)
{
    return t < 0;
}
template <typename T>
bool is_negative(T t, std::false_type)
{
    return false;
}

template<class IntegralType>
void randomFunction(IntegralType t)
{
    ...
    if (is_negative(t, std::is_signed<IntegralType>::type())
    ...
}

std::is_signed can be implemented in C++03.

A: C++11 has is_signed and cppreference shows this as possible implementation:
namespace detail {
template<typename T,bool = std::is_arithmetic<T>::value>
struct is_signed : std::integral_constant<bool, T(-1) < T(0)> {};

template<typename T>
struct is_signed<T,false> : std::false_type {};
} // namespace detail

template<typename T>
struct is_signed : detail::is_signed<T>::type {};

The problem is that is_integral_constant is only available in C++11 too, however, this might a starting point for you to implement the same in C++03.

A: I've been looking for a solution for this problem for some time.
The best solution I've found was using the same idea as in this answer:
    if (!(t == 0 || t > 0))

which it may be a compiler-specific workaround but at least in g++ 4.4.7 the warning fades away.


text:
Q: Spring boot server using jetty is not forwarding to index.html by default when running in eclipse since spring-boot-starter-parent 2.1.12-RELEASE UPDATE:
This problem exists in jetty from 9.4.25.v20191220, i have set the version back to 9.4.24 it correctly serves. Whether this is a bug or change of configuration I don't know.
Maybe someone can help, i appreciate this is all configuration issues but I've only had this issue having upgrade spring-boot-starter-parent to 2.1.13-RELEASE from 2.1.10-RELEASE.
Using @SpringBootApplication and everything else default, except with the following WebMvcConfigurer (found in another post here)
@Configuration
public class WebApplicationConfiguration implements WebMvcConfigurer
{
    @Override
    public void addViewControllers(ViewControllerRegistry registry)
    {
        registry
            .addViewController("/{spring:\\w+}")
            .setViewName("forward:/");
        registry
            .addViewController("/**/{spring:\\w+}")
            .setViewName("forward:/");
        registry
            .addViewController("/{spring:\\w+}/**{spring:?!(\\.js|\\.css|\\.svg)$}")
            .setViewName("forward:/");
    }
}

Using Jetty, and with an angular project present at \src\resources\public\ including a index.html in the public directory.
In the previous spring version I could navigate to localhost:8080 and it would direct automatically to localhost:8080/list this is setup up as the redirect within the angular project index file.
But now using 2.1.13 i have to explicitly go to localhost:8080/index.html which does work, redirects to /list and i can navigate the website, but if i refresh the page or if i went explicitly to :8080/list i get whitelabel error 500
I've tried:
1.
Adding various other view controller rules:
registry.addViewController("/").setViewName("forward:/index.html");
registry.addViewController("/").setViewName("forward:index.html");
registry.addViewController("/**").setViewName("forward:index.html");
... But I don't think these are the problem anyway.
2.
Viewed ResourceHandlerRegistry to see the default resource locations, so it should pick up my index.html file.
3.
Adding spring.resources.static-locations=classpath:/public/xxx/**
I then get by going to localhost:8080/xxx/ or localhost:8080/xxx/index.html whitelabel 404
I upgraded spring due to security vulnerabilities, so currently tempted to go back to 2.1.10 or 11, and pull only the dependency versions required to mitigate vulnerabilities. I'd just like to understand what is going wrong, and obviously don't enjoy being defeated.
Does anyone know if there is changelogs for versions of spring that would shed any light to what has changed? I guess it could be due to any number of dependent projects though.

A: So it turns out that whatever the issue was it is fixed in jetty 9.4.27.v20200227.
Spring Boot releases from 2.1.10 contained new Jetty version for each release, with now release currently using 9.4.27.
Using spring boot 2.1.13-RELEASE with  9.4.27.v20200227, returns forwarding to what is expected with localhost:8080 loading /list


text:
Q: VB.NET How to Upload of user profile in Online Storage Hello I have a question. Right now I can upload user Avatar to database then the location will be saved in my Computer locally. So my question is  how do I make it globally? How can I upload and retrieve User profile Globally?

A: I did something similar in the past, years ago. Considering you code in VB.NET WinForms, it should be easy for you to do VB.NET web forms.
Get a cheap hosting to practice (Windows) or set a local IIS, post the file to a service, and the code below (which I used years ago) will allow you to upload a file to a remote server. This code goes on the SERVER SIDE:
Dim Files As HttpFileCollection
            Files = Request.Files
            Dim ext As String = System.IO.Path.GetExtension(Files(0).FileName)
            Dim FileName = "MyFileID" & ext
            Files(0).SaveAs(Server.MapPath("/avatars/" & FileName))

You will need to invest some time in learning how to work with web services. Also, you will need to integrate validations, otherwise anyone could POST to your service.


text:
Q: Reducing response latency for public API hosted behind CloudFront I am using a public API hosted behind CloudFront. I want to get the least possible latency.
I have done the following things so far:

*

*Hosted my code on EC2 in the same region as the API origin server. (I have a clue as to which region the origin server could be hosted in based on ping times)

*Tried pinging the API domain name from various availability zones within that region and identified the zone with least ping time.
However during my testing, I came across instances where ping time from my desktop was smaller than the ping time from my EC2 instance. So I had a look at what the CNAME & IP, the original API domain name was getting resolved to in each case. I found them to be different.
Is there something I can do to ensure that DNS resolution of CloudFront leads me to the lowest latency link.
I can use the CNAME or IP that I found to be the fastest during my testing. But that CNAME/IP may change so that's not a proper solution.
I think the answer could lie in a smart DNS client which pings all the servers in DNS file periodically and resolves DNS requests to the the fastest IP. However I don't know if any such client exists and how to use it if it does.
I would like to hear your ideas.

A:
Is there something I can do to ensure that DNS resolution of CloudFront leads me to the lowest latency link.

If you have your own domain name, you could try using Route53's latency record or Geoproximity routing


text: Q: Бег по стенам на Unity Хочу реализовать в своей игре на Unity возможность горизонтального бега по стенам. Может знает кто как можно это реализовать? Хочу чтоб сначало игрок немного поднимался вверх, а потом постепенно опускаться вниз, как это в общем то было в Принце Персии. Я старался реализовать с помощью controller.Move,но не могу разобраться с самим алгоритмом задуманного движения.


text:
Q: Flask server does not recognize my own imported module (ModuleNotFoundError) In my main Python file, I import another script of mine called helper_1.py (from the subfolder my_helpers) like this:
from my_helpers.helper_1 as h1

However, when I now try to start my server (or deploy it to Heroku), the server will crash with the error notice:
ModuleNotFoundError: No module named 'my_helpers'

I do have a Procfile, requirements.txt, runtime.txt, and wsgi.py.
The content of my wsgi.py is:
from app.main import app

if __name__ == "__main__":
        app.run()

MY QUESTION:
Where and how do I have to declare my custom modules (own scripts) so they are properly detected when starting the Flask server?
Everything works fine if I leave out the external reference to my custom module.

A: The folder my_helpers needs to be a package. To do this put an __init__.py file inside the my_helpers folder. This maybe fix your problem.


text:
Q: How to get s3 env files in aws sam with github action These days I research SAM(Serverless Application Model) to deploy my fastapi sample. However, I can't get the s3 env file. The sam cli command is below.
$ sam build --use-container
$ sam deploy

The point of error in the code is below.
content_object = boto3.resource('s3').Object('config', 'test.json')

In the local env, I can get the env file in the s3 bucket, but when I deploy with sam, the error has occurred like this.
[ERROR] ClientError: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied

How to solve this issue? Have any good sources for getting env files in SAM? I just want to make deploy in github action.

A: I have an issue that loads an env file with SAM (AWS Serverless Application Model) application(FastAPI). However, I can't load the env file in the python script since SAM env is different from Zappa (Zappa can env file with remote_env in the config file). So, I use the copy method in the GitHub action (workflow).


text:
Q: Pagination and Eager Loading in Laravel My Controller method is:

$topics=Topic::with(array('subtopics'=>function($query){
            $query->orderBy('glc_subtopic_priority','asc');
        }))->with('subtopics.resources')->find($id)->paginate(1);
        return View::make('subtopics.index')->with('topics', $topics);

I am eager loading this and it works fine. But now I want to paginate this. I have tried
{{ dd($topics->toArray()) }} and it returns me this:
array (size=7)
  'total' => int 2
  'per_page' => int 1
  'current_page' => int 1
  'last_page' => int 2
  'from' => int 1
  'to' => int 1
  'data' =>
    array (size=1)
      0 =>
        array (size=5)
          'id' => int 1
...........

The problem is when I am displaying the data. I am using
@foreach($topics->subtopics as $topic)

{{ $topics->glc_subtopic_name }}

        {{ $topic->glc_subtopic_content }}
        @foreach($topic->resources as $resource)

{{ $resource->glc_subtopic_resource_url }}
    @endforeach
@endforeach

This returns me the error:
Undefined property: Illuminate\Pagination\Paginator::$subtopics
How should I access the data in the paginated variable $topics.

A: If you need to specify the query for subtopics, you should eager load your resources models from within that query rather than eager loading subtopics again.
Try this:
$topics = Topic::with(['subtopics' => function($query){
    $query->with('resources')->orderBy('glc_subtopic_priority','asc');
}])->find($id)->paginate(1);

return View::make('subtopics.index', ['topics' => $topics]);


text:
Q: UICollectionView Cell flick with it's previous cell while scrolling horizontally, using SDWebImage Here is what happened:
There are 4 cells that fully displayed and 2 cells are half displayed. All of their image is downloaded and displayed. But when I scroll down, most of the cell will be flicked with it's previous cell. Below are my drawing (the "+" means it flick between them):

Here is my code
  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LoansCell", for: indexPath) as? LoansCell
        guard let offers = offerArr else {return cell!}
        cell?.imageView.image = nil
        cell?.imageView.sd_imageIndicator = SDWebImageProgressIndicator.default
        cell?.imageView.sd_cancelCurrentImageLoad()
        cell?.imageURL = URL(string: offers[indexPath.item].productImageUrl)
        cell!.terms = offers[indexPath.item].terms
        return cell!
    }

I even double remove the previous cell's image in prepareForReuse
class LoansCell: UICollectionViewCell {

    override func prepareForReuse() {
        super.prepareForReuse()
        imageView.sd_cancelCurrentImageLoad()
        imageView.image = nil
    }
}


text:
Q: how to import node module in html/javascript page? How to call my node module in HTML/Javascript page.
node.js page
exports.books = async (req, res) => {
const booksRef = db.collection('Books');
try{
        booksRef.get().then((snapshot) => {
        const data = snapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
    }));
        console.log(data);
        return res.status(201).json(data);
    })
} catch (error) {
    return res
    .status(500)
    .json({ general: "Something went wrong, please try again"});
}

};
home.html page
how to import/call node module books in HTML/javascript function
<script type="module" src="./module.js"></script>

function funs_del(a)
    {
        alert('start');
        **// call node module(books) here.......**
        alert('stop');

    }


text:
Q: If $ y \in [0,1] \times [0,1]$, is $[0,1] \times [0,1]-y$ connected? $(a)$ If $ y \in [0,1] \times [0,1]$, then prove/disprove that $[0,1] \times [0,1]-\{y\}$ is connected.
$(b)$ Hence, prove that a continuous, onto mapping $f :[0,1] \rightarrow [0,1] \times [0,1]$  can never be one-one
Attempt:

For part $(a) :$

I have a graphical situation in my mind.  $[0,1] \times [0,1]$ represents a square in $\mathbb R^2$. Hence, even if we remove a single point from this square, we get an arc connected structure.
But, how do we write a formal proof?

For part $(b)$ : Suppose $f$ is one-one and onto. Then $f^{-1}$ exists and is continuous.

Unfortunately, I don't have much idea on how to move forward. Please suggest me an approach.
Thank you for your help..

A: a) You nearly have the proof. Given two points in  $X=[0,1]\times [0,1]-\{y\}$, say $p_1=(a,b)$ and $p_2=(c,d)$, how would you connect them with an arc $\gamma:[0,1]\to X$? Well, if the removed point $y$ does not lie on the line connecting the two points, then $\gamma (t)=tp_1+(1-t)p_2$ works. Otherwise, you'll need to adapt the path a bit.
b) If a continuous and bijective function $f:[0,1]\to [0,1]\times [0,1]$ exists, then its restriction to $[0,1]-\{1/2\}$ would give you a continuous bijective function between the non-connected space $[0,1]-\{1/2\}$ and the connected space $X$ (for which $y$?). Why is that impossible?

A: Note: it is easy to connect any two points in this set with a continuous path. This shows that the space is connected.

A: Here is how you should think about connectivity in this setting:
Definition: A topological space $X$ is called path connected (or arc connected) if, given any $a, b \in X$,
there exists a continuous function $f:[0,1] \rightarrow X$ such that $f(0) = a$, $f(1) = b$.
Lemma: $[0,1]$ is connected.
Proposition: If $X$ is path connected, then $X$ is connected.
Sketch of proof: Assume $X$ is path connected but that there exists a separation of $X$, i.e. there are nonempty open sets $U$, $V$ in $X$ such that $U \cap V = \varnothing$, $U \cup V = X$.  Pick $a \in U$, $b \in V$, and find a path $f$ from $a$ to $b$.  Consider
$f^{-1}(U)$ and $f^{-1}(V)$ in $[0,1]$ and derive a contradiction of the lemma.
A warning: there do exist spaces that are connected but not path connected.  These tend to be rather pathological, though.


text:
Q: How do you move the taskbar entries around separately for one program in Windows 7? I often have a bunch of Chrome windows open in Windows 7, and what I would like is to move one window to the left of the taskbar, one in the middle, one at the right side, with the other programs that are open mixed in between the different Chrome windows. I have the windows ungrouped in the taskbar, so I can see each window separately.
However, when I try to drag one window, they all drag together. Is is possible to move them separately, one per window?

A: For those coming here for the same reason as the poster, I'd like to give my recommendation to
7+ Taskbar Tweaker
It is a versatile taskbar tool which lets you 'unstick' same applications on the taskbar along with many other features. My track record with 7+ Taskbar Tweaker is long, I've previously used it on Windows 7 and now on Windows 10 and it's still my favourite tool. It's consistently low-memory usage; as we speak, it's using 2.3mb.
It's many features are:

Disclaimer: I'm in no shape or form affiliated with the guy who makes it, I just think it's a niftly little tool.

A: From Windows Help topic "Rearrange icons on the taskbar":

"All open files from the same program are always grouped together,
  even if you didn't open them one after the other. This is so all
  previews for an open program can be viewed together at the same time."

So no, it is not possible to move them separately, without the use of some form of third-party software.
Actually, making multiple copies of Chrome.exe with different names might work, though you might have to tweak some other parameters of the file besides filename. If Windows doesn't know they're the same program, it won't group the icons. However, even if you did get this to work, it might also cause some unintended side effects with browser history, extensions, cookies, etc.


text:
Q: Is there possibility to load all rows of table to array in JTable of Joomla 2.5? I use Joomla 2.5 framework.
I have simple table such as:
int id
string itemid

Now I just want to load all 'itemid's to array using JTable. Is here possibility?

A: Everything about the JTable Class only deals with one row, as soon as multiple rows are involved, you have two options:
1) Use the solution you gave.
2) Override the load() function in your Table class. This can be done as under:
Put the following load() function in your Table class:
 function load($key = null)
    {

            $db = $this->getDBO();
            $query = $db->getQuery(true);
            $query->select($key);
            $query->from($this->getTableName());
            $db->setQuery($query);
            $row = $db->loadRowList();

             if ($db->getErrorNum())
             {
                $this->setError($db->getErrorMsg());
                return false;
             }

            // Check that we have a result.

            if (empty($row))
            {
                    return false;
            }

            //Return the array
            return $row;

    }

Now call the load() function with a single argument 'itemid', and get the array you want.
This worked for me, hope it helps you too.

A: Solution that I decided to use is inherit model class from JModelList:
class modelModelcomponent extends JModelList
{
        protected function getListQuery()
        {
            // Create a new query object.
            $db = JFactory::getDBO();
            $query = $db->getQuery(true);

            // Select some fields
            $query->select('itemid');

            // From the hello table
            $query->from('#__table');

            return $query;
        }
}


text:
Q: Send automated e-mail to new user aspx When someone registers on my website he/she also needs to fill in his/her e-mail address.
After clicking on the ''Register''-button the system needs to send an automated e-mail to the e-mail address which is written in the textbox.
Anyone who can help me with this?
Thanks in advance!

A: To send email in asp.net you will want to look into System.Net.Mail. There are two steps two send mail from within asp.net
1) Email Account Settings - This can be set up globally in your web.config file
<system.net>
    <mailSettings>
      <smtp from="test@foo.com">
        <network host="host" port="25" userName="username" password="password" defaultCredentials="true" />
      </smtp>
    </mailSettings>
  </system.net>

2) Setting up your message - In your register pages code behind
MailMessage message = new MailMessage();
message.From = new MailAddress("sender@sender.com");

message.To.Add(new MailAddress("email@email.com"));

message.Subject = "subject";
message.Body = "content";

SmtpClient client = new SmtpClient();
client.Send(message);

http://weblogs.asp.net/scottgu/archive/2005/12/10/432854.aspx

A: Here is a simple instruction on how to send e-mail from .NET code: http://weblogs.asp.net/scottgu/archive/2005/12/10/432854.aspx
The main keyword you are looking for is System.Net.Mail.

A: The following script is a good starting place.
           using (System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage()) {
               System.Text.StringBuilder body = new System.Text.StringBuilder("Your message");
               System.Net.Mail.SmtpClient() smtp = new System.Net.Mail.SmtpClient();
               mail.To.Add("yourUser@email.com");
               mail.From = new System.Net.Mail.MailAddress("yourFrom@email.com");
               mail.Subject = "a Subject";
               mail.Body = body.ToString();
               try {
                smtp.Send(mail);
                } catch (Exception ex) {
                       // handle your exception here..
                }
            }

This assumes that you have some details in your config about the SmtpClient. Like this: http://msdn.microsoft.com/en-us/library/ms164240.aspx
If not, then you can provide the details to the client in the SmtpClient() constuctor. More info on that here: http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx

A: Here is a simple function to implement. You have to get network credentials if not anonymous and SMTP info about your SMTP relay server. Otherwise it should be straight forward.
 using System.Net.Mail; //goes on top

 //goes in your class
 public void sendEmail(string emailMessage,
     string emailSubject,
     string emailAddress, string from,
     string fromAddress, string emailCC,
     string emailBCC)
    {
        try
        {
            MailMessage msg = new MailMessage();

            msg.From = new MailAddress(fromAddress, from);
            msg.To.Add(emailAddress);

            if (emailCC != null && emailCC.ToString().Length > 1)
                msg.CC.Add(emailCC);

            if (emailBCC != null && emailBCC.ToString().Length > 1)
                msg.Bcc.Add(emailBCC);

            msg.Priority = MailPriority.High;

            msg.Subject = emailSubject;
            msg.Body = emailMessage;
            msg.IsBodyHtml = true;

            SmtpClient client = new SmtpClient();
            client.Host = info.SMTPServer;
            client.Port = 25;
            client.EnableSsl = true;
            // client.UseDefaultCredentials = some System.Net.NetworkCredential var;
            client.Credentials = info.networkCredentials;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            // Use SendAsync to send the message asynchronously
            client.Send(msg);
        }
        catch
        {
            //handle exception
        }
    }

USAGE & Implementation:
        this.sendEmail("test message", "your subject", "to@to.com","from person", "from@from.com","cc@cc.com","bcc@bcc.com");


text:
Q: Elliptic binary mask I would like to create a binary mask of two vectors which are the coordinates of 50 point that make an ellipse.
e.g. caxy(50,1) and caxy(50,2) are my coordinated in the image by the pixel size of 1024x1280.
I have seen different approaches, but they are using (x,y) of the ellipse centre point and long and short radius. I know I could find these features from my vectors but I am looking for direct approach.
Any help would be appreciated.

A: After a day of challenging with the question, finally I have figured out the answer and wanna post it if somebody encounter the same problem, it could helps.
There is function in matlab (image processing toolbox) for that purpose:
Mask = poly2mask(caxy(50,1), caxy(50,2), 1024, 1280);

It can be used for any kind of polygon regions to mask.


text:
Q: How to change the flash color? I want to change the flash color when using element.flash method. By default its yellow.
I was able to increase the number of flash times and delay time in elements.rb file. But i dont know how to change the highlight color.
Any idea on this?
Using different colors to highlight will be helpful if browser elements have yellow background.

A: Solution
The flashing is based on the element's container's activeObjectHighLightColor. This is set by doing:
element.container.activeObjectHighLightColor = "colour"

Where colour is a valid web-friendly color (as per the container.rb file).
Example - Flash For Individual Element
As an example, here is changing the flash colour for the text field on the Google search:
#Use google search text field as a test page
ie = Watir::Browser.new
ie.goto 'www.google.ca'
e = ie.text_field(:name => 'q')

#Set the flash colour
e.container.activeObjectHighLightColor = "green"

#Flash the object, which should now be green
e.flash

Note:

*

*This will only work with Watir-classic. Watir-webdriver does the flashing differently.

*I only tested this in the latest version of watir-classic, but the code for 2.0.4 appears to be the same.

Example - Default Flash Colour
To change the default flash colour for everything, you need to set the activeObjectHighLightColor for the browser.
If you want to change it for the current browser, do:
ie = Watir::Browser.new
ie.activeObjectHighLightColor = "green"

ie.goto 'www.google.ca'
e = ie.text_field(:name => 'q')
e.flash
#=> Will flash green

If you want to change it permanently (ie so you do not have to set it each time), you can change the colour in the ie-class.rb file:
HIGHLIGHT_COLOR = 'yellow'


text:
Q: Convex polygonal tiling of the square such that every line intersects at most k polygons Consider a tiling of a square by convex polygons, such that every line through the square intersects at most $k$ polygons. Let $n$ be maximum number of polygons such a tiling can have. What is the dependence of $n$ on $k$?
Tiling the square with a grid of $k/2$ by $k/2$ smaller squares gives a simple construction for $\Omega (k^2)$ polygons. But is $n \in O(k^2)$?
If each polygon has the same area $A$, the answer is yes. The sum of the horizontal lengths of the polygons cannot exceed $k$, otherwise some vertical line will intersect more than $k$ polygons by pigeonhole. The same follows for the vertical lengths of the polygons. Let $L_i$ be the sum of the horizontal and vertical lengths of polygon $i$, then $L_i \geq 2\sqrt{A}$. We have $n = \frac{1}{A}$ and $\Sigma_i L_i \leq 2k$ so $$2n\sqrt{A} \leq 2k$$ $$\sqrt{n} \leq k$$ $$n \leq k^2$$
This proof only makes use of vertical and horizontal lines intersecting at most $k$ polygons. If a general upper bound exists, the proof must make use of diagonal lines intersecting at most $k$ polygons as well: an arbitrary number of arbitrarily small squares could be placed along a diagonal line, with two large polygons filling the space above and below the line, and in this tiling vertical and horizontal lines would only intersect a small constant number of polygons.
Any suggestions or references would be greatly appreciated.

A: The correct upper bound seems to be of order $k^k$ in the sense that we can create $\ge k^k$ polygons so that each line intersects at most $Ck$ of them and the number is bounded from above by $k^{Ck}$. I'll prove the second part of this claim here.
Definition.
Let $A,B$ be two closed convex polygons with disjoint interiors. We say that a finite sequence of closed convex polygons with disjoint interiors also disjoint from the interiors of $A$ and $B$ is a chain connecting $A$ to $B$ if the first polygon has a common point with $A$, each other polygon has a common point with the previous one, and the last polygon has a common point with $B$.
Lemma. Suppose that $\mathcal F$ is a family of chains of length at most $L$ connecting $A$ to $B$. Suppose that no line intersects more than $k$ different polygons forming these chains. Then $|\mathcal F|\le (kL)^L$.
Viewing the original tiling as a sequence of chains connecting the left side to the right one of length at most $k$ (say, the chains of polygons crossing a fixed horizontal line), we get the upper bound $k^{2k+1}$ in the original problem.
Proof. Induction on $L$. If $L=0$, there is nothing to prove (there is only one empty chain). Case $L=1$ is also trivial because each chain consists of exactly one polygon that has to cross any line that separates the interiors of $A$ and $B$.
To make an induction step, let us first estimate the number of chains containing a fixed polygon $C$. Notice that for each such chain we can find two numbers $a,b\ge 0$ with $a+b=L-1$ such that our chain (of length $\le L$) consists of a chain of length $\le a$ connecting $A$ to $C$, then $C$ itself, and then a chain of length $\le b$ connecting $C$ to $B$. By the induction assumption, the total number of chains containing $C$ is then at most
$$
\sum_{a+b=L-1}(ka)^a(kb)^b=k^{L-1}\sum_{a+b=L-1}a^ab^b\le k^{L-1}L^L
$$
Now notice that each chain crosses any line separating the interiors of $A$ and $B$, so at least one polygon in it crosses that line. However, each particular polygon can be found in only $k^{L-1}L^L$ chains, so, unless the line crosses more than $k$ different polygons, we may have only $k\times k^{L-1}L^L=(kL)^L$ chains.
Of course, this upper bound can be improved a bit, but, as I said, not by too much.
Edit. I guess I simplified my original construction enough to make it postable, so here goes.
The starting point is a very long horizontal rectangle $R$ of height $1$ split by
$k$ extremely narrow diagonal (angle of 45 degrees with the horizontal axis) paralellograms placed into it at regular (also very long) intervals in the middle half (so we have $2k+1$ pieces in the original picture).
At every step, we shrink the picture we already have enormously in the vertical direction, scale it so that it gets width $2$ (something between $\sqrt 2$ and $2\sqrt 2$), rotate it by 45 degrees, place $k$ copies of it the way the narrow parallelograms were placed in the starting picture with some smalll shifts so that no 3 "narrow parallelograms" in different copies are crossing one line (which is possible because those look like points now), and cut out the pieces hanging outside $R$ (see the picture with $k=3$). We do this $k$ times.

The main property of this picture is that if we have a line that is almost vertical (say, making the angle of 10 degrees or less with the vertical axis), then it intersects at most 2 big pieces in the top generation and at most one picture in the next generation. Moreover, any line that violates the last property should be nearly horizontal, which means that with respect to the picture of the previous generation it is nearly vertical after we undo the enormous compression in the vertical direction, but being nearly vertical there, it stays nearly vertical for all following generations as well after the corresponding decompressions.
Suppose we have any line now. Let's see how it goes across the pictures from the top generation down. For a while it intersects just $\le 2$ pieces in the current generation and at most one picture in the next one. This sort of intersections is harmless because we get 2 pieces per generation only. At some generation $g$ this nice property may get violated. Then the line must be nearly hzontal in the decompressed picture for $g$, so it can cross $\le k+1$ big pieces  from generation $g$, $\le 2k$ big pieces from generation $g+1$ and at most $2$ pictures from generation $g+2$. Moreover, it stays nearly vertical for all generations starting with $g+1$, so we return to the rate of 2 pieces per generation (well, it is $4$ now because we crossed $2$ pictures in generation $g+2$, but it is still harmless). So the total number of crossed pieces is still under $Ck$ while we clearly have at least $k^k$ pieces total.

A: It seems that there is no upper polynomial bound, even for the rectangular tilings.
Choose a large $d$. Start with a $d\times d$ rectangular partition; make the sides of rectangles different. You may make this in a manner that you may choose $d$ vertices of these rectangles such that (i) they are in a general position and lie in the interior of the square, and (ii) no two are vertices of the same rectangle of partition.
Now, for every chosen vertex, perform the following operation. `Skew' the four rectangles sharing this vertex as shown in the Figure below, and partition $A$ into $d\times d$ rectangles again.

This way, you obtain about $d^3$ rectangles, but each line crosses $O(d)$ of them  (since it crosses at most two `insertions').
Iterating such procedure, you may obtain the number of rectangles greater than an arbitrary power of $d$, but each line will still cross $O(d)$ rectangles.
[ADDENDUM] Here is another procedure, working for general partitions.
Start with any partition of the square where the vertices are in a general position. At each step, we replace each interior vertex (adjacent, say, to $e$ edges) with a very small $e$-gon. We may do this preserving the condition that all the vertices are in general position.
At each step, the maximal number of crossings increases by at most 2 (if the new polygons are small enough). On the other hand, the number of vertices grows exponentially, thus so does the number of polygons.


text:
Q: C# WPF i can't enter foreach loop! I am creating an application with C# WPF:
I have have dynamically generated treeview
In that treeview I have a TreeViewItem called BoekenLijst.
There I generate dynamic TreeViewItems like "the hobbit". The book content, like "the hobbit", I store in the Content property of a Checkbox.
So the treeview will look like this:
Treeview>
     TreeViewItem(BoekenLijst)>
                      The Hobbit
                        Code Complete
I want to put the checked TreeViewItems in a ListBox so I did the following:
 private List<TreeViewItem> GetAllItemContainers(TreeViewItem itemsControl)
    {
        List<TreeViewItem> allItems = new List<TreeViewItem>();
        for (int i = 0; i < itemsControl.Items.Count; i++)
        {
            // try to get the item Container
            TreeViewItem childItemContainer = itemsControl.ItemContainerGenerator.ContainerFromIndex(i) as TreeViewItem;
            // the item container maybe null if it is still not generated from the runtime
            if (childItemContainer != null)
            {
                allItems.Add(childItemContainer);
                List<TreeViewItem> childItems = GetAllItemContainers(childItemContainer);

                foreach (TreeViewItem childItem in childItems)
                {
                    CheckBox checkBoxTemp = childItem.Header as CheckBox;

                    if (checkBoxTemp != null)
                        optieListBox.Items.Add(checkBoxTemp.Content);

                    allItems.Add(childItem);
                }
            }
        }
        return allItems;
    }

The problem is, it won't go into:  foreach (TreeViewItem childItem in childItems)
Can someone help me out?

A: Have you tried running it through the Visual Studio debugger?  If you insert the break point where the error is getting thrown, then you should be able to get a stack trace of what's going on, and if it's anything like the Eclipse debugger (I've not used VS in a while) you should be able to click on any variable in the code or hold the mouse over it, and it will display the current value of that variable in memory.
But I echo what the others say, try and figure out for yourself, take your time, and work through it step by step.  I had to learn that myself, and I still get it wrong as I always forget to use the debugger...ask my team leader if you don't believe me :-)
Welshboy


text:
Q: Differences in LaTeX3 function generation methods In l3basics module there are two methods provided for each command generating function. The one requires the function signature to be provided, whereas the second does not.
Since the second is more concise, are there any advantages of using the one rather than the other? (Except of course in the obvious case where one needs to remove one token completely, such as a hypothetical \removefirstoftwo case etc and the second method cannot be applied).
I provide a MWE illustrating the two approaches.
\documentclass{article}
\usepackage{expl3}
\begin{document}
\ExplSyntaxOn
  \cs_new:Npn \exampleone:nn #1 #2 {#1 #2}
  \cs_new:Nn \exampletwo:nn{#1 #2}
  \exampleone:nn {one~}{two~}
  \exampletwo:nn {three~}{four}
\ExplSyntaxOff
\end{document}

A: The two methods are perfectly equivalent, when a signature is added to the function being defined.
The \cs_new:Nn method is less efficient, as it has to build the parameter text.
If I add something to your example, the identity is clearer:
\documentclass{article}
\usepackage{expl3}
\begin{document}
\ExplSyntaxOn
  \cs_new:Npn \exampleone:nn #1 #2 {#1 #2}
  \cs_new:Nn \exampletwo:nn{#1 #2}

\texttt{\cs_meaning:N \exampleone:nn}\par

\texttt{\cs_meaning:N \exampletwo:nn}\par

\ExplSyntaxOff
\end{document}

Conciseness of the latter method may make one prefer it, but it's essentially a question of personal preference.
Generally I prefer seeing the explicit parameter text, but that's me.
Why are they both offered? Probably because the :Nn method is similar to the traditional \newcommand, where the parameter text is built from the optional argument, here substituted by the signature of the macro being defined.
Caveat. One can define a function without a signature, but in this case the :Npn method is mandatory. The same if the signature is not "standard", that is with only N, n, T or F specifiers. A function with a w specifier must use :Npn.


text:
Q: NiFi - Stop upon failure I've been trying to google and search stack for the answer but have beeen unable to find.
Using NiFi, is it possible to stop a process upon previous job failure?
We have user data we need to process but the data is sequentially constructed so that if a job fails, we need to stop further jobs from running.
I understand we can create scripts to fail a process upon previous process failure, but what if I need entire group to halt upon failure, is this possible? We don't want each job in queue to follow failure path, we want it to halt until we can look at the data and analyze the failure.
TL;DR - can we STOP a process upon a failure, not just funnel all remaining jobs into the failure flow. We want data in queues to wait until we fix, thus stop process, not just fail again and again.
Thanks for any feedback, cheers!
Edit: typos

A: You can configure backpressure on the queues to stop upstream processes.  If you set the backpressure threshold to 1 on a failure queue, it would effectively stop the processor until you had a chance to address the failure.

The screenshot shows failure routing back to the processor, but this is not required.  It is important that the next processor should not remove it from the queue to maintain the backpressure until you take action.


text:
Q: Parallel multiplication of many small matrices by fixed vector Situation is the following: I have a number (1000s) of elements which are given by small matrices of dimensions 4x2, 9x3 ... you get the idea. All matrices have the same dimension.
I want to multiply each of these matrices with a fixed vector of precalculated values. In short:
for(i = 1...n)
    X[i] = M[i] . N;

What is the best approach to do this in parallel using Thrust? How do I lay out my data in memory?
NB: There might be specialized, more suitable libraries to do this on GPUs. I'm interested in Thrust because it allows me to deploy to different backends, not just CUDA.

A: One possible approach:

*

*flatten the arrays (matrices) into a single data vector.  This is an advantageous step for enabling general thrust processing anyway.

*use a strided range mechanism to take your scaling vector and extend it to the overall length of your flattened data vector

*use thrust::transform with thrust::multiplies to multiply the two vectors together.
If you need to access the matrices later out of your flattened data vector (or result vector), you can do so with pointer arithmetic, or a combination of fancy iterators.
If you need to re-use the extended scaling vector, you may want to use the method outlined in step 2 exactly (i.e. create an actual vector using that method, length = N matrices, repeated).  If you are only doing this once, you can achieve the same effect with a counting iterator, followed by a transform iterator (modulo the length of your matrix in elements), followed by a permutation iterator, to index into your original scaling vector (length = 1 matrix).
The following example implements the above, without using the strided range iterator method:
#include <iostream>
#include <stdlib.h>
#include <thrust/device_vector.h>
#include <thrust/host_vector.h>
#include <thrust/functional.h>
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/transform.h>

#define N_MAT 1000
#define H_MAT 4
#define W_MAT 3
#define RANGE 1024

struct my_modulo_functor : public thrust::unary_function<int, int>
{
  __host__ __device__
  int operator() (int idx) {
    return idx%(H_MAT*W_MAT);}
};

int main(){

  thrust::host_vector<int> data(N_MAT*H_MAT*W_MAT);
  thrust::host_vector<int> scale(H_MAT*W_MAT);
  // synthetic; instead flatten/copy matrices into data vector
  for (int i = 0; i < N_MAT*H_MAT*W_MAT; i++) data[i] = rand()%RANGE;
  for (int i = 0; i < H_MAT*W_MAT; i++) scale[i] = rand()%RANGE;

  thrust::device_vector<int> d_data = data;
  thrust::device_vector<int> d_scale = scale;
  thrust::device_vector<int> d_result(N_MAT*H_MAT*W_MAT);

  thrust::transform(d_data.begin(), d_data.end(), thrust::make_permutation_iterator(d_scale.begin(), thrust::make_transform_iterator(thrust::counting_iterator<int>(0), my_modulo_functor())) ,d_result.begin(), thrust::multiplies<int>());

  thrust::host_vector<int> result = d_result;

  for (int i = 0; i < N_MAT*H_MAT*W_MAT; i++)
    if (result[i] != data[i] * scale[i%(H_MAT*W_MAT)]) {std::cout << "Mismatch at: " << i << " cpu result: " << (data[i] * scale[i%(H_MAT*W_MAT)]) << " gpu result: " << result[i] << std::endl; return 1;}
  std::cout << "Success!" << std::endl;
  return 0;
}

EDIT: Responding to a question below:
The benefit of fancy iterators (i.e. transform(numbers, iterator)) is that they often allow for eliminaion of extra data copies/data movement, as compared to assembling other number (which requires extra steps and data movement) and then passing it to transform(numbers, other numbers).  If you're only going to use other numbers once, then the fancy iterators will generally be better.  If you're going to use other numbers again, then you may want to assemble it explicitly.  This preso is instructive, in particular "Fusion".
For a one-time use of other numbers the overhead of assembling it on the fly using fancy iterators and the functor is generally lower than explicitly creating a new vector, and then passing that new vector to the transform routine.

A: When looking for a software library which is concisely made for multiplying small matrices, then one may have a look at https://github.com/hfp/libxsmm. Below, the code requests a specialized matrix kernel according to the typical GEMM parameters (please note that some limitations apply).
double alpha = 1, beta = 1;
const char transa = 'N', transb = 'N';
int flags = LIBXSMM_GEMM_FLAGS(transa, transb);
int prefetch = LIBXSMM_PREFETCH_AUTO;
libxsmm_blasint m = 23, n = 23, k = 23;
libxsmm_dmmfunction xmm = NULL;

xmm = libxsmm_dmmdispatch(m, n, k,
  &m/*lda*/, &k/*ldb*/, &m/*ldc*/,
  &alpha, &beta, &flags, &prefetch);

Given the above code, one can proceed and run "xmm" for an entire series of (small) matrices without a particular data structure (below code also uses "prefetch locations").
if (0 < n) { /* check that n is at least 1 */
  # pragma parallel omp private(i)
  for (i = 0; i < (n - 1); ++i) {
    const double *const ai = a + i * asize;
    const double *const bi = b + i * bsize;
    double *const ci = c + i * csize;
    xmm(ai, bi, ci, ai + asize, bi + bsize, ci + csize);
  }
  xmm(a + (n - 1) * asize, b + (n - 1) * bsize, c + (n - 1) * csize,
  /* pseudo prefetch for last element of batch (avoids page fault) */
      a + (n - 1) * asize, b + (n - 1) * bsize, c + (n - 1) * csize);
}

In addition to the manual loop control as shown above, libxsmm_gemm_batch (or libxsmm_gemm_batch_omp) can be used (see ReadTheDocs). The latter is useful if data structures exist that describe the series of operands (A, B, and C matrices).
There are two reasons why this library gives superior performance: (1) on-the-fly code specialization using an in-memory code generation technique, and (2) loading the next matrix operands while calculating the current product.
( Given one is looking for something that blends well with C/C++, this library supports it. However, it does not aim for CUDA/Thrust. )


text:
Q: how to put a jQuery $ (..).click (function () { inside a javascript object? I'm trying to put a  $(..).click(function () {...  inside a javascript object, but I feel like I'm asking for the impossible.
Inside this object there can be several Dom elements, so I think that making a jQuery extension is excluded too?
But I admit, I can not understand how to make an jQuery extension, there are still concepts that escape me in this respect.
Anyway, here's an example of what I'm looking to do, even if it's not functional:

$(document).ready(function() {
  class bt_Fab {
    constructor($elem_ID, $messageBox_ID, message) {
      this.$_ID = $elem_ID;
      this.$_ID_MsgBox = $messageBox_ID;
      this._msg = message;

      this.$_ID.click(function() {
        this.$_ID_MsgBox.text(this._msg); // does nothing...
      });
    }
  };

  var
    myOneButton = new bt_Fab($('#btn_one'), $('#messageBox'), 'message from button one!'),
    myTwoButton = new bt_Fab($('#btn_two'), $('#messageBox'), 'message from button two!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='btn_one'>button One</button>
<button id='btn_two'>button Two</button>
<!-- lot of html here -->
<div id="messageBox">... </div>

[ Update Edit ] ( for @Sam Hanley & @meagar )
This question is different from How to access the correct `this` inside a callback?
because this question is about the use of jQuery function inside a Javascript Object; and they are not about the corect usage of a this in Javascript object model.

A: In jQuery, within a event handler such as $.click(), the this keyword is overriden with the reference to the sender object, in this case $_ID. In this.$_ID.click, this is actually the instance of the class. Inside of the click handler, i.e. function() { this.msgBox... }, this refers to the element that was clicked.
When I create a class in javascript, I usually create a class variable called my that I set to this in the constructor of the class. Instead of using this use the my variable when you're using jQuery to avoid confusion.
Sometimes it's actually nice that this is overridden, but when you're defining a class it's just horrible.


text:
Q: Find all the emps and their salaries who earn minimum salary in their department, display result in salary ascending order employee database
SELECT name, MIN(salary)
FROM employee
GROUP BY deptid;

Why I can't select "name" here?
And what is the suggested query for this question?

A:
Why I can't select "name" here?

You can only use columns or expressions the the SELECT if they are present in the GROUP BY area, or part of a function that calculates an aggregation.
Think of grouping like buckets. When you say group by dept_id if there are 3 departments (even if they are mentioned 20 times; 20 employees in departments A,A,A,A,A,A,A,A,A,A,A,A,B,B,B,B,B,C,C,C) you get 3 buckets and there's a label on the outside of each bucket, one for each different value of dept_id (a bucket for A, a bucket for B and a bucket for C). Into those buckets, all the employees rows are thrown according to which department they're in: 12 rows in A, 5 rows in B, 3 rows in C. Then you say MIN(salary), the db searches each bucket looking for the minimum salary.
Why can't you say name? There simply isn't a bucket for it. Your buckets are labelled A, B and C for the departments. No bucket has a name written on it. While there are names inside the bucket, you can only ask for them in terms of a MIN, MAX, AVG, SUM, COUNT etc - it's the rule. "To get something out of a bucket you have to use some kind of function that calculates some statistic". Actually, in some DBs you can ask for a CSV string of all the names, but we'll ignore that because it's accessory to the main point: unless you use an aggregate function you can only ask for something written on the outside of a bucket
What information should the DB give you if you ask for name?
You could ask for MIN(name), but you'd only get one name. You could GROUP BY Name.. but then you'd have a lot more buckets, and your employees would be redistributed across the buckets. You would't be asking for the MIN salary per department bucket any more, you'd be asking for the min salary per name.. Not what you want

And what is the suggested query for this question?

Break it down:

"minimum salary in the department"

We're going to need a list of all departments and the minimum salary in the department
SELECT dept_id, MIN(salary) as min_sal_for_dept
FROM employee
GROUP BY dept_id

"Find all the emps .. who earn minimum salary in their department"

Now we know that the depatment ID and min salary is for that department, we can join it back to the employee data on the department id and the salary
SELECT *
FROM
(
  SELECT dept_id, MIN(salary) as sal
  FROM employee
  GROUP BY dept_id
) dep_min_sals
INNER JOIN
employee e
ON
  e.dept_id = dep_min_sals.dept_id AND e.salary = dep_min_sals.sal

"display result in salary ascending order"

ORDER BY sal

The key thing to realize is that you have to group up (lose) detail in order to get the minimum salary per department, so if you want the detail back you have to join the grouped up data back to the detail. You cannot both lose the detail to calculate the minimum AND also keep the detail to have the employee name

A: A database-independent solution is to filter with a subquery:
select e.*
from emp e
where e.salary = (select min(e1.salary) from emp e1 where e1.deptid = e.deptid)
order by e.salary


text:
Q: React useRef / useEffect HTMLCanvasElement not assignable I am fairly new to React and struggling to get a JS object to render through useRef and useEffect.
The JS render method is as follows:
import { Compass } from "steelseries";
const compass = new Compass(document.querySelector("#myCanvas"), {
  size: 200
});

Using a template for rendering a chart from chart.js I have tried to render this through React with typescript.
The react render method is as follows:
import { useCallback, useEffect, useRef } from "react"
import { observer } from "mobx-react"
import { Compass } from "steelseries"

type GaugeIndicatorProps = {
      value: 200
    }

export const Gauge = observer(({ value }: GaugeIndicatorProps) => {
      const canvasEl = useRef() as React.MutableRefObject<HTMLCanvasElement>
      const chartRef = useRef<Compass | null>()

      const createChart = useCallback(() => {
        const chartCanvas = canvasEl.current.getContext("2d")
        if (!chartCanvas) {
          return
        }
        chartRef.current = new Compass(chartCanvas, value)
      }, [value])

      useEffect(() => {
        if (!chartRef.current) {
          createChart()
        }
      }, [createChart])

      return (
        <div className={`canvas`}>
          <canvas className="top-chart" ref={canvasEl} />
        </div>
      )
    })

Not sure how to get this to render, because the compass object wants a Canvas | String | HTMLCanvasElement, which i have tried to pass to it using React.MutableRefObject and a getcontext("2d"), yet it is saying the following error for chartCanvas on this line of Code:
chartRef.current = new Compass(chartCanvas, value)
Argument of type 'CanvasRenderingContext2D' is not assignable to parameter of type 'string | HTMLCanvasElement'.
Type 'CanvasRenderingContext2D' is missing the following properties from type 'HTMLCanvasElement': hieght etc
Sorry if this is a newbie question.
Thanks for your support.
Christopher

A: You have to pass the canvas itself, not its context. Use :
chartRef.current = new Compass(canvasEl.current, value)


text:
Q: Ruby - Send GET request with headers I am trying to use ruby with a website's api. The instructions are to send a GET request with a header. These are the instructions from the website and the example php code they give. I am to calculate a HMAC hash and include it under an apisign header.
$apikey='xxx';
$apisecret='xxx';
$nonce=time();
$uri='https://bittrex.com/api/v1.1/market/getopenorders?apikey='.$apikey.'&nonce='.$nonce;
$sign=hash_hmac('sha512',$uri,$apisecret);
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult);

I am simply using an .rb file with ruby installed on windows from command prompt. I am using net/http in the ruby file. How can I send a GET request with a header and print the response?

A: As of Ruby 3.0, Net::HTTP.get_response supports an optional hash for headers:
Net::HTTP.get_response(URI('http://www.example.com/index.html'), { 'Accept' => 'text/html' })

Unfortunately this does not work for Ruby 2 (up to 2.7).

A: Using net/http as suggested by the question.
References:

*

*Net::HTTP https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html

*Net::HTTP::get https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html#method-c-get

*Setting headers: https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP.html#class-Net::HTTP-label-Setting+Headers

*Net::HTTP::Get https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTP/Get.html

*Net::HTTPGenericRequest https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTPGenericRequest.html and Net::HTTPHeader https://ruby-doc.org/stdlib-2.4.1/libdoc/net/http/rdoc/Net/HTTPHeader.html (for methods that you can call on Net::HTTP::Get)

So, for example:
require 'net/http'

uri = URI("http://www.ruby-lang.org")
req = Net::HTTP::Get.new(uri)
req['some_header'] = "some_val"

res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') { |http|
  http.request(req)
}

puts res.body # <!DOCTYPE html> ... </html> => nil

Note: if your response has HTTP result state 301 (Moved permanently), see Ruby Net::HTTP - following 301 redirects

A: Install httparty gem, it makes requests way easier, then in your script
require 'httparty'

url = 'http://someexample.com'
headers = {
  key1: 'value1',
  key2: 'value2'
}

response = HTTParty.get(url, headers: headers)
puts response.body

then run your .rb file..


text:
Q: Prevent counter from incrementing again if user has guessed I have created a small app that has a button that plays a different sound each time the user clicks it and if they guess the correct animal the score counter goes up.
However if he presses enter a couple of times the counter still scores and that enables him to cheat.
How can I make so that if he has guessed, the counter increments with one but if he presses enter again and they guessed the sound the counter stays the same? I tried with a boolean value like the isEntered logic but it did not work, I tried enclosing the shuffle logic in a function and call it each time he has guessed but that did not yield the desired result, here is my code:
var sounds = [
  {
    animalType: 'horse',
    sound: new Audio('../sounds/Horse-neigh.mp3')
  },
  {
    animalType: 'bear',
    sound: new Audio('../sounds/grizzlybear.mp3')
  },
  {
    animalType: 'goat',
    sound: new Audio('../sounds/Goat-noise.mp3'),
  },
  {
    animalType: 'cat',
    sound: new Audio('../sounds/cat.mp3')
  },
  {
    animalType: 'dog',
    sound: new Audio('../sounds/dog-bark.mp3')
  },
  {
    animalType: 'sheep',
    sound: new Audio('../sounds/sheep.mp3')
  },
  {
    animalType: 'rooster',
    sound: new Audio('../sounds/rooster.mp3')
  },
  {
    animalType: 'lion',
    sound: new Audio('../sounds/lion.mp3')
  },
  {
    animalType: 'hen',
    sound: new Audio('../sounds/hen.mp3')
  }
]

var player = document.getElementById('player');
var enteredWord = document.getElementById('entered-word');
var counter = document.getElementById('counter-score');
var errorMessage = document.getElementById('error-message');
var wrongAnswerSound = new Audio('../sounds/Wrong-answer-sound-effect.mp3');
var isEntered = false;

function startGame() {
  var currentSound;
    player.addEventListener('click', function() {
    var sound = sounds[Math.floor(Math.random()*sounds.length)];
    currentSound = sound.animalType;
    sound['sound'].play();
  })

  enteredWord.addEventListener('keyup', function() {
    if(event.key === 'Enter') {
      if(enteredWord.value.toLowerCase() === currentSound) {
        isEntered = true;
        counter.textContent ++;
        errorMessage.style.display = 'none';
        enteredWord.classList.remove('input-error-border');
      } else {
        isEntered = false;
        errorMessage.style.display = 'inline-block';
        enteredWord.classList.add('input-error-border');
        wrongAnswerSound.play();
      }
    }
  })
}

startGame();

and my html:

?

              ×

 Click on the note icon to hear a sound, then try to guess it by typing the animals name.

      <input type="text" autofocus id="entered-word" placeholder="Guess the animal sound" >

Score: 0

A: You should check the isEntered variable in the event listener, like this:
enteredWord.addEventListener('keyup', function() {
  if(event.key === 'Enter') {
    if(enteredWord.value.toLowerCase() === currentSound && isEntered === false) {
      isEntered = true;
      counter.textContent ++;
      errorMessage.style.display = 'none';
      enteredWord.classList.remove('input-error-border');
    } else {
      isEntered = false;
      errorMessage.style.display = 'inline-block';
      enteredWord.classList.add('input-error-border');
      wrongAnswerSound.play();
    }
  }
})


text:
Q: Need regex or piece of data for slicing the code and handling quotes Need help with writing a regex in python or need to slice this piece of data and then taking the double quotes separately
Tried the following piece of code for the input file but the initial lines contain the output as mentioned in the Actual Output, please help in rectifying the situation.
reader = csv.reader(file_sample, delimiter=delimiter, quotechar=quotechar, quoting= csv.QUOTE_ALL)
reader = csv.reader(x.replace('\0', '') for x in file_sample)

Actual Output:
CALLIN.csv0000700520310804322000005053126276127200687052113 0ustar  vzbaga2vmsuser"HEADER_ID","CAPITAL_ID","DIST_ID",

Expected Output:
HEADER_ID CAPITAL_ID DIST_ID


text:
Q: localhost route not working should be returning JSON back when locating to URL My fellow programmers, I basically have this async Get() method which is reading Json data successfully, but when locating to route -> localhost:59185/api/encompass/data I receive a message:

No HTTP resource was found that matches the request URL 'http://localhost:59185/api/encompass/data'.
</Message>

I was very hopeful that it would return my JSON especially when in debug the code its sitting in 'string res' at the bottom
anyone know why its not returning Json even thought its sitting in 'res'?
Controller:
    [HttpGet, Route("encompass/data")]
    public async Task<string> Get(string Accesstoken)
    {
         string res = "";
         using (var client = new HttpClient())
        {
            Accesstoken = Accesstoken.Substring(17, 28);
            client.BaseAddress = new Uri("https://api.elliemae.com/");
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Accesstoken);
            var response = client.GetAsync("encompass/v1/loans/ea7c29a6-ee08-4816-99d2-fbcc7d15731d").Result;
            using (HttpContent content = response.Content)
            {
                // ... Read the string.
                Task<string> result = content.ReadAsStringAsync();
                res = result.Result;
            }

            return res; //<- this is not returning the JSon thats sitting in here
        }

    }

A: fay, the bearer token used in the header of your Get method must be Base64 encoded
See [how-do-i-encode-and-decode-a-base64-string][1]
I have added a Bearer HEADER value for the token.
  [HttpGet, Route("values/get")]
        public async Task<string> Get(string resulted)
        {

            string res = "";
            using (var client = new HttpClient())
            {
                // HTTP POST

                client.BaseAddress = new Uri("https://api.elliemae.com/");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(resulted)));
                var response = client.GetAsync("/encompass/v1/loans/{ea7c29a6-ee08-4816-99d2-fbcc7d15731d}?Authorization=Bearer "+resulted+"&Content-Type=application/json").Result;

                using (HttpContent content = response.Content)
                {
                    // ... Read the string.
                    Task<string> result = content.ReadAsStringAsync();
                    res = result.Result;
                }
            }
            return res;
        }


text:
Q: Quadratic variation of continuous local martingales Dear all,
I hope you can help me with the proof of the following result:
Fact If $X$ is a continuous local martingale, then $[X]_t < \infty $ a.s. for every $t \geq 0$, where $[X]$ denote the quadratic variation of the process $X$.
I have tried in vain different ways for approaching this problem: firstly using the definition of quadratic variation and secondly using the Doob-Meyer decomposition of $X$ but in both cases I got stuck in mountains of calculations.

A: Assuming your process is one dimensional, by representation theorem there exist a Brownian motion $B$ and a (predictible) process $Y_s$ verifying $\forall t>0$, $\int_0^tY_s^2ds<+\infty$ almost surely such that :
$X_t=E[X_0]+\int_0^tY_sdB_s$ for all $t>0$
Then $[X]_t=\int_0^tY_s^2ds$ which is almost surely finite by representation theorem.
Note that your statement is only almost surely true
Regards

A: I guess I have found another different proof of the fact I have asked. Could you check whether it is correct? Thanks
Lemma If $(M_t)_{t\geq 0}$ is a continuous local martingale, then $|M_t| < \infty$ a.s. for every $t\geq 0$.
Proof of the lemma: Suppose for sake of contradiction that $\exists s$ such that $P(|M_s|=\infty)>0$. If $(T_n)_n$ is a reducing sequence for $M$, then $\exists n$ such that $P(T_n > s)>0$. Thus $P(|M_{T_n \wedge t} |=\infty)>0$, but $M_{T_n \wedge t}$ is in $L^1$, since it is a martingale. $\Box$
Now, if we take $X_t$ continuous local martingale we have that also $X^2_t$ is a continuous local martingale and $|X^2_t| < \infty$ a.s. for every $t \geq 0$. (see comments)
The lemma applied to $X_t$ gives that $|X_t| < \infty$ a.s. for every $t \geq 0$ and thus $|X_t|^2 < \infty$ a.s. for every $t \geq 0$.
Finally, also $X^2_t-[X]_t$ is a continuous local martingale and hence we have $|X^2_t-[X]_t| < \infty$. From these facts follow that $[X]_t < \infty$ a.s. for every $t \geq 0$.


text:
Q: I want to make my search textbox expand on mouse click and decrease when i remove the mouse //textbox not animating

HTML

      <input class="search.text" type="text" value=" search..."/>

I want my textbox to expand when it gains focus and decrease when I remove focus from the textbox.

A: <input class="search text" type="text" value=" search..."/>

A: Please change the class name
<input class="search.text" type="text" value=" search..."/>

to
<input class="search text" type="text" value=" search..."/>

otherwise your code is working fine


text:
Q: Hierarchical Bayes Normal-Normal Model I have the following data for 8 runners in a 100 meter dash:
runner 1 88 91 87 82
runner 2 81 85 78 91
runner 3 75 77 83 81
runner 4 92 89 84 82
runner 5 78 79 84 92
runner 6 89 75 79 83
runner 7 91 89 92 91
runner 8 87 86 88 91

The ratings represent a performance rating and are normally distributed with unknown mean and unknown variance. Each runner can be considered as a sub-group with a mean and variance.
Any guidance will be highly appreciated

A: My example here may help: When making inferences about group means, are credible Intervals sensitive to within-subject variance while confidence intervals are not?
I modified the model slightly for your data. Note that with such little data your results will be heavily dependent on the priors you use so I would attempt modifying the priors on the group means and precisions (1/variance) and seeing the different results to learn.
Here are the results I got:

This is modified from John Krushke's example here:
http://psy2.ucsd.edu/~dhuber/cr_SimpleLinearRegressionRepeatedBrugs.R
He has a helpful website and blog:
http://www.indiana.edu/~kruschke/DoingBayesianDataAnalysis/
#Note. To use rjags you need to first install JAGS from here:
#http://sourceforge.net/projects/mcmc-jags/files/

install.packages("rjags") #run first time to install package

require(rjags) #load rjags package

#Format your data
subID<-rep(1:8,each=4)

dat<-rbind(88, 91, 87, 82,
81, 85, 78, 91,
75, 77, 83, 81,
92, 89, 84, 82,
78, 79, 84, 92,
89, 75, 79, 83,
91, 89, 92, 91,
87, 86, 88, 91
)

dat<-cbind(subID,dat)
colnames(dat)<-c("Subject","Value")
dat<-as.data.frame(dat)

#Jags fit function
jags.fit<-function(dat){

  #Create JAGS model
  modelstring = "

  model{
  for(n in 1:Ndata){
  y[n]~dnorm(mu[subj[n]],tau[subj[n]]) T(0, )
  }

  for(s in 1:Nsubj){
  mu[s]~dnorm(muG,tauG) T(0, )
  tau[s] ~ dgamma(5,5)
  }

  muG~dnorm(80,.01) T(0, )
  tauG~dgamma(1,1)

  }
  "
  writeLines(modelstring,con="model.txt")

#############

  #Format Data
  Ndata = nrow(dat)
  subj = as.integer( factor( dat$Subject ,
                                 levels=unique(dat$Subject ) ) )
  Nsubj = length(unique(subj))
  y = as.numeric(dat$Value)

  dataList = list(
    Ndata = Ndata ,
    Nsubj = Nsubj ,
    subj = subj ,
    y = y
  )

  #Nodes to monitor
  parameters=c("muG","tauG","mu","tau")

  #MCMC Settings
  adaptSteps = 1000
  burnInSteps = 1000
  nChains = 1
  numSavedSteps= nChains*10000
  thinSteps=20
  nPerChain = ceiling( ( numSavedSteps * thinSteps ) / nChains )

  #Create Model
  jagsModel = jags.model( "model.txt" , data=dataList,
                          n.chains=nChains , n.adapt=adaptSteps , quiet=FALSE )
  # Burn-in:
  cat( "Burning in the MCMC chain...\n" )
  update( jagsModel , n.iter=burnInSteps )

  # Getting DIC data:
  load.module("dic")

  # The saved MCMC chain:
  cat( "Sampling final MCMC chain...\n" )
  codaSamples = coda.samples( jagsModel , variable.names=parameters ,
                              n.iter=nPerChain , thin=thinSteps )

  mcmcChain = as.matrix( codaSamples )

  result = list(codaSamples=codaSamples, mcmcChain=mcmcChain)

}

output<-jags.fit(dat) # fit the model to your data

###make plots
##Overall plots
par(mfrow=c(2,1))
#Plot overall means
hist(output$mcmcChain[,"muG"],col="Grey", freq=F,
main="Overall Mean", xlab="Performance"
)
#Plot overall variance
hist(1/output$mcmcChain[,"tauG"],col="Grey", freq=F,
main="Overall Variance", xlab="Performance")

##Indidvidual Mean Plots
dev.new()
par(mfrow=c(2,4))
for(i in 1:8){
hist(output$mcmcChain[,paste("mu[",i,"]",sep="")],
main=paste("Mean of Runner", i), xlab="Performance", freq=F, col="Grey"
)
}

##Indidvidual Variance Plots
dev.new()
par(mfrow=c(2,4))
for(i in 1:8){
hist(1/output$mcmcChain[,paste("tau[",i,"]",sep="")],
main=paste("Variance of Runner", i), xlab="Performance", freq=F, col="Grey"
)
}

# see what is in the output
attributes(output$mcmcChain)

Edit:
To see the percent of time the model predicts each runner will win we can take the mean and variance estimated for each individual at each mcmc step, then sample a performance from a distribution determined by those parameters. We can then simply count the number of times each runner had the highest performance.

nSamps<-length(output$mcmcChain[,paste("mu[",i,"]",sep="")])
out=matrix(nrow=nSamps*8,ncol=3)
cnt<-1
for(j in 1:nSamps){
for(i in 1:8){
m<-output$mcmcChain[,paste("mu[",i,"]",sep="")][j]
v<-1/output$mcmcChain[,paste("tau[",i,"]",sep="")][j]
t<-rnorm(1,m,sqrt(v))
out[cnt,]<-cbind(j,i,t)
cnt<-cnt+1
}
}
colnames(out)<-c("N","RunnerID","Time")

winners=matrix(nrow=nSamps,ncol=1)
for(i in 1:nSamps){
sub<-out[which(out[,"N"]==i),]
winners[i]<-sub[which(sub[,"Time"]==max(sub[,"Time"])),"RunnerID"]
}

dev.new()
barplot(100*table(winners)/nSamps, xlab="Runner ID", ylab="% of Wins")


text:
Q: Exporting OSM data as PBF with Python I managed to download OSM data as a graph and exported as XML file using OSMNX lib with polygon boundary
net = ox.graph_from_polygon(zone_polygon, network_type='drive_service', simplify=True)
ox.save_graph_xml(net,'osm.xml')

My goal is to export as PBF. Which way is the best to achieve it using Python?


text:
Q: aggregate in Mongodb driver(npm) result is different from robo3T result its my aggregate in robo3t and node app
db.getCollection('roles').aggregate([
{$match:{"_id" : ObjectId("63c8ad93eb3b2d975834a6d0")}},
   {
     $lookup: {
            from: 'modules',
            localField: 'moduleAccess.moduleId',
            foreignField: '_id',
            as: 'moduleData'
          }
        },
        {
            $unwind:'$moduleData'
        }
]).toArray()

my result in robo3t and nodejs is :
robo3t :
/* 1 */
[
    {
        "_id" : ObjectId("63c8ad93eb3b2d975834a6d0"),
        "roleName" : "SuperUser",
        "activeStatus" : "Active",
        "moduleAccess" : [
            {
                "moduleId" : ObjectId("63ca80563eea1005982f82d4"),
                "view" : 1,
                "create" : 1,
                "update" : 1,
                "delete" : 1
            },
            {
                "moduleId" : ObjectId("63ca80a13eea1005982f82f8"),
                "view" : 1,
                "create" : 1,
                "update" : 1,
                "delete" : 1
            },
            {
                "moduleId" : ObjectId("63ce1de83eea1005982f8f4f"),
                "view" : 1,
                "create" : 1,
                "update" : 1,
                "delete" : 1
            }
        ],
        "moduleData" : {
            "_id" : ObjectId("63ca80563eea1005982f82d4"),
            "displayName" : "Module List",
            "moduleName" : "moduleList",
            "moduleIcon" : "fa fa-circle",
            "moduleLevel" : 1,
            "moduleParent" : ObjectId("63ca80a13eea1005982f82f8"),
            "order" : 0,
            "Active" : "Active"
        }
    },
    {
        "_id" : ObjectId("63c8ad93eb3b2d975834a6d0"),
        "roleName" : "SuperUser",
        "activeStatus" : "Active",
        "moduleAccess" : [
            {
                "moduleId" : ObjectId("63ca80563eea1005982f82d4"),
                "view" : 1,
                "create" : 1,
                "update" : 1,
                "delete" : 1
            },
            {
                "moduleId" : ObjectId("63ca80a13eea1005982f82f8"),
                "view" : 1,
                "create" : 1,
                "update" : 1,
                "delete" : 1
            },
            {
                "moduleId" : ObjectId("63ce1de83eea1005982f8f4f"),
                "view" : 1,
                "create" : 1,
                "update" : 1,
                "delete" : 1
            }
        ],
        "moduleData" : {
            "_id" : ObjectId("63ca80a13eea1005982f82f8"),
            "displayName" : "Master App",
            "moduleName" : "masterApp",
            "moduleIcon" : "fa fa-circle",
            "moduleLevel" : 0,
            "moduleParent" : "",
            "order" : 0,
            "Active" : "Active"
        }
    },
    {
        "_id" : ObjectId("63c8ad93eb3b2d975834a6d0"),
        "roleName" : "SuperUser",
        "activeStatus" : "Active",
        "moduleAccess" : [
            {
                "moduleId" : ObjectId("63ca80563eea1005982f82d4"),
                "view" : 1,
                "create" : 1,
                "update" : 1,
                "delete" : 1
            },
            {
                "moduleId" : ObjectId("63ca80a13eea1005982f82f8"),
                "view" : 1,
                "create" : 1,
                "update" : 1,
                "delete" : 1
            },
            {
                "moduleId" : ObjectId("63ce1de83eea1005982f8f4f"),
                "view" : 1,
                "create" : 1,
                "update" : 1,
                "delete" : 1
            }
        ],
        "moduleData" : {
            "_id" : ObjectId("63ce1de83eea1005982f8f4f"),
            "displayName" : "Role",
            "moduleName" : "role",
            "moduleIcon" : "fa fa-circle",
            "moduleLevel" : 1,
            "moduleParent" : ObjectId("63ca80a13eea1005982f82f8"),
            "order" : 1,
            "Active" : "Active"
        }
    }
]

in robo3t result is answer as expected. its correct answer
nodejs result :
{
  _id: new ObjectId("63c8ad93eb3b2d975834a6d0"),
  roleName: 'SuperUser',
  activeStatus: 'Active',
  moduleAccess: [
    {
      moduleId: new ObjectId("63ca80563eea1005982f82d4"),
      view: 1,
      create: 1,
      update: 1,
      delete: 1
    },
    {
      moduleId: new ObjectId("63ca80a13eea1005982f82f8"),
      view: 1,
      create: 1,
      update: 1,
      delete: 1
    },
    {
      moduleId: new ObjectId("63ce1de83eea1005982f8f4f"),
      view: 1,
      create: 1,
      update: 1,
      delete: 1
    }
  ],
  moduleData: {
    _id: new ObjectId("63ca80563eea1005982f82d4"),
    displayName: 'Module List',
    moduleName: 'moduleList',
    moduleIcon: 'fa fa-circle',
    moduleLevel: 1,
    moduleParent: new ObjectId("63ca80a13eea1005982f82f8"),
    order: 0,
    Active: 'Active'
  }
}

in nodejs only unwidn 1 data
what i do wrong with my config?
mongodb(npm) : 4.13.0
mongodb version : 5.0.7
node version : 16.14.2
please help to configuration my app the output from node js can be the same as robo3t


text:
Q: Overall coverage is set to 0% while coverage on Unit tests is 37% We have maven based project, and runs on jenkins integrated with SonarQube which reports coverage using jacoco plugin.
Overall Coverage is showing 0% while coverage on tests is 37%.
Can anyone help? Let me know if you need anymore details?
SonarQube version = 5.6.6


text:
Q: How to replace new line with %0D%0A with PHP I have a JavaScript code that can replace new lines with %0D%0A
I need the same code in PHP.
This is how my JavaScript code looks like:
text = text.replace(/\n\r?/g, '%0D%0A');

I tried with PHP but I am getting only one line without newlines.

A: You don't need regular expressions for that. Simple string replacement will be enough.
Use str_replace function:
$test = 'Some very long text with multiple lines...';
$newText = str_replace(PHP_EOL, '%0D%0A', $text);

New line character differs in various systems. It's not a good idea to hard-code \n\r. Better solution is to use PHP_EOL constant.

A: a literal translation of your java code into php could use  preg_replace
http://www.php.net/preg_replace
<?php
$text = "some text";
$text = preg_replace("\r\n","%0D%0A",$text);
?>


text:
Q: PHP-SYMFONY3 add a formbuilder in a formbuilder I'm creating a form for an entity (sample) that contains a known number of form of an other entity (Result).
Sample has a collection of Result. (and also a collection of Parameter)
In my controller the code look like this
$em = $this->getDoctrine()->getManager();
$sample = $em->getRepository('ReceptionBundle:Sample')->find($id);
$formBuilder = $this->createFormBuilder();

$i = 0;
foreach ($sample->getParameter() as $param){

    $fb = $this->get('form.factory')->createNamedBuilder($i, FormType::Class, $sample);
    if ($param->getCriteria()===false){
        $fb->add('result', Result1Type::class, array('data_class'=>null));
    }
    else {
        $fb->add('result', Result2Type::class, array('data_class'=>null));
    }
    $formBuilder->add($fb);
    $i++;

}
$formBuilder->add('save',      SubmitType::class);
$form = $formBuilder->getForm();

When I try with this I have an error before to see the form :

The form's view data is expected to be an instance of class ReceptionBundle\Entity\Result, but is an instance of class Doctrine\ORM\PersistentCollection. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms an instance of class Doctrine\ORM\PersistentCollection to an instance of ReceptionBundle\Entity\Result.

So, when I try to set the "data_class" option to null, I can display the form, but I can't submit it :

Expected value of type "Doctrine\Common\Collections\Collection|array" for association field "ReceptionBundle\Entity\Sample#$result", got "boolean" instead.

I don't know why is receiving a boolean.

A: Finaly, I didn,t use the Result1Type::class, it was not necessary.
I use the collection type, the thing is that you can create directly the new results in the controller this way
foreach ($sample->getParameter() as $param){

$result = new Result();
$sample->addResult($result);
}
 $form = $this->createForm(AnalyseType::class, $sample);

The result is directly syncronised with the form.


text:
Q: Verification of telephone numbers I have to add an automated telephone verification feature for my web application. That is when the customer clicks a button in the web interface, he/she should be called (customer's phone already in the database) and asked to enter some identification number in the telephone keypad and then the calling system should notify the results to a URL.
I am searching a service provider for this. Please give me some recommendations.

A: Tropo or Twilio would both be appropriate for your needs.


text:
Q: Protractor tests with CucumberJS passing irregularly Trying out some BDD with AngularJS so I'm having a go at automating scenarios with Protractor and CucumberJS. Strangely, It been the devils job trying to get step defintions to fail intelligently.
Features.feature
Feature: Calculator
  As a user
  I want to perform arithmetic operations
  So that I don't have to think too hard

  Scenario: Addition
    Given I have opened the calculator application
    When I add 2 and 2
    Then the result 4 should be displayed

Steps.js
module.exports = function() {

  this.Given(/^I have opened the calculator application$/, function (callback) {
    //load protractor config baseurl
    browser.get('').then(
    callback());
  });

  this.When(/^I add (\d+) and (\d+)$/, function (arg1, arg2, callback) {
    //enter numbers to be added
    element(by.model('firstNumber')).sendKeys(arg1);
    element(by.model('secondNumber')).sendKeys(arg2);
    //select mathematical operator from dropdown list
    element(by.css('select')).click();
    element(by.css('select option[value="0"]')).click();
    //hit the calculate button
    element(by.buttonText('=')).click();
    callback();
  });

  this.Then(/^the result (\d+) should be displayed$/, function (arg1, callback) {

   element(by.binding('result')).getText()
    .then(function(result){
       result === arg1 ? callback() : callback.fail();
    });
  });
};

Index.html
    <!doctype html>

    <meta charset="utf-8">
    <title></title>

    <input ng-model="firstNumber">
    <select ng-model="selectedOperation" ng-options="op as op.value for op in operations"></select>
    <input ng-model="secondNumber">
    <button ng-click="Calculate()">=</button>

App.js
    angular
  .module('calculator', [])
  .controller('MainCtrl', function ($scope) {
    $scope.operations = [
        { label: 'Add', value: '+' },
        { label: 'Subtract', value: '-' }
    ];
    $scope.selectedOperation = $scope.operations[0];
    $scope.Calculate = function(){
        switch($scope.selectedOperation.label) {
            case 'Add':
                var result = Number($scope.firstNumber) + Number($scope.secondNumber);
                break;
            case 'Subtract':
                var result = Number($scope.firstNumber) - Number($scope.secondNumber);
                break;
        };
        $scope.result = result !== NaN || result === 0 ? result : 'Boo! bad input!';
    };
  });

Protractor output:
1 scenario (1 passed)
3 steps (3 passed)
The setup above works fine. Protractor gives the correct output and I can fail the scenario by evaluating incorrect outcomes in the Then() step. Seems nice.
First problem I see is when I try to make the When step fail. For example using the same setup above but attempting to locate a nonexistent element.
  this.When(/^I add (\d+) and (\d+)$/, function (arg1, arg2, callback) {
    //enter numbers to be added. Sabotage edition!
    element(by.model('AintNoGood')).sendKeys(arg1);
    element(by.model('secondNumber')).sendKeys(arg2);
    //select mathematical operator from dropdown list
    element(by.css('select')).click();
    element(by.css('select option[value="0"]')).click();
    //hit the calculate button
    element(by.buttonText('=')).click();
    callback();
  });

Protractor output:
NoSuchElementError: No element found using locator: by.model("AintNoGood")
...
1 scenario (1 failed)
3 steps (1 failed, 2 passed)
The 2nd step fails correctly. I'm under the impression that when a step fail all subsequent steps are skipped, but protractor continues on to the 3rd step which passes anyway.
Stranger still...I empty the HTML. BDD test-first and all.
Inmdex.html
<!doctype html>

    <meta charset="utf-8">
    <title></title>

Assuming I was going through the scenario one step at a time, I write the defintion for the 2nd step assuming it will fail.
module.exports = function() {

  this.Given(/^I have opened the calculator application$/, function (callback) {
    //load protractor config baseurl
    browser.get('').then(
    callback());
  });

  this.When(/^I add (\d+) and (\d+)$/, function (arg1, arg2, callback) {
    //enter numbers to be added
    element(by.model('firstNumber')).sendKeys(arg1);
    element(by.model('secondNumber')).sendKeys(arg2);
    //select mathematical operator from dropdown list
    element(by.css('select')).click();
    element(by.css('select option[value="0"]')).click();
    //hit the calculate button
    element(by.buttonText('=')).click();
    callback();
  });

  this.Then(/^the result (\d+) should be displayed$/, function (arg1, callback) {
    callback.pending();
  });
};

Protractor output:
1 scenario (1 pending)
3 steps (1 pending, 2 passed)
So the 2nd step passes. Clearly it should not when there are none of the elements it it supposed to be locating in the html.
Questions:
Any idea what's going on here?
If not, before I spend more time trying to make sense of it, I'm wondering if anyone has had success using Protractor with CucumberJS?

A: This:
browser.get('').then(
    callback());
});

should be:
browser.get('').then(callback);

As it is, you're invoking the callback immediately and passing whatever it returns as the argument to the then.
In your first this.When you end with:
 callback();

But the element() call chains preceding it do not block.  They simply schedule operations to be done on the WebDriver control flow, so I suspect this "callback()" will get invoked almost immediately.  You can fix this by doing:
element(by.buttonText('=')).click().then(callback);

to get the callback scheduled in the controlflow.
The WebDriver control flow is counter-intuitive and often obtuse, so you'll want to read https://github.com/angular/protractor/blob/master/docs/control-flow.md and https://github.com/SeleniumHQ/selenium/wiki/WebDriverJs#control-flows.


text:
Q: Calling a PowerShell script from Wix with Parameters I'm struggling with this, as the Wix CustomAction calls PowerShell.exe with one set of parameters (Including the PowerShell script), but then I need additional parameters passing to the powershell script. I've tried to simplify, tried various quote marks in various places to try and logically seperate the parameters, but I'm having no luck. Here's what I have:
<SetProperty Id="ReplaceConnectionString"
 Before ="ReplaceConnectionString"
 Sequence="execute"
 Value=""C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NonInteractive -ExecutionPolicy Bypass -InputFormat None -NoProfile -File "[INSTALLFOLDER]ReplaceConnectionString.ps1" "MyParam"" />

<CustomAction Id="ReplaceConnectionString" BinaryKey="WixCA" DllEntry="WixQuietExec" Execute="deferred" Return="check" Impersonate="no" />

<InstallExecuteSequence>
        <Custom Action="ReplaceConnectionString" After="InstallFiles">NOT Installed</Custom>
</InstallExecuteSequence>

What am I doing wrong?

A: The solution I found was as Mathias suggested, which is to use the parameter names.
The other issue was that PowerShell doesn't like a trailing / on a parameter, which was fixed by adding an extra / to the param. Here is what I wound up with:
    <SetProperty Id="ReplaceConnectionString"
    Before ="ReplaceConnectionString"
    Sequence="execute"
    Value=""C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NonInteractive -ExecutionPolicy Bypass -InputFormat None -NoProfile -File "[INSTALLFOLDER]ReplaceConnectionString.ps1" -servername "[DB_SERVER]" -database "[DB_DATABASE]" -configPath "[INSTALLFOLDER]\"" />


text:
Q: Execute javascript code downloaded from a random website I made a tool that grabs all html, css, javascript and images from other websites (any kind).
Then i execute this on my own domain name (after modification of links of course).
The javascript also executes, so the page render is identical as on the grabbed website. But all under my domain name.
Is there any method to secure this javascript execution (with uncontrolled code) so that the grabbed site will not be able to get cookies of the users of my website ? (or other potential security breach?)
Thanks.

A: Running the random page on a separate origin (i.e. running it on a separate domain) will at least avoid data leaks (cookies, localStorage, etc) between the random page and your site. To avoid leaks from one random page to an other, maybe also run each random page on its own sub-domain.
I believe this is what google does for the cache; the pages are served from the googleusercontent.com domain: https://webcache.googleusercontent.com/search?q=cache%3Astackoverflow.com&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:fr:official&client=firefox-a
There is no way to prevent data leaks without running the page on a separate domain.

A: thought you should never execute random js on your page.
still i think there is one way to do it though it requires huge amount of effort.
onces your pages gets loaded. override all the global variables of javascript that the browser injects to your own implementation and implement security checks in there. this way all the random js  being executed in your page will access all the functionalities that way you want them to do
ex. override document.cookie to something else on pageload which then execludes that cookies of your domain.
change the protoype of xmlHttprequest so that ajax requests to your domain are blocked. etc etc


text:
Q: how to backup before update so I just installed ubuntu 15.10 on my Macbook 6,2 core i5 and it is running flawlessly. Now before I got it to where it is now, I had a previous install which didn't work that great. In the previous install I installed the proprietary Nvidia drivers alongside with a bunch of updates and upon reboot, I was stuck at the login screen. I tried uninstalling the Nvidia driver and going back to noveau but didn't work that great either.
So I ended up doing a clean installation again and this time I installed the Nvidia drivers first and it worked, Now I have some pending updates to make but I'm afraid that it might break my system. I spend the whole day configuring the system to my liking and I would hate to do it all over again.
Is there a way I can backup my settings, ala "Windows System Restore" style, update and if anything goes wrong, I can just go back to where I was?

A: Yes, you have an option to do this:

*

*Boot an Ubuntu Live DVD.

*Select Try Ubuntu.

*Now, when you are in live environment, open GParted and look for the partitions you are trying to backup, i.e., /dev/sda1 or /dev/sda2

*Next, open three terminals:
a. In one of them write this command, do not press Enter now. Keep it open after typing the command:
sudo ps aux | grep dd | awk '/root/ {print $2" "$11}'

This command will give you the PID of the dd process used later on.
After you run this command at a later time, you will get a name that would say only dd and a number infront of that, you have to take note of that number then.
b. In the second terminal write this command, do not press Enter now. Keep it open after typing the command:
watch -n 1 kill -USR1 THE NUMBER FROM STEP 4.a

This command will show you the progress of the dd process in the third terminal.
c. In the third terminal, type the following, and run it:
After running this command, immediatly run the command from 4.a first and then the command from 4.b.
sudo dd bs=4M if=/dev/sdXY of=/path/to/your/backup-directory/anyfilename.iso

Here, /dev/sdXY is the partition you want to backup.
This command will actually execute the dd command.
Now, keep tab on the terminal from 4.c and wait for the command to finish.
Backup completes on the completion of the command. Now, you can do whatever you want. Cheers!


text:
Q: How to Show No data Found in Excel? I am using PHPexcel library for export data to excel. It's working fine. The problem is it displays empty cells when no data is in the database. I want to show No data found or any other message instead of empty Cells or alternatively when the export button is clicked show alert box with some message without download excel file. How can I do it? can anyone try to help me?
Thank you...

A: You can use IF ELSE condition when you entering data in cell.
If Database value found is Blank then Write Your Message in that cell.
Otherwise write database value to that cell.