text:
Q: Oracle sql sum column and return other columns I have the following query where I need sum up the FTBR_QTY_FAILED by each day but also output the other columns. I have tried a few grouping options but I am unable to output the summed failed_qty for each day and the other column values.
Can anyone give me any direction/ideas on this:
<cfquery datasource="UKCHAPP145" name="Q4">
 SELECT
TBL_RESULTS.FTBR_QTY_FAILED AS TotalFailedQty,
    TBL_RESULTS.FTBR_TASK_UUID,
    TBL_RESULTS.FTBR_DATE,
    TBL_TASK.TASK_NAME,
TBL_RESULTS.FTBR_UUID
FROM
    UKCHAPP145.TBL_RESULTS,
    UKCHAPP145.TBL_TASK
WHERE
    TBL_TASK.TASK_UUID = TBL_RESULTS.FTBR_TASK_UUID
AND
    TBL_RESULTS.FTBR_TASK_UUID = '#URL.TASK_UUID#'
AND
to_char(TBL_RESULTS.FTBR_DATE, 'YYYY') = '#URL.YEAR#'
AND
TBL_RESULTS.FTBR_WEEK_NO = '#URL.WEEK_NUMBER#'
AND
TBL_RESULTS.FTBR_SHIFT IN (#ListQualify(URL.SHIFT,"'",",","ALL")#)
ORDER BY
    TBL_RESULTS.FTBR_DATE
ASC
</cfquery>

Here is some example data outputted by this query:
FTBR_DATE              FTBR_TASK_UUID  FTBR_UUID  TASK_NAME                   TOTALFAILEDQTY
---------------------  --------------  ---------  -------------------------   --------------
2015-03-09 00:00:00.0  19971           594052     LOW OR NO FLOW - 1BAR TEST  3
2015-03-10 00:00:00.0  19971           594916     LOW OR NO FLOW - 1BAR TEST  4
2015-03-11 00:00:00.0  19971           595828     LOW OR NO FLOW - 1BAR TEST  12
2015-03-11 00:00:00.0  19971           595843     LOW OR NO FLOW - 1BAR TEST  1
2015-03-12 00:00:00.0  19971           597209     LOW OR NO FLOW - 1BAR TEST  3
2015-03-12 00:00:00.0  19971           597195     LOW OR NO FLOW - 1BAR TEST  13
2015-03-13 00:00:00.0  19971           597859     LOW OR NO FLOW - 1BAR TEST  13

Many thanks
JC


text:
Q: session store does not store data So, I am developing REST APIs, I am using express, mongojs, connect-mongo. and I am not able to figure out how to store the data in session:
var express = require('express'),
mongojs = require("mongojs"),
MongoStore = require('connect-mongo')(express);
GLOBAL.db = mongojs.connect(databaseUrl, collections);
app.configure(function () {
        app.use(express.bodyParser());
        app.use(express.cookieParser());
        app.use(express.session({
            key: 'express.sid',
            secret: 'secret',
            maxAge: new Date(Date.now() + 3600000),
            store: new MongoStore({ db: databaseUrl, collection: 'sessions' })
        }));
        app.use(app.router);
        app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
     });

The user attempts to login using:
curl -X POST http://localhost:2048/auth  -d @./sampleData/authUser.json -H "Content-Type: application/json" --cookie myCookie.txt

When the user logs in successfully I do:
req.session.user = {}
req.session.user.id = currentUser._id.toString()
req.session.user.userame = currentUser.username
req.session.user.firstName = currentUser.firstName
req.session.user.lastName = currentUser.lastName
req.session.user.title = currentUser.title
req.session.user.location = currentUser.location
res.send(500)

But when I send the next request
 curl -X GET http://localhost:2048/projects --cookie myCookie.txt

The req.session do not have the user that I had asssigned. What am I doing wrong here?

A: Ok the issue was that I do not have the environment mentioned there. Changing line 5 it to:
app.configure('development', function () {

And it was all rainbows and butterflies after that.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is the momentum always conserved in elastic collision? As the title above, why is the momentum always conserved in elastic collision (no loss of kinetic energy)?
Does it related to the conservation of kinetic energy? If so, how do we prove that?
Further more, can elastic collision release some energy but still obey the conservation of kinetic energy?
If so, where does the energy released come from?
And what about the angular momentum?Why is it conserved?

A: Momentum is conserved in collisions whether they are elastic or inelastic.
Momentum is conserved in a collision regardless of whether KE is conserved.
An elastic collision is defined as one in which the total KE of the colliding bodies is conserved, so any collision that 'releases' energy is by definition not elastic.
There is no requirement for KE to be conserved- there is only a requirement for total energy to be conserved, so KE can be converted to other forms of energy.
Angular momentum is also conserved, regardless of whether collisions are elastic.
The conservation of momentum is a general law- it does not just apply to collisions. It follows from Newtons third law.

A: Momentum, energy and angular momentum are always conserved. In inelastic collisions macroscopic kinetic energy is not conserved.

A:
As the title above, why is the momentum always conserved in elastic collision (no loss of kinetic energy)?

If there are no external forces acting on a system then the momentum of the system is conserved.
Note that there is absolutely no mention of energy in this statement.
So the answer to your question

Does it related to the conservation of kinetic energy?

is, no.

Further more, can elastic collision release some energy but still obey the conservation of kinetic energy?

An elastic collision is one in which kinetic energy is conserved with no mention of any other forms of energy.

And what about the angular momentum? Why is it conserved?

Same sort of idea as for linear momentum but now one needs to have no external torques acting on the system.

A:
why is the momentum always conserved in elastic collision (no loss of kinetic energy)?

Momentum is always conserved. Both in elastic and non-elastic collisions.
Of all the possible collisions that are possible, some happen to conserve mechanical energy (kinetic and potential). We give those collisions a name and call them elastic.

Does it related to the conservation of kinetic energy? If so, how do we prove that?

Momentum conservation is a result of Newton's 3rd law and is not a consequence of energy conservation.

Further more, can elastic collision release some energy but still obey the conservation of kinetic energy?

Unclear what you mean here. In elastic collisions kinetic energy is converted into potential elastic energy, which then in turn is converted 100 % back into kinetic energy. If there were energy losses along the way, we wouldn't call the collision elastic.

A: Whether it is elastic or inelastic collision momentum will always conserved, despite of k. E is conserved or not, momentum conservation and k. E conservation of system are two different  things, momentum transfer can make a rest body accelerate where energy transfer can produce several affects like sound, velocity, heat, etc.

A: There are a couple mentions of Newton's 3rd law, but without any elaboration.
Consider a 1-dimensional collision between a tennis ball and a rigid box.  The tennis ball deforms, and eventually the objects are pushed apart.  Maybe the collision took 0.1 seconds.  At any instant during that 0.1 seconds there are equal but opposite forces (Newton's 3rd law).  And since the forces at any instant are equal but opposite, the integrals of the forces over that 0.1 seconds will be equal but opposite.  Those integrals have the same units as momentum.  So if one object has some amount j added to its momentum, the other object will have some amount -j added to its momentum, so the change in total momentum is +j-j=0.  So there is no change in total momentum.
Note:  You don't know what the force curve with respect to time looks like.  But you can figure out what the area under that curve (aka impulse) must be.
In high school physics, 1-dimensional elastic collisions are solved by considering conservation of energy and conservation of momentum.  This gives you two equations and two unknowns (the unknowns are the final velocities).  It typically looks like this:

*

*$\frac{1}{2}m_1v_1^2+\frac{1}{2}m_2v_2^2=\frac{1}{2}m_1(v_1')^2+\frac{1}{2}m_2(v_2')^2$

*$m_1v_1+m_2v_2=m_1(v_1')+m_2(v_2')$
Forget about these for a moment.  We will find the final velocities without using these equations.  We will come up with some new equations.
Consider that the two objects in your 1-dimensional elastic collision are the only two objects in space.  And rather than being a 3rd party observer, you are sitting on one of the objects.  You don't know how fast you are moving, from your perspective it looks like you are sitting still.  You will see the other object move toward you, hit you, then move away from you.  It must move away from you at the same speed it moved toward you.  It intuitively couldn't be any other way (I'll just leave it at "intuitive" instead of justifying further).  In other words, the relative velocities before and after the collision must be opposite.  And also the final velocities will be affected by equal but opposite impulses.  This gives you three equations and three unknowns:

*

*$v_1-v_2=-(v_1'-v_2')$

*$m_1v_1+j=m_1v_1'$

*$m_2v_2-j=m_2v_2'$
And you can solve for the final velocities.  Ultimately these equations are algebraically equivalent to the high school equations.  For example, if you start with the high school equations, and you rearrange the conservation of energy equation so that you can factor each side using the difference of squares, and then you divide each side by a quantity you get from rearranging the conservation of momentum equation, you will get the relative velocity equation.  If you want two equations and you want them to be short, then use the relative velocity equation and the conservation of momentum equation.
You didn't ask about conservation of energy in an elastic collision, but I think it's important to understand.  First you need to understand why the equation for kinetic energy is what it is.  Imagine a guy walks up 10 feet of stairs and drops a hammer.  Now imagine he walks up 20 feet of stairs and drops a hammer.  Twice as much work was applied to the second hammer.  But its final velocity at the ground is not twice as high.  But what matters is the work.  In an elastic collision, whatever work was done to get the objects moving, that work cannot just vanish or increase out of nowhere.  That work must be conserved.  In other words the energy is conserved.  I'm not a physicist, I'm just some guy, but hopefully this helps.


text:
Q: Whats the volume of parallelopiped with two of its sides eqal? If the volume of a parallelopiped of sides $\vec{a},\vec{b},\vec{c}$ is given by $$\det\begin{pmatrix}\vec{a} & \vec{b} &\vec{c}\end{pmatrix}$$
But if two of those vectors are equal then $\det\begin{pmatrix}\vec{a} & \vec{b} &\vec{c}\end{pmatrix}=0$.
Here how can the volume of a paralleopiped with two equal sides be 0?

A: Try drawing it. A vector is an object with a length and direction. If two vectors are equal, then they have equal length and more importantly for this problem, they have the same direction. If you draw two of the three sides on top of one another, you get a parallelogram. A parallelogram has no volume.


text:
Q: Как правильно определить скорость роста времени работы алгоритма? Вот, дают задание такое, к которому есть такая формула:

Вроде бы сказано, что нужно взять член с самой большой степенью, и тогда будет O(n^3), но! Если просто включить логику немного и подумать, то получается, что даже при n = 10.000, будет 10^9 - 10^10 - 10^6 + 3.
Едва ли это реальная функция сложности какого-либо алгоритма, но просто ради самой задачи. Ведь, пускай это будет сортировка, тогда массив длинной 10.000 элементов, это уже не мелочь. Даже если из 1.000.000 элементов, то получится 10^15 - 10^14 - 10^8 + 3, что тоже очень существенно.

A: Сложность алгоритма - теоретическая математическая концепция, и, будучи таковой, должна использоваться именно так - при N, стремящемся к бесконечности. Возьмите N=гугол и посмотрите. Мало - берите гугоплекс.
Важно найти такое N0 и С1 и С2, что для всех N>N0 выполнялось C1f(n) < T(n) < C2f(n).
Так что если даже я скажу, что для N0 = 10100 C1 = 1/10000, а C2 = 100000 - то этого вполне достаточно...
Не напоминайте того, гм... инженера, который доказывает, что все нечетные числа простые: 3, 5, 7... 9 - ну, погрешность эксперимента... 11, 13... Ну и хватит.
Вам в условии, кстати, никто и не говорит, что это количество операций или там время. Просто - есть такая функция, выразите ее в Θ-обозначениях.


text:
Q: Is it possible for two variables to point to the same piece of memory? Is it possible for two variables to point to the same piece of memory?
My professor wrote a short snippet of code where he created a second instantiation of a class and assigned it a previously created object and referred to this as two variables pointing to the same location/info in the memory, which left me pretty confused

A: There is no such thing as an object name in Java. Classes have names like java.util.ArrayList. But instances of ArrayList are objects that have no name. You make them when you run code like new ArrayList(). They will live in different memory locations that you remember with references. Those you give names.
ArrayList al1 = new ArrayList(); // Object 1 being constructed at some address
ArrayList al2 = new ArrayList(); // Object 2 being constructed somewhere else
ArrayList al3 = al2;             // No object is being constructed here

Here are 3 references.  al1 refers to object 1. al2 and al3 refer to object 2.  So you can have two references to the same object. But that object still only lives in one place, at one address.  And again those aren't the name of the object. Those are the names of the references that point to that object.
My favorite metaphor for this is: you can hand out as many business cards with your home address on them as you like but you still only have one house.  You can name each business card (reference). You can name the house blueprints (the class) but you can't name the actual house (object).
The only truly 1 to 1 identifier an object has is it's address which you never see in Java unless you write some crazy code like this.
Us mere mortals make do with using references, hashcodes, and Id fields to keep track of which object we have.  That only sounds complicated because it is.

A:
Can a single object in Java have two distinct names?

In Java, objects don't have names, they have references.
Variables of all sorts have names, but variables are distinct from objects.  Variables can reference objects.

Is it possible for two object names references to point to the same object (i.e. piece of memory) ?

Yes, two or more references, say from parameters and/or local variables and/or instance variables and/or static variables can all reference the same object.
This is what happens when you copy a variable that is an object type (by simple assignment, e.g. a = b;): the reference is copied, i.e. duplicated — while the object itself is unaffected by such an assignment (it is only affected by what you might do later with the reference).  By such an assignment the new variable, post assignment, refers to the same object, and the old variable's reference continues to remain valid.
This same kind of reference copy happens during parameter passing, which is just like assignment.
Of course, any (active) reference keeps the object from being garbage collected.
A valid reference is one that is still in scope or reachable by something that is still in scope.  When a function ends, all its local variables and parameters go out of scope, releasing any references those hold.


text:
Q: Noetherian Schemes Property Let $X$ be locally Noetherian Scheme, therefore for every $a \in X$ there exist an affine open set $U =\mathrm{Spec}(R)$ such that $R$ noetherian.
Why is then every $S_V:= \Gamma(V, \mathcal{O}_X)$ for each affine open $V$ noetherian?

A: I will reduce this into a statement of commutative algebra for you.
It is enough to prove: If $X=\operatorname{Spec}(A)$ is locally noetherian, then $A$ is noetherian. We may cover $X$ by open affines $\operatorname{Spec}(B)$ with $B$ noetherian. Such an affine open may be covered by principal open subsets $D(f)$, with $f\in A$, of $X$. If $\varphi\colon A\to B$ denotes the morphism of rings corresponding to the inclusion $i\colon \operatorname{Spec}(B)\subset \operatorname{Spec}(A)$, then $D(f)=i^{-1}(D(f))=D(\varphi(f))$, i.e. $B_{\varphi(f)}\cong A_f$, so that $A_f$ is noetherian. This shows that we may cover $X$ by $D(f_1),\ldots,D(f_n)$ with $A_{f_i}$ noetherian, in other words: We are given elements $f_1,\ldots,f_n\in A$ generating the unit ideal such that $A_{f_i}$ is noetherian for $i=1,\ldots,n$. Deduce from this that $A$ is noetherian.

A: Let $a\in X$ and $V$ be an open affine n'hood of $a$. Since $X$ is locally Noetherian, $V=Spec(R)$ for some Noetherian ring $R$ and $\Gamma(V,\mathcal{O}_{X})\cong R$ (since $V$ is affine) hence it is Noetherian.


text:
Q: How to reset current directory after closing powershell script I had batch script for running NPM which when simplified looks like this:
cd ./subfolder
call npm run dev

Then after launching it inside Powershell, NPM server was running. When I press Ctrl+C twice to close it, my current directory is left as it was, which is fine. However, later I needed more sophisticated tasks in the script and I changed it to Powershell script, which when simplified looks like this:
Set-Location ./subfolder
npm run dev

But now when I run it from Powershell and close, my working directory is left at "subfolder", which is really annoying!
Does anybody know how to solve it, so Powershell script behaves the same as batch file?
EDIT: I noticed, that opposite is true, if I call batch script from Command Prompt, then current directory is also kept at "subfolder".
EDIT2: I tried putting Set-Location .. in the end. The problem is that when I press Ctrl+C to close NPM (it is never-ending process), not only NPM is closed, but also powershell script, therefore last command is never reached.

A: As a improvement of the suggestion by DavidPostill,
you may use the PowerShell TRY/FINALLY commands to gracefully terminate
the script:
try
{
    pushd ./subfolder
    npm run dev
}
finally
{
    write-host "Ended work."
    popd
}

A: How do I restore the previous directory in a Powershell script?
Use pushd / Push-Location and popd / Pop-Location:
pushd ./subfolder
npm run dev
popd

Further Reading

*

*PowerShell commands - PowerShell - SS64.com

*PowerShell How-to guides and examples - PowerShell - SS64.com

*Pop-Location - PowerShell - SS64.com

*Push-Location - PowerShell - SS64.com
Source


text:
Q: an efficient way acess a range in a user defined type? I've got a user defined type with about 5000 entries. I would like to select a range of the data in about 1,000 entry blocks and use it as an array. Is there a way to do this without looping?
Something like
 MyArray = MyType(1:1000).property

rather than
 for i = 1 to 1000
     MyArray(i) = MyType(i).property
 Next i

Thanks!

A: No, there is no way to convert a collection of elements into an array without looping or special accessor methods for the type - let alone convert a common property from a collection of elements into an array.
The only objects that support anything like this are Range objects, for which you can convert certain properties of an array of cells (range) into an array using:
MyArray = Range("A1:A1000").Value

Again, nothing like this is available for other types unless the programmer goes through the trouble of defining the behaviour - and even if they did define it, odds are the method would likely include iterating over the elements anyways, just within the type class.


text:
Q: Configure REDIS in Gitlab CI/CD for usage in Django I had a working pipeline on GitLab which started failing after I added tests involving REDIS. I've applied (?) what is written inside GitLab docs but still REDIS is not discovered by my tests.
Here's my gitlab-cy.yml file:

pep8:
  image: python:latest
  services:
    - postgres:10-alpine
    - redis:latest
  variables:
    POSTGRES_DB: ci
    DATABASE_URL: "postgresql://postgres:postgres@postgres:5432/$POSTGRES_DB"
    REDIS_URL: redis
  stage: test
  script:
    - python -V
    - pip install -r ./requirements/gitlab.txt

    - pytest --pep8
  cache:
    paths:
    - ~/.cache/pip/

And here's how I'm using it inside Django:
REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379/0")
cache = redis.StrictRedis.from_url(url=REDIS_URL)
I've also set Environment Variables inside CI/CD settings in GitLab  REDIS_URL to redis however still when the test executes None gets assigned to host and the test fails ....-> self = Connection<host=None,port=6379,db=0>
Any idea how to connect with Redis on GitLab?

A: Finally figured it out, so I'm posting it here if you are also having this problem :)
I removed the REDIS_URL variable from gitlab-ci.yml and I have added the following variable in GitLab CI Environment variables settings:
REDIS_URL -> redis://redis:6379/0
which solved the problem :)


text:
Q: Nested grouping elements using XSLT I am in need to Group elements and apply a div element for those group. Also kindly note that element levels are optional and they should be grouped accordingly. The levels "prelims","part","chapter","levela","levelb" and "endmatter" should be grouped. Also note that if "levelc" exists then it should also be grouped
Input:
<toc>
<toc.entry level="prelims">Half Titlepage</toc.entry>
<toc.entry level="prelims">Titlepage</toc.entry>
<toc.entry level="prelims">Imprint</toc.entry>
<toc.entry level="part">Part 1. This is part title</toc.entry>
<toc.entry level="chapter">Chapter 1. This is chapter title</toc.entry>
<toc.entry level="author">This is author</toc.entry>
<toc.entry level="levela">This is level a head</toc.entry>
<toc.entry level="levelb">This is level b head</toc.entry>
<toc.entry level="levelb">This is level b head</toc.entry>
<toc.entry level="levelb">This is level b head</toc.entry>
<toc.entry level="chapter">Chapter 2. This is chapter title</toc.entry>
<toc.entry level="author">This is author</toc.entry>
<toc.entry level="levela">This is level a head</toc.entry>
<toc.entry level="chapter">Chapter 3. This is chapter title</toc.entry>
<toc.entry level="author">This is author</toc.entry>
<toc.entry level="levela">This is level a head</toc.entry>
<toc.entry level="part">Part 2. This is part title</toc.entry>
<toc.entry level="chapter">Chapter 4. This is chapter title</toc.entry>
<toc.entry level="author">This is author</toc.entry>
<toc.entry level="chapter">Chapter 5. This is chapter title</toc.entry>
<toc.entry level="author">This is author</toc.entry>
<toc.entry level="chapter">Chapter 6. This is chapter title</toc.entry>
<toc.entry level="author">This is author</toc.entry>
<toc.entry level="endmatter">References</toc.entry>
<toc.entry level="endmatter">Index</toc.entry>
</toc>

OUTPUT REQUIRED
<toc>

<toc.entry level="prelims">Half Titlepage</toc.entry>
<toc.entry level="prelims">Titlepage</toc.entry>
<toc.entry level="prelims">Imprint</toc.entry>

<toc.entry level="part">Part 1. This is part title</toc.entry>

<toc.entry level="chapter">Chapter 1. This is chapter title</toc.entry>
<toc.entry level="author">This is author</toc.entry>

<toc.entry level="levela">This is level a head</toc.entry>

<toc.entry level="levelb">This is level b head</toc.entry>
<toc.entry level="levelb">This is level b head</toc.entry>
<toc.entry level="levelb">This is level b head</toc.entry>

<toc.entry level="chapter">Chapter 2. This is chapter title</toc.entry>
<toc.entry level="author">This is author</toc.entry>

<toc.entry level="levela">This is level a head</toc.entry>

<toc.entry level="chapter">Chapter 3. This is chapter title</toc.entry>
<toc.entry level="author">This is author</toc.entry>

<toc.entry level="levela">This is level a head</toc.entry>

<toc.entry level="part">Part 2. This is part title</toc.entry>

<toc.entry level="chapter">Chapter 4. This is chapter title</toc.entry>
<toc.entry level="author">This is author</toc.entry>

<toc.entry level="chapter">Chapter 5. This is chapter title</toc.entry>
<toc.entry level="author">This is author</toc.entry>

<toc.entry level="chapter">Chapter 6. This is chapter title</toc.entry>
<toc.entry level="author">This is author</toc.entry>

<toc.entry level="endmatter">References</toc.entry>
<toc.entry level="endmatter">Index</toc.entry>

</toc>

XSLT TRIED
<?xml version='1.0'?>
<xsl:stylesheet version="2.0" xmlns="http://www.w3.org/1999/xhtml" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:RSUITE="http://www.reallysi.com" xmlns:m="http://www.w3.org/1998/Math/MathML" xmlns:epub="http://www.idpf.org/2007/ops" epub:prefix="index: http://www.index.com/" exclude-result-prefixes="RSUITE">
<xsl:import href="Entity.xsl"/>
<xsl:output method="xml" indent="no"/>

<xsl:template match="toc">
<toc><xsl:apply-templates select="toc.entry"/></toc>
</xsl:template>

<xsl:template match="toc.entry">
<xsl:choose>
<xsl:when test="@level='prelims'">
<xsl:for-each select="@level='prelims'"><xsl:apply-templates/></xsl:for-each>
</xsl:when>
<xsl:when test="@level='levela'"><xsl:for-each select="@level='levela'">
<xsl:apply-templates/>
</xsl:for-each></xsl:when>
</xsl:choose>
 </xsl:template>

</xsl:stylesheet>

A: Following XSLT
<?xml version='1.0'?>
<xsl:stylesheet version="2.0"  xmlns="http://www.w3.org/1999/xhtml"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:RSUITE="http://www.reallysi.com"
     xmlns:m="http://www.w3.org/1998/Math/MathML"
     xmlns:epub="http://www.idpf.org/2007/ops"
     epub:prefix="index: http://www.index.com/"
     exclude-result-prefixes="RSUITE epub m">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
  <xsl:template match="/">
    <toc>

        <xsl:apply-templates select="//toc.entry[@level='prelims']"/>

      <xsl:for-each select="//toc.entry[@level='part']">

          <xsl:apply-templates select="." mode="part">
            <xsl:with-param name="positionPart" select="position()"/>
          </xsl:apply-templates>

      </xsl:for-each>

        <xsl:apply-templates select="//toc.entry[@level='endmatter']"/>

    </toc>
  </xsl:template>
  <xsl:template match="toc.entry" mode="part">
  <xsl:param name="positionPart"/>
   <xsl:apply-templates select="."/>
   <xsl:for-each select="following-sibling::*[@level='chapter'
        and not(count(preceding-sibling::*[@level='part']) > $positionPart)]">
      <xsl:variable name="positionChapter" select="position()"/>

          <xsl:apply-templates select="." mode="chapter">
            <xsl:with-param name="positionPart" select="$positionPart"/>
            <xsl:with-param name="positionChapter" select="$positionChapter"/>
          </xsl:apply-templates>

   </xsl:for-each>
  </xsl:template>
  <xsl:template match="toc.entry" mode="chapter" >
  <xsl:param name="positionPart"/>
  <xsl:param name="positionChapter"/>
  <xsl:apply-templates select="."/>
  <xsl:apply-templates select="following-sibling::*[1][@level='author']"/>
    <xsl:for-each select="following-sibling::*[@level='levela'
      and not(count(preceding-sibling::*[@level='chapter']) > $positionChapter)]">

        <xsl:apply-templates select="."/>
        <xsl:if test="following-sibling::*[@level='levelb'
             and not(count(preceding-sibling::*[@level='chapter']) > $positionChapter)]">

            <xsl:for-each select="following-sibling::*[@level='levelb'
                 and not(count(preceding-sibling::*[@level='chapter']) > $positionChapter)]">
              <xsl:apply-templates select="."/>
            </xsl:for-each>

        </xsl:if>

    </xsl:for-each>
  </xsl:template>
  <xsl:template match="toc.entry">
    <toc.entry>
      <xsl:attribute name="level" select="@level"/>
      <xsl:value-of select="."/>
    </toc.entry>
  </xsl:template>
</xsl:stylesheet>

when applied to your input XML produces the output
<toc xmlns="http://www.w3.org/1999/xhtml">

  <toc.entry level="prelims">Half Titlepage</toc.entry>
  <toc.entry level="prelims">Titlepage</toc.entry>
  <toc.entry level="prelims">Imprint</toc.entry>

  <toc.entry level="part">Part 1. This is part title</toc.entry>

     <toc.entry level="chapter">Chapter 1. This is chapter title</toc.entry>
     <toc.entry level="author">This is author</toc.entry>

        <toc.entry level="levela">This is level a head</toc.entry>

           <toc.entry level="levelb">This is level b head</toc.entry>
           <toc.entry level="levelb">This is level b head</toc.entry>
           <toc.entry level="levelb">This is level b head</toc.entry>

     <toc.entry level="chapter">Chapter 2. This is chapter title</toc.entry>
     <toc.entry level="author">This is author</toc.entry>

        <toc.entry level="levela">This is level a head</toc.entry>

     <toc.entry level="chapter">Chapter 3. This is chapter title</toc.entry>
     <toc.entry level="author">This is author</toc.entry>

        <toc.entry level="levela">This is level a head</toc.entry>

  <toc.entry level="part">Part 2. This is part title</toc.entry>

     <toc.entry level="chapter">Chapter 4. This is chapter title</toc.entry>
     <toc.entry level="author">This is author</toc.entry>

     <toc.entry level="chapter">Chapter 5. This is chapter title</toc.entry>
     <toc.entry level="author">This is author</toc.entry>

     <toc.entry level="chapter">Chapter 6. This is chapter title</toc.entry>
     <toc.entry level="author">This is author</toc.entry>

   <toc.entry level="endmatter">References</toc.entry>
   <toc.entry level="endmatter">Index</toc.entry>

</toc>

I've kept the namespaces from your example XSLT, though they were not needed for the online XSLT processor I used (Saxon 9.5.1.6). In case it would be necessary to remove the xmlns-namespace from the toc root element in the output, it's possible to remove it from the stylesheet declaration.
Explanation: As the elements with the prelims and the endmatter level should be displayed at the beginning / the end of the XML, they are just applied in the main template matching the root in div containers with the appropriate class.
All part levels are applied to the template with the mode="part" and the position of the current part as parameter. To generate all chapters that belong to the current part, templates are only applied to all following sibling with the level chapter that do not have more preceding siblings with the level part as the current part element:
<xsl:for-each select="following-sibling::*[@level='chapter'
    and not(count(preceding-sibling::*[@level='part']) > $positionPart)]">
    ....

with the position of the current chapter as additional parameter.
The template mode="chapter" will only generate an author in case the next sibling of the chapter has the level author:
<xsl:apply-templates select="following-sibling::*[1][@level='author']"/>

To generate only the levela level elements that belong to the current chapter, only the levela elements are selected that don't have more preceding chapters as the current chapter:
<xsl:for-each select="following-sibling::*[@level='levela'
     and not(count(preceding-sibling::*[@level='chapter']) > $positionChapter)]">
     ...

Similar approach was taken for the levelb level elements.
As it's not clear if it's possible that chapters don't have levela elements, I've only added a check for levelb before writing the div container:
<xsl:if test="following-sibling::*[@level='levelb'
    and not(count(preceding-sibling::*[@level='chapter']) > $positionChapter)]">

    ...

I've left the part with possible levelc elements out - in case this kind of approach would work for you it shouldn't be too much of a problem to add it.
In addition I want to notice that the result depends on the XSLT processor you use - e.g. when switching to Saxon 6.5.5, above XSLT won't generate the values for the level attributes.
For convenience or further testings I saved above example here: http://xsltransform.net/eiZQaF7

A: If you want to group, why don't you use the proper grouping tool?
XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:template match="/toc">
    <toc>

            <xsl:copy-of select="toc.entry[@level='prelims']"/>

        <xsl:for-each-group select="toc.entry[not(@level='prelims' or @level='endmatter')]" group-starting-with="toc.entry[@level='part']">

                <xsl:copy-of select="current-group()[@level='part']"/>

                <xsl:for-each-group select="current-group()[not(@level='part')]" group-starting-with="toc.entry[@level='chapter']">

                        <xsl:copy-of select="current-group()[@level='chapter' or @level='author']"/>

                        <xsl:if test="current-group()[@level='levela']">

                                <xsl:copy-of select="current-group()[@level='levela']"/>

                                <xsl:if test="current-group()[@level='levelb']">

                                        <xsl:copy-of select="current-group()[@level='levelb']"/>

                                        <xsl:if test="current-group()[@level='levelc']">

                                                <xsl:copy-of select="current-group()[@level='levelc']"/>

                                        </xsl:if>

                                </xsl:if>

                        </xsl:if>

                </xsl:for-each-group>

        </xsl:for-each-group>

            <xsl:copy-of select="toc.entry[@level='endmatter']"/>

    </toc>
</xsl:template>

</xsl:stylesheet>


text:
Q: Capturing the max value in a data flow I'm just getting back into SSIS after several years of not using it. Here is what I need to do.
1) Read a value from a table and store into a variable
2) Create a data flow where I retrieve some number of rows
   having a value greater than the value retrieved in #1.
3) Store the rows retrieved in #2 into another table
4) Determine the maximum value of a particular column from the rows
   read in from step #2 and update the table referenced in #1.

The first three steps are easy, straightforward and working. However, I'm not certain the best way to accomplish #4.

A: Best can always be subjective but the most straight forward mechanism would be to add a Multicast component prior to your destination.
The Multicast will allow all the data flowing through the pipeline to show up in more than one stream. This is all done through pointers to the actual data buffers and doesn't result in physical copies of the data being strewn about.
From the Multicast, connect it to an Aggregate component and perform a MAX operation on whatever column you're using.
You know that you will only have one row coming from this aggregate so I'd use an OLE DB Command component to update your table #1. Something like
UPDATE ETLStatus
SET MaxValue = ?
WHERE PackageName = ?;

And then you'd map column names in like
MaxValue => Parameter_0
PackageName => Parameter_1


text:
Q: Exchange contacts do not appear in iCloud On my iPad and iPhone I have several email accounts: three Gmail and one Exchange account. I stopped using the Exchange account and tried to remove it from the iPhone, but also all my contacts were deleted. On the iPad the Exchange account is still configured and the contacts are still there.
Is there a way to transfer all contacts into iCloud and distribute it again on the iPhone (and my MacBook)?

A: From http://support.apple.com/kb/HT5058 :

Data stored with iCloud will not interact with your Microsoft
  Exchange data, while likewise your Exchange data will not interact
  with iCloud data.

A: Thought I'd share how I did this since I'm new to iPhones, iCloud.
I found other tutorials that involved iTunes and such but I didn't want the hassle.
Requirements are Gmail Account and a valid iCloud account (Apple ID)

*

*Go to your Google Contacts

*Click the More menu > Export

*Choose the group or all of your contacts you wish to export, whichever you prefer.

*Choose vCard format and click the Export button.

*You will now have a contacts.vcf which has been downloaded to your computer. Put it on your desktop if you prefer.

*Rename contacts.vcf to yournamehere.vcf (example: stephan.vcf)

*Log in to iCloud. www.icloud.com

*Click Contacts
Important Note: Make sure there are no contacts listed here before importing or this may not work. The page needs to be blank.

*Drag the .vcf file into the window under All Contacts.
The page will highlight with a blue rectangle when you drag the .vcf onto it. Wait a little bit. (It took about 8 seconds for mine to import. I only have 136 contacts though.)
On your iPhone, go to Settings > iCloud and make sure Contacts is listed as ON.
The only issue I had with this was the pictures of my contacts did not port over. Not a big deal I guess for how easy it was. Let me know if this helped.
Source: http://forums.macrumors.com/showthread.php?t=1253546

A: complicated...but I got it working...here it goes. You will need:

*

*Outlook 2010 on a PC

*A Gmail account

*An iCloud account.

To be able to import Outlook .vcf cards into iCloud, you will not be able to do it directly. You need to export from Outlook, then import to your Google account, then export out of the Google account in the *vCard format (for importing into Apple's Address Book or another application). There you will be able to get all your Outlook contacts, exactly as they are, into your iCloud account. There are some limitations, as Outlook does not let you export several vCards at the same time, and Google does not let you import several vCards at the same time.
Here are the instructions to get this rolling:

*

*On Outlook 2010, go to File>Options>Mail, and in the compose messages section select "Plain Text" from the dropdown box, then hit OK. This is very important, for the next step to work.

*Now go to contact, hit Command ⌘ + A (Ctrl ⌃ + A for Windows users) This will select all your contacts. Then, go up to the ribbon and on the "Share" section, where it reads "Forward Contact", click on the dropdown and select "As Business Cards" (if you don´t do step one, Outlook will crash attempting to create images of the vCards for each contact on an email message).

*If you did right, now you have a new email window opened, with all your vCards as attachment. Select all the Vcards and copy.

*Create a folder and save all the vCards in the folder.

*Time to merge all vCards into a single one, for them to be uploaded into your Gmail account, follow the instructions here.

*Once you managed to create one single .vcf files with all your contacts (don´t try to open it cause you will see nothing), go to your Gmail account and import them. To do that, on the left upper corner of the screen, 3rd row, you'll see the word "Gmail". Click the dropdown there and select Contacts. Moving along the same row, go to "More", click the dropdown and select "Import Contacts", then select the .vcf file and voilà, your contacts are now in Gmail.

*Now we will export the contacts. Select All contacts (if you have more than 100 contacts, you will need to do this in 3 or 4 pieces, selecting no more than 100 contacts to export) , then hit "More" and select "Export Contacts". Use the last option, *vCard format (for importing into Apple Address Book or another application).

This will give you a VCF files with all the contacts, in a format that iCloud will accept with no issues, then just sync your iOS device, and that is it.
Do not try to export a CSV file from Outlook to import into Gmail, because it will dump most of the contact info into notes instead of the fields. I hope it works for you all as it worked for me.

A: There will be no automatic syncing between Exchange and iCloud. You can manually import the contacts to iCloud. There are different ways to do this, depending on a lot of factors:
If you have Microsoft Outlook with access to the same Exchange account:

*

*Export all contacts as vcf (some hints here: Export Outlook )

*Import into iCloud by following second part of this (Macrumors )
If you don't have Microsoft Outlook, you can still export them from the iPad into a file, which you can import to iCloud using above link. Try this app (Export contacts) or see if you are able to sync it to your computer using iTunes (I'm however doubting that it would sync from the Exchange account for this purpose).

A: I don't have a google account, nor a windows computer with outlook.
I am running iOS 9, and my iPhone was linked to my work's Exchange server (2010 - version 14) with all my personal contacts.
I bought a new Macbook and wanted to link my iMessages on the Macbook to my phones contacts, but I didn't want to link my personal computer to my work's Exchange server.
So...these were the steps I took to move my contacts from Exchange to iCloud.
Log into the Exchange server's OWA web interface (Usually https://your.exchangeserver.com/owa )
Click on the Contacts on the left side.
On the right hand side should be your list of contacts. Select a bunch of them (I had to do it in 3 bunches because it complained when I selected too many). Right click and pick 'Forward as Attachment'. It attached all of them as individual attachments, 1 .vcf each. I sent the email to myself.
When I got all the emails, I saved all the attachments to a directory.
Now...on the phone, in the Settings App->Mail,Contacts,Calendars I went to my Exchange account and turned off Contact syncing. It told me it would delete all my Exchange contacts on the phone, and when I accepted, it did.
So, now I had no contacts.
On my MacBook, I logged into iCloud.com and clicked on 'Contacts'.
From the Finder as a test I dragged and dropped a single .vcf file into the 2nd pane from the left (where the list of contacts is). It imported fine.
But dragging and dropping more than 1 always gave me an import error (the error message was something like "bad data in field").
I didn't want to import 188 files, one at a time. I wanted to do them all at once. From reading on the Web, I suspected that iCloud could import more than 1 record per file, so I concatenated them all into 1 file.
To do so, I opened a terminal and changed directory to where I saved the .vcf files. Then I ran this:
cat *.vcf >> all_contacts.vcf

Then i dragged all_contacts.vcf into the iCloud.com contacts list pane, and it imported all 188 perfectly. Even the photos of my contacts.
On my phone, I went to Settings App->Mail,Contacts,Calendars then picked the iCloud account. I enabled syncing of Contacts, and they were all there.
Hope this helps.

A: There's a $0.99 app that can transfer your Exchange contacts to iCloud in a matter of seconds.  It's called "Contact Mover & Account Sync."  You can read about it at:
http://itunes.apple.com/us/app/contact-mover-account-sync/id582605968?mt=8

A: fwiw, you can set up your contacts on an apple device (iOS10 or above, and MacBook Pro Mojave, at least) to use your Microsoft Exchange account by opening the Contacts app on your iOS or MacBook Pro> Preferences> Accounts> Add account (exchange, yahoo, etc)> let it configure (ie not manual) > sign in to your source account (like ms exchange or yahoo, etc.) and if you deactivate the iCloud account in the Contacts > Accounts window, then you won't have duplicates.  this allows you to use the ms Exchange server across all of your devices and computers rather than iCloud. :)


text:
Q: Need advice as I am trying to use drag and drop grid as well as a bootstrap modal on asp.net I have a bootstrap modal on my form. I am using it as a static pop up to show extra information about some data. The data is from an asp.net gridview that the user selects. One of our grid requires user to make up their own sequence of how to show data (basically a sort) but it is stored in the db as a sequence number. After researching the best way to allow users to sequence I cam across drag and drop using jquery (bare in mind the modal also uses a different version of jquery). I have managed to implement this via the following way.
<script type="text/javascript" src="jquery/jquery.1.9.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.3.3.7.min.js"></script>
<link rel="stylesheet" href="styles/bootstrap.3.3.7.min.css" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>

    <script type="text/javascript">
        var $x = jQuery.noConflict();
       $x(function () {
            $x("[id*=gvCurrencies]").sortable({
                items: 'tr:not(tr:first-child)',
                cursor: 'pointer',
                axis: 'y',
                dropOnEmpty: false,
                start: function (e, ui) {
                    ui.item.addClass("selected");
                },
                stop: function (e, ui) {
                    ui.item.removeClass("selected");
                },
                receive: function (e, ui) {
                    $(this).find("tbody").append(ui.item);
                }
            });
        });
    </script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/smoothness/jquery-ui.css" />

Could someone please have a look and this and confirm it this is a preferred way of doing it. Basically i will download all the js/styles into my project however as I have never tried to reference multiple different versions of jquery files I am unsure if this is advisable. This does work, but last thing i want is for it to fall down after it is released.
Thanks

A: Whats with all the dislikes, anyway so after researching for a while it seems to be standard to apply a character so you can differentiate between the jquery files.


text:
Q: Password protecting a directory and all of it's subfolders using .htaccess I am trying to password protect a subdomain and all of it's subdirectories and files, but my knowledge on the matter is very limited, how can I go about doing that?

A: It's a simple two step process
In your .htaccess put
AuthType Basic
AuthName "restricted area"
AuthUserFile /path/to/the/directory/you/are/protecting/.htpasswd
require valid-user

use http://www.htaccesstools.com/htpasswd-generator/ or command line to generate password
and put it in the .htpasswd
Note 1: If you are using cPanel you should configure in the security section "Password Protect Directories"
EDIT: If this didn't work then propably you need to do a AllowOverride All to the directory of the .htaccess (or atleast to previous ones) in http.conf followed by a apache restart
<Directory /path/to/the/directory/of/htaccess>
      Options Indexes FollowSymLinks MultiViews
      AllowOverride All
</Directory>

A: You need to generate a password (username+password) string for authentication, write it to a file and place it inside the subdirectory you want to restrict access.
String looks like,
username:hashkey

*

*You can use HTTP password generator tool to do this.

*Copy and paste the string you obtained from the above site to a new file (.htpasswd) anywhere outside your site's webroot (better to keep anywhere inside home directory of the user).

*Add following lines in your .htaccess file.

AuthType Basic
AuthName "Require Authentication"
AuthUserFile [PATH_TO_FILE]/.htpasswd
Require valid-user

*

*If the password is not triggering, check the permission of .htaccess file.

*If authentication fails, check the existence of .htpasswd file in the specified location. (Make sure your user account has enough privileges on .htpasswd file to read)

*You do not need to restart the server to achieve this.
Please let me know if you have any queries.

A: To password protect a directory served by Apache, you need a .htaccess file in the directory you want to protect and a .htpasswd file that can be anywhere on your system that the Apache user can access (but put it somewhere sensible and private). You most likely do not want to put .htpasswd in the same folder as .htaccess.
The .htaccess file may already exist. If not, create it. Then insert:
AuthType Basic
AuthName "Your authorization required message."
AuthUserFile /path/to/.htpasswd
require valid-user

Then create a .htpasswd file using whatever username and password you want. The password should be encrypted. If you are on a Linux server, you can use the htpasswd command which will encrypt the password for you. Here is how that command can be used for this:
htpasswd -b /path/to/password/file username password

A: Just extend Mahesh's answer.
.htaccess
AuthType Basic
AuthName "restricted area"
AuthUserFile /path/to/the/directory/you/are/protecting/.htpasswd
require valid-user

If you don't want to use online password generator, you could use htpasswd or openssl:
1. Using htpasswd
htpasswd -c /path/to/the/directory/you/are/protecting/.htpasswd my_username
# then enter a password
# -c means Create a new file

2. Using openssl
openssl passwd -apr1 your_password

Then put the generated password to .htpasswd with format:
username:<generated_password>

Example:
.htpasswd
my_username:$apr1$ydbofBYx$6Zwbml/Poyb61IrWt6cxu0

A: You'd probably want to use the mod_auth_digest module. Apache has provided a very nice guide to using the full range of authentication and authorization modules.

A: To create a proper password, you may create a php file and run it locally (on your computer, not on the webserver) with the following content:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form method="post" accept-charset="utf-8">
    <input type="text" name="clear"/>
    <input type="submit" name="submit" value="generate" />
</form>

<?php
header("Content-Type: text/html; charset=utf-8");

if (isset($_POST['clear']) && $_POST['clear'] != '') {
    $cl = $_POST['clear'];
    $pw = crypt($cl, base64_encode($cl));
    echo $pw;
}
?>
</body>
</html>

I usually put my .htpasswd file in a directory called /htpasswd/ outside of the webcontent directory, like AuthUserFile /home/www/usr122/files/htpasswd/.sportsbar_reports_htpasswd (and not in the webcontent folder /home/www/usr122/html/htpasswd/) and rename .htpasswd file to what it is for, e.g. .sportsbar_reports_htpasswd
The password file itself should look like
testusername:dGATwCk0tMgfM

where the username is testusername and the password is testuserpassword


text:
Q: Boost.Log: How to forward a loging source I am trying to figure out, what the best way is to use a logging source within a class. The straight forward solution, simply to define it as a member (stack) variable has the big drawback, that I have to include Boost.Log header files, which really slows down the compilation.
I'd like to use a  severity channel logger. So my first approach was to define a new type, e.g.:
#include <boost/log/sources/severity_channel_logger.hpp>

typedef boost::log::sources::severity_channel_logger_mt<SeverityLogLevel, std::string> DefaultLogger;

This approach only simplifies defining a logger, but I still need to include the header file.
My next idea was to create a new class, which subtypes the logger and then using a forward declaration of this class:
// MyLogger.h
class MyLogger : public boost::log::sources::severity_channel_logger_mt<SeverityLogLevel, std::string>
{
  public:
    MyLogger(const std::string& name);
};

// MyLoggingClient.h
include <memory>

class MyLogger;

class MyLoggingClient
{
  // Actual implementation

  private:
    std::unique_ptr<MyLogger> lg;

};

But doing this, the compiler complains that MyLogger does not define the binary "[" operator or a conversion to a type acceptable to the predefined operator.
So, my question is, what is a good way of simply forwarding the definition of logger?
(I am refactoring the logging of existing code, so using the PIMPL or similar pattern, would result in a lot of extra effort.)
Thanks,
- Lars

A: I think you've already showed the best way to forward-declare a logger, although I would suggest to store Boost.Log logger as a member of MyLogger instead of deriving from it. Boost.Log loggers are designed using CRTP, so deriving from it may result in unexpected behavior.
The compiler error you're getting is probably caused by some part of your code which was not updated to account for the change you made - that lg is no longer a logger but a pointer.
PIMPL is another way to achieve what you want, and I think it actually might be easier than using a pointer. What you need is to implement a wrapper for the logger that implements an interface similar to Boost.Log loggers you use. For instance, for severity_channel_logger_mt this might suffice:
// MyLogger.h
#include <string>
#include <boost/log/core/record.hpp>
#include <boost/log/keywords/severity.hpp>
#include <boost/log/keywords/channel.hpp>

enum SeverityLogLevel { ... };

class MyLogger
{
private:
    struct Impl;
    Impl* impl;

public:
    MyLogger();
    MyLogger(MyLogger const&);
    MyLogger(MyLogger&& that) noexcept : impl(that.impl) { that.impl = nullptr; }
    ~MyLogger();

    MyLogger& operator= (MyLogger const&);
    MyLogger& operator= (MyLogger&& that) noexcept
    {
        MyLogger copy(static_cast< MyLogger&& >(that)); // you can use use std::move here and include <utility>
        this->swap(copy);
        return *this;
    }

    boost::log::record open_record();
    boost::log::record open_record(SeverityLogLevel sev, std::string const& chan);
    template< typename Args >
    boost::log::record open_record(Args const& args)
    {
        return open_record(args[boost::log::keywords::severity], args[boost::log::keywords::channel]);
    }

    void push_record(boost::log::record&& rec);

    void swap(MyLogger& that) noexcept
    {
        Impl* p = impl;
        impl = that.impl;
        that.impl = p;
    }
};

// MyLogger.cpp
#include "MyLogger.h"
#include <utility>
#include <boost/log/sources/severity_channel_logger.hpp>

typedef boost::log::sources::severity_channel_logger_mt<
    SeverityLogLevel,
    std::string
> DefaultLogger;

struct MyLogger::Impl
{
    DefaultLogger lg;
};

MyLogger::MyLogger() : impl(new Impl())
{
}

MyLogger::MyLogger(MyLogger const& that) : impl(new Impl(*that.impl))
{
}

MyLogger::~MyLogger()
{
   delete impl;
}

MyLogger& MyLogger::operator= (MyLogger const& that)
{
    MyLogger(that).swap(*this);
    return *this;
}

boost::log::record MyLogger::open_record()
{
    return impl->lg.open_record();
}

boost::log::record MyLogger::open_record(SeverityLogLevel sev, std::string const& chan)
{
    return impl->lg.open_record((boost::log::keywords::severity = sev, boost::log::keywords::channel = chan));
}

void MyLogger::push_record(boost::log::record&& rec)
{
    impl->lg.push_record(std::move(rec));
}

You should be able to use Boost.Log macros with this wrapper as is. You still have to include a few headers in MyLogger.h but hopefully this will be an improvement significant enough for you. It can be improved further if you remove support for keywords (the Boost.Log includes and the templated open_record overload) but then you will have to define and use your own logging macros throughout the code.
If you use other logging features, such as attributes, you may need to add more forwarding functions to the wrapper. See Reference for signatures of logger functions.


text:
Q: I want to output numbers 1-10 using JavaScript but when I click start it literally doesn't do anything Literally just want my webpage to output numbers 1-10 in a loop. What am I doing wrong guys

  <title>JavaScript Example</title>

  <button onclick="start()">start</button>

Javascript Test Page


text: Q: How to create Web pages with paragraphs and images in sharepoint using REST API? i'm trying to create a webpage in my sharepoint site. Can someone please help me to create webpage containing paragraph and images using REST APIs.


text:
Q: Setup Azure DevOps Notifications for commits/changes to specific branch I want to be notified by email each time new commits are made to the master branch on our project.
Found this and know to do what it says under the 'Add a custom subscription' heading...
However the example given is different to what i want, so I'm not sure what to put into the mandatory 'filter criteria' section to get an email each time a commit is pushed, by anyone, to a specific branch...could go by trial and error with the options that sound plausible but wondering, has anyone done this / what's the best way to do it?

A:
I want to be notified by email each time new commits are made to the master branch on our project.

As is shown in your screenshot, A commit is pushed subscription could meet your requirements.
In filter criteria, you could try to add the filter Branches updated contains master
For example:

In this case, when a commit is pushed to the master branch(Affect all repos), it will send notification emails.


text:
Q: JNI -- C implementation with boolean values This is a two part question. My first question relates to boolean values in the C portion of a JNI implementation. Since C doesn't have a boolean type, I am confused about how to do this. I have a Java object that looks like this:
public class JNIResult {

    private boolean successful;
    private String data;

    public JNIResult(boolean successful, String data) {
        this.successful = successful;
        this.data = data;
    }
}

On the C side, I want to create a new JNIResult object. I have gotten the constructor method ID, and now I am calling (*env)->NewObject(). Let's say, for instance, that I want to create this object:
JNIResult(true, null);

How would I do that in C? I know that it would be something like this:
jobject JNIResult = (*env)->NewObject(env, JNIResultClass, JNIResultConstructor, true, NULL);

but the boolean thing is confusing me.
Secondly, stemming from that question, when supplying parameters to a native Java method in C, whether it's a constructor or another method, what should the type be for those values? For instance, if I am calling a Java square root function that takes a double value as an argument, on the C side should I supply a jdouble or a double value to the function?

A: C normally uses the integer value 0 for "false" and 1 for "true". That way, the if statement will return the appropriate value.
This is explained in Using boolean values in C and the link is to the selected answer.
typedef enum { false, true } bool;

When I called a Java funtion from C, I had to create an intermediate JAVA function in order to make the appropriate changes and then use the intermediate Java function to call the java function.
Thus, instead of C calling JNIResult directly, hav it call an intermediate function in Java which will contain
boolean jbool;
typedef enum (myfalse, mytrue) mybool;

mybool cbool;
if (cbool == mytrue)
  {
    jbool = true;
  }
else
  {
    jbool = false;
  }

Now create your JNIResult object (in Java), make whatever changes need to be made before returning to C. You can use similar methods for any other situations when calling from one language to another.
@adelphus points out that JNI does the equivalent of what I show above within the JNI processing.

In JNI, Java boolean values are mapped to jboolean (which is an
  unsigned char) - just inlclude jni.h and pass JNI_TRUE or JNI_FALSE. –
  adelphus Jul 30 at 17:39


text:
Q: Is it possible to check for the Visual C++ runtime at startup of an MFC application? When an MFC application starts, is it possible to check for the Visual C++ runtime before the "application configuration" error is displayed?
I assume it must be done via pure Win32 API at some point before the CRT loads.

A: The error is coming from the operating system, before your program is even finished loading. There is no part of the program, not even initialization, which has run yet. Thus no way your program can eliminate the error message by itself.
Edit: You might be able to set the runtime DLL as a delay-loaded DLL to get your program loaded in the absence of the runtime. Then you'd have to substitute your own function for the .exe entry point and have it check for the existence of the runtime library. There are many technical difficulties associated with this approach, and I'm not even sure it would work at all - but it might be possible.

A: Well, you get that error because you're missing the redistributables. So instead of trying something like that, you should rather install the VC++ redistributables from Microsoft (as prerequisite for your application). I used to keep a list of the downloads here.


text:
Q: Find command path variable find not recognising spaces Im trying to iteratively compose a directory exclusion list for Find.
I construct the exclusion path through iterating through a text file. This is all working however Ive come across a stumbling block when it comes to paths with spaces in them. If I pass a path in with spaces Find doesn't recognise them. Despite the path being within speech marks
This demonstrates:
####
line="Documents/Microsoft User Data"
excludehead="-not ( -path "
excludetail=" -prune )"
excludefolder="$HOME/$line"

###
base_list=$(printf %s "$excludehead" "\"$excludefolder\""  "$excludetail" )
find  $HOME  $base_list  -name "*[<>:/|?#%\\\\*]*"

This results in:
find: User": unknown primary or operator

A: This is where you must use a shell array:
find_opts=( -not "(" -path "$HOME/$line" -prune ")" )
find "$HOME" "${find_opts[@]}" -name ...

You can see what the array contains:
$ declare -p find_opts
declare -a find_opts='([0]="-not" [1]="(" [2]="-path" [3]="/home/jackman/Documents/Microsoft User Data" [4]="-prune" [5]=")")'

Note that element #3 contains a string with spaces.

A: Define a function instead of trying to construct a command line dynamically.
find_with_exclude () {
  find "$HOME" -not \( -path "$HOME/$1" -prune \) -name "*[<>:/|?#%\\\\*]*"
}

find_with_exclude "Documents/Microsoft User Data"


text:
Q: ECDH with P-256 generating shared secret using static keys bouncy castle c# I am trying to create a shared secret using the ECDH-P-256 algorithm using the bouncy castle (c#) API.  I need to use 2 static keys to generate this.  These will then get hashed with some other (varying) data to produce a new key.
Does anyone know how to perform ECDH by using the C# API? I have been looking for a while and can only find code that uses Java.

A: I hope you have found something to proceed.
For others landing here, please take a look at my answer here https://stackoverflow.com/a/31419559/190476 (to my own question). I've explained one variant of Key-derivation using ECDH and as per NIST SP 800-56A, section 5.8.1 together with the BouncyCastle C# API


text:
Q: Google Authentication in single page application returns invalid_request when running on azure compute emulator I have recently created a new Azure web role for a cloud service using the ASP.NET MVC5 Single Page Application template and also configured it to allow Google to be used for auth.  When I deploy the service to Azure everything works as expected and I can successfully authenticate with Google.
However, when I'm trying to develop on my local machine, I just get an invalid_request response from Google whenever I try to authenticate.  I've narrowed this down to the fact that Google doesn't consider a return URL of 127.0.0.1:81 to be valid.  Is there any way around this?

A: Not really an answer to your question but I ran into exact same issue in my application as well though mine is an MVC 5 Application. In my case, the problem is caused by Windows Azure Caching Session State Provider. If I have the following lines of code in my web.config file, the authentication simply does not work.
<sessionState mode="Custom" customProvider="AFCacheSessionStateProvider">
  <providers>
    <add name="AFCacheSessionStateProvider" type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" applicationName="AFCacheSessionState"/>
  </providers>
</sessionState>

The moment I comment the above XML, everything works great. Not sure why this is happening but I thought I would share my findings with you.
Please see if this is not the case with you.


text:
Q: Connecting to the internet using Concept N I can't connect to the internet using Concept N. I am using jquery with a simple $.get, but it is just not working. Can someone help me with this?

A: You actually need to use the da.getXHr() function to access external web services. Here is an example of how to access rss data using jquery. First thing to do is download jquery and include it in your index.html file:
    <script type="text/javascript" src="app/jquery.min.js"></script>

Now use this code snippet to access a rss url with jquery. Be sure to replace the line "** Enter-rss-2.0-url-here **" with your own rss url
/*
 * Copyright 2016 Sony Corporation
 */
var title;
var description;
/**
 * The callback to prepare a segment for play.
 * @param  {string} trigger The trigger type of a segment.
 * @param  {object} args    The input arguments.
 */
da.segment.onpreprocess = function (trigger, args) {
    console.log('onpreprocess', { trigger: trigger, args: args });
    //da.startSegment(null, null);
    $.ajax({
        url:"** Enter-rss-2.0-url-here **",
        type: "GET",
        dataType: 'xml',
        xhr: function () { return da.getXhr(); },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('ajax error jqXHR.status[' + jqXHR.status + ']');
            def.reject("failed with error "+jqXHR.status);
            return;
        },
        success: function (data, textStatus, jqXHR) {
            $(data).find("item:first").each(function() {
                title = $(this).find("title").text();
                description = $(this).find("description").text()
            })
            da.startSegment(null, null)
        }
    })
};

/**
 * The callback to start a segment.
 * @param  {string} trigger The trigger type of a segment.
 * @param  {object} args    The input arguments.
 */
da.segment.onstart = function (trigger, args) {
    console.log('onstart', { trigger: trigger, args: args });
    var synthesis = da.SpeechSynthesis.getInstance();
    synthesis.speak("Title "+title+", Content "+description, {
        onstart: function () {
            console.log('speak start');
        },
        onend: function () {
            console.log('speak onend');
            da.stopSegment();
        },
        onerror: function (error) {
            console.log('speak cancel: ' + error.messsage);
            da.stopSegment();
        }
    });
};


text:
Q: Estou tentando enviar uma imagem junto a notificação via php! Estou tentando enviar uma imagem junto a notificação via php, a notificação é enviada normalmente, mas a imagem não vai. Podem me dizer o que está de errado nesse código?
<?php

if (isset($_POST['titulo'])) {

    move_uploaded_file($_FILES['Imagem']['tmp_name'], 'Imagens/' . $_FILES['Imagem']['name']);

    function sendMessage()
    {
        $content = array(
            "en" => $_POST['mensagem']
        );

        $imagem = $_FILES['Imagem'];
        $headings = array("en" => $_POST['titulo']);
        $fields = array(
            'app_id' => "2ac0abda-15ae-4d27-aa5b-da8400941d97",
            'included_segments' => array('All'),
            'contents' => $content,
            'headings' => $headings,
            //'small_icon'
            'large_icon' => 'https://www.iconexperience.com/_img/v_collection_png/64x64/shadow/ok.png', //  Ok
            'big_picture' => $imagem, //  Ok
            // 'android_led_color' => "FF0000FF",
            //'notification[android_accent_color]' => "FF0000FF",

        );

        $fields = json_encode($fields);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
            'Authorization: Basic M2I5MDEzYTItN2VkYS00YTVhLWE0OWMtMzY3MzNkOTU3NWQ3'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        $response = curl_exec($ch);
        curl_close($ch);

        return $response;

    }

    $response = sendMessage();
    $return["allresponses"] = $response;
    $return = json_encode($return);

}


text:
Q: It costs nothing to say Suppose a group of researchers claimed that they were working on 7G technology, and someone said, "It costs nothing to say you're working on something so advanced. What could "cost" mean here?
I'm considering which of the two senses given by Merriam-Webster is relevant:

a. to cause (someone) to lose something
b. to cause (someone) to experience something unpleasant

I'd appreciate your help.

A: Neither. It's talking about cost in the sense of money or effort.


text: Q: One Minecraft Skin will not load I recently created a new Minecraft skin on minecraftskins.com, and every time I load the skin in Minecraft, it is always the Alex skin. I know it is not something to do with 1.17 because I have loaded another skin in the same version and it works, but for some reason the one skin will not load.


text:
Q: Java beginner: convert an image to a binary array this is what I've gone so far and I can't seem to go further because I don't understand bitwise operations on the RGB
// Read from a file
File file = new File("src/a.gif");
image = ImageO.read(file);
int[] rgbarr = image.getRGB(0, 0, 13, 15, null, 0, 13);// image is 13*15
System.out.println(rgbarr.length);
for (int i : rgbarr)
    {
        System.out.println(i);
    }

Output: was values such as -16777216 and -1 Because I've already made an image black and white just to ease my understanding

But in our case here let's suppose it would be just random image , how do I get from normal RGB image to binary values (0 or 1) for each pixel.

A: I'm betting that each int in the array is a packed ARGB value;
boolean [] output = new boolean[rgbarr.length];
for ( int i=0; i<rgbarr.length; ++i ) {
  int a = (rgbarr[i] >> 24 ) & 0x0FF;
  int r = (rgbarr[i] >> 16 ) & 0x0FF;
  int g = (rgbarr[i] >> 8  ) & 0x0FF;
  int b = (rgbarr[i]       ) & 0x0FF;
  output[i] = (0.30*r + 0.59*g + 0.11*b) > 127;
}

The output equation I choose was taken from a definition of Luminance from wikipedia. You can change the scales so long as the coefficients add up to 1.

A: You can do some thing like this,
BufferedImage img = (BufferedImage) image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img , "jpg", baos);
byte[] previewByte = baos.toByteArray();

Hope this helps!!

A: You already have RGB values in the int[], that is color of each pixel. You could compare this to a specific background color, like black, to get a 1-bit pixel value. Then maybe set a bit in another appropriately sized byte[] array...


text:
Q: Springboot yaml properties as map is not working I am using Spring boot 1.5.9. I can not get this simple configuration class to work. What am I missing here?
yaml file:
lala:
  jobs:
    foo1: bar
    foo2: bar
  foo: lala

Configuration class:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.HashMap;
import java.util.Map;

@Configuration
@ConfigurationProperties(prefix = "lala", ignoreUnknownFields = false)
@PropertySource("classpath:jobs.yml")
public class Jobs {
    private Map<String, String> jobs = new HashMap<>();
    private String foo;

    public Map<String, String> getJobs() {
        return jobs;
    }

    public void setJobs(Map<String, String> jobs) {
        this.jobs = jobs;
    }

    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }

    @Override
    public String toString() {
        return "Jobs{" +
                "jobs=" + jobs +
                ", foo='" + foo + '\'' +
                '}';
    }
}

I keep getting: Jobs{jobs={}, foo='null'}

A: You can't load YAML the way you're doing it now.

YAML files can't be loaded via the @PropertySource annotation. So in the case that you need to load values that way, you need to use a properties file.

The main alternative is to use an application.yml file instead of a dedicated jobs.yml file.  If you must have separation, then your only option is to use a properties file.


text:
Q: Grouping by rolling date interval in Netezza I have a table in Netezza that looks like this
Date         Stock    Return
2015-01-01   A        xxx
2015-01-02   A        xxx
2015-01-03   A        0
2015-01-04   A        0
2015-01-05   A        xxx
2015-01-06   A        xxx
2015-01-07   A        xxx
2015-01-08   A        xxx
2015-01-09   A        xxx
2015-01-10   A        0
2015-01-11   A        0
2015-01-12   A        xxx
2015-01-13   A        xxx
2015-01-14   A        xxx
2015-01-15   A        xxx
2015-01-16   A        xxx
2015-01-17   A        0
2015-01-18   A        0
2015-01-19   A        xxx
2015-01-20   A        xxx

The data represents stock returns for various stocks and dates. what I need to do is group the data by a given interval, and day of that interval. Another difficulty is that weekends the (0s) will have to be discounted (ignoring public holidays). And the start date of the first interval should be an arbitrary date.
For example my out put should look sth like this
Interval    Q01    Q02    Q03    Q04    Q05
1           xxx    xxx    xxx    xxx    xxx
2           xxx    xxx    xxx    xxx    xxx
3           xxx    xxx    xxx    xxx    xxx
4           xxx    xxx    xxx    xxx    xxx

This output would represent an interval of the length 5 working days, with averaged returns as results, in terms of the raw data from above,
start date 1st Jan, 1st Interval includes 1/2/5/6/7 (3 and 4 are weekends and are ignored) Q01 would be the 1st, Q02 the 2nd, Q03 the 5th  etc. The second interval goes from 8/9/12/13/14.
What I tried unsuccessfully is using
CEIL(CAST(EXTRACT(DOY FROM DATE) AS FLOAT) / CAST (10 AS FLOAT)) AS interval
EXTRACT(DAY FROM DATE) % 10 AS DAYinInterval

I also tried playing around with rolling counters and for variable starting dates setting my DOY to zero with s.th like this
CEIL(CAST(EXTRACT(DOY FROM DATE) - EXTRACT(DOY FROM 'start-date' AS FLOAT) / CAST (10 AS FLOAT)) AS Interval

The one thing that came closest to what I would expect is this
    SUM(Number) OVER(PARTITION BY STOCK ORDER BY DATE ASC rows 10 preceding) AS Counter
Unfortunately it goes from 1 to 10 followed by 11s where it should start from 1 to 10 again.
I would love to see how this can get implemented in an elegant way. thanks

A: I'm not entirely sure I understand the question, but I think I might, so I'm going to take a swing at this with some windowed aggregates and subqueries.
Here's the sample data, plugging in some random non-zero data for weekdays.
    DATE    | STOCK | RETURN
------------+-------+--------
 2015-01-01 | A     |     16
 2015-01-02 | A     |     80
 2015-01-03 | A     |      0
 2015-01-04 | A     |      0
 2015-01-05 | A     |     60
 2015-01-06 | A     |     25
 2015-01-07 | A     |     12
 2015-01-08 | A     |      1
 2015-01-09 | A     |     81
 2015-01-10 | A     |      0
 2015-01-11 | A     |      0
 2015-01-12 | A     |     35
 2015-01-13 | A     |     20
 2015-01-14 | A     |     69
 2015-01-15 | A     |     72
 2015-01-16 | A     |     89
 2015-01-17 | A     |      0
 2015-01-18 | A     |      0
 2015-01-19 | A     |    100
 2015-01-20 | A     |     67
(20 rows)

Here's my swing at it, with embedded comments.
select avg(return),
   date_period,
   day_period
from (
        -- use row_number to generate a sequential value for each DOW,
        -- with a WHERE to filter out the weekends
      select date,
         stock,
         return,
         date_period ,
         row_number() over (partition by date_period order by date asc) day_period
      from (
            -- bin out the entries by date_period using the first_value of the entire set as the starting point
            -- modulo 7
            select date,
               stock,
               return,
               date + (first_value(date) over (order by date asc) - date) % 7 date_period
            from stocks
            where date >= '2015-01-01'
            -- setting the starting period date here
         )
         foo
      where extract (dow from date) not in (1,7)
   )
   foo
group by date_period, day_period
order by date_period asc;

The results:
    AVG     | DATE_PERIOD | DAY_PERIOD
------------+-------------+------------
  16.000000 | 2015-01-01  |          1
  80.000000 | 2015-01-01  |          2
  60.000000 | 2015-01-01  |          3
  25.000000 | 2015-01-01  |          4
  12.000000 | 2015-01-01  |          5
   1.000000 | 2015-01-08  |          1
  81.000000 | 2015-01-08  |          2
  35.000000 | 2015-01-08  |          3
  20.000000 | 2015-01-08  |          4
  69.000000 | 2015-01-08  |          5
  72.000000 | 2015-01-15  |          1
  89.000000 | 2015-01-15  |          2
 100.000000 | 2015-01-15  |          3
  67.000000 | 2015-01-15  |          4
(14 rows)

Changing the starting date to '2015-01-03' to see if it adjusts properly:
...
from stocks
where date >= '2015-01-03'
...

And the results:
   AVG     | DATE_PERIOD | DAY_PERIOD
------------+-------------+------------
  60.000000 | 2015-01-03  |          1
  25.000000 | 2015-01-03  |          2
  12.000000 | 2015-01-03  |          3
   1.000000 | 2015-01-03  |          4
  81.000000 | 2015-01-03  |          5
  35.000000 | 2015-01-10  |          1
  20.000000 | 2015-01-10  |          2
  69.000000 | 2015-01-10  |          3
  72.000000 | 2015-01-10  |          4
  89.000000 | 2015-01-10  |          5
 100.000000 | 2015-01-17  |          1
  67.000000 | 2015-01-17  |          2
(12 rows)


text:
Q: PHP Operator strange behavior ===
echo var_dump( ! end($lines)['id'] === $r['line_id'] );

outputs:
bool(false)

==
echo var_dump( ! end($lines)['id'] == $r['line_id'] );

outputs:
bool(true)

but....
echo var_dump( end($lines)['id'] === $r['line_id'] );
echo var_dump( end($lines)['id'] == $r['line_id'] );

both output:
bool(false)

Why?  Should the first two examples be the exact same?
Note:  In this example end($lines)['id'] doesn't exist and $r['line_id'] is: string(1) "2"

A: When the === comparator is used, it compares data type and value. Since the same expression albeit using the == comparator (comparing only value) evaluates to bool(true), we can assume these variables are the same value, but not the same type. For more information, see PHP: Comparison Operators.
In the second example, you're not using the ! operator to negate the end($lines)['id'] reference, which doesn't yield equivalency in your case.

In your case, an unset variable will evaluate to a FALSE boolean, and the set $r['line_id'] will evaluate to a TRUE boolean. Thus, !FALSE == TRUE. For more information on this aspect of PHP, please refer to PHP: PHP type comparison tables, specifically column boolean: if($x) column of table Comparisons of $x with PHP functions.
In the same fashion, the expression ! end($lines)['id'] === $r['line_id'] will yield bool(false) as end($lines)['id'] does not have a datatype, and $r['line_id'] is a string(1). As such the datatypes do not match for the === comparator to return bool(true).


text:
Q: Scala 2.9 : Any way to use toArray on a Set inline If the answer to my question is already out here please link it... I did look.
I'm working through some tutorials and it struck me a little odd that this code:
val my_set = Set("one","two","three")
println("First Value:" + my_set.toArray(0))

when run from the command line resulted in this error:
$ scala settoarray.scala
/Users/rwheadon/devStuff/scala_sandbox/so_settoarray.scala:2: error: type mismatch;
found   : Int(0)
required: ClassManifest[?]
println("First Value:" + my_set.toArray(0))
                                        ^
one error found

I googled and searched SO for some direction on providing the ClassManifest[?] requirement but couldn't get anything to work inline.
Out of curiosity I tried to do the same simple toArray() into a val and pulled the array bound successfully:
Code:
val my_set = Set("one","two","three")
val my_arry = my_set.toArray
println("First Value:" + my_arry(0))

run from console:
$ scala so_settoarray.scala
First Value:one

What I am wondering is if there's something I need to add when attempting to just do a quick inline conversion like my_set toArray(0) for a quick println of the first element? If I must set the result of a variable I can easily accept that but my guess is that I'm missing some small point here to make inline array casts work.
(... Scala is magic right?)

A: The toArray method takes an implicit argument of type ClassManifest[A], where A is the element type. If you call it like mySet.toArray(0), the compiler thinks you want to pass the implicit argument explicitly and then complains that it doesn't have the right type. To avoid that, you can write it like so:
mySet.toArray.apply(0)


text:
Q: How to make a queue (FIFO) in JS using arrays? I am working a question on FreeCodeCamp. I need to add a number to the end of the array, then remove the first element of the array. The function called nextInLine should return the element that was removed from it.
I'm not completely new, but I'm not advanced in JS either. However, I'm new to algorithms. I've watched Youtube videos for assistance with Queues. I have this concept fairly understood as follows:
//array as queue (FIFO)
const arr = [];
arr.push(5); // [5]
arr.push(7); // [5,7]
arr.push(9); // [5,7,9]
console.log(arr.shift()); // [7,9]
console.log(arr.shift()); // [9]
console.log(arr.shift()); // []

However, when trying to implement this idea into my code, I seem to not maybe fully understand the presented problem in order to make it run. I am to modify the function nextInLine, and the comment that says //Display Code, I am to change that line as well.
function nextInLine(arr, item) {
  // Your code here
  arr.push(arr[0]);
  arr.shift();
  return console.log(arr, item);  // Change this line
}

// Test Setup
var testArr = [1,2,3,4,5];

// Display Code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr)); // Modify this line to test
console.log("After: " + JSON.stringify(testArr));

When running the code, this is what is showing for me.
nextInLine([], 5) should return a number.
nextInLine([], 1) should return 1
nextInLine([2], 1) should return 2
nextInLine([5,6,7,8,9], 1) should return 5
After nextInLine(testArr, 10), testArr[4] should be 10

My function is outputting /* 2,3,4,5,1 */ but it seems to be incorrect. Perhaps I am failing to put it into an array? I have the first number (1) at the beginning, but am I failing to simply put my answer in an array? Or am I not even producing the right numbers?

A: You can do shift first and then push.
function nextInLine(arr, item) {
  var removedElement = arr.shift();
  arr.push(item);
  return removedElement;
}

A: You should be pushing item onto the array. You're simply moving the first element of the array to the end, without adding the new element.
And console.log() prints its arguments, it doesn't return them. So your function is just returning undefined.
function nextInLine(arr, item) {
  arr.push(item); // add new item to end
  return arr.length > 1 ? arr.shift() : null; // remove first item and return it
}

The conditional in the return statement prevents it from shifting off the new element if it's the only thing in the array, i.e. the array was originally empty.

A: You can use Array.prototype.splice to remove the first element from an array.

function nextInLine(arr, item) {
  var firstElement = arr[0];
  arr.splice(0, 1);
  arr.push(item);
  return firstElement;
}

var arr = [];
console.log('nextInLine(arr, 5) should return undefined and arr should be [5]:');
console.log('return value:', nextInLine(arr, 5));
console.log('array:', arr);
console.log('--------------------------------------')

console.log('nextInLine(arr, 1) should return 5 and arr should be [1]:');
console.log('return value:', nextInLine(arr, 1));
console.log('array:', arr);
console.log('--------------------------------------')

arr = [5,6,7,8,9];
console.log('nextInLine(arr, 10) should return 5 and arr should be [6, 7, 8, 9, 10]:');
console.log('return value:', nextInLine(arr, 10));
console.log('array:', arr);
console.log('--------------------------------------')

A: Update: With the help of everyone, I was not only able to solve, but understand WHY the solution was, what it was! I just had to switch around the following lines of code and that did it. Apparently they wanted you to push the item first, THEN shift on the array. Who would've knew LOL. Thanks everyone! I don't know how to close a forum post down, so I will leave it. Happy coding!

A:
You can try this also

function nextInLine(arr, item) {
       arr.push(item);
       return arr.shift();
    }

 var arr = [1,5,6]
 console.log("removed element is : ", nextInLine(arr,10))
 console.log("array is  : ", arr)

A: i did fifo function with two array method -
concat
slice
const nextInLine = (arr, item) => item ? arr.concat(item).slice(1) : arr;


text:
Q: Google Spreadsheet - Data validation with variable date I'm trying to set up a data validation drop down menu in a cell with a few set terms like: N/A, Booked, Waiting, and a variable date value which can be any date.
I have tried creating a data validation with those items and then show warning on incorrect data, but I don't want the warning to show up and also want to make sure it is a correct date entered and with the right format.


text:
Q: Citet command not an option for Biblatex I am a bit new to LaTeX etc. so please excuse me if this is a beginner question.
I would like to cite references within my document in the following style:

According to Powell et al. (2007)...
This is the best way to do it (Powell et al., 2007)

And so forth. To the best of my understanding, I want to use authoryear style to achieve this. The problem I'm having is getting the first result with the year in parentheses.
Here is my code:
\documentclass[12pt]{article}
\usepackage{lmodern}
\usepackage[english]{babel}
\usepackage{csquotes}
\usepackage{filecontents}
\addbibresource{\jobname.bib}
\usepackage[
backend=biber,
style=authoryear,
maxcitenames=2,
bibencoding=latin1
]
{biblatex}

\begin{filecontents}{\jobname.bib}

 @article{powell2007fastfood,
 title={The availability of fast-food and full-service restaurants in
 the United States: associations with neighborhood characteristics},
 author={Powell, Lisa M and Chaloupka, Frank J and Bao, Yanjun},
 journal={American journal of preventive medicine},
 volume={33},
 number={4},
 pages={S240--S245},
 year={2007},
 publisher={Elsevier}
}
\end{filecontents}

\begin{document}

Here you see \cite{powell2007fastfood}
Here you can also see \parencite{powell2007fastfood}
Also, you have \textcite{powell2007fastfood}

\printbibliography
\end{document}

So the first two, \cite and \parencite, work. They produce the desired results of:

Here you see Powell et al. 2007
Here you can also see (Powell et al. 2007)

For \textcite, I have to manually type it in (using Texmaker provides an autocomplete or autosuggestion option) and then once I have typed the command, I also have to manually type the citation ID. Then when I compile, it gives me the error message "undefined control sequence." It's like the \textcite command is simply not recognized at all. What could cause this?
As an aside, I would prefer a style that put a comma between the author/et al. and year, so

Powell et al., 2007

But I am also trying to explore different citation styles to get what I want.

A: Most biblatex styles offer a variety of citation commands. You can find what all standard styles and therefore most contributed styles do in §3.8 Citation Commands and its subsections, pp. 100-110, of the biblatex documentation.
The following example shows the most common citation commands for authoryear styles
\documentclass[british]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}
\usepackage{csquotes}

\usepackage[style=authoryear, backend=biber]{biblatex}

\addbibresource{biblatex-examples.bib}

\begin{document}
\autocite{sigfridsson}

\cite{sigfridsson}

\parencite{sigfridsson}

\textcite{sigfridsson}

Lorem\footcite{sigfridsson}

\fullcite{sigfridsson}

\printbibliography
\end{document}

The behaviour of the \autocite commands, whose use I can't recommend enough, can be configured freely. By default it behaves like \parencite or \footcite for most standard styles (it will behave like \footcite for styles of the authortitle and verbose style families and like \parencite for most other styles). But you can easily switch to footnote citation should you want to. Just have a look at the autocite option.
It does not matter whether or not those commands show up in some autocompletion feature of your editor. They are defined by all biblatex standard styles and all good contributed styles and should therefore work. If your editor's autocompletion does not display these commands, then that is something you can take up with the developers of the editor or the author of the autocomplete function. (But see also Auto-complete feature for Texmaker citations, Biblatex - Texmaker auto-complete commands.)
There is the natbib compatibility option that lets you use natbib's equivalent shorter names for \parencite and \textcite (namely \citep and \citet, respectively). I would normally try to avoid using that option since the handling of the starred forms of citation commands differ for the biblatex and the natbib names. Furthermore, the natbib compatibility mode changes the definition of nameyeardelim, which means that there will be a comma between author and year in \cite and \parencite/\citep. See also Is there a disadvantage to using natbib=true with biblatex?.

If you want to see a comma between author and year you can just set
\DeclareDelimFormat{nameyeardelim}{\addcomma\space}

the natbib compatibility mode is not required for that.


text:
Q: PHP and Regex if word found I'm looking to only perform a strip of characters if a certain word is found in a string, so if the word numbers is matched with regex it will perform a strip all actual numbers 0-9 or preg replace them to nothing, BTW The numbers will always be wrapped in "". What would be the best way to put these two functions together? An example would be if the data was Man, Numbers are fun! "123ABC" it would return Man, Numbers are fun! "ABC" If numbers isn't present they are ignored.

A: I feel like some of the answers here are overcomplicated. Maybe it's just me, but this should be all you need:
if (stripos($str, 'numbers') !== false) {
    $str = preg_replace('/\d/', '', $str);
}

EDIT: If you only want numbers that are inside quotation marks, you might be able to do it with a regex, but I'd definitely do it this way:
if (stripos($str, 'numbers') !== false) {
    $arr = explode('"', $str);

    for ($i = 1; $i < count($arr); $i += 2) {
        $arr[$i] = preg_replace('/\d/', '', $arr[$i]);
    }

    $str = implode('"', $arr);
}

A: If I understand the question correctly, maybe something like:
if (strpos($string, "numbers") !== false) {
    $string = preg_replace('/"\d+"/', '', $string);
}

A: You could use the strpos function to check for the string in the first place.
Something like
if(strpos($mystr,"Some value")!==false)
{
    /*preg_replace here.*/
}

A: @Ryan Cooper: Try --
$input = 'Man, Numbers are fun! "123ABC"';

echo stripnums("Numbers", $input);

function stripnums($needle, $haystack)
{
    if (stripos($haystack, $needle) !== 0)
    {
        return preg_replace('/[0-9]/', '', $haystack);
    }
}

A: Something like this should work for you:
$str = 'Man, Numbers are fun! "123ABC"';
var_dump(preg_replace_callback("(.*\bNumbers\b.*)",
create_function(
'$matches',
'return preg_replace("/(\"[^\d]*)\d+(.*\")/", "$1$2", $matches[0]);'
),
$str));

OUTPUT:
string(27) "Man, Numbers are fun! "ABC""

\bNumbers\b will make sure to match word Numbers with word boundaries so that xyzNumbers and Numbersxyz are NOT matched.


text:
Q: Writing to Bigtable from Python I am developing an IoT data pipeline using Python and Bigtable, and writes are desperately slow.
I have tried both Python client libraries offered by Google. The native API implements a Row class with a commit method. By iteratively committing rows in that way from my local development machine, the write performance on a production instance with 3 nodes is roughly 15 writes / 70 KB per second --granted, the writes are hitting a single node because of the way my test data is batched, and the data is being uploaded from a local network... However Google represents 10,000 writes per second per node and the upload speed from my machine is 30 MB/s, so clearly the gap lies elsewhere.
I have subsequently tried the happybase API with much hope because the interface provides a Batch class for inserting data. However, after disappointingly hitting the same performance limit, I realized that the happybase API is nothing more than a wrapper around the native API, and the Batch class simply commits rows iteratively in very much the same way as my original implementation.
What am I missing?

A: I know I'm late to this question, but for anyone else who comes across this, the google cloud libraries for python now allow bulk writes with mutations_batcher. Link to the documentation.
You can use batcher.mutate_rows and then batcher.flush to send all rows to be updated in one network call, avoiding the iterative row commits.


text:
Q: CastError: Cast to ObjectId failed for value "{ '$in': [ new ObjectId("6359f421fd4678e2eba3ffee") ] }" (type Object) at path "author" for model "Blog" I have a blog model:
let blogSchema = new mongoose.Schema({
author: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
title: { type: String, required: true, unique: true },
description: { type: String, required: true, unique: true },
content: { type: String, required: true, unique: true },
likes: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
views: { type: Number, default: 0, required: true },
tags: [],
currentState: { type: String, enum: ['draft', 'published'], required: true, default: 'draft' }}, { timestamps: true });

and a user model which I don't think is necessary to show.
When I try querying for a blog with the author matching a list of userids that the current user is following as such:
let blogs = await Blog.find({ author: { $in: blogIds } })
It gives me the error: CastError: Cast to ObjectId failed for value "{ '$in': [ new ObjectId("6359f421fd4678e2eba3ffee") ] }" (type Object) at path "author" for model "Blog"
How do I get the blogs? I've tried using the $or operator but I would have to loop and it doesn't work anyway. The array values in $in is found correctly as shown in the error, it isn't converting properly though.
The blogids array is [ new ObjectId("6359f421fd4678e2eba3ffee") ]. It is dynamic and is an array of userids that the user follows (OOPS, the name isn't clear)

A: I think there might be problem in your blogIds array.Try to convert all value inside it with mongoose.Types.ObjectId.
const allIds=blogIds.map(item=>mongoose.Types.ObjectId(item));

Then update your find query.
const blogs = await Blog.find({ author: { $in: allIds } });


text:
Q: Azure: Web Apps - List Application Settings from deployed nodejs app I've deployed a nodeJs app to a Linux Azure AppService. Now I would like to list the server settings of that same app-service. Under the Identity tab I enabled the managed Identity for this AppService. In my NodeJs App I've tried the following:
const { DefaultAzureCredential } = require("@azure/identity");

const credential = new DefaultAzureCredential();

credential.getToken().then(token => {
  ...
});

I'm not really sure what this is doing, but I don't think it connects, because the getToken never resolves. Any suggestions what I'm missing here?

A: If you want to get server setting values inside of the app service, you can just try process.env.NODE_ENV as this doc indicated. Instead of calling Azure management API.
If you want to get server setting values outside of the app service, your code can't access server setting values directly, so you should call Azure management API. If you have some problem with DefaultAzureCredential, you can try ClientSecretCredential. Just try the code below:
const { ClientSecretCredential } = require("@azure/identity");

const fetch = require("node-fetch")

let  tenantId='';
let  clientID = '';
let clientSecret = '';

let subscriptionID = ''
let resourceGroup = ''
let appServiceName = ''

new ClientSecretCredential(tenantId,clientID,clientSecret).getToken(['https://management.azure.com/.default']).then(result=>{
    accessToken = result.token
    reqURL = `https://management.azure.com/subscriptions/${subscriptionID}/resourceGroups/${resourceGroup}/providers/Microsoft.Web/sites/${appServiceName}/config/appsettings/list?api-version=2019-08-01`
    fetch(reqURL, {
        method: 'post',
        headers: { 'Authorization': 'Bearer ' +  accessToken},
    })
    .then(res => res.json())
    .then(json => console.log(json));

})

Result :

For how to create an Azure AD app and assign a role to it so that it could have permission to call Azure mgmt APIs, see this doc.