text:
Q: C# LINQ statement I have two lists; List<int> numList has identifier number as its elements, and List<string> filePaths has path to file that needs to be analyzed as its elements. I want to filter filePaths based on the numList; that is, I only want to select the filePaths whose file names have the identifier number that is present in the numList.
For example, filePaths has
C:/test/1.test.xlsx
C:/test/2.test.xlsx
C:/test/3.test.xlsx
C:/test/4.test.xlsx

and, numList has
1
2

In this case, I want to construct LINQ statement to only get
C:/test/1.test.xlsx
C:/test/2.test.xlsx

I tried
for(int i = 0; i < numList.Count; i++)
{
    filePaths = filePaths.Where(f => Convert.ToInt32(GetNumberFromString(Path.GetFileName(f))) == numList[i]).ToList();
}

And this is GetNumberFromString Helper Method
// Find number in the string
private string GetNumberFromString(string value)
{
    int number;

    string resultString = Regex.Match(value, @"\d+").Value;

    if (Int32.TryParse(resultString, out number))
    {
        return resultString;
    }
    else
    {
        throw new Exception(String.Format("No number present in the file {0}", value));
    }
}

I think this will work, but is there more elegant/efficient way of achieving this?

A: You can do it with a one-liner:
var filteredFilePaths = filePaths.Where(x => numList.Contains(GetNumberFromString(x));

A: I'd do it like this. The test method assumes that all the files in directory have appropriately formatted names. If that's not a reasonable assumption, it's easy enough to fix.
This is overkill, however, if you only ever care about the "file number" in one place.
public class TestClass
{
    public static void TestMethod(String directory)
    {
        var files = System.IO.Directory.GetFiles(directory).Select(f => new FileInfo(f)).ToList();

        var numList = new[] { 1, 2 };

        var oneAndTwo = files.Where(fi => numList.Contains(fi.FileNumber)).ToList();
    }
}

public class FileInfo
{
    public FileInfo()
    {
    }
    public FileInfo(String path)
    {
        Path = path;
    }

    public int FileNumber { get; private set; }
    private string _path;
    public String Path
    {
        get { return _path; }
        set
        {
            _path = value;
            FileNumber = GetNumberFromFileName(_path);
        }
    }

    public static int GetNumberFromFileName(string path)
    {
        int number;

        var fileName = System.IO.Path.GetFileName(path);

        string resultString = Regex.Match(fileName, @"\d+").Value;

        if (Int32.TryParse(resultString, out number))
        {
            return number;
        }
        else
        {
            throw new Exception(String.Format("No number present in the file {0}", path ?? "(null)"));
        }
    }
}

A: A stand-alone One-liner using a Join :
var result = filePaths.Select(x => new { Filename = Path.GetFileName(x), x })
    .Join(numList, x => Regex.Match(x.Filename, "^([0-9]+)").Value,
                   y => y.ToString(),
                   (x, y) => x.x);


text:
Q: Pure Css transition slide down panel not working Im trying to make slideDown Menu on hover.So on hovering HButton3 i want to extend the height of AccomodationPanel so that the buttons inside it display becasue the extend but nothing happens on hover it looks like its something in the position of the elements
HTML :
<asp:Panel runat="server" ID="Header" CssClass="header">

                   <asp:LinkButton runat="server" ID="Hbutton3" CssClass="HButton" >
                   </asp:LinkButton>

                       <asp:LinkButton runat="server" ID="StayOpen1" CssClass="StayOpen" OnClick="StayOpen1_Click" ></asp:LinkButton>

                         <asp:LinkButton runat="server" ID="StayOpen2" CssClass="StayOpen" OnClick="StayOpen2_Click" ></asp:LinkButton>

                        <asp:LinkButton runat="server" ID="StayOpen3" CssClass="StayOpen" OnClick="StayOpen3_Click" ></asp:LinkButton>

</asp:Panel>

CSS:
 .HButton {
    position:relative;
    width:20%;
    text-align: center;
    float:left;
    text-anchor:middle;
    color:white;
    text-decoration:none;
    font-size:25px;
    left:20vw;
    bottom:0;
    right:0;
    top:2vh;
    font-family:'Arial Unicode MS';
    z-index:3;
    }
.header {
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
width:100vw;
height:10vh;
background-color:#333333;
-moz-box-shadow:    0 0 3px 1px black;
  -webkit-box-shadow:  0 0 3px 1px black;
  box-shadow:          0 0 3px 1px black;

z-index:4;
position:fixed !important;
position:absolute;
}

hovering css:
#StayOpen:hover ~ #AccomodationPanel {

         height:300px;

}

A: Height of #StayOpen is 0px. Also you have to check CSS rule priorities. Your code might look like this:
#StayOpen {
    height: 100%;
}
#StayOpen:hover #AccomodationPanel {
    height:300px !important;
}

Look at this fiddle.
Transition
In your question you've mentioned about transition. You can add it in #AccomodationPanel (updated example):
#AccomodationPanel {
    -webkit-transition: height 2s;
    transition: height 2s;
}

A: It's because inline style has priority over stylesheet styles. If you move your inline style to the stylesheet it's working as expected.
#AccomodationPanel {
    position:fixed;
    left:60vw;
    width:20vw;
    top:10vh;
    background-color:#333333;
    height:0px;
    overflow:hidden;
    z-index:10;
}

Example

A: I think because your #AccomodationPanel has inline style that set height to 0px and your css wont won. To win the inline styles, you can add !important to your css. Example:
#StayOpen:hover #AccomodationPanel {
    height:300px !important;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best Way to get facebook share count and update using wp_schedule_event or any other method I recently developed a news blog, and my client needs facebook share count. I Successfully able to get the share count and update the custom field using below code.(with the help of cybermeta). What this code does is, it loops through all the available posts and gets the share count from facebook api and
updates the individual post's custom field.
register_activation_hook( __FILE__, 'cb_fb_share_count_activation' );
    function cb_fb_share_count_activation() {
        wp_schedule_event( time(), 'hourly', 'cb_update_fb_share_count' );
    }

    register_deactivation_hook( __FILE__, 'cb_delete_fb_share_count_schedule' );
    function cb_delete_fb_share_count_schedule() {
        wp_clear_scheduled_hook( 'cb_update_fb_share_count' );
    }

    add_action( 'cb_update_fb_share_count', 'cb_update_count' );
    function cb_update_count(){
        $posts = get_posts(array('numberposts' => -1) );
        foreach($posts as $post) {
            $url = get_permalink( $post->ID );
            $response = wp_remote_get('https://api.facebook.com/method/links.getStats?urls='.$url.'&format=json' );
            if( ! is_wp_error( $response ) ) {
                $fbcount = json_decode( wp_remote_retrieve_body( $response ) );
                $fb_share_count = $fbcount[0]->share_count;
                update_post_meta( $post->ID, 'cb_fb_share_count', $fb_share_count );
            } else {
                //Do something if it was an error comunicating with Facebook
            }
        }

    }

However, It does'nt seem to be a good way to get share count and updating custom field.
Is there any better approch? I don't want any problem even if the blog has 2000 articles in the long run.

A: I've actually made a plugin called Social Metrics Tracker which does exactly what you are trying to achieve. Please also feel free to read the source code on GitHub.
To answer your questions:
You are right that running an hourly cron task to update all of the posts would cause a problem with even just 200 articles because the server would make one GET request for each post every hour to the Facebook API.
Here is what I learned and what I did for my implementation:
1. Only run the update task if there is actually traffic to a post.
There is no reason to update stats for an old post with no visitors. Instead of running the update check every hour for every post, in my implementation I run the update check in the head of each individual post.
2. Use a TTL to prevent frequent updates
Store and retrieve the timestamp every time that we update stats for a given post. This way, a post won't be updated more frequently than every 3600 seconds (for example). This value is configurable since blogs with a high volume of posts will need a longer TTL.
3. Run the update in the cron
In your example above, you are already running the update in the cron (which is good). In my implementation, updates are also run in the cron to prevent additional page load time for site visitors.
Here is some example code which takes into account the three considerations above:
add_action( 'wp_head', 'checkThisPost');

public function checkThisPost() {
    global $post;
    if ($post) $post_id = $post->ID;

    $last_updated = get_post_meta($post_id, "socialcount_LAST_UPDATED", true);

    // Just an example of how this works:
    if ($last_updated > time()-3600) {
        wp_schedule_single_event( time(), 'social_metrics_update_single_post', array( $post_id ) );
    }

}

function social_metrics_update_single_post($post_id) {
    // Run the update!
}


text:
Q: Triangles of light This exercise is taken from the book Introduction to Lorenztian Geometry: Curves and Surfaces.
Exercise 1.2.13. (Triangles of light). Prove that there are not three vectors $u,v,w\in \mathbb{L}^n$ all of the light type such that $u+v+w=0$ and $\{u,v,w\}$ is linearly independent. Generalize.
Tip. You can use the square matrix of order $k$ with zeros on the diagonal and 1 in the other entries is non-singular if $k\ge 2$.
There is a result that says that: given $u,v \in \mathbb{L}^n$ light-type vectors then $u+v$ and $u-v$ are not light-type and have opposite causal characters.
So my question is: How to prove that the sum of a space- or time-type vector with a light-type vector is never the null vector?
That is, if $j$ is a space-type vector and $t$ is a light-type vector then $j+t\neq 0$. Also, if $y$ is a time vector then $y+t\neq 0$.
How would the tip's non-singular $k$ order matrix look like?
Thanks for the hel!!!


text:
Q: Java random class, need to randomize only 0,10, 20,30,40,50 instead of any number in that range Need help with my java program, I know how to use the random class to generate a random number up to a certain number; but for this specific program I need to generate a random number out of 0 ,10 ,20 ,30 ,40 , and 50.

A: Generate a number in the range of [0, 5], then multiply it by 10.

A: First generate a randomNumber in the range 0-5 and then multiply it times 10
Random random = new Random();
int randomNum = 10 * random.nextInt(6);


text:
Q: How to allow many IP address to connect MemCache Server I want to allow many IP address to connect my memcache server.
In memcache.conf,I tried with
-l ip,ip2 and some other appraches. but they didn't work. Any Idea how to connect ?
-l 0.0.0.0 works for any IP. But I want to limit for given IP addresses.


text:
Q: A new stackexchange for Linux Desktop Environments is needed : Askubuntu is too specific, Unix and Linux is too broad PPS. I have added a related question now - How to proceed when proposal for a new Stack Exchange is turned due to admin's ignorance of domain? which addresses the point raised here.
PS. The reason not to close can found at the end
Some years ago I proposed a new StackExchange for non-Ubuntu desktop environments because

*

*Ask Ubuntu did not like questions on Debian

*There are whole areas of Linux which are not Ubuntu specific

*Unix SE tends to be focused more on lower level, glue level aspects of Linux and the command line and it doesn't go into desktop issues as much.
utilities
bash 14758
grub 6639
swap 5937
init 5076
mysql 3618
init.d 2845
crontab 2626
systemd 2090
docker 1873
zsh 1460
system v 1451
python 1333
upstart 877
rc.d 922
puppet 502

desktops
debian 9389
arch 7574
ubuntu 7510
mint 6290
fedora 3009
gnome 1552
kde 986
kde4 322
kde5 186

You can see from the tags how much Unix/Linux is focused more on the underlying glue and utilities rather than issues relating to the desktop environment. Combining the two areas is like trying to serve Windows server administrators and Windows end users from the same forum. I don't think any SE developers and administrators would ever do that
In Linux server administrator issues are quite different from desktop user related issues, but as most Linux desktop users have to be their own administrators, there is an overlap but only the minimum desktop users need to do to fix the desktop issues and get back to work.
To be honest each of the Linux desktop derivatives need their own SE and admins can probably tag them and move them if they are miscategorized or are in the wrong forum.
I brought this up some years ago and it was shot down immediately on the grounds that Unix and Linux SE is a good substitute. You only have to look at r/unix and r/linux on reddit to see how conceptually differently they are viewed.
Whatever the case may or may not be for different Stack Exchanges for the desktop environments the desktop environments and the OS proper should have different exchanges. Linux itself is the operating system, the kernel more accurately and the derived OSs and desktop environments are quite different.
UPDATE
For those who believe I should make a new proposal this is question explains the reason why. Is there any trace of my closed proposal?.
If there is a means of getting past a proposal which will allow other interested users to chime in before it is immediately turned down  or there is some other faq, question or Q&A on how this point can be discussed I'd like to be directed to it

A: These questions might be on-topic on Unix & Linux.  SE won't create a site for questions that are already in scope on the network, so you need to try that first.
Yeah, it's not their most popular tag -- so what?  If the question is still on-topic there, you're set.  If it's not, it should produce a clear audit trail -- a close reason, a meta FAQ, or similar -- that demonstrates it's off-topic there too, at which point you can head over to Area 51 to explore a new site, armed with evidence that the questions you have in mind aren't welcome on the existing sites.


text:
Q: Why does my project copy not compile? I want to copy an old project in overleaf as I'd like to keep the old version as it is.
When I copy the entire project, the unchanged exact copy fails to compile a pdf.
The only difference I found is in the Raw logs the original version lists:
This is XeTeX, Version 3.14159265-2.6-0.999991 (TeX Live 2019) (preloaded format=xelatex 2019.12.13)  9 MAY 2022 09:00
entering extended mode
 \write18 enabled.
 %&-line parsing enabled.
**cv.tex
(/compile/cv.tex
LaTeX2e <2019-10-01> patch level 3
(/usr/local/texlive/2019/texmf-dist/tex/latex/base/article.cls
Document Class: article 2019/10/25 v1.4k Standard LaTeX document class
(/usr/local/texlive/2019/texmf-dist/tex/latex/base/size10.clo
File: size10.clo 2019/10/25 v1.4k Standard LaTeX file (size option)
)

While the copy has another version:
This is XeTeX, Version 3.141592653-2.6-0.999993 (TeX Live 2021) (preloaded format=xelatex 2021.9.30)  9 MAY 2022 08:59
entering extended mode
 \write18 enabled.
 %&-line parsing enabled.
**cv.tex
(./cv.tex
LaTeX2e <2021-06-01> patch level 1
L3 programming layer <2021-07-12> (/usr/local/texlive/2021/texmf-dist/tex/latex/base/article.cls
Document Class: article 2021/02/12 v1.4n Standard LaTeX document class
(/usr/local/texlive/2021/texmf-dist/tex/latex/base/size10.clo
File: size10.clo 2021/02/12 v1.4n Standard LaTeX file (size option)
)

How can I make an exact copy, including the correct version?

A: Click the menu button (top right)

Then find Settings and make sure the Compiler it is set to XeLaTex

Then set the > TeX Live version to the desired one to match the original one:


text:
Q: I am trying to instantiate few modules to work in top level design, but even though there is no error but I am not getting proper output This is my verilog code. Though I am not getting any output, if any two of the instantiated modules are commented then I am getting proper partial output(For full output I need all of them to work). But all three as simulated together then the variables are as if they haven't been instantiated. All of the calculations are for Posit Numbers. I will send the link for understanding this number format.
I have to perform:x1=xin2 and then x2=1-x1tmp(this is where I am using x1tmp=-x1) and finally err=xx2. Over all I have to perform err=x(1-x*in2).
    module check(x, in2, err, start);//x and in2 are inputs for this module and //err is the output.Start is the signal given from testbench for starting this module
    parameter N = 32;// This is the bus width for all the variables.
    parameter es = 3;// This is the parameter required for calculating
    input       [N-1:0]x;
    input   [N-1:0]in2;
    output  [N-1:0] err;
    wire        [N-1:0] x1;//These are nets declared for intermediate calculation
    wire        [N-1:0] x2;//Same as that of x1
    wire        [N-1:0] oru = {{(3){1'b0}},1'b1,{(N-4){1'b0}}};// This is "1" in //posit number format
    posit_mult #(.N(N),.es(es)) m1(x, in2, start, x1, inf, zero, done);//x1=x*in2, where the rest of them are status signals(1-bit)
    wire        [N-1:0] x1tmp = -x1;//To get 2's complement of x1
    posit_adder #(.N(N),.es(es)) a1(x1tmp, oru, start, x2, inf, zero, done);//x2=x1tmp+oru
    posit_mult #(.N(N),.es(es)) m2(x, x2, start, err, inf, zero, done);//err=x*x2
endmodule

A: The mistake I did was using same status signals for multiple instances. I sincerely thank @toolic for helping me out. The italicized signals in the code should have been distinct for each module, because of using same variables it caused contention.
module check(x, in2, err, start);//x and in2 are inputs for this module and //err is the output.Start is the signal given from testbench for starting this module
    parameter N = 32;// This is the bus width for all the variables.
    parameter es = 3;// This is the parameter required for calculating
    input       [N-1:0]x;
    input   [N-1:0]in2;
    output  [N-1:0] err;
    wire        [N-1:0] x1;//These are nets declared for intermediate calculation
    wire        [N-1:0] x2;//Same as that of x1
    wire        [N-1:0] oru = {{(3){1'b0}},1'b1,{(N-4){1'b0}}};// This is "1" in //posit number format
    posit_mult #(.N(N),.es(es)) m1(x, in2, *start*, x1, *inf*, *zero*, *done*);//x1=x*in2, where the rest of them are status signals(1-bit)
    wire        [N-1:0] x1tmp = -x1;//To get 2's complement of x1
    posit_adder #(.N(N),.es(es)) a1(x1tmp, oru, *start*, x2, *inf*, *zero*, *done*);//x2=x1tmp+oru
    posit_mult #(.N(N),.es(es)) m2(x, x2, *start*, err, *inf*, *zero*, *done*);//err=x*x2
endmodule

This can be solved either by using distinct variables or by removing them(if they are not useful) as:
module check(x, in2, err, start);//x and in2 are inputs for this module and //err is the output.Start is the signal given from testbench for starting this module
    parameter N = 32;// This is the bus width for all the variables.
    parameter es = 3;// This is the parameter required for calculating
    input       [N-1:0]x;
    input   [N-1:0]in2;
    output  [N-1:0] err;
    wire        [N-1:0] x1;//These are nets declared for intermediate calculation
    wire        [N-1:0] x2;//Same as that of x1
    wire        [N-1:0] oru = {{(3){1'b0}},1'b1,{(N-4){1'b0}}};// This is "1" in //posit number format
    posit_mult #(.N(N),.es(es)) m1(x, in2, , x1, , , );//x1=x*in2, where the rest of them are status signals(1-bit)
    wire        [N-1:0] x1tmp = -x1;//To get 2's complement of x1
    posit_adder #(.N(N),.es(es)) a1(x1tmp, oru, , x2, , , );//x2=x1tmp+oru
    posit_mult #(.N(N),.es(es)) m2(x, x2, , err, , , );//err=x*x2
endmodule

A: For code review, I have reformatted and added comments that reflect my partial understanding of this code. One thing that makes this type of code difficult to read and understand is that the port names do not give any hint whether they are input or output. Since this is a toplevel module only, I can only guess about the signature of the submodules and the semantics of the ports. There was a comment about MCVE (Minimal, Complete, Verifiable Example), there's a limit to what can be seen with just one module missing the submodules.
I suspect that the problem is somewhere in the undeclared, implicit connections of the ports inf, zero, and done. With no explicit definition of these wires, Verilog will assume that these are single-bit wires.
Recommendations
I recommend you examine the RTL output of translation phase, very likely something is going wrong at that level. See my other answer about using RTL as a diagnostic here: https://electronics.stackexchange.com/a/497663/35022
Reading and understanding another person's code is always hard, hopefully you can see from the gaps in my comments the areas that can be unclear. Even for homework, it's good to develop the habit of explaining through variable names and brief comments what each module, wire, and reg is supposed to be doing. The module itself should also have a standard block comment, explaining in a few sentences or a paragraph what the module is intended to accomplish.
The style of indentation that I'm using here is one that I use on larger projects, having many more parameters and ports. I use indentation to help distinguish input ports from output ports. Usually I also append a suffix of _i, _o, or _io to port names in the modules, to further distinguish inputs from outputs. Wires themselves are neither input nor output, but there should be exactly one output driver connected to each wire (unless it's some tricky tri-state wire scheme).
// https://electronics.stackexchange.com/questions/500439/i-am-trying-to-instantiate-few-modules-to-work-in-top-level-design-but-even-tho
// code review https://electronics.stackexchange.com/users/35022/marku
//
// Module check
// navaneet rao https://electronics.stackexchange.com/users/252818/navaneet-rao
// licensed under cc by-sa. rev 2020.5.18.36843
//
// testbench for module posit_mult and module posit_adder.
// usage: set up data inputs x and in2, then enable with a high level on start.
// there is no clock, this is all combinational logic.
// expect output port err should report ???____??? if all is well.
//
module check(x, in2, err, start);
parameter N = 32; // data width
parameter es = 3; // ??? not sure what this is, but it is passed to the submodules
// input/output port declaractions
input   wire [N-1:0] x;
input   wire [N-1:0] in2;
input   wire         start; //Everything is explained in the below module.
                            // ???
output  reg  [N-1:0]         err;    // driven by instance m2

// internal connection wires
wire [N-1:0] x1; // driven by instance m1

wire [N-1:0] x2; // driven by instance a1

wire [N-1:0] oru = {{(3){1'b0}},1'b1,{(N-4){1'b0}}};

// wire inf;  // ??? implied, not declared, is this a 1-bit wire or a reg?
// wire zero; // ??? implied, not declared, is this a 1-bit wire or a reg?
// wire done; // ??? implied, not declared, is this a 1-bit wire or a reg?

// internal submodule declarations
posit_mult #(
    .N(N),
    .es(es)
) m1 (
    x,      // driven from toplevel
    in2,    // driven from toplevel
    start,  // driven from toplevel
        x1,     // output
            inf,    // ??? what drives this wire?
            zero,   // ??? what drives this wire?
            done    // ??? what drives this wire?
);

wire [N-1:0] x1tmp = -x1; // x1tmp is 2's complement negation of x1

posit_adder #(
    .N(N),
    .es(es)
) a1 (
    x1tmp,  // 2's complement of x1 driven from toplevel
    oru,    // constant input
    start,  // driven from toplevel
        x2,     // output
            inf,    // ??? what drives this wire?
            zero,   // ??? what drives this wire?
            done    // ??? what drives this wire?
);

posit_mult #(
    .N(N),
    .es(es)
) m2 (
    x,      // driven from toplevel
    x2,     // driven from instance a1
    start,  // driven from toplevel
        err,    // output
            inf,    // ??? what drives this wire?
            zero,   // ??? what drives this wire?
            done    // ??? what drives this wire?
);

endmodule


text:
Q: Is salesman the natural term to use about a male appliance store employee who walks around trying to help customers? Is salesman the natural term to use about a male appliance store employee who walks around trying to help customers?
According to the OALD a salesman is

a man whose job is to sell goods, for example, in a shop

*

*a car salesman

A: "Sales assistant" would be a better term.  Usually a "salesman" or "salesperson" is not someone working in retail, but someone who travels to customers. "Sales assistant", or perhaps "Sales associate" is  the job working in a shop.
Note. You should use "salesperson" unless you want to specifically exclude women. Use the gender neutral term if possible. A man who sells things is a "salesperson".

A: 'Salesman' (or the gender neutral 'salesperson') is a common generic term in many dialects for someone whose job is to actively sell things. Depending on context, it may be interchangeable with the term 'dealer', though I would hesitate to use that outside of fixed phrases in modern English (due to the most common usage being in the phrase 'drug dealer', for someone who sells illegal drugs). Traditionally, the term 'salesman' also, in many parts of the world, implies a position where the employee is paid at least in part on commission (that is, they get paid based on how much they sell, either calculated by total revenue they generate, or by total units of product sold). Note that 'salesman' does not imply that the job is a comercial retail position.
In many places, the preferred terms have become 'sales associate' or 'sales assistant'. This has occurred largely because the stereotype of a 'salesman' is, for most people, a somewhat sleazy person trying very aggressively to sell an often inferior product and willing to do almost anything to get a sale (because as mentioned above, they're probably paid on commission), which is not an image most businesses wish to convey about their employees. Unlike 'salesman', these terms do not necessarily imply employees paid on commission. Just like 'salesman' however, neither of these terms implies commercial retail either. 'Sales associate' especially has become popular as a job title for people who respond to sales inquiries for online retail or for purchases made directly from manufacturers (especially in the technology sector).
In the context of modern brick-and-mortar retail though, you may see any number of different terms for this type of job. 'Clerk' is often usable as a generic (though it also includes the people running the cash registers, among other roles), and is what I would probably use in this case unless I knew for certain that the person in question's sole job was to answer customer questions. 'Floorwalker' may also be used, but that's a bit more regional, and may also cover employees tasked with loss prevention or restocking. 'Shop assistant' is another possibility, though that is also rather generic (albeit in different ways from 'clerk' or 'floorwalker'. Unlike the other terms I've mentioned, all three of these do generally imply commercial retail.

A: A person in the role you describe could be a floorwalker. This person is not directly involved in sales, but helps customers by helping them find the correct salesperson or the goods they are looking for. An example from television is Captain Peacock in Are you being served?

A: You can also let the term be extremely generic, "member of staff", which is what I frequently use

*

*clearly and simply someone who works for the store

*can be used in most situations without any implication of rank or role

*non-gender-specific

I think this is especially useful and I would use this query when it's not clear if someone works for the store, but I'm looking for someone to ask them a question, and someone who might work for the store simply has similar attire, appears to be making changes to a shelf (such that I cannot see if they're wearing a logo), etc.

excuse me, are you a member of staff?

A "salesman" is in my mind, expected to be in the business of selling, must identify themselves as male, and very often receives some form of commission for their work (directing, informing, etc. customers), while often any member of a store's staff can and should direct you, such as closer or directly to some item or area you're looking for, or even a more knowledgeable member of staff, regardless of if it's their primary role and you are somewhat interrupting their activity (dedicated shelf-restocking, manager, etc.)

A:
Is salesman the natural term to use about a male appliance store employee who walks around trying to help customers?

"Salesman" is a perfectly fine and natural English language expression. But it is outdated in many parts of the world.
Having worked in retail, I can tell you that these terms (i.e., salesman, salesperson) are commonly used for people who work in the stores as well as for those who visit customers/clients in their homes/offices.

Merriam-Webster:
a person (especially a man) whose job is to sell a product or service in a given territory, in a store, or by telephone
Cambridge:
a person, usually a man, whose job is to sell products in a store, or by visiting or phoning customers or possible customers:
a car/computer salesman
a bond/equity/insurance salesman

But try not to refer to a female salesperson as a salesman - that may very well get you into trouble.
Note that in some regions, retail businesses prefer using the term "sales associate" or "sales assistant" as opposed to "salesman" or "salesperson". The "associate" or "assistant" variants are considered by some to be a bit more respectful, and to reflect higher status and expertise than the other terms. This is however anecdotal (based on my experience), and there could very well be regional differences.
This is from Indeed:

A Sales Associate, or Shop Assistant, promotes the company's products and services and helps to answer questions customers may have about the company's activities. Their duties include helping customers make buying decisions, servicing existing customers, and overseeing purchase agreements.
Sales Associates are part of the sales team. They are usually front-liners, meaning that they represent the voice of the business and are the first to interact with the customers. They help customers meet their buying needs. Sales Associates are also responsible for drafting and submitting periodical reports based on sales and other occurrences in the company.

Another similar role is that of a "sales/retail clerk". They have slightly different duties (including some overlap with those of a cashier and a teller). See Wikipedia.


text:
Q: indexOf is not a function error while focusing on an input

$('input').focusout(function() {

  if ($(this).indexOf('@') > -1 && $(this).indexOf('.') > -1) {
    $('.status').html('Valid Email');
  } else {
    $('.status').html('Your email is invalid, Please try again');
  }
});

<input name="email" placeholder="Email">

When I focus out from input area, it gives error indexOf is not a function.

A: There are two things you should consider in your solution.

*

*$(this) will refer to its parent which is in your particular case it is $('input'). So if you want to check whether @ or . exists in your input value, you should refer to val() method within your query, so it will return the current value of your input.

So your final code should be something like this:

$('input').focusout(function() {

  if ($(this).val().indexOf('@') > -1 && $(this).val().indexOf('.') > -1) {
    $('.status').html('Valid Email');
  } else {
    $('.status').html('Your email is invalid, Please try again');
  }
});

<input name="email" placeholder="Email">

*Whilst your solution for checking special symbols in email working fine it won't check the entire input characters. So the best way (best practice) to check such a thing is to using regular expressions. Thus you should create a proper regex with either RegExp or regular expression literals.

So your final code would be like this:

const emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

$('input').focusout(function() {
  if (emailRegex.test($(this).val())) {
    $('.status').html('Valid Email');
  } else {
    $('.status').html('Your email is invalid, Please try again');
  }
});

<input name="email" placeholder="Email">


text:
Q: How to factorise $x^2 + x - 1$? I was asked to prepare a set of notes for year 12 students. These notes are going to be used by these students to prepare for the examinations. Naturally, I searched for problems to include so the students could get practice and I came across the following problem

Factorise $7x^2 + 7x - 7$ as far as possible

When making the solutions document I had difficulties in going far "as far as possible". I easily saw that $7(x^2 + x - 1)$ was one possible factorisation, but then I proceeded to see if I could factorise $x^2 + x - 1$ and it was here that I became stuck. I tried using the quadratic formula to find the roots and express $x^2 + x - 1$ as $(x_1 - root1)(x_2 - root2)$, but I couldn't seem to find such an expression. After all of that I used Wolfram Alpha and was given an irreducible factorisation of $-1/4 (-2x + \sqrt{5} -1)(2x + \sqrt{5} + 1)$. I tried to work backwards to see if could come to this factorisation, but either my lack of creativity or my terrible computation skills have left with me no solution.
If I could get a hint (maybe a solution too, but one hidden by spoiler block would be nice just so I can attempt it myself first), I'd be really thankful.

A:
I tried using the quadratic formula to find the roots and express $x^2 + x - 1$ as $(x_1 - root1)(x_2 - root2)$, but I couldn't seem to find such an expression.

That's a good idea; perhaps something went wrong when finding those roots?
Carefully use the quadratic formule for the roots of $\color{red}{a}x^2 + \color{blue}{b}x + \color{green}{c}$, so:
$$\color{red}{1}x^2 + \color{blue}{1}x \color{green}{-1} = 0 \iff x = \frac{- \color{blue}{1} \pm \sqrt{\color{blue}{1}^2-4 \cdot \color{red}{1} \cdot (\color{green}{-1}})}{2\cdot\color{red}{1}}=\frac{-1 \pm \sqrt{5}}{2}$$
So:
$$x^2 + x - 1=\left(x-\left(\frac{-1 + \sqrt{5}}{2}\right)\right)\left(x-\left(\frac{-1 - \sqrt{5}}{2}\right)\right)$$
You could rewrite/simplify this further to see it matches WolframAlpha's answer.

A: You can either use the quadratic formula or complete the square.  The quadratic formula gives you the roots directly.  If you don't know it, write
$$
    \begin {align}
        x^2+x-1&=\left(x^2+x+\frac 14\right)-\frac 54\\
        &=\left(x+\frac 12\right)^2-\frac 54\\
        &=\left(x+\frac 12+\frac {\sqrt 5}2\right)\left(x+\frac 12-\frac {\sqrt 5}2\right)
    \end {align}
$$
where you can combine the fractions if you want.  From the second to the third line is seeing the difference of squares.

A: Write your equation as
$$x^2 + x -1 = (Ax+B)(Cx+D)$$
for some real numbers $A,B,C,D$. Multiplying out the right side, we find that
$$x^2+x-1 = ACx^2 + (BC + AD)x - AC$$
This implies that $AC = 1$, $BC + AD = 1$, and $BD = -1$. You can solve this system to return some desired values.


text:
Q: Switched to VS 2012 and now form doesnt resize properly? I switched to VS 2012 yesterday from VS 2010 and all seemed to go well except this.
I have a button on my form that when pressed extends the width of the form to show additional controls. Press the button again and it reduces the width to hide those controls. Now all of this worked great in VS 2010 and also works fine when I debug in VS 2012 but as soon as I publish or compile the project and open the .exe when you click on the button it adds like 5 to the width instead of the 100+ it needs to. I click it again and it will then change it to 372 like it should and shows all my controls. I click it again to hide the controls and it hides the controls partially (goes to the 188 + the mysterious 5) I hope all of this makes sense and am hoping there is a better way to run the process I need to.
Here is the code I am currently working with and I didn't change anything between switching from 2010 to 2012. In fact, if I open this same solution in 2010 and publish everything works fine.
    private void button1_Click(object sender, EventArgs e)
    {
        if (this.Width == 188)
        {
            this.Width = 372;
            this.Height = 540;
            progressBar.Value = 100;
            copied_status.Text = ("Output View Enabled");
        }
        else
        {
            progressBar.Value = 100;
            copied_status.Text = ("Output View Disabled");
            this.Width = 188;
            this.Height = 540;
        }

        if (this.Width == 372)
        {
            button1.Text = "<<";
        }
        else
            button1.Text = ">>";

    }

A: The width of your form hasn't been 188 pixels in a long time.  Now with VS2012, Windows finally stops lying about it.
At issue are the fat window borders in Aero.  They were an extreme appcompat problem when the feature was introduced in Vista.  Very necessary because those two pixels where getting hard to hit with a mouse.  But drastically incompatible with the way an application creates a window.  It asks for a specific window size, the outer size, the nWidth and nHeight arguments of the CreateWindow() function.  But what really matters is the size of the client area, the part of the window inside the borders.  If Microsoft wouldn't have done something about it, old applications would have ended up with a client area that was too small.  Which looks very bad, the window content would not fit anymore.  A control towards the bottom or right side of the form would not be completely displayed for example.
So, sneakily, Aero makes the window larger by the extra width of the fat borders.  And when the app asks for the window size, it sneakily says that it is smaller by the same added width.  The app doesn't know any better than it is still running with the same window size it had on XP.  This works pretty well, but is not exactly ideal.  Hard to get window edges to align properly with that lie for example.
Whether or not Aero will lie about the window size is based on the target operating system recorded in the EXE header.  When it sees a version older then 6.00, the Vista version number, then it will assume that your EXE is a legacy program that doesn't know about the fat border feature.  So needs to be lied to.  You've been running with that target version number set to 4.00 for a long time, it is written by the .NET compiler when it builds your program.  You can see it with dumpbin.exe /headers yourapp.exe.
This finally changed in VS2012 and .NET 4.5.  Which is a .NET version that is not available in XP.  The compiler can finally make the hard assumption that XP is history and you are going to run on a version of Windows that supports Aero.  So it sets the target Windows version in the EXE header to 6.00.  Correspondingly, Aero will now stop lying about the window size.  You get the real one, not the faked one.
So a quick fix is to change the target .NET framework version to 4.0.  That's available on XP so you'll get lied to again.
Of course it is better to fix your code.  Never use the Size, Width or Height property, they'll inevitably depend on the border and caption size.  Use the ClientSize property instead, that's the stable one and the one you really care about.  But be careful with that property as well, a form may rescale when it runs on a machine that has its video adapter set to more than 96 dots per inch.  Another feature that's very accessible in Vista and up.  Rescaling changes the ClientSize proportionally by the DPI setting.
The real fix is to use a bool field instead that keeps track of the window state.  And set the ClientSize property based on the position of a control you want to hide or reveal.  So roughly:
private bool enlarged;

private void button1_Click(object sender, EventArgs e)
{
    enlarged = !enlarged;
    int width = someControl.Left - 5;
    if (enlarged) width = someControl.Right + 5;
    this.ClientSize = new Size(width, this.ClientSize.Height);
}

Replace someControl in this code with the name of your controls.


text:
Q: How to start Docker containers on boot, managed with Ansible (Tower) Currently we use the combination of Ansible + Ansible Tower to deploy and run our applications in Docker containers.
However, I was wondering how to automatically run the deployed containers after a system reboot. What would be the way to go here? The only solution we came up with is to automatically request the Tower callback URL of the application deployment playbook(s) on boot, but that seems suboptimal.

A: You could use restart policies.
I do not know how exactly ansible creates containers. But usually you could add a parameter on command line like:
docker run --restart=always ...

A: restart_policy: always

or
restart_policy: unless-stopped

link:
https://docs.ansible.com/ansible/latest/modules/docker_container_module.html


text:
Q: Specifying a specific browser version in a selenium test run I have two windows Selenium slaves, one with IE9 and one with IE10.
The nodes are configured using node json config:
    {
      "browserName": "internet explorer",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "version": 10
    }

And in the test (running through Robotframework and Selenium2Library):
Open test browser
    Log to console  Open ${siteUrlFull} in ${browser}
    Open browser  ${siteUrlFull}
    ...  remote_url=http://192.168.10.207:4443/wd/hub
    ...  desired_capabilities=version:10,browserName:${browser}

However, the test keeps failing with the error:

WebDriverException: Message: Error forwarding the new session cannot
  find : Capabilities [{marionette=false, browserName=internet explorer,
  javascriptEnabled=true, version=9, platform=ANY,
  firefox_profile=UEsDBBQAAAAIACJxREjOFgm64wIAA...}]

The hub status page shows clearly that the browsers are configured with a "9" and a "10" in front of the IE icons.
But for some reason, Selenium refuses to accept the version request.

A: It turned out that the version property is a string and thus must be specified as such in the node config:
    {
      "browserName": "internet explorer",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "version": "10" <-.
    }                   |
 >--------Quotes!-------'


text:
Q: Pyramid config .ini files, setup.py and requirements.txt I just started learning Pyramid using the official documentation and I found it very cool so far.
Unfortunately, while the basic one-file app is really simple and straight, I'm having an hard time trying to understand how a "serious app", generated using the pcreate scaffolding command (alchemy in my case), is supposed to be handled.
For example:

*

*is setup.py mandatory or can I just use requirements.txt as I'm used to do with Django in order to install dependencies?

*if I have to rely on setup.py am I supposed to execute python setup.py develop each time I create/delete a new file (since I saw them listed in SOURCES.txt)?

*In settings.ini how "use" (under [app:main]) works? (can I "bypass" the egg-info which is it pointing to and "bootrsapping" the app in an alternative way?)

A: There are several tutorials that addresses all these topics, and provide references to further relevant reading for each step along the way. I suggest starting with the Quick Tutorial.
To answer your bullet points in order:

*

*setup.py is a standard for installing Python packages and dependencies and testing your app.

*If you need to install more packages as a result of your changes, then yes. EDIT: It is now recommended to use pip install -e . for installing more packages. Also while developing, you can use pserve development.ini --reload which will monitor file changes and restart the server for you.

*For more information about the meaning of the use = egg:MyProject, see Entry Points and PasteDeploy .ini Files. There are many ways to configure Pyramid apps including Application Configuration and Advanced Configuration.

A: You chose Pyramid, the best Python web microframework, a very choice! Here are some pointers for further insight. Actually your question is not specific to Pyramid, but generally how Python packages and applications generally work.

is setup.py mandatory or can I just use requirements.txt as I'm used to do with Django in order to install dependencies?

It is not. You can use requirement.txt. setup.py install_dependencies is mainly for libraries. For more information read blog post Declaring dependencies in Python.

if I have to rely on setup.py am I supposed to execute python setup.py develop each time I create/delete a new file (since I saw them listed in SOURCES.txt)?

It's not necessary.

In settings.ini how "use" (under [app:main]) works? (can I "bypass" the egg-info which is it pointing to and "bootrsapping" the app in an alternative way?)

Please see the other answer regarding Paster and Entry points.


text:
Q: opendkim only signs for 1 zone on a hosted server I am implementing opendkim but I can only get it to sign for 1 zone.
The tld is failing to sign even though it is the same key/signature/file for both domains.
my .conf:
cat /usr/local/etc/mail/opendkim.conf

LogWhy                 yes
Syslog                  yes
SyslogSuccess           yes

Canonicalization        relaxed/simple

Socket                  inet:8891@107.191.60.48
MilterDebug             5
ReportAddress           postmaster@e-mailer.com
SendReports             yes

InternalHosts           file:/usr/local/etc/TrustedHostList.txt
SigningTable            refile:/var/db/opendkim/dkim-signtable
KeyTable                file:/var/db/opendkim/dkim-keytable

signing table:
cat /var/db/opendkim/dkim-signtable
*@nyctelecomm.com nycmap
*@e-mailer.com emailmap

key table going to the same key:
cat /var/db/opendkim/dkim-keytable
emailmap e-mail.com:default:/var/db/opendkim/keys/e-mailer.com.key
nycmap nyccomm.com:default:/var/db/opendkim/keys/e-mailer.com.key

response from port25.com:
----------------------------------------------------------
DKIM check details:
----------------------------------------------------------
Result:         permerror (key "default._domainkey.e-mail.com" doesn't exist)
ID(s) verified:
Canonicalized Headers:
    from:"user"'20'<user@e-mailer.com>'0D''0A'
    to:<check-auth@verifier.port25.com>'0D''0A'
    subject:'0D''0A'
    date:Mon,'20'16'20'Mar'20'2015'20'16:53:33'20'-0400'0D''0A'
    dkim-signature:v=1;'20'a=rsa-sha256;'20'c=relaxed/simple;'20'd=ex-mail.com;'20's=default;'20't=1426539201;'20'bh=MhPgNzFR7ZDrllybqjf7Ky1x0INMPJ5OEWy00nl+zGI=;'20'h=From:To:Subject:Date;'20'b=

just like  ->  server fault
How do I get opendkim to sign both of my domains and not just one?

A: Try changing ex-mail.com to ex-mailer.com in your key file.


text:
Q: Securing docker containers between 2 servers One of my RPI's (3B+) (192.168.0.3) is running out of memory so I want to remove NginxProxyManager running in docker container from RPI to save some memory.
I put couple of the containers running on RPI (192.168.0.3) behind another NginxProxyManager running on my main server (192.168.0.2). So far so good.
The only problem with this solution I have is that you can access the containers with RPI's IP and port number from any device on the same network and if I think correctly the data between NPM on my main server and RPI containers are not encrypted (some containers do not use HTTPS).
The connection is on my local LAN so it should be secure and there should not be any snooping but still I would like to create some kind of direct tunnel between 192.168.0.2 and 192.168.0.3 (certain ports and containers only).
What would be the proper way to allow ONLY my main server to certain ports on my RPI?
Or am I worrying too much? ;-)


text:
Q: Catch FCM notification message in service worker after click_action triggered The issue, I am facing with notification messages is, that a new tab is opened, whenever the complete URL of the defined click_action is not matching any opened tab.
Assuming click_action equals mydomain.com and there is an opened tab with the URL mydomain.com/anyroute. A new tab is opened, because the URLs do not match. But I would like the already opened tab to be focused instead of opening a new tab.
Can a notification message be catched by the service worker after a user clicks on the message or is there any other possibility?
EDIT: So far, the service worker's events like onBackgroundMessage or notificationclickare not passed, since the push notification is if type notification_message.

A: You can use the on like explained here.
messaging.onBackgroundMessage((payload) => {
  console.log(
    "[firebase-messaging-sw.js] Received background message ",
    payload
  );
  // Customize notification here
  const notificationTitle = "Background Message Title";
  const notificationOptions = {
    body: "Background Message body.",
    icon: "/firebase-logo.png",
  };

  // Loop trough all clients controled by the SW
  self.clients.matchAll(options).then(function (clients) {
    // Let's see if we already have a chat window open:
    const url = new URL(client.url);

    if (url.pathname == "/custom_url/") {
      // Excellent, let's use it!
      client.focus();
    }

    // do something with your clients list
  });

  self.registration.showNotification(notificationTitle, notificationOptions);
});

Where you can use self.clients to loop trough all tabs/clients of your app that are controled by the SW. You can focus to a specfic client if the url/patch matches.


text:
Q: Eliminating NULL by using NULL object pattern interface Parent{
    void process();
}

class Child1 implements Parent{
    void process(){
        //process by method 1
    }
}

class Child2 implements Parent{
    void process(){
        //process by method 2
    }
}

class DummyChild implements Parent{
    void process(){
        //do nothing
    }
}
class D {
    Parent getObj(){
        if(condition1){
            return new Child1();
        }
        else if(condition2){
            return new Child2();
        }
        else
        return new DummyChild();
    }
    public static void main(String[] args){
        Parent obj = getObj();
        obj.process();
    }
}

In the above code, I have created a DummyChild class so that whenever getObj() is invoked for fetching the correct class object, instead of returning NULL I return the dummyClass object(singleton). This eliminates the NULL check in my code thereby removing the branching because of this condition.
Is this a correct place of using the NULL object pattern or should I use the NULL approach?

A: Use of a 'do nothing' implementation of an interface is a good use of the pattern when it semantically makes sense to do so.  The question is, when does it make semantic sense to do so?
The key question that I use is: 'am I modelling a 0-1 relationship or a 1-1 relationship'.  In the first case, then using Optional to communicate that fact makes it very clear to developers and helps us with compile time support. If we are modelling a 1-1 relationship, and we really mean 'do nothing' in some case then the 'do nothing' implementation that passes the Liskov substitution principle is a very elegant solution.
For a discussion on cardinality in data modelling, have a read of the following book snippet: Cardinality.  In brief, cardinality is the number of things that a relationship between two things can represent. For example, when modelling a car;  how many engines would we expect it to have?  0-1 would mean that a car can have zero or one engine, 1-1 would mean that a car must have exactly one engine, 0-many would mean that the car could have 0, 1, 2, 3, 4 ... engines.

A: You can use Optional instead of re-inventing the wheel:
class D {
    Optional<Parent> getObj(){
        if(condition1){
            return Optional.of(new Child1());
        }
        else if(condition2){
            return Optional.of(new Child2());
        }
        else {
            return Optional.empty();
        }
    }
    public static void main(String[] args){
        Optional<Parent> obj = new D().getObj();
        obj.ifPresent(Parent::process);
    }
}


text:
Q: Laravel 5 relationships hasOne save()? I have two tables Projects and Galleries. Project has one gallery. In galleries table I have a foreign key project_id.
Schema::table('galleries', function (Blueprint $table) {

            $table->integer("project_id")->unsigned()->nullable()->default(null);

            $table->foreign("project_id")
                    ->references("id")
                    ->on("projects")
                    ->onDelete("set null");

        });

In Project model I have a function that gets the gallery associated with the project:
public function gallery()
  {
    return $this->hasOne("App\Gallery");
  }

When creating new project, user selects from drop down the gallery then when saving a new project, how can I update galleries table to use newly created projects_id
$gallery_id = 2; // user selected gallery 2

$project = new Project();
$project->title = "new project";
$project->save();

A: Try the following:
$gallery_id = 2; // user selected gallery 2

$project = new Project();
$project->title = "new project";
$project->save();

$gallery = Gallery::find($gallery_id);
$gallery->project_id = $project->id;
$gallery->save();


text:
Q: Camera image picker and shake gesture? Is it possible to detect a shake gesture when an UIImagePickerController is presented with camera source type? In such case, where/how should I implement it?

A: It is not possible.
A workaround is to make a custom image picker and then in that view controller implement the shake gesture.


text:
Q: Population issue using Mongoose It's been a longtime i didn't use MongoDB, i am doing some queries and there is a basic situation i can't achieve:
//Works fine
Db['group'].findOne({ token: "token" })
.exec();

//Doesn't return the result
Db['group'].findOne({ "User.pseudo": "John", token: "token" })
.populate('User')
.exec();

//Return undefined
Db['group'].findOne({ User: { pseudo: "John" }, token: "token" })
.populate('User')
.exec();

var UserSchemaModel = {
  pseudo: { type: String, required: true }
};

var GroupSchemaModel = {
  User: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  token: { type: String, required: true }
};

Maybe it's not possible to query this and we have to parse all the Users who match with token, then parse it with javascript to get the pseudo we are looking for (in another way, that we couldn't use findOne() in that case)...?

A: The thing to do is to declare your condition(s) into your populate() call:
Db['group'].findOne({ token: "token" })
.populate('User', '', { pseudo: "John"} )
.exec();


text:
Q: Is Big O(logn) log base e? For binary search tree type of data structures, I see the Big O notation is typically noted as O(logn).  With a lowercase 'l' in log, does this imply log base e (n)  as described by the natural logarithm?  Sorry for the simple question but I've always had trouble distinguishing between the different implied logarithms.

A: Once expressed in big-O() notation, both are correct.  However, during the derivation of the O() polynomial, in the case of binary search, only log2 is correct.  I assume  this distinction was the intuitive inspiration for your question to begin with.
Also, as a matter of my opinion, writing O(log2 N) is better for your example, because it better communicates the derivation of the algorithm's run-time.
In big-O() notation, constant factors are removed.  Converting from one logarithm base to another involves multiplying by a constant factor.
So O(log N) is equivalent to O(log2 N) due to a constant factor.
However, if you can easily typeset log2 N in your answer, doing so is more pedagogical. In the case of binary tree searching, you are correct that log2 N is introduced during the derivation of the big-O() runtime.
Before expressing the result as big-O() notation, the difference is very important.  When deriving the polynomial to be communicated via big-O notation, it would be incorrect for this example to use a logarithm other than log2 N, prior to applying the O()-notation. As soon as the polynomial is used to communicate a worst-case runtime via big-O() notation, it doesn't matter what logarithm is used.

A: It doesn't really matter what base it is, since big-O notation is usually written showing only the asymptotically highest order of n, so constant coefficients will drop away.  Since a different logarithm base is equivalent to a constant coefficient, it is superfluous.
That said, I would probably assume log base 2.

A: Big O notation is not affected by logarithmic base, because all logarithms in different bases are related by a constant factor, O(ln n) is equivalent to O(log n).

A: Yes, when talking about big-O notation, the base does not matter.  However, computationally when faced with a real search problem it does matter.
When developing an intuition about tree structures, it's helpful to understand that a binary search tree can be searched in O(n log n) time because that is the height of the tree - that is, in a binary tree with n nodes, the tree depth is O(n log n) (base 2).  If each node has three children, the tree can still be searched in O(n log n) time, but with a base 3 logarithm. Computationally, the number of children each node has can have a big impact on performance (see for example: link text)
Enjoy!
Paul

A: First you must understand what it means for a function f(n) to be O( g(n) ).
The formal definition is: *A function f(n) is said to be O(g(n)) iff |f(n)| <= C * |g(n)| whenever n > k, where C and k are constants.*
so let f(n) = log base a of n, where a > 1 and g(n) = log base b of n, where b > 1
NOTE: This means the values a and b could be any value greater than 1, for example a=100 and b = 3
Now we get the following: log base a of n is said to be O(log base b of n) iff |log base a of n| <= C * |log base b of n| whenever n > k
Choose k=0, and C= log base a of b.
Now our equation looks like the following: |log base a of n| <= log base a of b * |log base b of n| whenever n > 0
Notice the right hand side, we can manipulate the equation: = log base a of b * |log base b of n| = |log base b of n| * log base a of b = |log base a of b^(log base b of n)| = |log base a of n|
Now our equation looks like the following: |log base a of n| <= |log base a of n| whenever n > 0
The equation is always true no matter what the values n,b, or a are, other than their restrictions a,b>1 and n>0.
So log base a of n is O(log base b of n) and since a,b doesn't matter we can simply omit them.
You can see a YouTube video on it here: https://www.youtube.com/watch?v=MY-VCrQCaVw
You can read an article on it here: https://medium.com/@randerson112358/omitting-bases-in-logs-in-big-o-a619a46740ca

A: Both are correct. Think about this
log2(n)=log(n)/log(2)=O(log(n))
log10(n)=log(n)/log(10)=O(log(n))
logE(n)=log(n)/log(E)=O(log(n))

A: Technically the base doesn't matter, but you can generally think of it as base-2.


text:
Q: Agrupar duas colunas em duas tabelas mysql Tenho duas tabelas que estou unindo para recuperar os dados relacionados dessa forma:
Tabela Processos:              Tabela Anexos

id  |  processos              processoid  |  titulo

1   |  Processo 1             1           |  REQUERIMENTO
2   |  Processo 2             1           |  Apostilamento
3   |  Processo 3             2           |  requisição
4   |  Processo 4             2           |  REQUERIMENTO
5   |  Processo 5             3           |  Apostilamento
6   |  Processo 6             3           |  CRAF

SELECT processos.processos,
       processos.id as processoid,
       anexos.*,
       anexos.id as anexoid
  FROM anexos
  INNER JOIN processos ON (processos.id = anexos.processoid)
  GROUP By processos.id
  ORDER By anexos.processoid

Com a query acima ele retorna da seguinte forma:
Processo 1 =>  REQUERIMENTO
Processo 1 =>  Apostilamento

Processo 2 =>  requisição
Processo 2 =>  REQUERIMENTO

Processo 3 =>  Apostilamento
Processo 3 =>  CRAF

O que preciso está abaixo:
Processo 1 =>  REQUERIMENTO
               Apostilamento

Processo 2 =>  requisição
               REQUERIMENTO

Processo 3 =>  Apostilamento
               CRAF

Creio que é só o uso do GROUP BY mas nesse caso nao funciona.

A: Obrigado pela ajuda pessoal, não foi bem uma solução genérica que encontrei, mas sim uma lógica diferente e o entendimento de que a logica não precisaria de exibir os nomes dos processos mas somente os titulos, nesse caso nao foi necessário nenhuma mudança, já que o objetivo é exibir os titulos de cada processo.
Entao a Query ficou assim mesmo e retornei da forma abaixo:
        $valida = $this->db->query("SELECT processos.processos, processos.id as processoid, anexos.*, anexos.id as anexoid FROM anexos INNER JOIN processos ON (processos.id = anexos.processoid) WHERE processos.id = '$this->processo'");

foreach ($valida->fetchAll() as $folderProcesso) {
        echo $folderProcesso['titulo'] .' Data: '.folderProcesso['data'];
}

Ressalvo que nao foi necessario o uso do GROUP BY já que os titulo são diferentes e nao duplicam.


text:
Q: Keeping American Style dates in numeric order in R I am trying to make a simple graph of high and low temperatures over a month.  The data comes from a table with this format.
Date    High    Low
8/1/2016    84  78
8/2/2016    83  79
8/3/2016    93  57
8/4/2016    94  68
8/5/2016    99  75
8/6/2016    82  78
8/7/2016    88  57
8/8/2016    100 58
8/9/2016    92  68
8/10/2016   84  55
8/11/2016   85  55
8/12/2016   96  56
8/13/2016   85  71
8/14/2016   74  66
8/15/2016   73  53
8/16/2016   93  79
8/17/2016   86  71
8/18/2016   90  70
8/19/2016   71  51
8/20/2016   87  53
8/21/2016   96  66
8/22/2016   70  66
8/23/2016   81  71
8/24/2016   77  76
8/25/2016   83  65
8/26/2016   82  64
8/27/2016   78  52
8/28/2016   86  61
8/29/2016   81  50
8/30/2016   95  53
8/31/2016   92  56

I plot like so:
data=read.table('data location', header=1)
plot(data[,1],data[,2])
lines(data[,1],data[,2])

when I look at the date data frame i get the following
data[,1]
[1] 8/1/2016  8/2/2016  8/3/2016  8/4/2016  8/5/2016  8/6/2016  8/7/2016  8/8/2016  8/9/2016  8/10/2016 8/11/2016 8/12/2016 8/13/2016 8/14/2016 8/15/2016 8/16/2016 8/17/2016 8/18/2016
[19] 8/19/2016 8/20/2016 8/21/2016 8/22/2016 8/23/2016 8/24/2016 8/25/2016 8/26/2016 8/27/2016 8/28/2016 8/29/2016 8/30/2016 8/31/2016
31 Levels: 8/1/2016 8/10/2016 8/11/2016 8/12/2016 8/13/2016 8/14/2016 8/15/2016 8/16/2016 8/17/2016 8/18/2016 8/19/2016 8/2/2016 8/20/2016 8/21/2016 8/22/2016 8/23/2016 ... 8/9/2016

The Levels at the bottom are clearly sorting the data in an alphabetical format and not a numerical format....  I've tried converting it with as.character.date but then it will not plot with it, complaining about infinite xlim values.

A: It is better to convert to Date class
data$Date <- as.Date(data$Date, "%m/%d/%Y")
plot(data[,1],data[,2])
lines(data[,1],data[,2])

If we need the original format for 'Date' in the plot, then we can set xaxt="n" in the plot and change the tick labels with axis
plot(data[,1],data[,2], xaxt = "n")
lines(data[,1],data[,2])
axis(1, data[,1], format(data[,1], "%m/%d/%Y"))


text:
Q: R Shiny checkboxGroupInput - Actions based on different combinations? I'm working with R shiny to build a simple plotting app, and I don't think I really understand how checkboxGroupInput works, and the documentation from the R shiny app website isn't too helpful, so I was hoping to get some clarification.
This is what my checkboxGroupInput looks like:
checkboxGroupInput("trend1DisplayOptions", "Graph Display Options",
                                    choiceNames = list("Connect Data Points", "Display Loess Smoother with Uncertainty Bounds"),
                                    choiceValues = list("connect", "loess"),
                                    selected = "connect")

So, I'm essentially looking to display 4 different "types" of plots depending on which checkboxes are selected (whether to display loess/connect points or not).
And in my server code, here are the if/else statements:
if (input$trend1DisplayOptions == "connect" && input$trend1DisplayOptions != "loess") {
  # Only connect points
  p <- plot_ly(x = df2$labels, y = df2$values, type = 'scatter', mode='lines+markers') %>%
    layout(xaxis = list(type = "category"))
  p

# Probably wrong way to check
} else if (input$trend1DisplayOptions == "connect" && input$trend1DisplayOptions == "loess") {
  # Should display nothing

# Probably wrong way to check
} else if (input$trend1DisplayOptions != "connect" && input$trend1DisplayOptions == "loess") {
  # Should display nothing

} else if (is.null(input$trend1DisplayOptions)) {
  # Should show
  p <- plot_ly(x = x_labels, y = df$values, type = 'scatter') %>%
    layout(xaxis = list(type = "category"), title = input$trendTitle)
  p

}

The issue I'm running into is that when both checkboxes are selected, the shiny app should display nothing, but it still displays the plot from the first if statement (i.e. when only "connect" is selected). And, when neither are selected, I get a missing value where TRUE/FALSE needed error.
What did I misunderstand about checkboxGroupInput?
I can see the issue is assuming the input values are equal to 2 things at the same time. So, what is the correct way to check if checkbox 1 is selected and checkbox 2 isn't, and vice versa? Also, I've searched on this forum to see how to deal with when neither are selected, and it seems is.null() is the right way to go. Why isn't it working for my case?

A: Looks like I misread one of the S.O. answers. I should be using %in% and !(... %in% ...) to check for combinations.
Here is the correct version if anyone needs it:
if ("connect" %in% input$trend1DisplayOptions && !("loess" %in% input$trend1DisplayOptions)) {
  p <- plot_ly(x = df2$labels, y = df2$values, type = 'scatter', mode='lines+markers') %>%
    layout(xaxis = list(type = "category"))
  p

} else if (!("connect" %in% input$trend1DisplayOptions) && "loess" %in% input$trend1DisplayOptions) {
  # Should display nothing

} else if ("connect" %in% input$trend1DisplayOptions && "loess" %in% input$trend1DisplayOptions) {
  # Should display nothing

} else if (is.null(input$trend1DisplayOptions)) {
  p <- plot_ly(x = df2$labels, y = df2$values, type = 'scatter') %>%
    layout(xaxis = list(type = "category"), title = input$trendTitle)
  p

}


text:
Q: how to redirect custom html site to wordpress How to Redirect
Old Link:
http://www.astrokapoor.com/products/gems/gemstones/ruby-manik-new-burmees/ (this is custom php/html site)
New Link- http://astrokapoor.com/en/ruby-manik-gemstone/  (this is wordpress site link)
I used below code but no success
RewriteRule ^/products/gems/gemstones/ruby-manik-new-burmees /en/ruby-manik-gemstone [L,R=301]

A: Let's assume both the source and the target reside in the different virtualhosts and that you are defining this in VirtualHost context. Let's also assume you are the admin of the site and you have no reason to define this in .htaccess context.
All you need is a Redirect directive in the source virtualhost:
Redirect /products/gems/gemstones/ruby-manik-new-burmees/ http://astrokapoor.com/en/ruby-manik-gemstone/

This will redirect /products/gems/gemstones/ruby-manik-new-burmees/ and all subpaths from it to the new url, such if someone requests:
Host: www.astrokapoor.com
GET /products/gems/gemstones/ruby-manik-new-burmees/something
they will get redirected to:
http://astrokapoor.com/en/ruby-manik-gemstone/something
Note: Redirect belongs to mod_alias. In such simple redirection cases you should avoid mod_rewrite. Use mod_rewrite only when you have no other choice.

A: Try to use this code in .htaccess file.
RewriteRule ^products/gems/gemstones/ruby-manik-new-burmees/$ http://astrokapoor.com/en/ruby-manik-gemstone/ [L]

RewriteRule ^sunsign/aquarius%4027.html/$ http://www.astrokapoor.com/en/Aquarius-sunsign/ [L]

A: Add this line in your old page html page.
<meta http-equiv="refresh" content="0; url=http://astrokapoor.com/en/ruby-manik-gemstone/" />

A: By using simple redirect plugin You can set your redirect links easily by define each URL to match each page.


text:
Q: Find which one of a list of patterns is matched by a given string I have a fixed unknown set of pattern strings, which use the wildcards * and ? (? = one character, * = zero or more characters). For example:

*

*"abcd?"

*"dogcat*"

*"*car"

*"hello*world"
I want to generate some data structure out of these patterns, that has a method called findPattern. The method accepts a string which is guaranteed to match at most one of the patterns, and returns the pattern to which the string matches (if any).
In the above example:

*

*findPattern("abcde") returns "abcd?"

*findPattern("hellocar") returns "*car"

*findPattern("edbca") returns null
A string such as "dogcatfrogcar" is guaranteed not to be given as input for this method.
Building the data structure can be slow, since the pattern set is given once. The function will be called for many strings on the same pattern set, so it needs to be efficient.
How do I achieve this?
P.S. I'm programming-language agnostic

A: Aho-Corasic algorithm is intended to find multiple patterns in the text. Fortunately, it is possible to work with '?' wildcards (single symbols), and "If the number of wild cards is bounded by a constant, patterns with wild-cards can be matched in linear time"

A: We can replace each pattern with a regular expression and try to solve a more general problem.
In that case I have found to interesting approaches:

*

*The RE2 library, which allows matching several regular expressions simultaneously (as long as they don't have back references, which is the case here) - see this answer.

*Lex and Lex-like lexical analyzers - see this answer.


text:
Q: Label for point in plots in matplotlib So this is sort of a question about a posted solution. I was trying to put some data labels on points in a matplotlib scatterplot I have. I was trying to imitate the solution here:
Is there a matplotlib equivalent of MATLAB's datacursormode?
within def __call__(self, event): I get a failure at line:
xdata, ydata = event.artist.get_data()
AttributeError: 'CircleCollection' object has no attribute 'get_data'

Looking to the docs here: http://matplotlib.sourceforge.net/api/artist_api.html#module-matplotlib.artist
I see no method get_data() for Artist. Is this just something that has been deprecated or did I miss something? If it has been, anyone know of how else to get an equivalent call?

A: If you look at the rest of the code in __call__ you'll see xdata and ydata are never used. You can simply delete the line
xdata, ydata = event.artist.get_data()

and the rest of Joe's beautiful code works just fine.


text:
Q: Select statement with where condition in oracle by python a space and alphabetical parameter not working currently data in table of this service if i am using year and month then query give proper output but if i am using all three variable in same case query give 0 output
**mis_year="2016"
mis_month="2"
name="HB (HIB)"
Q2 = myC1.execute('select * from r13 where MIS_SERVICE= :name and MIS_SERVICE_YEAR= :mis_year and MIS_SERVICE_MONTH= :mis_month',name=name,mis_year=mis_year,mis_month=mis_month)**

A: Try this:
Q2 = myC1.execute('select * from r13 where trim(MIS_SERVICE)=:name and MIS_SERVICE_YEAR= :mis_year and MIS_SERVICE_MONTH= :mis_month',name=name,mis_year=mis_year,mis_month=mis_month)


text:
Q: problems when using pip install I am not quite experienced using pip. When I tried to install some packages, I had this error and had no idea what that meant. This happened to multiple packages that I tried to install. Any suggestions would be appreciated.
sudo pip install mysql-python
Password:
WARNING: The directory '/Users/yzr/Library/Caches/pip' or its parent directory is not owned or is not writable by the current user. The cache has been disabled. Check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting mysql-python
  Downloading MySQL-python-1.2.5.zip (108 kB)
     |████████████████████████████████| 108 kB 2.2 MB/s
    ERROR: Command errored out with exit status 1:
     command: /Users/yzr/opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/tmp/pip-install-0kcqh5vw/mysql-python/setup.py'"'"'; __file__='"'"'/private/tmp/pip-install-0kcqh5vw/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/tmp/pip-install-0kcqh5vw/mysql-python/pip-egg-info
         cwd: /private/tmp/pip-install-0kcqh5vw/mysql-python/
    Complete output (7 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/tmp/pip-install-0kcqh5vw/mysql-python/setup.py", line 13, in <module>
        from setup_posix import get_config
      File "/private/tmp/pip-install-0kcqh5vw/mysql-python/setup_posix.py", line 2, in <module>
        from ConfigParser import SafeConfigParser
    ModuleNotFoundError: No module named 'ConfigParser'
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

A: I'm assuming you are using an Unix system such as Linux or MacOS.
Maybe you are accidentally using the python2.7 version installed on your system.
You can use a specific version of python for pip with:
python3 -m pip install mysql-python

Let me explain myself, every MacOS or Linux system has two Python versions (2.7 and 3.x) by default, and both of those versions has a pip module related to it, in other words, you have a pip module for Python 2.7 and other pip module for Python 3.x.
However, I'm assuming you are using python3 for your project, therefore, you must specify the pip module to use.
Other way to avoid this problem is using a virtual environment manager, such as pipenv or built in virtualenv module.

A: It looks like your pip package doesn't have the module "ConfigParser" installed. You should be able to install it by running:
pip install ConfigParser

Alternatively, depending on your Python version, try installing mysqlclient instead:
pip install mysqlclient


text:
Q: Not able to send mail from heroku using nodemailer This is the error I get on heroku when I am trying to send emails from my deployed application.
{ Error: Connection timeout
2018-07-28T21:37:39.586059+00:00 app[web.1]:     at SMTPConnection._formatError (/app/node_modules/nodemailer/lib/smtp-connection/index.js:606:19)
2018-07-28T21:37:39.586061+00:00 app[web.1]:     at SMTPConnection._onError (/app/node_modules/nodemailer/lib/smtp-connection/index.js:579:20)
2018-07-28T21:37:39.586063+00:00 app[web.1]:     at Timeout._connectionTimeout.setTimeout (/app/node_modules/nodemailer/lib/smtp-connection/index.js:261:18)
2018-07-28T21:37:39.586066+00:00 app[web.1]:     at ontimeout (timers.js:365:14)
2018-07-28T21:37:39.586067+00:00 app[web.1]:     at tryOnTimeout (timers.js:237:5)
2018-07-28T21:37:39.586069+00:00 app[web.1]:     at Timer.listOnTimeout (timers.js:207:5) code: 'ETIMEDOUT', command: 'CONN' }

I am using nodemailer version 4.6.7 and here's the code:
'use strict';
const nodemailer = require('nodemailer');

module.exports = {
   sendMail: function(email) {
      console.log(email)
      // create reusable transporter object using the default SMTP transport
      let transporter = nodemailer.createTransport(sails.config.connections.mailer);

      // setup email data with unicode symbols
      let mailOptions = {
        from: '"Medico " <test@testgmail.com>', // sender address
        to: email, // list of receivers
        subject: 'Test', // Subject line
        text: 'Hello world?', // plain text body
        html: 'Hello world?' // html body
      };

      // send mail with defined transport object
      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return console.log(error);
        }
        console.log('Message sent: %s', info.messageId);
        // Preview only available when sending through an Ethereal account
        console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
      });
   }
}

I am using the generated app password from google and that works perfectly fine when I run it locally but on heroku it is throwing error.
What am I doing wrong?


text:
Q: Populate drop down options - javascript Im using javascript to populate options for my select and cant understand what Is going wrong.
I am trying to input dates into a select option, but it is only adding 2003-2004.
Here is my javascript function:
function populateDropDown(previousYear, currentYear) {
    console.log(previousYear)
    console.log(currentYear)
    var prevYear
    var curYear
    var i
    var y = document.getElementById("membershipYear");
    var option = document.createElement("option");
    for(i = 1;i <= 10;i++) {
        prevYear = previousYear - i
        curYear = currentYear - i
        console.log(prevYear + "-" + curYear)
        option.text = prevYear + "-" + curYear
        y.add(option,y[i])
    }
}

and printing in my console log is this:
2012-2013
2011-2012
2010-2011
2009-2010
2008-2009
2007-2008
2006-2007
2005-2006
2004-2005
2003-2004

Any help appreciated

A: You have to move createElement into the loop like this:
function populateDropDown(previousYear, currentYear) {
console.log(previousYear)
console.log(currentYear)
var prevYear
var curYear
var i
var y = document.getElementById("membershipYear");

for(i = 1;i <= 10;i++) {
    var option = document.createElement("option");
prevYear = previousYear - i
curYear = currentYear - i
console.log(prevYear + "-" + curYear)
option.text = prevYear + "-" + curYear
y.add(option,y[i])
}
}

A: You have to create option element each time then add in your Dropdown otherwise opetion will be overwrite everytime.
keep var option = document.createElement("option"); into for loop so every it will create new option.


text:
Q: What is the best way to switch between different ranges when designing a multimeter using microcontroller? We are developing a multimeter using a PIC18 microcontroller and we are searching for the best method to switch between different ranges in multimeter with the smallest possible amount of switching delay.

A: You don't give a number for the maximum delay you require, or much description of the design, but I'm assuming it's to be an autoranging/switching type of meter.
There are plenty of cheap analogue multplexers available, the best known being the 74xx4051, 4052 and 4053 series.
These are dual polarity 8:1 (4051), 2 x 4:1 (4052), and 4 x 2:1 (4053) muxes, available for under 50 cents and made by various manufacturers (e.g. TI, AD, Maxim, etc) I would have a look at these and similar offerings. Here is an example 4051 part from Farnell (many more here). Also see analogue switches.
For slower switching only one or two ways, but better isolation and lower resistance there are mechanical relays (or solid state relays, such as the PhotoMOS type from Clare) These can be used where appropriate, together with IC switches, e.g. to isolate one channel from the next when active.

A: For a lot of applications nowadays, you can use a single high resolution delta-sigma A/D and not bother with ranging at all.  The tradeoff to get the high resolution is long conversion times, but in a multimeter time is measured on a human scale so a few 10s of ms is still instantaneous.
Another trick is to present the input signal with different gains to the different A/D inputs of the micro.  The micro then uses the one with the highest reading that isn't saturated.  Usually you do a little blending with the next lower reading down so that there isn't a sudden jump when different ranges are used.  It also helps to do some calibration during manufacturing to store offsets and gains separately for each of the A/D inputs.


text:
Q: Jquery and dynamic content I have the following HTML code:

    <textarea class="summary">Please fill in</textarea>

    <textarea class="summary">Please fill in</textarea>

And I have the following JS code that is called on document.ready:
var summaries = $('textArea.summary');

This JS grabs all textareas with the class name 'summary' and stores it in the summaries variable.
I also have a link that when users click on it, will dynamically add another textarea with the 'summary' class name using Ajax, as follows:
$("#add_summary").click(function(){
  $('#temp').load("/addSummary.html", function() {
  $("#summary_form").append($('#temp').html());
  summaries = $('textArea.summary');
});

The addSummary.html simply contains the following HTML:
<textarea class="summary">Please fill in</textarea>

When the form is submitted, I am running the following code to clear the textareas of the "Please fill in" helper text as follows:
$("#user-form").submit(function () {
 //First reload all old and new textareas into summary variable - THIS PART IS NOT WORKING!
 summaries = $('textArea.work_history_summary');

 for (var i=0; i<summaries.length; i++)
    {
      if (summaries[i].value == 'Please fill in')
      {
        summaries[i].value = '';
      }
    }
 });

But when the form submits, all the original textareas are cleared, but the newly added textareas are not.  For some reason, JQuery is not able to see the new textareas and store them in the summary variable.
Any idea what I may be doing wrong?
Thanks!

A: Is it possible that what you load is a bit different - not textArea, or not summary? Just by mistake?
Additionally, consider using $.ajax() method:
$.ajax({
    url: '/addSummary',
    success: function(response) {
        $('#summary_form').append(response);
        summaries = $('textArea.summary');
    }
});

This way you will not need any temporary storage, but will be able to append obtained html directly to you form. Maybe this will also fix your issue. (I could be a bit wrong with the parameter names or function arguments order, but you have got the main idea, have not you?)


text:
Q: How can I find a very old paper by W.L. Bragg from 1913? I'm often looking for old physics papers that had a big impact on science (Nobel prize, for example). But I can't seem to find a lot of them. Is there a reason why some papers are not digitally available, but others (that had less impact) are?
Specifically, currently I'm looking for:

W.L. Bragg, The Diffraction of Short Electromagnetic Waves by a Crystal,
  Proceedings of the Cambridge Philosophical Society, 17 (1913), 43–57.

Does anybody know where to find it online? I have access to most of the journal databases.

A: The whole volume XVII of the Proceedings of the Cambridge Philosophical Society is available on the Internet Archive at the url

https://archive.org/details/proceedingsofcam1718191316camb

It is p.43 as marked in the text and p.60 in the document. It is available in pdf, ePub, Kindle, Daisy and DjVu formats, as well as a dedicated (very nice) online reader.

A: Here is a link to the paper - within another doc.
http://www.xtal.iqfr.csic.es/Cristalografia/archivos_10/Bragg-firstpaper-mini.pdf

A: Further to Arnold's answer, if you do find you need to go to a library, worldcat is a great resource. For this particular case, go to the Proc Camb Phil Soc page at worldcat; it doesn't look like a lot of libraries have it.

A: In general, inter-library loan is a wonderful resource for finding rare volumes and articles.
Of course, it is pretty slow.

A: Bragg's Nobel lecture ''The diffraction of X-rays by crystals'' is at
http://diamond.kist.re.kr/knowledge/nobel-physics/1915/wl-bragg-lecture.pdf
The Cambridge Philosophical Society is digitizing its old journal volumes, but this takes time, and the more recent ones are usually processed first. At present, you can find the back issues since 1920. http://journals.cambridge.org/action/displayBackIssues?jid=PSP
Thus you need to go to a library and copy it, or ask for it by interlibrary loan as in the old times. Or wait for another few months and try again.


text:
Q: iTunes 12 Apple Music search: is there a way to play all songs returned by search? Using iTunes 12 on Mac.  I search for an artist in Apple Music.  I get results, including the artist page, albums, songs.  I want to explore this artist, so I want to listen to a stream of his or her songs.  I can only seem to play one song at a time, each with a new play click, or tediously create a playlist by adding each individual song to My Music, then creating a playlist.  Is there no way to stream search results in toto?

A: In iTunes 12.3.1, you can play multiple songs from search results by playing one of the songs listed on the initial search results page -- the one divided into "Top Results" "Songs" "Albums" etc. iTunes will continue playing from your search results after the initial song.
However, you cannot play multiple songs automatically from the detailed search results, e.g. if you click on "Songs" to see the all of the matching songs, and play one from there, it will stop playing at the end of the selected song.

A: Answer: in iTunes 12.4 you will see a blue Filter button above any search results in the songs list (top one) and it reads [Filter Music for "..." (your search)]. Just click it and go play!


text:
Q: Calculate skewness and kurtosis fast Calculating the variance and the central moments with a dumb calculator can be a pain. My question is if I have the standard deviation is there a quick way to calculate the skewness and the kurtosis

A: In order to calculate the standard deviation, you need to calculate $\sum x_i^2$.
To calculate the skewness, you need to calculate $\sum x_i^3$.
To calculate the kurtosis, you need to calculate $\sum x_i^4$.
Your calculator will calculate the standard deviation for you, but probably does not calculate higher order moments. These higher moments will need to be calculated if you want the skewness or kurtosis.
Calculate $s_0= \sum 1 , s_1= \sum x_i , s_2= \sum x_i^{2} , s_3= \sum x_i^{3} , s_4= \sum x_i^{4} $ then the first second, third & fourth moment quantities of interest , the mean, standard deviation , skewness & kurtosis can be calculated as follows
\begin{eqnarray*}
\mu &=& \frac{s_1}{s_0} \\
\sigma &=& \sqrt{\frac{s_2-s_1^2}{s_0}} \\
\gamma_1 &=& \frac{s_3-3 s_1 s_2 +2s_1^3}{s_0 \sigma^3} \\
\kappa &=& \frac{s_4-4s_1 s_3 +6 s_1^2 s_2 -3 s_1^4}{s_0 \sigma^4}.
\end{eqnarray*}

A: Skewness:
$$skw(X) = E\left[\left(\frac{X - \mu}{\sigma}\right)^3\right]$$
$skew(X)$ can be expressed in terms of the first three moments of
$X$:
$$skw(X) = \frac{E\left(X^3\right) - 3 \mu E\left(X^2\right) + 2 \mu^3}{\sigma^3} = \frac{E\left(X^3\right) - 3 \mu \sigma^2 - \mu^3}{\sigma^3}$$
Kurtosis:
$$kur(X) = E\left[\left(\frac{X - \mu}{\sigma}\right)^4\right]$$
$kurt(X)$ can be expressed in terms of the first four moments of
$X$:
$$kur(X) = \frac{E\left(X^4\right) - 4 \mu E\left(X^3\right) + 6 \mu^2 E\left(X^2\right) - 3 \mu^4}{\sigma^4} = \frac{E\left(X^4\right) - 4 \mu E\left(X^3\right) + 6 \mu^2 \sigma^2 + 3 \mu^4}{\sigma^4}$$


text:
Q: How to prevent race conditions in a distributed nodejs web servers architecture backed by mongodb Here' s the description of my problem:

*

*I have x web workers written in nodejs (express.js) behind a load ballancer. These workers write data into mongodb (mongoose.js)

*I've setup endpoint y such that at some point in the middleware chain of the handler I'm doing the following logic: If the requesting user exists in the database, then fetch it, update some fields then store it back. If it doesn't exist, insert it in mongo.

NOTE! I'm unable to use Mongoose's findAndUpdateOne() - which would be atomic - due to domain specific logic, ie. if the user already exists update it with a certain value, else insert it with another value.

*

*The problem is, quite often, two requests from the same user (who doesn't yet exist in the db) will hit two different workers. When user processing middleware kicks in, both workers will determine that the user doesn't exist and attempt to insert it then update it. Naturally this causes errors, eg. validation errors: I've setup a unique email per user validation and others.

How can I prevent this?

A: You can use $set and $setOnInsert update operators to achieve that.
From MongoDB $setOnInsert docs:

If an update operation with upsert: true results in an insert of a
  document, then $setOnInsert assigns the specified values to the fields
  in the document. If the update operation does not result in an insert,
  $setOnInsert does nothing.

and

If the db.collection.update() with upsert: true had found a matching document, then MongoDB performs an update, applying the $set operation but ignoring the $setOnInsert operation.

so, this should do the trick:
var now = Date.now();

Users.update({ _id: 1 }, {
  $set:         { updatedAt: now },
  $setOnInsert: { createdAt: now }
}, {upsert: true}, function(err, doc) {

  // resultant doc is available here

})


text:
Q: How to encapsulate stun binding request in Send indication in python I'm trying to send binding request to TURN/Relay server but have it encapsulated in Send Indication as a client would do when talking to TURN server to relay to a far end party.
Any pointers would be much appreciated.
Thanks.


text:
Q: How to only read first none empty line in python using sys.stdin I want my Python code to read a file that will contain numbers only in one line. But that one line will not necessarily be the first one. I want my program to ignore all empty lines until it gets to the first line with numbers.
The file will look something like this:

In this example I would want my Python code to ignore the first 2 lines which are empty and just grabbed the first one.
I know that when doing the following I can read the first line:
import sys

line = sys.stdin.readline()

And I tried doing a for loop like the following to try to get it done:
for line in sys.stdin.readlines():
    values = line.split()
    rest of code ....

However I cannot get the code to work properly if the line of numbers in the file is empty. I did try a while loop but then it became an infinite loop. Any suggestions on how does one properly skip empty lines and just performs specific actions on the first line that is not empty?

A: Here is example of a function to get the next line containing some non-whitespace character, from a given input stream.
You might want to modify the exact behaviour in the event that no line is found (e.g. return None or do something else instead of raising an exception).
import sys
import re

def get_non_empty_line(fh):
    for line in fh:
        if re.search(r'\S', line):
            return line
    raise EOFError

line = get_non_empty_line(sys.stdin)
print(line)

Note: you can happily call the function more than once; the iteration (for line in f:) will carry on from wherever it got to the last time.

A: You probably want to use the continue keyword with a check if the line is empty, like this:
for line in sys.stdin.readlines():
    if not line.strip():
        continue
    values = line.split()
    rest of code ....


text:
Q: GPower: unequal number of measurements? I'm in psych research, so typically I have my subjects do ~40 trials per condition. If I have an uneven number of trials per condition (say, 30 in one and 40 in another) and a 2 x 2 within-subjects ANOVA, how would this impact the output on a power analysis (e.g. G Power)?
After cleaning my data the output is: each row is 1 participant and each column is their average across those trials for 1 condition (so 2 x 2 ANOVA = 4 conditions).
Thanks in advance!

A: I am not sure whether this really helps you, but you cannot consider the number of trials per person in a power analysis in GPower. If you want to examine the effect of number of trials in power, you have to switch to a mixed model analysis as deteiled, e.g. in this paper.
Best,
Stefan


text:
Q: How do i pass variable from multiples pages to one page flutter? In my flutter project i have many pages. I want to pass variables from different pages(named destination,departure,date,time etc) to one page (named homePage).How do i get many variables from different pages to one page and construct them ?

A: Idea #1
One possible way is to store them in a singleton so you can access them everywhere inside your app.
You can update the values inside the singleton and then later access them in your "homepage".
Package to use : https://pub.dev/packages/global_configuration
Idea #2
Use a database to store the data and access them in your "homepage".
Package to use :
https://pub.dev/packages/sqflite
Idea #3
Store the data inside the shared preferences and access them in your "homepage".
Package to use :
https://pub.dev/packages/shared_preferences
Idea #2 and #3 are persistent, that means the data is available after the app is closed and started again at any other time.
Idea #1 is not persistent and the data is lost when the app is closed.
So the main idea is to store the data somewhere and access them later.

A: *

*You can you redux for your flow and data management.
you can follow this Click here

*You can you shared_preferences to get data over multiple screens.
Add following code in your .yaml file.
dependencies:
    flutter:
    sdk: flutter
    shared_preferences: ^0.4.3

Example Code:
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.blue),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Saving data'),
      ),
      body: Row(
        //mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: RaisedButton(
              child: Text('Read'),
              onPressed: () {
                _read();
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: RaisedButton(
              child: Text('Save'),
              onPressed: () {
                _save();
              },
            ),
          ),
        ],
      ),
    );
  }

  // Replace these two methods in the examples that follow

  _read() async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'my_int_key';
    final value = prefs.getInt(key) ?? 0;
    print('read: $value');
  }

  _save() async {
    final prefs = await SharedPreferences.getInstance();
    final key = 'my_int_key';
    final value = 42;
    prefs.setInt(key, value);
    print('saved $value');
  }
}

A: Include a state management library in your app. State management libraries allow you to separate business logic from UI and such state can also be accessed from any part of the app.
Official flutter website lists a few approaches to state management, you can pick one which suits you best. See state management approaches.