Q: Gärtner-Ellis theorem on Markov chains Let $Z_n \in \mathcal{X}$ be a sequence of independent random variables where $\mathcal{X}$ is a topological vector space and let $\mu_n$ the probability measures associated with $Z_n$. Suppose that $Z_n$ that satisfies the conditions for the abstract Gärtner-Ellis Theorem. So the rate function $I(\cdot)$ associated with $Z_n$ is the Fenchel–Legendre transform of $M(\lambda) =\lim_{n \rightarrow \infty}  \frac{1}{n} \log E[\exp \langle n\lambda, Z_n \rangle ]$.
Now consider a second random variable $Y_n$ that is a Markov chain ($Y_n$ is sampled from $Y_{n-1}$) and the probability measure associated with $Y_n$ is $\mu_n$.
My question is:
Is $I(\cdot)$ the rate function associated with $Y_n$?
If answer is yes to the above question, let me provide a counter-example of the equivalence of the rate function of $Z_n$ and $Y_n$.
Consider two random variables on $\{0,1\}$
let $g_n$ be 1 with probability $1/2$, else 0
let $h_1$ = $g_1$ and then for $n>1$, let $h_n=1-h_{n-1}$ with probability
$(1/2)^n$ and else $h_n=h_{n-1}$.
Note that for all $n$, $h_n$ and $g_n$ have the same probability distribution,
$Prob(g_n = 1) = 1/2$ (by definition).
$$
Prob(h_n = 1) = Prob(h_{n-1}=1)\cdot(1/2)^n + Prob(h_{n-1}=0)\cdot(1-(1/2)^n) = (1/2) \cdot (1/2)^n+(1/2) \cdot (1-(1/2)^n) = (1/2)\cdot((1/2)^n + 1-(1/2)^n) = 1/2
$$
Hence $Prob(g_n=1) = Prob(h_n=1)$.
At the limit both random variables have the same distribution,
but the convergence of the sequences is rather different. ($h_n$
converges, $g_n$ doesn't)
My other question is: Does this example invalidate the positive answer to first question?


Q: Zabbix - Create Trigger that parse the time in a file I have a file that is written on each of my Zabbix clients with a time inside of it every hour.
I need the Zabbix server(s) to check these files and alert if the time is at least 6 hours old.
I cannot see where or how this trigger might be implemented and the Zabbix documentation does not give me enough detail.

A: The easiest solution would be to output Unix timestamp into the file and read that value using vfs.file.contents[] (see item documentation). This has the benefit that you can specify "unixtime" as the unit in item configuration and you will see a pretty value in "Latest data".
A trigger could then be as follows:
{host:vfs.file.contents[/tmp/timestamp.txt].now()} -
    {host:vfs.file.contents[/tmp/timestamp.txt].last()} > 6h


Q: Is every subgroup of an algebraic group a stabilizer for some action? Suppose G is an algebraic group (over a field, say; maybe even over ℂ) and H⊆G is a closed subgroup. Does there necessarily exist an action of G on a scheme X and a point x∈X such that H=Stab(x)?
Before you jump out of your seat and say, "take X=G/H," let me point out that the question is basically equivalent† to "Is G/H a scheme?" If G/H is a scheme, you can take X=G/H. On the other hand, if you have X and x∈X, then the orbit of x (which is G/H) is open in its closure, so it inherits a scheme structure (it's an open subscheme of a closed subscheme of X).
†I say "basically equivalent" because in my argument, I assumed that the action of G on X is quasi-compact and quasi-separated so that the closure of the orbit (i.e. the scheme-theoretic closed image of G×{x}→X) makes sense. I'm also using Chevalley's theorem to say the the image is open in its closure, which requires that the action is locally finitely presented. I suppose it's possible that there's a bizarre example where this fails.

A: In his book "Linear algebraic groups", 6.8, p98, Borel shows that the quotient of an affine algebraic group over a field by an algebraic subgroup exists as an algebraic variety, and he notes p.105 that Weil proved a similar result for arbitrary algebraic groups.

A: The representability theorem [Demazure-Gabriel, III.2.7.1, p. 318] implies the following.
Theorem
Let $A$ be a local artinian ring,
let $G$ be a group over $A$ locally of finite type,
and let $H\hookrightarrow G$ be a closed subgroup which is flat over $A$.
Then the quotient $G/H$ in the category of fppf sheaves is a scheme; and the canonical morphism $G\rightarrow G/H$ is faithfully flat and of finite presentation.
Note that the group $G$ in the above theorem need not be either affine or flat over $A$; also, Demazure-Gabriel write in comprehensible language, unlike Weil.


Q: PrimeFaces Poll I try to make a site where I place a clock. Not a default primefaces clock because I need the actual time not just to show it. I use Netbeans8.0, Java8.0, Primefaces5.0, and I'm building a Mobile site.
So I tried the p:poll but it not works for me.
@ViewScoped
@ManagedBean(name = "navigationTo")
public class NavigationTo implements Serializable{

    private int number;

    public int getNumber() {
        return number;
    }

    public void increment() {
        number++;
    }
}

<h:body>
        <pm:page id="index">
            <pm:header title="xyz"></pm:header>
            <pm:content>
                <h:form>
                    <p:growl id="growl" showDetail="true"/>
                    <h:outputText id="txt_count" value="#{navigationTo.number}" />
                    <p:poll interval="3" listener="#{navigationTo.increment}" update="txt_count" />
                    <p:graphicImage value="xyz.png" style="width: 30%;

I use this default primefaces example but only shows the 0 and it's not incrementing...
Anyone any idea?
!!!EDIT: Primefaces Mobile (here: pm) not support polling. So it only work with the basic primefaces.

A: well, I look your situation, I did a example about it, It work for me!
I have created a Bean similar to your bean.
    @ViewScoped
    @ManagedBean(name="clockBean")
   public class clockBean implements Serializable{

        private  int number;

        public void increment(){
           number++;
        }

        public int getNumber() {
          return number;
        }

        public void setNumber(int number) {
          this.number = number;
        }
}

Besides I created a simple web page
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui"
    xmlns:pe="http://primefaces.org/ui/extensions">
  <ui:composition template="/layout/template.xhtml">
  <ui:define name="body">
   <h:form id="form">
            <p:poll interval="1"
                listener="#{clockBean.increment}" update=":form" />
            <p:outputLabel value="#{clockBean.number}" />
    </h:form>
  </ui:define>
  </ui:composition>

 </html>

It has worked for me, I hope it can help you!.
I think that your problem is that you need use id for the different components in your web page for exaMple the component form, it should has a id.

A: Adding
<h:outputScript library="primefaces" name="primefaces.js" />

inside h:body solved for me. I'm using PrimeFaces 5.1.20

A: For me, adding this line to <h:body> helped:
<h:outputScript library="primefaces/poll" name="poll.js" />

A: Have you debugged the actual navigationTo.increment method, and checked that the poll actually goes inside?
It seems that you are missing attributes inside the poll, if you want to trigger the back end method, and start the actual poll as soon as you load the page, add this:
process="@this" autoStart="true"


Q: How to deal with locks (JPA)? According to the Java Persistent/Locking wikibooks*, the best way to deal with locks is to report the Optimistic Lock Error/Exception to the user.
The problem is that it's not scalable. Suppose that I have many users who are likely to cause a lock with the same action. The user does not care about the lock error message.
In a nutshell :

*

*The best way is to disable all locks ?

*The best way is to report to the user the error lock message ? But the user must retry his action until it will work !

*The best way is to retry the transaction until there's no lock ?

*

Handling optimistic lock exceptions
Unfortunately programmers can frequently be too clever for their own good. The first issue that comes up when using optimistic locking is what to do when an OptimisticLockException occurs. The typical response of the friendly neighborhood super programmer, is to automatically handle the exception. They will just create a new transaction, refresh the object to reset its version, and merge the data back into the object and re-commit it. Presto problem solved, or is it?
This actually defeats the whole point of locking in the first place. If this is what you desire, you may as well use no locking. Unfortunately, the OptimisticLockException should rarely be automatically handled, and you really need to bother the user about the issue. You should report the conflict to the user, and either say "your sorry but an edit conflict occurred and they are going to have to redo their work", or in the best case, refresh the object and present the user with the current data and the data that they submitted and help them merge the two if appropriate.
Some automated merge tools will compare the two conflicting versions of the data and if none of the individual fields conflict, then the data will just be automatically merged without the user's aid. This is what most software version control systems do. Unfortunately the user is typically better able to decide when something is a conflict than the program, just because two versions of the .java file did not change the same line of code does not mean there was no conflict, the first user could have deleted a method that the other user added a method to reference, and several other possible issues that cause the typically nightly build to break every so often.

A: The user will care about the message, because he wanted to do some modification, and the modifications have not been made. He will thus refresh the page to see the new state of the data, and will redo his modifications, or decide they should not be made anymore given the new state.
Is it a problem if two users modify an entity concurrently, and if the last modification wins, whatever the modification is? If it is a problem, then use optimistic locking, and inform your user when there is a problem. There's no way around it.
If it's not a problem, then don't use optimistic locking. The last modification, if it doesn't break constraints in your database, will always win. But having concurrent users modifying the same data will always lead to exceptions (for example, because some user might delete an entity before some other user submits a modification to the same entity).
Retrying is not an option:

*

*either it will fail again, because it's just not possible to do the modifications

*or it will succeed, but will defeat the point of having optimistic locking in the first place.

Your problem could be explained with a car analogy. Suppose you choose to buy a car with a speed limiter, in order to make sure you don't break the speed limit. And now you ask: but I don't care about the speed limits. Shouldn't I always disable the speed limiter? You can, but then don't be surprised if you get caught by the police.


Q: not getting the proper page through jsoup I am trying to get this page with jsoup: http://poalimparents.bankhapoalim.co.il/
But all I get is this:
<html>
 <head>
  <meta charset="utf-8">
 </head>
 <body>
  <script>window.rbzns = {fiftyeightkb: 43200000, days_in_week : 1};</script>
  <script src="//d1a702rd0dylue.cloudfront.net/js/sugarman/v7/flat.js"></script>
  <script>rbzns.challdomain="poalimparents.bankhapoalim.co.il"; rbzns.ctrbg="FBJbOCP+Rehoy7Oy/WdwW78giok75ZJ41qiRAeMY6ngbkLDEoRQiaRnij/E1vDpJr8bXfF2RriK5XaIq/Hp55vlAaMCPBIVryBF/YYXoti09rQmZeDa16289c+L2T8eFOCCIjmmtSn7gp75lWrKDHxJgS7Te/RxMGL/93TjdGxpofgMceO/Z2y/d7oCYNO/HKn4ZciE4aqCU8AU6rtyVjH0HxWz47/pps9uqcV0VnR/up4gHLztME+GHfJzjZ80Vy/14g5wvCKRtZU7P6I3zgQ==";rbzns.rbzreqid="bnhp-rbzr0131343537323737333137e0b31050bf436236"; winsocks(true);</script>
 </body>
</html>

I'm not trying to get the script tag inside the page.
Why am I not getting all the other tags? How can I get this kind of pages?
Thanks ahead.

A: Try adding some headers that your browser would send, too. Also a cookie might be required - you could fetch one with a "normal" browser.
Example (curl):
curl "http://poalimparents.bankhapoalim.co.il/" -H "Host: poalimparents.bankhapoalim.co.il" -H "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0" -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" -H "Accept-Language: de,en-US;q=0.7,en;q=0.3" --compressed -H "DNT: 1" -H "Cookie: rbzreqid=bnhp-rbzr0231343537323737353630894b901088a07d30; rbzid=YnVIYjc0K2RmTDFXZFdiZy95UTNrOUJ0NEp0MzgzbW9oNlhHcFdVMU1mR25oT1NGQXowdGdZbjR3WktuQ2ZBZ0ljUTVCbHFDK213bGZXRk1DekJMMnhQMVFZVG4zcHpNT1lEWTRpM3FVeiswbkxtaFVCR25CU0taQ2pnNU1IQ1Z5WDc2ZWgxa2ZxR25vR1JadFpTVThidWs0d0s5QUF2YUVRSG1QcUpsS1ltRGpYNzhPR0lpRDNkak1VRmVxdm5nY0RpM1dEUnYrWU1rR2R1c3pWY2JGZHd6ODlOdkxHUkxuOW03N0VzWC9oOD1AQEAwQEBALTc0MDc0MDczNDA-" -H "Connection: keep-alive" -H "If-Modified-Since: Mon, 22 Feb 2016 11:40:18 GMT" -H "If-None-Match: W/""af3920fb581df1e4de68d46a4694689a""" -H "Cache-Control: max-age=0"


Q: Is there an easy way to copy a variable in the heap into shared memory I have a couple of structs with pointers to one another allocated on the heap. I'm converting a multi-threaded program to a multi-process program so I have to make those structs on the heap into shared memory. So far, I've run into nothing but problems on top of problems. MY TA suggested I use memcpy, but I'm not sure that's going to work. Is there any way to convert a set of structs on the heap into shared memory?
Structs I'm using:
 struct SharedData {
    int da;
    int         isopen;
    int     refcount;   // reference count:  number of threads using this object
    unsigned int    front;      // subscript of front of queue
    unsigned int    count;      // number of chars in queue
    unsigned int    bufsize;
    pthread_cond_t buffer_full;
    pthread_cond_t buffer_empty;
    pthread_mutex_t mtex;
    fifo_t* queue;
    sem_t       empty_count;

    sem_t       full_count;
    sem_t       use_queue;  // mutual exclusion
};

struct OverSharedData{
    struct SharedData ** rep;
    int rop;
};

I malloc'd OverSharedData , the SharedData structs, and the fifo_t queue, along with multiple char pointers later on. Do they all have to be declared as shared memory?

A: In the way malloc() request memory from heap, there are system calls (for e.g. shmget()) to request/create shared memory segment. If your request is successful, you can copy whatever you like over there. (Yes, you can use memcpy.) But remember to be careful about pointers, a pointer valid for one process, kept in its shared memory, is not necessarily valid for another process using that shared memory segment.
The shared memory is accessible to all processes for reading and/or writing. If multiple processes are reading/writing to a shared memory segment, then, needless to say, some synchronization techniques (for e.g. semaphore) need to be applied.
Please read up on shared memory. An excellent source is "The Linux Programming Interface" by Michael Kerrisk.
Reference:

*

*http://man7.org/linux/man-pages/man7/shm_overview.7.html

*http://man7.org/linux/man-pages/man2/shmget.2.html

*http://www.amazon.com/The-Linux-Programming-Interface-Handbook/dp/1593272200


Q: Chain rule in derivatives Well, I have to derive this function: $$f(x)=\sin(2x \sqrt[3]{x+1} )$$
I want to use the chain rule, and I want to use it like this;
I will call:
$$T=x+1$$
$$Q=2x. \sqrt[3]{t} $$
$$f=\sin (Q)$$
So then I have:
$$\cfrac{df}{dx} = \cfrac{df}{dQ} . \cfrac{dQ}{dT} . \cfrac{dT}{dx} . $$
And now I just have to derive. For example,
$$\cfrac{df}{dQ} = \cos (Q) $$ and then I put $$2x. \sqrt[3]{t} $$ instead of Q, and so on.
But what should I do when I want to do $ \cfrac{dQ}{dT} $ ? Because I have a product, and I know that I have to use the product rule and it would be $$Q'=2x'.\sqrt[3]{t}+2x.(\sqrt[3]{t})'$$ but what shall I do when deriving that X in $(2x)'$? Because the derivative is $ \cfrac{dQ}{dT} $, not $ \cfrac{dQ}{dx} $
I know that I could avoid putting names to these "sub-functions", but this way is easier to me, so, please, don't teach me any other method.
Thanks!

A: According to the chain rule, $(f(g(x)))'=g'(x)\cdot f'(g(x))$
So for the function, $f(x)=\sin(2x\sqrt[3]{x+1})$, will be differentiatd as follows...
By chain rule obviously, we get, $(2x\sqrt[3]{x+1})'\cos(2x\sqrt[3]{x+1})$...Then,
$$\text{Taking } (2x\sqrt[3]{x+1})' = (2x)'(\sqrt[3]{x+1})+(\sqrt[3]{x+1})'(2x)$$
$$= 2(\sqrt[3]{x+1})+\frac{2x}{3}(\sqrt{(x+1)^3})$$
Multipying this together with $\cos(2x\sqrt[3]{x+1})$,
$$\Biggl\{2(\sqrt[3]{x+1})+\frac{2x}{3}(\sqrt{(x+1)^3})\Biggr\}\cdot\cos(2x\sqrt[3]{x+1})$$
This is the derivative. Maybe converted into other forms

A: Hint:
$$\bigg(\sin[f(x)]\bigg)'=f'(x)\cos[f(x)]$$
by the chain rule.
Then by the product rule:
$$(2x\cdot(x+1)^\frac13)'=(2x)((x+1)^\frac13)'+(2x)'(x+1)^\frac13$$

A: As $$Q'=2x'.\sqrt[3]{t}+2x.(\sqrt[3]{t})'$$ you can write $x'$ as $$ x' = \frac{dx}{dT}$$
Then in the next step;$$2(\frac{dx}{dT}).(\frac{dT}{dx})\sqrt[3]{t} + (\frac{2x}{3\sqrt[3]{t^2}})(\frac{dT}{dx})$$
$$2.\sqrt[3]{x+1} + (\frac{2x}{3\sqrt[3]{(x+1)^2}}).2(x+1)$$
The full answer will be $$\cos(2x. \sqrt[3]{x+1}).[2\sqrt[3]{x+1} + (\frac{2x}{3\sqrt[3]{(x+1)^2}}).2(x+1)]$$


Q: CSS padding not applying to parent div I really don't understand CSS :(
Why is the following padding not pushing out the size of the parent div?
HTML

              My Leads

CSS
 .lead-table .table-head-1 {
        background-color: #053449;
        text-transform: uppercase;
        color: #ffffff;
        font-size: 12px;
    }
    .lead-table .table-head-1 span {
        padding: 20px 18px;
    }

http://www.bootply.com/gsT2mwsA8h#
Any help appreciated for this CSS noob.
Thanks

A: span is not a block element.
padding will not work for inline elements. But margin will work.

*

*either you can use margin: 20px 18px;  or

*add display:block; or display:inline-block; to the span.

padding will take effect once you make it a block element.

A: Unlike div, p 1 which are Block Level elements which can take up padding or margin on all sides,span2 cannot as it's an Inline element which takes up padding or margin horizontally only.
From the specification :
Use div instead of span...below code will work
.lead-table .table-head-1 {
    background-color: #053449;
    text-transform: uppercase;
    color: #ffffff;
    font-size: 12px;
}
.lead-table .table-head-1 .col-txt{
    padding: 20px 18px;
}

My Leads

A: Just replace that both css with following, it may help you :-
.lead-table .table-head-1 {
    background-color: #053449;
    text-transform: uppercase;
    color: #ffffff;
    font-size: 12px;
    padding: 20px 18px;
}

A: Your html needs to be wrapped in a "container" class division tag with bootstrap.
HTML:

          My Leads

Also, your CSS can be reduced for what you have currently as shown below.
CSS:
/* CSS used here will be applied after bootstrap.css */
.lead-table{
    background-color: #053449;
    text-transform: uppercase;
    color: #ffffff;
    font-size: 12px;
}
.table-head-1{
    padding: 20px 18px;
}

A: By default a span is an inline element. You cannot add padding top or bottom to it unless you add display:block.
.lead-table .table-head-1 span {
    padding: 20px 18px;
    display:block;
}

Working code example: http://www.bootply.com/kSh1hNCkTb#


Q: What's removing stuff from /var/run at reboots from a fedora machine? I am running a FC18 machine on which I am testing a piece of software (smf-sav, a milter) keeping part of its working files under /var/run/smf-sav/.
That directory keeps disappearing after reboots. Hence the question: what is removing it? Is there a way to mark it permanent?

A: The software should define what directories it needs in /run (which replaced /var/run in Fedora 15) by placing a configuration file in /usr/lib/tmpfiles.d. During the boot process, systemd-tmpfiles populates /run based on that confguration.

A: /var/run is usually mounted as tmpfs, which is a partition mapped into your RAM. Obviously RAM gets cleared on reboot, so do all tmpfs file systems.
http://fedoraproject.org/wiki/Features/var-run-tmpfs
You should consider storing your application data on a persistent file system e.g. mounted on a hard disk.


Q: How to configure cascade delete where there are cycles and multiple cascade paths I'm having a bit of trouble getting my head around this relationship, and how to possibly setup cascade delete settings for it.

*

*There is a table of employees, where each employee has any number of handles, attachments and jobs

*There is a table of handles, where each handle belongs to an employee and may be used in a tool

*There is a table of attachments, where each attachment belongs to an employee and may be used in a tool

*There is a table of tools, where each tool is made up of one attachment, one handle and is used on any number of jobs

*There is a table of jobs, where each job belongs to an employee, and may or may not have a tool used on it

Note: it's possible for handles and attachments to exist without being used to make a tool
In short: an employee can mix-and-match handles and attachments to make tools, and then use a tool on a job they are assigned.
This diagram shows how the database is wired together (feel free to suggest a better design)
DB Diagram
This is how the models are setup, the Job model has a nullable reference to the tools FK (ToolId) so a job can exist without a tool.
public class Employee
{
    public int EmployeeId { get; set; }
    public string Name { get; set; }

    public List<Handle> Handles { get; set; }
    public List<Attachment> Attachments { get; set; }
    public List<Job> Jobs { get; set; }
}

public class Handle
{
    public int HandleId { get; set; }
    public string Material { get; set; }
    public double ExpectedLife { get; set; }
    public double LifetimeMaintenance { get; set; }

    public int EmployeeId { get; set; }
    public Employee Employee { get; set; }
    public List<Tool> Tools { get; set; }
}

public class Attachment
{
    public int AttachmentId { get; set; }
    public string Material { get; set; }
    public string Type { get; set; }
    public double ExpectedLife { get; set; }
    public double LifetimeMaintenance { get; set; }

    public int EmployeeId { get; set; }
    public Employee Employee { get; set; }
    public List<Tool> Tools { get; set; }
}

public class Tool
{
    public int ToolId { get; set; }
    public string OperationSpeed { get; set; }

    public int HandleId { get; set; }
    public Handle Handle { get; set; }

    public int AttachmentId { get; set; }
    public Attachment Attachment { get; set; }

    public List<Job> Jobs { get; set; }
}

public class Job
{
    public int JobId { get; set; }
    public string Name { get; set; }
    public double EffortRequired { get; set; }

    public int EmployeeID { get; set; }
    public Employee Employee { get; set; }
    public int? ToolId { get; set; }
    public Tool Tool { get; set; }
}

This is how the DB context has been created. There is a cascade delete setting to set the tool FK in Jobs (ToolId) to null when a tool is deleted (so the job wont get deleted when its tool is deleted).
public class ToolsDbContext : DbContext
{
    public ToolsDbContext(DbContextOptions<ToolsDbContext> options) : base(options)
    {

    }

    public DbSet<Employee> employees { get; set; }
    public DbSet<Handle> handles { get; set; }
    public DbSet<Attachment> attachments { get; set; }
    public DbSet<Tool> tools { get; set; }
    public DbSet<Job> jobs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Tool>()
            .HasMany(j => j.Jobs)
            .WithOne(t => t.Tool)
            .OnDelete(DeleteBehavior.SetNull);
    }
}

Creating the migration works, but then updating the database fails with the following error:
Introducing FOREIGN KEY constraint 'FK_tools_handles_HandleId' on table 'tools' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.

I'm not too sure how to understand this error.
Thinking it through:

*

*If a handle is deleted, it will delete all tools it's used in, which in turn will set ToolId in related Jobs to null

*If an attachment is deleted, it will delete all tools it's used in, which in turn will set ToolId in related Jobs to null

*If a tool is deleted it will set ToolId in related Jobs to null

*If a job is deleted, there will be no cascade effect

Therefore I think the problem must be with deleting an employee, but I can't see why (yet?)...

*

*If an employee is deleted everything should be deleted; it should delete all related jobs, handles and attachments. Then those deleted handles or attachments should in turn delete the tools associated with them (it shouldn't matter what came first).

So there is cascade paths deleting an employee, but I would expect this would all work based on the model setup as-is... So do I need to configure more cascade delete requirements in the dbcontext? If so, I'm not sure how it should be configured...
Note: without the employees model in the database, everything seems to work

A: SQL server doesn't allow to have multiple cascade paths to the same table in the database. In your case there are two of them for Tools:

*

*Employee -> Handle -> Tool

*Employee -> Attachment -> Tool

All ways to fix the issue consist in setting DeleteBehavior.Restrict for one relationship or the other, for example:

*

*Setting DeleteBehavior.Restrict for Entity -> Handle relationship and handling this cascade path by a trigger (otherwise "restrict" won't allow to delete a record having references to it)

*Setting DeleteBehavior.Restrict for Entity -> Handle relationship and handling this cascade path in application code (update/delete all related entities explicitly before deleting the main one)

*Setting "restrict" behavior for both Entity relationships

etc...

A: You said:

There is a table of employees, where each employee has any number of handles, attachments and jobs

But your diagram establishes a direct link between an employee and a handle, one handle has many employees, and an employee has only one handle
Your statement is in conflict with your diagram
I think this modelling is wrong, from the database perspective. I think a job should have an employee. (If a job has multiple employees you'll need another table jobemployees that maps one job id  to multiple employees.) A job has a tool, a tool has a handle and an attachment. I fail to see why deleting an employee should delete their jobs (if I fired someone the house he built while working for me still exists) but you can clean this up without using cascading constraints
Ultimately you can see in the diagram the cycle you've created. If deleting something at a 1 end deletes everything at the * end then deleting anything in your diagram starts a chain that takes a split path that comes back together. Removing the employee entity does indeed break this up
Ultimately an employee should not directly have a job, a handle or an attachment


Q: If the sum of two independent random variables is in $L^2$, is it true that both of them are in $L^1$? Let $X$ and $Y$ be two independent random variables. If $\mathbb E(X+Y)^2 < \infty$, do we have $\mathbb E |X| < \infty$ and $\mathbb E |Y| < \infty$?
What I actually want is that $X$ and $Y$ are both in $L^2$, i.e., $\mathbb E X^2 < \infty$ and $\mathbb E Y^2 < \infty$. But this can be reduced to $\mathbb E |X|\mathbb E |X| < \infty$. Thus it suffices to show that $X$ and $Y$ are in $L^1$.
It might be helpful to see that since $|X| < |Y| + |X+Y|$, (and by symmetry), either both of $X$ and $Y$ or none of them are in $L^1$. So we may assume $\mathbb E |X| = \infty$ and $\mathbb E |Y| = \infty$ and try to find a contradiction. But here is where I got stuck.

A: Notice that
$$\mathbb E(X+Y)^2=\int_{\mathbb R^2}(x+y)^2\mathrm d\mathbb P_X\otimes \mathbb P_Y(x,y)=\int_{\mathbb R}\left(\int_{\mathbb R}(x+y)^2 \mathrm d \mathbb P_X(x)\right)\mathrm d\mathbb P_Y(y)=\\=\int_{\mathbb R}\mathbb E[(X+y)^2]\mathrm d\mathbb P_Y(y).$$
Since $y\mapsto \mathbb E[(X+y)^2]$ is integrable over $\mathbb R$ for some probability measure, it's in particular finite for some $y$, hence $\mathbb E(X^2)$ is finite. Similarly, one can show that $\mathbb E(Y^2)$ is finite.

A: If they have the finite mean x=$E X < \infty$  and $y= E Y <\infty$ then yes
$E(X+Y)^2 = E(X^2)+E(Y^2)+2 E(X)*E(Y) = E(X^2)+E(Y^2)+2xy < \infty$. If no, I am affraid one can found a pathological case  when this is not true.
Let me update myself. I think the previous answer given by David Giraudo is correct. Let me just a little expand it. $E(X+y)^2<\infty$ for some $y$ means
that $E(X+y)=E(X)+y<\infty$ for this $y$. This means that $E(X)<\infty$. This means that   $E(X+y)^2=E(X^2)+2E(X)y+y^2 <\infty$. So $E(X^2)<\infty$.


Q: Python recursion - how to exit early I've been playing with BST (binary search tree) and I'm wondering how to do an early exit. Following is the code I've written to find kth smallest. It recursively calls the child node's find_smallest_at_k, stack is just a list passed into the function to add all the elements in inorder. Currently this solution walks all the nodes inorder and then I have to select the kth item from "stack" outside this function.
def find_smallest_at_k(self, k, stack, i):
    if self is None:
        return i

    if (self.left is not None):
        i = self.left.find_smallest_at_k(k, stack, i)

    print(stack, i)
    stack.insert(i, self.data)
    i += 1
    if i == k:
        print(stack[k - 1])
        print "Returning"

    if (self.right is not None):
        i = self.right.find_smallest_at_k(k, stack, i)

    return i

It's called like this,
our_stack = []
self.root.find_smallest_at_k(k, our_stack, 0)
return our_stack[k-1]

I'm not sure if it's possible to exit early from that function. If my k is say 1, I don't really have to walk all the nodes then find the first element. It also doesn't feel right to pass list from outside function - feels like passing pointers to a function in C. Could anyone suggest better alternatives than what I've done so far?

A: Passing list as arguments: Passing the list as argument can be good practice, if you make your function tail-recursive.  Otherwise it's pointless.  With BST where there are two potential recursive function calls to be done, it's a bit of a tall ask.
Else you can just return the list.  I don't see the necessity of variable i.  Anyway if you absolutely need to return multiples values, you can always use tuples like this return i, stack and this i, stack = root.find_smallest_at_k(k).
Fast-forwarding: For the fast-forwarding, note the right nodes of a BST parent node are always bigger than the parent.  Thus if you descend the tree always on the right children, you'll end up with a growing sequence of values.  Thus the first k values of that sequence are necessarily the smallest, so it's pointless to go right k times or more in a sequence.
Even in the middle of you descend you go left at times, it's pointless to go more than k times on the right.  The BST properties ensures that if you go right, ALL subsequent numbers below in the hierarchy will be greater than the parent.  Thus going right k times or more is useless.
Code: Here is a pseudo-python code quickly made.  It's not tested.
def findKSmallest( self, k, rightSteps=0 ):
    if rightSteps >= k: #We went right more than k times
        return []
    leftSmallest = self.left.findKSmallest( k, rightSteps ) if self.left != None else []
    rightSmallest = self.right.findKSmallest( k, rightSteps + 1 ) if self.right != None else []
    mySmallest = sorted( leftSmallest + [self.data] + rightSmallest )
    return mySmallest[:k]

EDIT The other version, following my comment.
def findKSmallest( self, k ):
    if k == 0:
        return []
    leftSmallest = self.left.findKSmallest( k ) if self.left != None else []
    rightSmallest = self.right.findKSmallest( k - 1 ) if self.right != None else []
    mySmallest = sorted( leftSmallest + [self.data] + rightSmallest )
    return mySmallest[:k]

Note that if k==1, this is indeed the search of the smallest element.  Any move to the right, will immediately returns [], which contributes to nothing.

A: As said Lærne, you have to care about turning your function into a tail-recursive one; then you may be interested by using a continuation-passing style. Thus your function could be able to call either itself or the "escape" function. I wrote a module called tco for optimizing tail-calls; see https://github.com/baruchel/tco
Hope it can help.

A: Here is another approach: it doesn't exit recursion early, instead it prevents additional function calls if not needed, which is essentially what you're trying to achieve.
class Node:
    def __init__(self, v):
        self.v = v
        self.left = None
        self.right = None

def find_smallest_at_k(root, k):
    res = [None]
    count = [k]

    def helper(root):
        if root is None:
            return

        helper(root.left)
        count[0] -= 1
        if count[0] == 0:
            print("found it!")
            res[0] = root
            return

        if count[0] > 0:
            print("visiting right")
            find(root.right)

    helper(root)
    return res[0].v

A: If you want to exit as soon as earlier possible, then use exit(0).
This will make your task easy!


Q: Css calling class into other style I don't understand why this doesn't work
.mix{
  -moz-border-radius: 5px 5px;
  border-radius: 5px 5px / 5px 5px;
  -moz-box-shadow: 2px 2px 2px #888;
  -webkit-box-shadow: 2px 2px 2px #888;
  box-shadow: 2px 2px 2px #888;
}
#adm_content_login, .mix{
  top:100px;
  position:relative;
  width:450px;
  height:200px;
  margin:auto;
  background-color:#ccc;
  text-align:center;
  border:5px solid #111;
}

When I try to call a class into another class with adm_content_login, .mix , because there is no need if I use this code each time I have the same content I have in the .mix. I don't understand what's wrong with this code. The CSS works if I put it into adm_content_login, but if I try using this method it doesn't work.

A: Hi if you are trying to use .mix class with #adm_content_login you can make both of them either a class or id. for instance, if both of them are class you can you it like this

notice that there is a space between two classes.
If that's not what you are trying to achieve then you can achieve something like that using LESS(CSS FRAMEWORK)

A: you are using class but you define id
used to this way as like this


Q: Обновление отдельного блока fsockopen Суть такая: есть отдельный блок, в нем функция fsockopen. Если сервер, который пингуется, функция пытается весь тайм аут пингануть, его что приводит к зависанию страницы.
Т.е. необходимо сделать, чтобы изначально был блок с типом (загрузка... итд). А как fsockopen пропингует, выводился бы его результат.


Q: Javascript/AJAX/send to server text and file with JSON I'm developing a small software that allow to insert of my client's store products, description text and product photos, then i need to send with $.ajax() either text and files with 1 call.
I have no problem sending text or file separately, with 2 call, but can i do it with 1?

A: var formData = new FormData();
formData.append("file-identifier", $('#file-identifier').get(0).files[0]);
formData.append("variable", $.session.get("variable"));
$.ajax({
    url     : "path/to/file.file",
    type    : "POST",
    processData: false,
    contentType: false,
    data    : formData,
    dataType: "json",
    success : function(data){
        //handle on success
    },
    error    : function(jqXHR, textStatus, errorThrown){
        console.log(arguments);
   }
});

This is a sample from a script I used recently to upload a jpeg and a variable taking content from a session variable. Appending these to a FormData object allows you to transfer both file and variable in one request.


Q: how to find selected fields from sample data in nested array in mongodb I have sample collection of data
[
  {
    data: [
      {
        "id": "0001",
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "batters": {
          "batter": [
            {
              "id": "1001",
              "type": "Regular"
            },
            {
              "id": "1002",
              "type": "Chocolate"
            },
            {
              "id": "1003",
              "type": "Blueberry"
            },
            {
              "id": "1004",
              "type": "Devil's Food"
            }
          ]
        },
        "topping": [
          {
            "id": "5001",
            "type": "None"
          },
          {
            "id": "5002",
            "type": "Glazed"
          },
          {
            "id": "5005",
            "type": "Sugar"
          },
          {
            "id": "5007",
            "type": "Powdered Sugar"
          },
          {
            "id": "5006",
            "type": "Chocolate with Sprinkles"
          },
          {
            "id": "5003",
            "type": "Chocolate"
          },
          {
            "id": "5004",
            "type": "Maple"
          }
        ]
      },
      {
        "id": "0002",
        "type": "donut",
        "name": "Raised",
        "ppu": 0.55,
        "batters": {
          "batter": [
            {
              "id": "1001",
              "type": "Regular"
            }
          ]
        },
        "topping": [
          {
            "id": "5001",
            "type": "None"
          },
          {
            "id": "5002",
            "type": "Glazed"
          },
          {
            "id": "5005",
            "type": "Sugar"
          },
          {
            "id": "5003",
            "type": "Chocolate"
          },
          {
            "id": "5004",
            "type": "Maple"
          }
        ]
      },
      {
        "id": "0003",
        "type": "donut",
        "name": "Old Fashioned",
        "ppu": 0.55,
        "batters": {
          "batter": [
            {
              "id": "1001",
              "type": "Regular"
            },
            {
              "id": "1002",
              "type": "Chocolate"
            }
          ]
        },
        "topping": [
          {
            "id": "5001",
            "type": "None"
          },
          {
            "id": "5002",
            "type": "Glazed"
          },
          {
            "id": "5003",
            "type": "Chocolate"
          },
          {
            "id": "5004",
            "type": "Maple"
          }
        ]
      }
    ]
  }
]

and I need data only in this formate of a specific id.
[
  {
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55
  }
]

A: aggregate
db.collection.aggregate({
  "$unwind": "$data"
},
{
  "$match": {
    "data.id": "0001"
  }
},
{
  "$project": {
    "_id": "$data.id",
    "type": "$data.type",
    "name": "$data.name",
    "ppu": "$data.ppu"
  }
})

mongoplayground


Q: AzureDevOps ServiceTags Availability for NSG Is service tag for Azure DevOps in roadmap? if yes, do we have an ETA on the availability? or Do we have any other tags which covers Azure DevOps IP range?
As of now, we have Azure DevOps Agent IP ranges available online through weekly XML but we dont have a tag for Azure DevOps as of now to be used with NSGs.
https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/hosted?view=azure-devops&tabs=yaml#agent-ip-ranges

A: It appears from this issue that Azure is not implementing a service tag, but instead thinking of creating a product where you can spin up semi-managed build agents inside your own subscription.
Details can be found on the design in github

A: Azure DevOps Service Tag have been released

Now that a service tag has been set up for Azure DevOps Services, customers can easily allow access by adding the tag name AzureDevOps to their NSGs or firewalls programmatically using Powershell and CLI. The portal will be supported at a later date. Customers may also use the service tag for on-prem firewall via a JSON file download. Azure Service Tags are supported for inbound connection only from Azure DevOps to customers’ on-prem. Outbound connection from customers’ networks to Azure DevOps is not supported. Customers are still required to allow the Azure Front Door (AFD) IPs provided in the doc for outbound connections. The inbound connection applies to the following scenarios documented here.

Note: Service Tag AzureDevOps is available from the portal now.
However this will not cover IP Ranges of MS Hosted agents


Q: How to refactor the code of a class composed of one public method and multiple private method that only do check There is a code I'm working on that I find kind of annoying.
Indeed, the class is composed of one public method and many private methods to check stuff and or to output some logs.
There are 3 types of private method in the code.
The firsts private method only do some check on the input data and raise if something is inconsistent. (3 methods)
The seconds do the only produce some log reports. (2 methods)
And the thirds prepare and save the data (2 methods) (The purpose of this class), those are composed of many other external library that I have to mock.
Then each of the private method are called in the public method of the class that we will call execute().
Every test runs on the execute method that include the whole logic of the code behind private functions.
To test the code, I mock many call of external methods inside the method that save and look at the args that are called when I run the execute method in my test, because of this every test I write are 75% function mocking calls.
It's annoying.
I would like to split it but each I tried I look at it and find it useless because it's more like I just extract the private method in another.
Here is pseudo code of the class. It's in python but it is irrelevant :
class MyDigustingClass():

    def _first_check(self, args...):
        pass

    def _second_check(self, args...):
        pass

    def _third_check(self, args...):
        pass

    def _log_method_1(self, args...):
        pass

    def _log_method_2(self, args...):
        pass

    def _prepare_data(self, args...):
        pass

    def _save_data(self, args...):
        pass

    def execute(self, args...):
        # Call check methods

        # Call prepare_data

        # Call save_data

        # Call logs method

As I said, I struggle to find a good idea of refactoring because I can't do better than a flat pass.
What would you suggest.


Q: open protected excel file with com, but the running excel does not support addins I need to open the encrypted excel file from code, and the end user can also edit or save the opened file. Then I found a way to handle it by using com:
https://learn.microsoft.com/zh-cn/previous-versions/office/troubleshoot/office-developer/automate-excel-from-c
However, The opened excel application does not support excel addins.
for example: the excel setting like
excel setting 1
excel setting 2
when open excel.exe normally，it's like:
normally open, correct
but when use com to open excel.exe by the code, it's like:
open from code, incorrect
the addins disappear.
Also, if you reconfig addins option, addins appear again. So I think there may have no initialization when excel.exe was started.
Is there any way to start open encrypted excel file by excel.exe from code, and all excel function are fine?
Here is the code with vbs(the link below is c code):
Set oExcel = CreateObject("Excel.Application")
Set oWorkbook = oExcel.Workbooks.Open("C:\Users\melon\Desktop\excel\excel tests\chat&sample exam.xlsm", 0, 0, 5, "76350e01-a0bd-44c6-9e4d-0df382c2d789")
oExcel.Visible = true

A: Programs started with COM are started by COM with the slash /a parameter. This means Automation is starting the program so it should load clean.

/a
Starts Word and prevents add-ins and global templates (including the
Normal template) from being loaded automatically. The /a switch also
locks the setting files.

https://support.microsoft.com/en-us/office/command-line-switches-for-microsoft-office-products-079164cd-4ef5-4178-b235-441737deb3a6


Q: Elastic search structure AND/EXISTS Im new to Elasticsearch and this is driving me crazy. The docs are pretty unhelpful and so about 6 hours in I come to the amazing SO community.
I have a query which is implemented all over a large and 95% finished website, so I cannot rewrite much at this point.
I need add a check to make sure that the userID is not null. In SQL this would take seconds, but I have a pretty large query which is giving me either crazy unhelpful error messages or not working. I have tried restructuring, moving the "exists" into an existing "and" where it doesnt work at all.
This is what I have:
GET _search
{
"from": 0,
"size": 30,
"query": {
    "filtered": {
        "query": {
            "match_all": {}
        },
        "filter": {
            "and": [
            {
            "bool": {
                "must": [
                   {
                        "exists" : { "field" : "userID" }
                   }
                ]
            }
            },{
                "term": {
                    "property.rental": false
                }
            }, {
                "term": {
                    "property.status": 100
                }
            }, {
                "term": {
                    "property.showOnHomepage": true
                }
            }
         ]
       }
    }
},
"sort": {
    "_script": {
        "script": "Math.random()",
        "type": "number",
        "params": {},
        "order": "asc"
    }
},
"aggregations": {
    "min_price": {
        "min": {
            "field": "basePrice"
        }
    },
    "max_price": {
        "max": {
            "field": "basePrice"
        }
    },
    "avg_price": {
        "avg": {
            "field": "basePrice"
        }
    }
},
"filter": {
    "range": {
        "property.price": {
            "lte": 1000000000
        }
    }
}
}

This gives the following results:
{
"took": 7,
"timed_out": false,
"_shards": {
  "total": 5,
  "successful": 5,
  "failed": 0
},
"hits": {
  "total": 0,
  "max_score": null,
  "hits": []
},
"aggregations": {
  "min_price": {
     "value": null
  },
  "max_price": {
     "value": null
  },
  "avg_price": {
     "value": null
  }
}
}

I simply don't understand where to place the
 "exists" : { "field" : "userID" }

inorder for it to filter out just the properties with null for a userID.
Any help would be amazing.


Q: Splitting a Clojure namespace over multiple files Is it possible to split a Clojure namespace over multiple source files when doing ahead-of-time compilation with :gen-class? How do (:main true) and (defn- ...) come into play?

A: Overview
Certainly you can, in fact clojure.core namespace itself is split up this way and provides a good model which you can follow by looking in src/clj/clojure:
core.clj
core_deftype.clj
core_print.clj
core_proxy.clj
..etc..

All these files participate to build up the single clojure.core namespace.
Primary File
One of these is the primary file, named to match the namespace name so that it will be found when someone mentions it in a :use or :require.  In this case the main file is clojure/core.clj, and it starts with an ns form.  This is where you should put all your namespace configuration, regardless of which of your other files may need them.  This normally includes :gen-class as well, so something like:
(ns my.lib.of.excellence
  (:use [clojure.java.io :as io :only [reader]])
  (:gen-class :main true))

Then at appropriate places in your primary file (most commonly all at the end) use load to bring in your helper files.  In clojure.core it looks like this:
(load "core_proxy")
(load "core_print")
(load "genclass")
(load "core_deftype")
(load "core/protocols")
(load "gvec")

Note that you don't need the current directory as a prefix, nor do you need the .clj suffix.
Helper files
Each of the helper files should start by declaring which namespace they're helping, but should do so using the in-ns function.  So for the example namespace above, the helper files would all start with:
(in-ns 'my.lib.of.excellence)

That's all it takes.
gen-class
Because all these files are building a single namespace, each function you define can be in any of the primary or helper files.  This of course means you can define your gen-class functions in any file you'd like:
(defn -main [& args]
  ...)

Note that Clojure's normal order-of-definition rules still apply for all functions, so you need to make sure that whatever file defines a function is loaded before you try to use that function.
Private Vars
You also asked about the (defn- foo ...) form which defines a namespace-private function.  Functions defined like this as well as other :private vars are visible from within the namespace where they're defined, so the primary and all helper files will have access to private vars defined in any of the files loaded so far.


Q: How to access Entity Framework DbContext entities in Server-Side Blazor Components I'm new to .NET Core and Blazor, with mostly WebForms and MVC experience.
All the Blazor documentation and tutorials I've found use a separate API project and access data through HttpClient and Json serialization/deserialization. I see why this would be necessary for client-side Blazor using WebAssembly, but for Server-Side Blazor using SignalR what's the best way to access the database directly from the components' .razor files using an Entity Framework DbContext?
For example, in an MVC controller you can just do something like:
private ApplicationDbContext context = new ApplicationDbContext();

and then query the data by doing something like:
var things = context.Things.Where(t => t.ThingAttributes == something);

Is there an approach that is this clean and efficient when working with components in server-side Blazor?
Sorry for the broad nature of this question, feel free to point me to blogs, docs, or tutorials I should have already read. Thanks!

A: What you call a controller should be turned into a service class, that retrieves data from the database, and pass it to the calling methods. You should add this service to the DI container in the Startup class. To use this service in your components you should inject it like this:
@inject DataService myDataService

I think that the Blazor templates come with sample how to define such a service and use it in your components.
Here's a link to a sample by the Blazor team how to create a service and how to use it in your components. The service doesn't use Entity Framework, but this is something really minor I'm sure you'll cope with.


Q: How to pad strings inside curly braces with odd number of character with a single space? We have many \foo{something}. As the string inside the curly braces contains odd number of character, we want to add a space after the string. The result will be \foo{something }. We only want odd number of characters only. For example, in \foo{string} the string inside the curly braces has even number of character, then we do not add a space.
What I have tried:

*

*a dot means a character, two dots means two characters

*asterisk means repeat 0 or more times

*Then, [..]*. means 1, 3, 5 ... characters.

*Then, \foo{[..]*.} will be my matching sequence.

*Then, :%s/\foo{[..]*.}/\foo{[..]*. }/g will add the space we want.

But we failed.

A: This cmd should do:
:%s/\\foo{\zs[^}]\+\ze}/\=substitute(submatch(0), '$', len(submatch(0))%2?' ':'','g')/

A: :%s/\\\w\+{\([^}]\{2}\)*[^}]\zs\ze}/ /g

Explanation:
Find pairs of characters (\([^}]\{2}\)*) followed by another character ([^}]) in between a macro \\\w\+{...}. Then do a substitution adding an additional space.
Glory of details:

*

*\\\w\+{...} find macros of the pattern \foo{...}

*Look for character that does not match an ending curly brace, [^}]

*Look for pairs of non-}'s, \([^}]\{2}\)*

*Find an odd length string by finding pairs and then finding one more, \([^}]\{2}\)*[^}]

*Use \zs and \ze to set where the start and end of the match

*Use a space in the replacement portion of the substitution to add additional space and thereby making the string even in length

Fore more help see:
:h :s
:h :range
:h /\[]
:h /\(
:h /\zs
:h /\w
:h /star
:h /\+

A: This should work
:%s/\v[(\{(\w{2})*) ]@<!}/ }/g

break down:
%s           " run substitute on every line
\v           " very magic mode
[(\{(\w{2})*) ] " matches every `{` followed by an equal number of word
characters and space, since you don't want to add a space again everytime
you run it.
@<!}         " negative lookahead, matches all } not following the pattern before

Update
To solve the precise problem as you can read in the comments, the following command helps.
g/^\\foo/s/\v(\{([^}]{2})*)@<!}/ }/g

Changes:
 g/^\\foo/...    " only run it on lines starting with \foo
 [^}]            " it does now match all characters between { and } not only word
 characters.

Pitfalls: won't work correct with multiple braces on the line ( \foo{"hello{}"} and \foo{string} {here it would also match} f.e. will fail). if one of these is a problem. just tell me


Q: Catching errors at the end of a chain of promises I am using a factory to query data from Parse.com, this occurs many times in my ionic app and would like to apply a little more DRY to my code.
To call data I am using:
ParseFactory.provider('Clients', query).getAll().success(function(data) {
    $localStorage.Clients = data.results;
}).error(function(response) {
    errorFactory.checkError(response);
});

And often run many of these back to back to get data from different classes on the loading of a page.
Is it possible to use one error block at the end of all of these? like this:
ParseFactory.provider('Favourites', query).getAll().success(function(data) {
    $localStorage.Favourites = data.results;
})
ParseFactory.provider('Somethings/', query).getAll().success(function(data) {
    $localStorage.Programmes = data.results;
})
ParseFactory.provider('UserItems', query).getAll().success(function(data) {
    $localStorage.UserExercises = data.results;
})
ParseFactory.provider('Customers', query).getAll().success(function(data) {
    $localStorage.Clients = data.results;
}).error(function(response) {
    errorFactory.checkError(response);
});

A: You could create helper method:
function query(resource, query) {
  function querySucceeded(data) {
    $localStorage[resource] = data.results;
  }

  function queryFailed() {}

  ParseFactory.provider(resource,  query)
     .getAll()
     .success(querySucceeded)
     .error(queryFailed);
}

and, then just call:
query('Favourites', query);
query('Customers', query);

and so on.
Alternatively, you could factor queryFailed out, as such:
function query(resource, query) {
  function querySucceeded(data) {
    $localStorage[resource] = data.results;
  }

  return ParseFactory.provider(resource,  query)
     .getAll()
     .success(querySucceeded);
}

function queryFailed() {

}

$q.all([
    query('Favourites', query1),
    query('UserItems', query2)])
    .error(queryFailed);

A: $q.all takes an array (or object) of promises, and returns a single one.
The returned promise is resolved when all the original promises are resolved. It's rejected as soon as one of the original promises is rejected.
So, what you can simply do is something like
var request = function(path) {
    return ParseFactory.provider(path, query).getAll();
};

var promises = {
    favourites: request('Favourites'),
    programmes: request('Somethings/'),
    exercises: request('UserItems'),
    customers: request('Customers')
};
$q.all(promises).then(function(results) {
    $localStorage.Favourites = results.favourites.data.results;
    // ...
}).catch(function() {
    // ...
});


Q: Как загрузить файл, используя move_uploaded_file() Вот код загрузки файла:
try {
    if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $file)) {
        //print_r(error_get_last());
        //print_r($_FILES['userfile']['error']);
        throw new Exception(500, 'Could not move file');
    }
    echo $f;
} catch (Exception $e) {
    die ('File did not upload: ' . $e->getMessage());
}

print_r(error_get_last());
// возвращает ошибку
//  [type] => 2
//  [message] => move_uploaded_file(): Unable to move '/tmp/php4t0xH0'
//      to   '/var/www/ua/images/todo/B5SD4iK9zbbG549bEykT9QDyk.jpeg'

print_r($_FILES['userfile']['error']);
// возвращает 0

Что самое интересное: если с другого места сайта делать загрузку, то всё работает отлично.
Сохранение в директорию $file происходит нормально с другой формы, поэтому права доступа, думаю, здесь ни при чём.

A: Ну раз, как вы говорите, есть зависимость от места где вызывается, предположу, что вы используете относительное имя файла-назначения, которое в одном случае указывает куда надо, а в другом мимо.
Включите вывод всех предупреждений и проверяйте буквально все промежуточные значения.
http://phpfaq.ru/debug


Q: Discord Bot will not login to server I will start this off by saying I'm a bit new to discord bot making. I'm just trying to get the bot online at this point and I keep getting the error:

TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
at Client._validateOptions (C:\Users\levan\Desktop\Discordbot\node_modules\←[4mdiscord.js←[24m\src\client\Client.js:544:13)
at new Client (C:\Users\levan\Desktop\Discordbot\node_modules\←[4mdiscord.js←[24m\src\client\Client.js:73:10)
at Object. (C:\Users\levan\Desktop\Discordbot\main.js:3:16) ←[90m
at Module._compile (node:internal/modules/cjs/loader:1101:14)←[39m

←[90m

at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)←[39m

←[90m

at Module.load (node:internal/modules/cjs/loader:981:32)←[39m

`←[90m    at Function.Module._load (node:internal/modules/cjs/loader:822:12)←[39`m

←[90m    at Function.executeUserEntryPoint [as runMain] ``(node:internal/modules/run_main:79:12)←[39m
←[90m    at node:internal/main/run_main_module:17:47←[39m {

  [←[32mSymbol(code)←[39m]: ←[32m'CLIENT_MISSING_INTENTS'←[39m

}

thus far this is what I have

const Discord = require('discord.js');

const client = new Discord.Client();

client.once('ready', () => {
console.log('Tec Control Bot is online!');
});

client.login('redacted sign in key');

A: So, you are using discord.js v13 which is a lot different from the previous version which is v12. In v13, it is compulsory to add intents.
You can read this for more information: here

A: new Discord version V13 requires you to set the intents your bot will use.
First, you can go to https://ziad87.net/intents/ where you can choose the intents you want and gives you a number, you should use that number like this:
const intents = new Discord.Intents(INTENTS NUMBER);
const client = new Discord.Client({ intents });

For example, if you want all the intents, you will have:
const intents = new Discord.Intents(32767);
const client = new Discord.Client({ intents });


Q: Jerky animation on window open/close Today, I received and installed Windows 7, and one of the first (slightly) annoying things I noticed is a visible jerk when opening of closing new windows. When I minimize or maximize already running window, the animation is smooth from beginning to end, but when I start a new program, it seems that just at the end of the animation Windows thinks for a fraction of a second. It is a bit distracting; especially since Windows 7 seems to be overall more responsive than Windows Vista. Does anybody has the same experience? Could it, for instance, a 64bit version specific issue (just in case)? I upgraded Vidia drivers, and even though my video card is not capable running latest games, it should be able to handle this (since it was OK in Vista, and since it does not look like a video issue).

A: Is this the animation stutter you are referring to? http://www.youtube.com/watch?v=YWdVrSUhvLE&NR=1
This is a well known problem (I'm not sure if its a bug or a "feature") in Windows 7.  For some reason or another Microsoft just changed the aero animation for opening and closing windows - I suspect that they wanted it to be more apparent to users when the animation was finished and they could start using the window.  It bugs me too, but I have not found any way to revert it back to the vista-style animations.

A: I have noticed the same exact thing and it is very annoying.  Have same processor as you but nVidia 9800M GS.  Windows rates aero perfomance at 6.7 but the windows jerking on open/close really annoys me for some reason.

A: Same thing here. I have a 6.9 graphics score but to me it seems like the jerky animation is on purpose. It also happens when I close a window (first a little hiccup, then it disappears smoothly).
Annoying!


Q: Add class to Reply button in Comments area Under each comment there is a link called 'Reply'. I want to add a class to this link. It's default class is comment-reply-link. How can I do so? I am creating my own theme and I don't want to manually edit files inside the wp-includes directory.

A: Quite old post, but while searching I came here, maybe someone else will find it useful.
The only solution I found is to completely rebuilt the button that comment_reply_link returns.
I first made two vars reconstructing href and onclick attributes for the reply button:
$reply_href = wp_make_link_relative(
    get_permalink( $comment->comment_post_ID )
    )
    . '?replytocom=' . $comment->comment_ID . '#respond';

$reply_onclick = 'return addComment.moveForm("comment-'
    . $comment->comment_ID
    . '", "'
    . $comment->comment_ID
    . '", "respond", "'
    . $comment->comment_post_ID
    . '")';

And then output the whole reply block, adding your custom classes:

    <a class="comment-reply-link custom-class" href="<?php
        echo $reply_href;
        ?>" onclick="<?php
        echo $reply_onclick;
        ?>"><?php
        _e('Reply', 'yourthemename');
    ?>

A: In your comments.php template file use wp_list_comments and set the parameter callback to your defined function that will generate the template. Inside the function you can style the comment reply link.
wp_list_comments codex
Further reading on comment display

A: I know this is quite an old post and maybe this could help someone.
You can replace the class of an element using add_filter();
Here's an example:
// filter to replace class on reply link

//           class name             function name
add_filter('comment_reply_link', 'replace_reply_link_class');

function replace_reply_link_class($class){
    $class = str_replace("class='comment-reply-link", "class='reply", $class);
    return $class;
}

With this you should be able to replace the class in your themes.
I hope this can be of any help for someone :)

A: This might not be an elegant solution but it gets the job done. Do it with jQuery. Basically find the element and add the class you need. WordPress totally didn't make this easy to customize:
jQuery('a#comment-reply-link').addClass('mycustomcssclass');

A: Also something to double check (as I overlooked this for about half an hour)...
Make sure under: Settings > Discussion
This checkbox is checked:

Enable threaded (nested) comments levels deep

Otherwise the reply button will not show up at all


Q: Konsole always stays in foreground and retains focus I recently realized strange behaviors of Konsole. It always stays in foreground and remains the focus.
Examples:

*

*I start Konsole. Then, I start Dolphin (or any other application). Dolphin will start but the Window will be behind Konsole. I have to use the task manager to switch to the Dolphin window. I'd expect that Dolphin starts in the foreground.

*I start Konsole. The I press Alt+F2 to start KRunner. Krunner appears but immediately disappears. When I type a command, it's typed in Konsole. I'd expect that KRunner appears, stays and that I can run a command.

*I start Konsole. I click on the Application Launcher in the panel. The application launcher appears. If I now start to type, I would expect that it searches my applications, instead the command is typed in Konsole.
The problem seems to be unique to Konsole. Other applications (I tried Kate and Xterm) do not show this behavior. The behavior of Konsole seems to be new and I cannot remember what I did before it changed. I'm on Kubuntu 16.04.
The Keep above others option is not activated:

Also the Application Launcher menu appears in front of Konsole. It would appear behind Konsole if the Keep above others option would be used.
What can I do to make Konsole behave as I expect?

A: It sounds like you have enabled Keep Above others via right click --> more actions on the window border
The image below shows dolphin, but the option is available for all windows.

If this does not help, you could reset your kde profile by running:
mv ~/.kde4 ~/.kde4.old


Q: Re-read environment variables from VBScript I'm running a VBScript from a MSI installer (created using WiX toolset). This script checks using the PATH environment variable whether another software
is installed or not. The installer also offers a retry button which runs the script again.
Now the problem is this: If the PATH environment variable is changed while my installer is running, my script will not detect that change. My script only uses the new value of the PATH environmental variable after a re-start of the installer.
So the question is this: How can I force the installer process to update its copy of the environment variables using VBScript?
Edit:
It looks like this article explains how to solve the problem with PowerScript. But I need a solution for VBScript.

A: With WScript.CreateObject("WScript.Shell")
    .Environment("PROCESS")("PATH") = .ExpandEnvironmentStrings(Replace( _
        .Environment("USER")("PATH") & ";" & .Environment("SYSTEM")("PATH"), ";;", ";" _
    ))
End With

This will overwrite the in memory current process PATH environment variable with the information retrieved from registry for the user and system environment variables.
note: Previous code only updates the environment copy of the [c|w]script process that executes the code. It does not update the installer's copy of the environment (you can not update another process environment).

A: Alternately, from jscript (still the cscript interpreter, but the jscript language)
// Re-read PATH vars in case they've changed
var shell = new ActiveXObject("WScript.shell");
var newPath = (shell.Environment("USER")("PATH") + ";" + shell.Environment("SYSTEM")("PATH")).replace(/;;/g, ";");
// Expand any %STRINGS% inside path and set to the new running process
shell.Environment("PROCESS")("PATH") = shell.ExpandEnvironmentStrings(newPath);

shell.Exec('myprocess.exe'); // throws exception if not found


Q: Determine number of row spans given a start index and a length I have a matrix start index of my data and the number of elements of my data
and I need to find the number of rows that the data span.
e.g. the matrix

 0              5
-------------------
|  |  |  |  |x |x |
-------------------
|x |x |x |x |x |x |
-------------------
|  |  |  |  |  |  |
-------------------
|  |  |  |  |  |  |
-------------------

My data is marked with x. I know the start index 4, the length of the data 8.
And I need to determine the number of rows this data spans, 2 in this case. (just doing length/6 is off by one in many cases, surely there have to be a simple formula for this..)

A: If you only know offset (i.e. index of the starting column), size (i.e. how many data), cols (i.e. maximum number of colums), and you want to calculate how many rows your data will span, you can do
int get_spanned_rows(int offset, int size, int cols) {
  int spanned_rows = (offset + size) / cols
  if ( ( (offset + size ) % cols) != 0 )
    spanned_rows++
  return spanned_rows
}

where % is the modulus (or reminder) operator

A: int calc_rows(int start,int length){
    int rows = 0;
    int x= 0;
    if (start != 0){
        x = 6%start;
        rows+=1;
    }
    if ((start+length) % 6 != 0){
        x +=(start+length) % 6;
        rows+=1;
    }
    rows+= (length - x)/6;
    return rows;
}

calculates number of rows by dividing by 6 but after subtracting partially filled rows count

A: In case you only want the number of rows you can calculate
num_rows = (offset + size + cols - 1) / cols

which in this case is
num_rows = (4 + 8 + 6 - 1) / 6 = 17 / 6 = 2


Q: Fortify- spring-boot-starter-actuator deserialization vulnerability with latest spring boot version I am facing Dynamic Code Evaluation: Unsafe Deserialization in fortify scan with latest spring boot version 2.2.4 Release. can you anyone help to resolve this issue?


Q: javascript syntax reader is wrong? i have this code , don't get me wrong it all work fine
var w = "window" ,
  gg = "gg" ,
  pr = "prototype" ,
  al = "alert" ,
  pi = "parseInt" ,
  st = String ,
  ts = "toString";

st[pr][gg] = function(){return window[this[ts]()];};
w = w[gg]();
w[al](w[pi]("0"));

the problem starts when i replace this piece of code
w = w[gg]();
w[al](w[pi]("0"));

with this one
w[gg]()[al](w[pi]("0"));

now it's not working.
i don't get it , it suppose to get the same result , what is wrong here?

A: There are two places that w is used:
w[al](w[pi]("0"));
^     ^

So you need to substitute in w[gg]() twice:
w[gg]()[al](w[gg]()[pi]("0"));
^^^^^^^     ^^^^^^^

Note also that this transformation might still not equivalent, for example if w[gg]() has side-effects or is non-deterministic.


Q: Mysql rollBack error from different database try{
   $SQL=$user_db->prepare("INSERT INTO user (...");
   $SQL->execute();
   $id=$user->lastInsertId('user');//Need this id for next query

   //connect to 2nd db
   //$SQL2=$message_db->prepare("UPDATE....");
}catch{...}

I have 2 queries from 2 different db
is any way to roll back the error & stop process if there is any error?
because its from 2 different db so I couldn't use transaction.
ps.1st db is innodb, but my 2nd db is mysqlISAM (not support transaction)


Q: Dynamic Route Matching -- how to bind an object key that contains a space? I am trying to use Vue Router dynamic route matching and have an object key of NAS ID with a space.
How would I bind that to the router path?
{
    path: '/:NAS ID',
    component: DataDetail
  }

The above path value gives me an error in console:
Expected "NAS" to be defined

A: Route matching is powered by https://github.com/pillarjs/path-to-regexp .  You can use their documentation to look for a similar case.
My first guess would be to try escaping the space: path: '/:NAS\ ID'


Q: Javascript: on click change button text color Hey I have the below javascript code with accompanying HTML.  I am trying to get each button when clicked to change the text color to blue and then when the next button is clicked it changes text of the previously clicked button back to green. basically only the most recently clicked button has blue text.  I have tried this code but with this it changes all button text to blue on the first button click.  Any help is appreciated.  Javascript, HTML, and CSS below.
function swapIphoneImage( tmpIPhoneImage ) {
    var el = document.getElementById('my-link');
    var el1 = document.getElementById('my-link1');
    var el2 = document.getElementById('my-link2');
    var el3 = document.getElementById('my-link3');
    var el4 = document.getElementById('my-link4');

    var iphoneImage = document.getElementById('iphoneImage');
    iphoneImage.src = tmpIPhoneImage;
    el.className = 'clicked-class';
    el1.className = 'clicked-class1';
    el2.className = 'clicked-class2';
    el3.className = 'clicked-class3';
    el4.className = 'clicked-class4';

}

html

HaPPPs Calendar

Weekend Events

Places & People

Customize Events

Interaction

css

a#my-link.clicked-class {
    color: #71a1ff !important;
}
a#my-link1.clicked-class1 {
    color: #71a1ff !important;
}
a#my-link2.clicked-class2 {
    color: #71a1ff !important;
}
a#my-link3.clicked-class3 {
    color: #71a1ff !important;
}
a#my-link4.clicked-class4 {
    color: #71a1ff !important;
}

Where am I failing?

A: Try using JavaScript to change the classes then you only need one class to determine which one is clicked.
Here is an example:
JS:
   $("UL.features LI A").click(function(){
      $("UL.features LI A").removeClass('clicked');
      $(this).addClass('clicked');
   });

CSS:
A.clicked {
    color:#71a1ff !important;
}

Here it is in jsfiddle:
 http://jsfiddle.net/57PBm/
EDIT: This solution uses JQuery which will I would definitely suggest using if you are not already

A: Rewrite JS code to:
function swapIphoneImage( elThis, tmpIPhoneImage ) {
    var el = document.getElementByClassName('clicked-class');

    var iphoneImage = document.getElementById('iphoneImage');
    iphoneImage.src = tmpIPhoneImage;

    el.className = '';
    elThis.className = 'clicked-class';
}

and each button to:

HaPPPs Calendar

You don't need to set up 5 CSS classes for the same thing.

A: You are changing every element to a clicked class. Just pass in a number to the function that identifies which button to color blue, then color that one blue and all the others green via JS.


Q: Mongo C# Driver - How to apply ToLower() to a DistinctAsyc I am retrieving a list of strings from MongoDB using DistinctAsync. The problem is that the results are distinct except that I get some values all in uppercase and some are in lower case which count as distinct of course.
How could I apply a .ToLower() to this query?
public async Task<List<string>> GetAllAuthorsUserNames()
{
    var filter = Builders<Episode>.Filter.Where(x => x.CreatedBy != null);

    var cursor = await GetCollection().DistinctAsync(o => o.CreatedBy, filter);

    return cursor.ToList();
}

I have tried this but it doesn't work:
var cursor = await GetCollection().DistinctAsync(o => o.CreatedBy.ToLower(), filter);

A: There are various approaches you can take to yield the result you want. Some are:

*

*Store the authors's names in lowercase only (or at least in a consistent manner such that you do not have to transform their names to yield distinct ones among them in the first place) and in that case a distinct query alone is enough to get you the desired result.

*After you fetch the distinct authors's names from the current data, map their names to their respective lowercase version in-memory and then apply another distinct function on it to get all authors's names in lowercase and distinct form. That will look like:
var filter = ...
var cursor = await GetCollection().DistinctAsync(v => v.CreatedBy, filter);
var list = await cursor.ToListAsync();

var names = list.Select(v => v.ToLower()).Distinct().ToList();

*Use aggregation. Basically, you can project all authors's names to their respective lowercase form (see: toLower) and then group all the projected lowercase names to a set (see: addToSet). That set will be your result which you can extract from the aggregated result.

My opinion is that you should consider altering your data so as to not add unnecessary computational complexity which takes up valuable resources. If that is not possible, but the names themselves are relatively few, you can use the second approach. Use the third approach with the understanding that it is not the ideal and it will add to more processing on the part of your DBMS.


Q: Add previous load count using the the present count and the timestamp column I have a table with the following columns
id, timestamp, current load count, previous load count

and it has many rows. I have values for all the first three columns, but for the "previous load count", I need to get the count of the date one day before the count of the current load count.
See the below image (table example) to view the sample table
For example: previous load count of id:4 is the count same as the current load count of id:5.
Is there anyway to write a SQL statement to update the previous load count?

A: Can you try this?
SELECT [id]
      ,[timestamp]
      ,[current load count]
      ,LAG([current load count]) OVER (ORDER BY [timestamp] ASC, [id]) AS [previous load count]
FROM [table]

The LAG function can be used to access data from a previous row in the same result set without the use of a self-join.
It is available after SQL Server 2012.
In the example I added ordering by id, too - in case you have records with same date, but you can remove it if you like.

A: If you need exactly one day before, consider a join:
select t.*, tprev.load_count as prev_load_count
from t left join
     t tprev
     on tprev.timestamp = dateadd(day, -1, t.timestamp);

(Note:  If the timestamp has a time component, you will need to convert to a date.)
lag() gives you the data from the previous row.  If you know you have no gaps, then these are equivalent.  However, if there are gaps, then this returns NULL on the days after the gap.  That appears to be what you are asking for.
You can incorporate either this or lag() into an update:
update t
    set prev_load_count = tprev.load_count
from t join
     t tprev
     on tprev.timestamp = dateadd(day, -1, t.timestamp);


Q: Qt. Is connection name valuable to connect to the MySQL server? Is connection name valuable to connect to the MySQL server?
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "conectionName");

A: No it is not, If you don't provide then a default name will be given but you can use that name to get that connection some where else.
QSqlDatabase db = QSqlDatabase::database("connectionName");

Here's what documentation says.

If connectionName is not specified, the new connection becomes the
  default connection for the application, and subsequent calls to
  database() without the connection name argument will return the
  default connection. If a connectionName is provided here, use
  database(connectionName) to retrieve the connection.

So if you don't provide any name, then whenever the below will return you that connection.
QSqlDatabase db = QSqlDatabase::database();


Q: How can we check whether empty partitions are present in Athena using lambda function code or query I am trying to fetch whether partition is added or not to Athena table using lambda function code. But when I use
Select * from "table $partitions" where batch date ='yyyymmdd'
It is showing error because in lambda function " is not taking.
But with out " my code is not working.
Can someone suggest anything on this


Q: Cyclomatic Complexity - Delphi API I am searching for a Cyclomatic Complexity Api in Delphi (2010). I need to create a program that will analize a source code and report the Cyclomatic Complexity of all methods in all classes (just like SourceMonitor does).
I cant use other softwares, I really need to build one.
Does anyone knows an API for delphi 2010 that does that?

A: You'll need a language parser from which you can generate a control flow graph. Then you need to calculate the CC using this formula.
I know of no library that will do this for you.
You may be able to use the free pascal source to generate the control flow graph (its a common technique used in compilers to eliminate unreachable code).
Unfortunately, Delphi hasn't shipped with a complete formal definition(bnf grammar) of the language in its documentation since Delphi 6 I believe. (even then it wasn't completely accurate) So all third party parsers are shooting in the dark.


Q: Need to redirect to 403 if / is not supplied by included conf I should say that i'm very new to Nginx so i'm sorry if this is a stupid question.
In my Nginx configuration I use includes to determine wether or not I export a webpage.
If export the web page I do I want the http://hostname/ to redirect to http://hostname/ui/.
If not I would like to return 403 error code.
The code in my included ui.conf contains this location block:
location = / {
  return 302 " /ui";
}

I want to define default behaviour when this is not included but when I add a location / in my regular nginx.conf I get an error saying I can't define the same location twice.
what should I do?

A: So what ended up working is using
location = / {
}

in my ui.conf file
and
location / {
}

In my main conf file.


Q: PF 11.0.0: which mojarra versions are supported? PF 11.0.0: which mojarra versions are supported?
It is not specified in pom.xml. The showcase used to show the mojarra version, but not now.

A: Based on documentation PrimeFaces 11 has dependency JSF with ver. 2.0, 2.1, 2.2, 2.3, 3.0, 4.0. Where JSF can be Apache MyFaces or Eclipse (former Oracle) Mojarra.


Q: Add multiple users to multiple groups from one import csv I have a csv with 2 columns, one column is AD group names and one is user account names. I am trying to read the csv and import the users into their corresponding group.
Here is what i have to so far. It's saying both arguments(identity,member) are null, which makes no sense since the headers are correctly specified.
import-module activedirectory
$list = import-csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv"

Foreach($user in $list){
    add-adgroupmember -identity $_.Group -member $_.Accountname
}

Heres whats in the csv file
Group             Accountname
group1            user1
group1            user2
group1            user3
group2            user4
group2            user5
group3            user6
group3            user7
group3            user8
group4            user9
group5            user10

EDIT Command and error
Here is my script, error i receive and csv.
Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups.csv" |
ForEach { get-aduser $_.Accountname | add-adgroupmember $_.Group}

A: Change this:
add-adgroupmember -identity $_.Group -member $_.Accountname

To this:
add-adgroupmember -identity $user.Group -member (Get-ADUser $user.Accountname)

A: @EBGreen has answered what's wrong with your code. Just coming up with an alternative here. Instead of running the command once per member, you can try to add all members of a group at the same time. The Member parameter supports an array, so try this:
Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv" | Group-Object Group | % {
    #Foreach Group, get ADUser object for users and add members
    $users = $_.Group | % { Get-ADUser $_.Accountname }
    Add-ADGroupMember -Identity $_.Name -Member $users
}

EDIT I've sucessfully tested this on 2012 DC with following content in test.csv (values represent existing group name and existing samaccountname/username):
Group,Accountname
"Mytestgroup","kim_akers"
"Mytestgroup","user1"

EDIT2 It shouldn't have any problems with deeper level OUs. I tested with an OU that was 7 levels deep and it had no problem. If you have all the user inside one OU (or find the closest OU that contains all the sub-OUs), see if this script helps. Remember to replace DN for "base OU" in -Searchbase parameter.
Import-Csv "C:\Scripts\Import Bulk Users into bulk groups\bulkgroups3.csv" | Group-Object Group | % {
    #Foreach Group, get ADUser object for users and add members
    $users = $_.Group | % { Get-ADUser -Searchbase "OU=mybaseou,OU=test,OU=users,OU=contoso,DC=Contoso,DC=com" -Filter { samaccountname -eq $_.Accountname } }
    Add-ADGroupMember -Identity $_.Name -Member $users
}


Q: Switching language by Alt + Shift after update from Ubuntu 22.04 beta to release is not working Switching language settings made by Tweaks tool (gnome-tweak-tool) like described in accepted answer here.
After performing update to release version by
sudo apt update && sudo apt upgrade
language switching by Alt + Shift stopped working. How to fix it?
Related question: How to have Alt+Shift shortcut for language switching and be able to use other shortcuts that contain Alt+Shift combination keys?

A: *

*Use gnome-tweaks to set shortcut

*For Ubuntu 22.04: Open /etc/gdm3/custom.conf and uncomment "WaylandEnable=false" than save it and reboot. This step makes layout indication work. (and xdotool too...)

A: Look at https://bugs.launchpad.net/ubuntu/+source/gnome-control-center/+bug/1956916/comments/38
In short:
Use dconf editor, navigate to org.gnome.desktop.wm.keybindings.switch-input-source and set it to '<Alt>Shift_L'

A: Execute the following line by line in terminal on Ubuntu 22 LTS:
gsettings set org.gnome.desktop.wm.keybindings switch-input-source "['<Shift>Alt_L']"
gsettings set org.gnome.desktop.wm.keybindings switch-input-source-backward "['<Alt>Shift_L']"

Open Settings > Keyboard > Keyboard Shortcuts (View and Customise Shortcuts) > Typing to confirm changes.

Source: https://bugs.launchpad.net/ubuntu/+source/gnome-control-center/+bug/1956916/comments/38

A: Like in recommended setup:

*

*Launch Tweaks tool

*Go to Keyboard & Mouse section.

*Click on the Additional Layout Options. A new window should pop up.

*Look for Switching to another layout and expand it.

Here uncheck all checked options. Check Alt+Shift option again. Leave only one this option. Or only Ctrl+Shift if you prefer to use it.
After this Alt + Shift started working for me but in top right corner of the screen there was no information about corresponding switch - seems to bug introduced in Ubuntu 22.04. In Ubuntu 20.04 this function worked fine.
Win + Space also works normally (with updating of corresponding information about current language in top right corner) even if unchecked in Tweeks.


Q: Can't dissasemble function in Linux kdb I have kdb launched in my crashed Linux. And for some reason there is no id instruction in list of instructions (? command). So I can't disassemble any code.
But here is some cheat-sheet, where we can see the id command in common list.
So how could I disassemble any known function in Linux kernel with kdb?


Q: How to get a string variable in sql Postgresql Can someone help-me set up an SQL command that retrieves only the value of the first occurrence of "cost" in a string like the example below.
See below two results returned from a table where I store sql query execution plan. I use Postgres. The word cost always comes at the beginning, but it does not always come in the same position, so you can not simply do substring (...). I think you should find the initial and final position every time, to be able to extract only the cost value. If anyone can help me, the expected result for the example below is:
select (.... )
-----------------
cost=399301  (only this)

----------------------SAMPLE STRING SOURCE ------------------
Sort  (cost=399301.55..399301.57 rows=6 width=36)
  Sort Key: l_returnflag, l_linestatus
  ->  HashAggregate  (cost=399301.21..399301.48 rows=6 width=36)
        ->  Seq Scan on h_lineitem  (cost=0.00..250095.98 rows=5968209 width=36)
              Filter: (l_shipdate <= (to_date('1998/12/01'::text, 'YYYY/MM/DD'::text) - '10 days'::interval day))

-------------------- SECOND SAMPLE --------------------------------
Aggregate  (cost=7922058.70..7922058.71 rows=1 width=16)"
  ->  Hash Join  (cost=1899763.92..7922058.69 rows=1 width=16)"
        Hash Cond: (h_lineitem.l_partkey = h_part.p_partkey)"
        Join Filter: (((h_part.p_brand = 'Brand#13'::bpchar) AND (h_part.p_container = ANY ('{"SM CASE","SM BOX","SM PACK","SM PKG"}'::bpchar[])) AND (h_lineitem.l_quantity >= 4::double precision) AND (h_lineitem.l_quantity <= 14::double precision) AND (h_ (...)"
        ->  Seq Scan on h_lineitem  (cost=0.00..235156.84 rows=211094 width=32)"
              Filter: ((l_shipmode = ANY ('{AIR,"AIR REG"}'::bpchar[])) AND (l_shipinstruct = 'DELIVER IN PERSON'::bpchar))"
        ->  Hash  (cost=1183158.46..1183158.46 rows=35278997 width=33)
->  Seq Scan on h_part  (cost=0.00..1183158.46 rows=35278997 width=33) Filter: (p_size >= 1)"

Best Regards

A: Assuming the plans are stored in a table named plan_table in a column named execution_plan you can use the following:
select replace(substring(execution_plan from '\(cost=[0-9]+'), '(cost=', '')
from plan_table;

The substring(...) returns the first occurrence of (cost= and the replace is then used to remove that prefix.

A: I get successful and the solution, the obcjetive was get the value 27726324.41, the Expression Regular final developted is:
select substring('Aggregate (cost=27726324.40..27726324.41 Rows' from '[.]Y*([0-9]+.?[0-9]{2})')

RESULT 27726324.41
Thanks a_horse_with_no_name and anothers that help-me.


Q: maven assembly dir with a jar dependency from project I am trying to use maven to assemble a directory for a install package.  The install package requires several things: configuration files, dependency libraries and an executable jar of my class files.  I am having trouble figuring out how to add the executable jar.
Here is what I have so far:
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.myproject</groupId>
  <artifactId>myproject</artifactId>
  <version>8.1.1</version>
  <name>my project</name>
  <packaging>pom</packaging>
  <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>

        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.2-beta-2</version>
            <configuration>
                <descriptor>${basedir}/src/main/assembly/client.xml</descriptor>
            </configuration>
            <executions>
                <execution>
                    <id>create-client</id>
                    <configuration>
                        <descriptor>${basedir}/src/main/assembly/client.xml</descriptor>
                    </configuration>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
  </build>

  <dependencies>
      .
      .
      .
  </dependencies>
</project>

Then my assembly descriptor looks like this:
<assembly>
  <id>client</id>
  <formats>
    <format>dir</format>
  </formats>
  <includeBaseDirectory>false</includeBaseDirectory>

  <fileSets>
    <fileSet>
        <directory>${basedir}/src/main/reports</directory>
        <outputDirectory>/reports</outputDirectory>
    </fileSet>
    <fileSet>
        <directory>${basedir}/src/main/resources/audio</directory>
        <outputDirectory>/audio</outputDirectory>
    </fileSet>
    <fileSet>
        <directory>${basedir}/src/main/client</directory>
        <outputDirectory>/</outputDirectory>
    </fileSet>
  </fileSets>
  <dependencySets>
    <dependencySet>
        <scope>runtime</scope>
        <useProjectArtifact>false</useProjectArtifact>
        <outputDirectory>lib</outputDirectory>
        <unpack>false</unpack>
    </dependencySet>
  </dependencySets>
</assembly>

If i call mvn assembly:assembly I get a directory with all the libraries and configuration files.   Works great.
But now I want to add an executable jar of all my compiled code.  I can create this jar alone by adding this to my pom and calling mvn jar:jar
 <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <finalName>run</finalName>
                <archive>
                    <manifest>
                        <mainClass>com.myproject.main.StartProcess</mainClass>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

The question is, how can I get that jar into my assembly automatically?
I have tried a couple things but I have no idea where to start.  Can I somehow call the jar execution from my assembly?
Any help appreciated.

A: I think you should turn your useProjectArtifact to true (this is the default value).
It determines whether the artifact produced during the current project's build should be included in this dependency set.


Q: Why Index object is not shared across different pandas objects that are reindexed with it? As per pandas docs, Index objects can be shared between different series and dataframes.
So let's say I have the following:
df = pd.DataFrame(np.random.randn(5, 2), index=list("abcde"), columns=["x", "y"])

s = pd.Series(np.random.randn(5), index=list("abcde"))

It's also clearly stated that passing an Index object directly to reindex() is preferable to passing an array-like object, since it avoids duplicating data.
So I'm assuming that:
rs = s.reindex(df.index)

would use the same Index object for s as for df. However:
rs.index is df.index

is False, and I cannot understand why. Am I missing or misunderstanding something, or I'm reading an outdated section in docs?


Q: rpm build from src file I'm trying to build from a *.src.rpm file on FC 12 in such a way that the files are distributed a across my system as they would with a normal binary build (in this case, *.h files end up in /usr/include).  When I ran rpmbuild, the headers weren't present.  Here's my rpmbuild command:
[root@localhost sphirewalld]# rpm -ivv /home/dan/Downloads/gtest-1.3.0-2.20090601svn257.fc12.src.rpm
============== /home/dan/Downloads/gtest-1.3.0-2.20090601svn257.fc12.src.rpm
Expected size:       489395 = lead(96)+sigs(180)+pad(4)+data(489115)
  Actual size:       489395
loading keyring from pubkeys in /var/lib/rpm/pubkeys/*.key
couldn't find any keys in /var/lib/rpm/pubkeys/*.key
loading keyring from rpmdb
opening  db environment /var/lib/rpm/Packages cdb:mpool:joinenv
opening  db index       /var/lib/rpm/Packages rdonly mode=0x0
locked   db index       /var/lib/rpm/Packages
opening  db index       /var/lib/rpm/Name rdonly mode=0x0
 read h#     931 Header sanity check: OK
added key gpg-pubkey-57bbccba-4a6f97af to keyring
 read h#    1327 Header sanity check: OK
added key gpg-pubkey-7fac5991-4615767f to keyring
 read h#    1420 Header sanity check: OK
added key gpg-pubkey-16ca1a56-4a100959 to keyring
 read h#    1896 Header sanity check: OK
added key gpg-pubkey-a3a882c1-4a1009ef to keyring
Using legacy gpg-pubkey(s) from rpmdb
/home/dan/Downloads/gtest-1.3.0-2.20090601svn257.fc12.src.rpm: Header SHA1 digest: OK (3e98ed9b1631395d417e00f35c83ebe588ea9d3b)
     added source package [0]
found 1 source and 0 binary packages
Expected size:       489395 = lead(96)+sigs(180)+pad(4)+data(489115)
  Actual size:       489395
InstallSourcePackage at: psm.c:232: Header SHA1 digest: OK (3e98ed9b1631395d417e00f35c83ebe588ea9d3b)
gtest-1.3.0-2.20090601svn257.fc12
========== Directories not explicitly included in package:
         0 /root/rpmbuild/SOURCES/
         1 /root/rpmbuild/SPECS/
==========
warning: user mockbuild does not exist - using root
warning: group mockbuild does not exist - using root
fini      100664  1 (   0,   0)    478034 /root/rpmbuild/SOURCES/gtest-1.3.0.tar.bz2;4ba93ce1 unknown
warning: user mockbuild does not exist - using root
warning: group mockbuild does not exist - using root
fini      100644  1 (   0,   0)     30505 /root/rpmbuild/SOURCES/gtest-svnr257.patch;4ba93ce1 unknown
warning: user mockbuild does not exist - using root
warning: group mockbuild does not exist - using root
fini      100644  1 (   0,   0)      2732 /root/rpmbuild/SPECS/gtest.spec;4ba93ce1 unknown
GZDIO:      63 reads,   511788 total bytes in 0.005930 secs
closed   db index       /var/lib/rpm/Name
closed   db index       /var/lib/rpm/Packages
closed   db environment /var/lib/rpm/Packages

Thanks for your help.

A: I'm sorry I don't use Fedora so I can't be sure, but I see this has gone unanswered for some time. I do build extensive numbers of RPM's, but for a different distro (PLD).
Your output doesn't say much about what DID get generated. Are you sure a -devel subpackage did not get generated along with the main binary rpm? Did you look at the files inside the src.rpm package and make sure the files you're looking for are in there? Are there any flags for your rpmbuild script to say "include devel files" or something like that?

A: My answer is quite likely no longer relevant, but rpm -i(vv) can not be used to build a binary RPM package from a source RPM package. This requires the use of rpmbuild, e.g. rpmbuild --rebuild /<…>/gtest-1.3.0-2.20090601svn257.fc12.src.rpm. All that is actually happening with rpm -i(vv) for a source RPM package is that the content of the source RPM package is extracted into the rpmbuild directory structure, specifically /root/rpmbuild/{SOURCES,SPECS}/ in this case. To build this filled rpmbuild directory structure, cd /root/rpmbuild/SPECS/ followed by rpmbuild -ba gtest.spec could be used (which I would not recommend, because RPM packages should not be built as privileged user, because a mistake or a bug in the software and/or the spec file could damage your operating system when accidentially referring to a path outside of the build environment).


Q: Create large amount of user accounts in OS X Lion Server's Server App/Server Admin/Workgroup Manager I'm trying to managing iOS devices by OS X Lion Server on Mac Mini.
Now I need to create more than 100 user accounts in Server App. If there's any way to do this without creating each account one by one? Writing script?
http://manuals.info.apple.com/en_US/UserMgmt_v10.6.pdf
According to this document, the exported file of accounts is a XML file. But I find no where to create or edit this file in a efficient way.

A: If you are using Open Directory (which you probably should with that amount of users) one option is to use dscl which is probably a little easier to automate. There's a thread at Apple Discussions describing how to add users to a group.

A: Workgroup Manager (part of the Server Admin Tools package) can import tab-delimited text files with a little work.  When you do the import, you'll need to tell it the file's format -- what the record and field delimiters are (generally newline and tab), then what data each field contains.  See this video for an example of the process.
If you need to set attributes that aren't in the file, you can either select all of the imported accounts and set the attribute for all of them at once (the video shows doing this for the home directory location), or (if you think of it before doing the import) create a template account with the relevant settings, save it as a preset (there's a pop-up menu at the bottom of WGM's window), then select that preset in the import dialog box.

A: Try using Passenger http://macinmind.com/?area=app&app=passenger&pg=info
If you have more than 20 users you might want to buy it for $60 or do what I do and group them by 20 users and run it 5 times.