text:
Q: Compare database table with value of option select box php I am trying to sort table data using a select option box which also gets options from the database. So basically If i select option Chairman, it is supposed to populate the table with candidates vying for chairman position. However I am running into a wall because the sql syntax seems incorrect. Please help
<?php
if(!empty($_POST['sort'])) {
            $sql1=" SELECT tbpositions.position_id, tbcandidates.candidate_name, tbcandidates.candidate_position FROM tbpositions
            INNER JOIN tbcandidates ON
            tbpositions.position_id=tbcandidates.position_id WHERE ($row['position_name']==$_POST[$position_name])";

            $result =   mysqli_query($con, $sql1);
            $count  =   mysqli_num_rows($result);
        }
?>


text:
Q: How to group rows in SQL with more than 2 columns are of the same value? One of the usages of GROUP BY is to group entries where a specified column is of the same value. How can we group entries if 2 or more selected rows have the same value?

A: You can GROUP BY Multiple columns (which is what you're asking, I think).
Select column1, column2 from MyTable
GROUP BY column1, column2

redpajama_set_name: RedPajamaStackExchange


text:
Q: Magento 301's with PHP code aquire Seo Url? I am looking to migrate a website from Cubecart 4 to Magento  1.8. I have created a script that grabs the old cat id from the url, then searches the database to where this is stored (I copied them over) It then grabs the new magento category ID and then needs to grabs the URL of that category. I then want to make a 301 redirect from to the new url.
I cant grab the SEO url from the ID however. So far I can grab the un written url from the id with this where $caturl2 is the category id.
Mage::getModel("catalog/category")->load($caturl2)->getUrl();

Is there anyway to grab the seo url by ID? Any ideas?
At the minute it's outputting: /catalog/category/view/s/cat-name/id/4448/

A: To get the full SEO url, stored in URL rewrite management tables, you should use the follwing code.
Mage::getModel("catalog/category")->load($caturl2)->getUrlPath();


text:
Q: Exception on Limit() with Gremlin.Net I am looking to make a query with Gremlin.net on a JanusGraph server, who will find the best route in my Graph (between one point and another, the best route).
To replay the error
I made a repo on Github with a sample application. source Github, it's the project "TestGremlinNet".
I use a docker container, janusgraph.
docker run --name janusgraph -d -p 8180:8182 janusgraph/janusgraph:latest

This is a test project to see how JanusGraph and the Gremlin.net library work. I use data from the game EveOnline. I create a Graph that represents solar systems and the connections between systems. The goal is to calculate the route from one point to another.
The universe is divided into regions, and in one region there are several solar systems.
I put a site that calculates routes, and this represents the graph of a region: "The Forge". dotlan

To test, I'm trying to calculate the route "Jita" to "Mitsolen" with the method :
await loadData.Test("Jita", "Mitsolen");

These are the tests I have done.
Here's my 1st test :
var allSystems = GremlinRequest.V().HasLabel("SystemSolar").Has("SolarSystemName", start)
                        .Repeat(__.Out().SimplePath())
                        .Until(__.HasLabel("SystemSolar").Has("SolarSystemName", arrive))
                        .Path()
                        .Limit<Vertex>(1)
                        .Project<Object>("SolarSystemId", "SolarSystemName", "Securite", "RegionName")
                        .By("SolarSystemId")
                        .By("SolarSystemName")
                        .By("Securite")
                        .By("RegionName")
                        .ToList();

Result :
ServerError: The by("SolarSystemId") modulator can only be applied to a traverser that is an Element or a Map
- it is being applied to [path[v[41112], v[110776], v[118968], v[53296], v[41136]]]
a ImmutablePath class instead

The [path[v[41112], v[110776], v[118968], v[53296] are all Vertice's ID of my route, so my query is good. Ok he cant apply .By(...) on .Path(), so I changed my request not to make a projection, and to recover the Path directly :
2nd/3rd/4th tests :
var allSystems = GremlinRequest.V().HasLabel("SystemSolar").Has("SolarSystemName", start)
                        .Repeat(__.Out().SimplePath())
                        .Until(__.HasLabel("SystemSolar").Has("SolarSystemName", arrive))
                        .Path()
                        .Limit<Vertex>(1)
                        // Tested with .Unfold<Vertex>() too...
                        .ToList();
                        // and Tested with .Next(); too...

I have a Exception :
Exception Message :
ServerError:

StackTrace :
   at Gremlin.Net.Driver.Messages.ResponseStatusExtensions.ThrowIfStatusIndicatesError(ResponseStatus status)
   at Gremlin.Net.Driver.Connection.HandleReceivedMessage(ResponseMessage`1 receivedMsg)
   at Gremlin.Net.Driver.Connection.HandleReceivedAsync(Byte[] received)
   at Gremlin.Net.Driver.ProxyConnection.SubmitAsync[T](RequestMessage requestMessage)
   at Gremlin.Net.Driver.GremlinClient.SubmitAsync[T](RequestMessage requestMessage)
   at Gremlin.Net.Driver.Remote.DriverRemoteConnection.SubmitBytecodeAsync(Guid requestid, Bytecode bytecode)
   at Gremlin.Net.Driver.Remote.DriverRemoteConnection.SubmitAsync[S,E](Bytecode bytecode)
   at Gremlin.Net.Process.Remote.RemoteStrategy.ApplyAsync[S,E](ITraversal`2 traversal)
   at Gremlin.Net.Process.Utils.WaitUnwrap(Task task)
   at Gremlin.Net.Process.Remote.RemoteStrategy.Apply[S,E](ITraversal`2 traversal)
   at Gremlin.Net.Process.Traversal.DefaultTraversal`2.ApplyStrategies()
   at Gremlin.Net.Process.Traversal.DefaultTraversal`2.GetTraverserEnumerator()
   at Gremlin.Net.Process.Traversal.DefaultTraversal`2.get_TraverserEnumerator()
   at Gremlin.Net.Process.Traversal.DefaultTraversal`2.MoveNextInternal()
   at Gremlin.Net.Process.Traversal.DefaultTraversal`2.ToList()
   at GremlinDriver.Loader.<>c__DisplayClass11_0.<Test>b__0()

5th test :
Try to recover all routes.
var allSystems = GremlinRequest.V().HasLabel("SystemSolar").Has("SolarSystemName", start)
                        .Repeat(__.Out().SimplePath())
                        .Until(__.HasLabel("SystemSolar").Has("SolarSystemName", arrive))
                        .Path()
                        .ToList();

With the result more 7100 possible paths :
{path[v[41112], v[110776], v[118968], v[53296], v[41136]]} // <--- It's mine !
{path[v[41112], v[106680], v[110776], v[118968], v[53296], v[41136]]}
and more...

I have my result, but its killing my memory and performance !
If you have any ideas.
Thank you for your help.
Edit :
6th test :
var allSystems = GremlinRequest.V().HasLabel("SystemSolar").Has("SolarSystemName", depart) //vdepart.Id
                                            .Repeat(__.Out().SimplePath())
                                            .Until(__.HasLabel("SystemSolar").Has("SolarSystemName", arrive)) //.V(varrive.Id)
                                            .Path()
                                            .By("SolarSystemName")
                                            .ToList();

I have more 7000 results, but with this aspect :
{path[Jita, New Caldari, Josameto, Poinen, Nomaa]}
{path[Jita, New Caldari, Josameto, Liekuri, Poinen, Nomaa]}
.....+7000

When I'm adding .Limit<string>(1), I have the exception.

A: I found the problem. The problem come to JanusDb. With a Gremlin server I have no problem, and here is the code to get the shortest path, and with the return in object form.
Run docker Gremlin :
docker run -d tinkerpop/gremlin-server:latest

and the code :
internal Task<List<SolarSystem>> GetItineraire(string depart, string arrive)
{
    return Task.Factory.StartNew(() =>
    {
        List<SolarSystem> systemsRegion = new List<SolarSystem>();

        try
        {
            Path allSystems = GremlinRequest.V().HasLabel(LABEL_VERTEX).Has(SOLAR_SYSTEM_NAME, depart)
                                    .Repeat(__.Out().SimplePath())
                                    .Until(__.HasLabel(LABEL_VERTEX).Has(SOLAR_SYSTEM_NAME, arrive))
                                    .Path()
                                    .Limit<Path>(1)
                                    .Next();

            foreach (var systemRoute in allSystems.Objects)
            {
                SolarSystem system = new SolarSystem();

                var etapeItineraire = GremlinRequest.V(((Vertex)systemRoute).Id)
                                                    .Project<Object>(SOLAR_SYSTEM_ID, SOLAR_SYSTEM_NAME, SECURITE, REGION_NAME)
                                                    .By(SOLAR_SYSTEM_ID)
                                                    .By(SOLAR_SYSTEM_NAME)
                                                    .By(SECURITE)
                                                    .By(REGION_NAME)
                                                    .Next();

                // Key : correspond au nom de la propriété
                // Value : la valeur de la propriété
                foreach (var etape in etapeItineraire)
                {
                    // Key : correspond au nom de la propriété
                    // Value : la valeur de la propriété
                    var property = typeof(SolarSystem).GetProperty(etape.Key);
                    property.SetValue(system, etape.Value);
                }

                systemsRegion.Add(system);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine("#############");
            Console.WriteLine(ex.StackTrace);
        }

        return systemsRegion;
    });
}


text:
Q: Triangle inequality Bures distance Given the Bures distance between two density matrices $D_B(\rho_1,\rho_2) = 2(1-\|\rho_{1}^{1/2}\rho_2^{1/2}\|)$ where $\|\cdot\|$ is the norm defined by $\|A\| = \mathrm{Tr}(\sqrt{A^\star A})$, I try to show that this obeys the triangle inequality. Let $\rho_1,\rho_2,\rho_3$ be density matrices. We need that $D_B(\rho_1,\rho_2)\leq D_B(\rho_1,\rho_3) + D_B(\rho_2,\rho_3)$.
My attempt is to show that $\|\rho_1^{1/2} \rho_3^{1/2}\| + \|\rho_{2}^{1/2} \rho_3^{1/2}\| \leq 1+\|\rho_1^{1/2} \rho_2^{1/2}\|$. I know that $\|\rho_{i}^{1/2}\rho_{j}^{1/2}\| \leq 1$ for any $i,j$. However, this is not sufficient for the proof. I am clearly overlooking something. Could someone give me a hint?


text:
Q: While loop with true condition in java Will the below 'while' loop run infinitely?
 while (true)

          try {
                year = Integer.parseInt(sc.nextLine());
                break;
            } catch (NumberFormatException nfe) {
                System.out.println("Enter valid Year");
                System.out.print("try Again:-");

            }

A: Due to the break, it will not.

A: This loop will break when the input is a proper integer.

A: Your while will break if you parse correctly the variable year,
However I think that a better practice is to use a boolean variable to verify when should you stop the while operation.
while(!isYearInCorrectFormat) {
 ...
}


text:
Q: JQuery - Highlight an element using ajax based on values in database Ok, so I've looked through documentation and Googled this, yet surprisingly I can't find a solution and nobody seems to be having the same trouble I am. I am fairly new to JQuery AJAX, and I am putting together a sort of booking calendar from scratch and I am looking for a way to highlight elements or "dates" in the calendar GUI based on whether that "date" has bookings in the database. Here's the block of JQuery I'm tinkering with, but I feel like I'm way off for some reason.
$(".box").load(function() {
    date_time = $(this).attr('id');
    month = $(this).attr('month');
    year = $(this).attr('year');
    $.ajax({
        type: 'GET',
        url: '/book.me/check.php',
        data: "date=" + date_time + "&month=" + month + "&year=" + year,
        success: function(msg) {
                $(this).css("background-color", "#cccccc");
        }
    });
});

Any help would be appreciated, thanks.

A: You are pointing to a different object in success. Use var that = $(this); and that.css("background-color", "#cccccc"); if you are planning to highlight .box like below.
$(".box").load(function() {
    var that = $(this);
    date_time = $(this).attr('id');
    month = $(this).attr('month');
    year = $(this).attr('year');
    $.ajax({
        type: 'GET',
        url: '/book.me/check.php',
        data: "date=" + date_time + "&month=" + month + "&year=" + year,
        success: function(msg) {
                that.css("background-color", "#cccccc");
        }
    });
});


text:
Q: Restrict direct url access in struts2 I am developing business application by using struts2.
I'd like to restrict direct url accessing.
If the user is accessed an action by browser url direct access, not click the link,
I'd like to show the error page.(You can't use url direct access.)
If someone have the solution, please share to me.
Thank you.

A: The requirement is strange & I don't understand the reason behind.
But let me explain on how such a functionality can be attained :

*

*When a direct url-request is being made, then the Referer header is not present in the request.

*You can simply write an interceptor that checks whether the incoming request has the Referer header & it comes from your domain. If no, then you can send error if yes then continue.
Although it's easily possible to by-pass this, but majority of your users won't be doing this.
Sample Interceptor Code :
public String intercept(ActionInvocation ai) throws Exception {
        HttpServletRequest request =
                (HttpServletRequest) ai.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
        if (request != null) {
            if (request.getHeader("Referer") == null) {
                return "error";
            }
            return ai.invoke();
        }
}

A: User can makes a request, which is a url.
This url can be called

*

*By clinking a link

*Submitting a form

*Manually type URL in address bar

*Make a request by using some libraries like commons-http

*.....

They are many ways. You can not make sure which one should be used. You server (Struts Action) receives these request and process them.
Even if you could identify the request cam from a link or button, you can not trust it. A hacker can easily mimic the request object came from different sources.
I believe you are not in the correct path. Or please explain more.

A: May be you can check the session for particular values, so that to confirm that the request is an authorized one, you can even check for some values in the request , you can use hidden fields in JSP for this purpose.The value checking can be done in the method prepare() ,in the action, which will be executed every time when action is called, so before rendering the jsp ,you can easily redirect to any page by writing logic in the prepare method.To use the prepare method you want to implement the Preparable interface


text:
Q: AcmStreamNotPossible when using Naudio library on Windows Server 2008 RC2 (on Amazon EC2) Similar but different to:
Firstly
NAudio error: "NoDriver calling acmFormatSuggest"
and now
ACM Stream Convert exception displaying AcmNotPossible
I'm having similar problems trying to get NAudio to work on an Amazon EC2 instance that has "no sound card"
I got the ACM codec from here:
http://www.rarewares.org/mp3-lame-dshow-acm.php
However now I get a different error message:
"AcmNotPossible" which i'm trying to work out how to solve...
I've tried installed Virtual Sound Card on the EC2 instance but that has not helped...
The instance is running Windows Server 2008
I've been reading about ACM on wikipedia:
Audio Compression Manager (ACM) is a Windows multimedia framework that manages audio codecs (compressor/decompressors). ACM can also be considered an API specification. A codec must conform to the implicit ACM specification to work with Windows Multimedia.
http://en.wikipedia.org/wiki/Windows_legacy_audio_components
Anyone got any ideas?

A: It is nothing to do with whether the machine has a soundcard, but what ACM codecs are installed. You may have installed an ACM codec on the machine, but you must pass exactly the right WaveFormat to it for it to recognise the incoming audio as something it can handle. The Mp3WaveFormat NAudio creates is one recognised by the Fraunhoffer ACM that ships with many versions of Windows.
You can use the NAudioDemo program to query the machine for installed ACM codecs. Each ACM codec can enumerate the input formats it supports (NAudioDemo also does this). I then look at the binary values in a debugger, and make a WaveFormat derived class that exactly matches the supported WaveFormat reported by the ACM codec.


text:
Q: SOCIALENGINE: get gender of the user SocialEngine4: How can I get the gender of the user using sql query?

A: $subject = Engine_Api::_()->core()->getSubject(); //Get user

$fields = $subject->fields()->getFieldsValuesByAlias();
$gender = $fields['gender'];

$this->view->gender = $gender;

A: Use this listed below code:
<?php
$currentUserID=Engine_Api::_()->user()->getViewer()->getIdentity();
$sSqlInviter="select gender from engine4_user_fields_search where item_id=".$currentUserID;
$dbInviterSqli=Zend_Db_Table_Abstract::getDefaultAdapter();
$stmtInviter=$dbInviterSqli->query($sSqlInviter);
$rowInviter=$stmtInviter->fetch();
$gender=$rowInviter['gender'];
if($gender==2)
  echo " Male";
else
  echo " Female";
?>

A: $viewer = Engine_Api::_()->user()->getViewer();
$fields = Engine_Api::_()->fields()->getFieldsValuesByAlias($viewer);
echo $fields['gender'];

A: Are you using default profile question? Then:
From engine4_ser_fields_option

There is  and option id for the particular field.


text:
Q: Make iPhone use speaker for calls when charging I have a few MagSafe charging stands (with phone vertically oriented), and I expected that iPhone would automatically pick speaker mode rather than assuming I'd be holding the phone against my ear.
Is there a way to configure the iPhone to assume that when it's on the charging stand to always select Speaker when it's charging?
Update: I already had Auto-Select Speaker in Call enabled which seems like it should do what I want automatically, but doesn't

A: Although this may not entirely answer the question (in fact, maybe not at all) since it will probably not allow you to specify the kind of loudspeaker on the iPhone, I still want to share it since it may lead you to a solution that works for you anyway.
In the Shortcuts app, you can determine whether the iPhone is connected to a charger and then select a playback destination to iPhone, headphones, TVs, HomePods, etc.


text:
Q: When an account is scheduled for deletion, make every action reset the timer Consider the following scenario:

*

*A high-reputation user schedules their account for deletion – which has 24 hours time.

*23 hours and fifty minutes later, the user engages in vandalic activity.

*This may trigger auto-flags and similar, but before anybody can react, the account is deleted.

*It is impossible or at least difficult for moderators to undo this mess because they only have access to a list of the user's posts but not to their recent actions like comments, deleted comments, edits, etc.

*While staff can probably still access the information after deletion, they may lack the subject knowledge to decide which actions should be undone.

While I get that we do not want to hit quitting users with the hammer of suspension and also give them the opportunity to do an honest clean-up, it does seem a good trade-off to me to have any (or at least most, see below) actions delay the deletion (by resetting the timer).
This gives the community and moderators time to notice rage quitters and react and particularly avoids the above scenario.
Also it may at least somewhat disincentivise vandalism.
The easiest way is probably to make all actions reset the timer, but it would suffice to limit this to all potentially vandalising or community-disturbing ones that do not leave a track (at all or after deletion):

*

*posting comments

*deleting comments

*editing posts (in particular those of others)

*downvoting, unaccepting,

*reviewing

*flagging

*setting bounties

This would at least have the same disincentivising effect as this feature request.

A: Let's just block actions from accounts awaiting deletion, and provide clear messaging:

*

*On the page with the "delete" button, say something like: "After you request deletion your account will be locked and you won't be able to take further actions on the site. You can revoke the deletion request and unlock your account at any time by..." So they're told up front what the consequences will be.  (For bonus points, update the help on deleting accounts and link to it.)

*On the profile page where it says "this account is scheduled for deletion", add something like "and cannot take further actions on the site", so that somebody who blew past that first notice gets a reminder about why he can't edit or vote or whatever.

*Don't say anything publicly about the status of the account.  This isn't a suspension and shouldn't carry that badge (banner) of shame.  It's just an administrative detail.

A: As animuson says, the specific request here isn't possible but you have recognized a situation that I'd already identified to be a concern - that of users rage quitting and taking some of their content with them. I actually have a plan for this but I'll get to it a bit further down.
I don't think that your general idea is a bad one - doing something to disincentivize users from taking their ball and going home, so to speak. If it's feasible, it might make sense to just prohibit any actions by a profile while it's in the deletion queue and we could make that clear to them before they schedule it.

You are scheduling your profile for deletion. If you begin this process, your profile will be suspended/locked/frozen until it is deleted, preventing you from taking any action on this site or the associated meta site. You will be able to cancel the deletion at any time before deletion occurs. This will release the suspension/lock/freeze on your profile.

We can encourage users to do any cleanup before the 24 hours starts and let them know that their profile will essentially be in stasis while waiting. This seems like a reasonable middle ground that allows users to have ownership of their profile deletion and a countdown to deletion but also not letting them do damage immediately before they leave.
We do have an auto flag that gets raised if a user goes on a deletion spree but that only catches so much... as the trigger point is pretty high. For users who aren't deleting their accounts, this may get caught later but with deleting users, it's unlikely to get caught in the future.
One of the things I'd love to do is to set up an automatic flag as part of the account deletion process that notifies moderators whenever a user has deleted some of their posts within the last week before and points them at the deleted user's posts page that you can generally find on their deleted profile stub. When I've reviewed these sorts of events in the past, this page was the most valuable resource for reviewing deleted posts by the user to see if anything needed to be undeleted.
JNat actually put in some time doing research on this and we have some targets for this trigger. The idea is that there will be a flag for any user whose account is deleted if, within seven days of deleting their profile, they delete a post with a score higher than a number we set. This will probably be set at a different number depending on the site and different for a question vs an answer.
I don't know if/when we'll be getting this rolling out but it's definitely something we've been thinking about.


text:
Q: for what values of x the series converges? For what values of $x$ the series summation$x^{log(n)}$ converges.
I've just used the necessary condition for the convergence of series that $x^{log(n)}$ should tends to zero as $n$ tends to infinity.This is possible only if $|x|<1$.
But this does not surely conclude that the original series converges if $|x|<1$

A: For $x > 0$:
$$\begin{array}{rcl}
\displaystyle \sum_{n=1}^{\infty} x^{\log n}
&=& \displaystyle \sum_{n=1}^{\infty} e^{\log x\log n} \\
&=& \displaystyle \sum_{n=1}^{\infty} n^{\log x} \\
&=& \zeta(-\log x)
\end{array}$$
The last equality holds if and only if the series is convergent, which per this question is if and only if $-\log x > 1$, i.e. $x < \dfrac1e$.
Notice that for the series to be defined, we must have $x \ge 0$.

The series converges if and only if $x \in \left[0,\dfrac1e\right)$.


text:
Q: Expand and collapse blocks of code in eclipse Having to read lots of legacy code to check what it makes and get a bigger picture.
Is there any way to expand / collapse blocks of code in eclipse,
like
+ if {...} or
+ else {...}
I already saw those SO on the topic
ide fold
how to collapse
and this eclipse bug
but they are quite old, perhaps there is a solution available now.


text:
Q: Castor XML Mapping same name with the child node I am facing a problem with castor while trying to parse an xml which contains same name for the parent and child node... Here are the details:
This is the part of the mapping file:
<class name="com.somepackage.Item">
    <field name="id" type="java.lang.long">
      <bind-xml name="itemiD" node="element"/>
    </field>
    <field name="amount" type="com.somepackage.Amount">
      <bind-xml name="amount" />
    </field>
</class>
<class name="com.somepackage.Amount" >
  <field name="amount" type="java.lang.String">
    <bind-xml name="amount" />
  </field>
  <field name="currency" type="java.lang.String">
    <bind-xml name="currency" />
  </field>
</class>

And this is the xml which I am trying to parse:
<?xml version="1.0" encoding="UTF-8"?>
<list xmlns="http://someurl">
<item>
<itemID>42425</itemID>
<amount>
  <amount>10.00</amount>
  <currency>EUR</currency>
</amount>
<item>
</list>

And this is the error logs related with the above stuff:

[#|2013-11-20T13:48:54.670+0800|INFO|glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=32;_ThreadName=Thread-2;|13-11-20 13:48:54 ERROR util.XMLConvertUtil http-thread-pool-8181(1) - org.exolab.castor.xml.MarshalException: Illegal Text data found as child of: amount
  value: "10.00"{File: [not available]; line: 14; column: 29}
org.exolab.castor.xml.MarshalException: Illegal Text data found as child of: amount
  value: "10.00"{File: [not available]; line: 14; column: 29}
  at org.exolab.castor.xml.Unmarshaller.convertSAXExceptionToMarshalException(Unmarshaller.java:761)
  at org.exolab.castor.xml.Unmarshaller.unmarshal(Unmarshaller.java:727)
  at org.exolab.castor.xml.Unmarshaller.unmarshal(Unmarshaller.java:616)
  at some.package.XMLConvertUtil.xmlToObject(XMLConvertUtil.java:58)
  at some.package.ConverUtil.xmlToPojo(ConverUtil.java:31)
  at some.package.XMLParser.process(XMLParser.java:89)
  at some.package.XMLParser.doPost(XMLParser.java:1063)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
  at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
  at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
  at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
  at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
  at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
  at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
  at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
  at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
  at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
  at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
  at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
  at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
  at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
  at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
  at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
  at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
  at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
  at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
  at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
  at java.lang.Thread.run(Thread.java:662)
Caused by: org.xml.sax.SAXException: Illegal Text data found as child of: amount
  value: "10.00"
  at org.exolab.castor.xml.UnmarshalHandler.endElement(UnmarshalHandler.java:874)
  at org.exolab.castor.xml.UnmarshalHandler.endElement(UnmarshalHandler.java:1159)
  at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:601)
  at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1782)
  at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2938)
  at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
  at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
  at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
  at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
  at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
  at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
  at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
  at org.exolab.castor.xml.Unmarshaller.unmarshal(Unmarshaller.java:715)
  ... 31 more
Caused by: org.xml.sax.SAXException: Illegal Text data found as child of: amount
  value: "10.00"
  at org.exolab.castor.xml.UnmarshalHandler.endElement(UnmarshalHandler.java:874)
  at org.exolab.castor.xml.UnmarshalHandler.endElement(UnmarshalHandler.java:1159)
  at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:601)
  at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1782)
  at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2938)
  at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
  at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
  at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
  at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
  at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
  at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
  at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
  at org.exolab.castor.xml.Unmarshaller.unmarshal(Unmarshaller.java:715)
  at org.exolab.castor.xml.Unmarshaller.unmarshal(Unmarshaller.java:616)
  at some.package.XMLConvertUtil.xmlToObject(XMLConvertUtil.java:58)
  at some.package.ConverUtil.xmlToPojo(ConverUtil.java:31)
  at some.package.XMLParser.process(XMLParser.java:89)
  at some.package.XMLParser.doPost(XMLParser.java:1063)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:688)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
  at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
  at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
  at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
  at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
  at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
  at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
  at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
  at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
  at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
  at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
  at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
  at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
  at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
  at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
  at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
  at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
  at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
  at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
  at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
  at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
  at com.sun.gr|#]

[#|2013-11-20T13:48:54.671+0800|INFO|glassfish3.1.2|javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=32;_ThreadName=Thread-2;|izzly.ContextTask.run(ContextTask.java:71)
  at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
  at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
  at java.lang.Thread.run(Thread.java:662)
|#]

Is it a bug or some other problem that I need to change something in the mapping? There is no way to change the xml and its schema as I am getting it from a third party. if there is no way to handle this changing the mapping and so on, shall i use another parser?

A: I tried to edit the question and I don't have enough rep to comment but this question seems to be the same as https://stackoverflow.com/questions/16650013/parsing-with-castor-xml-parser.
Over there, a comment was made that castor cannot parse elements where the child and parent have the same name. With that, you'll have to change one or the other.


text:
Q: Avoiding intermediate computation in folding a spark column I'm looking to create a function that takes some sequence of numbers and a spark column, then efficiently computes a new column with the highest number matched from the list, defaulting to 0 if none are matched.
For example take the sequence [500, 100, 1].
The naive approach is to do manually write the following for the sequence:
val manualAdjustment = (c: Column) =>
    when(c.isNull, -1)
      .when(c > 500, 500)
      .when(c > 100, 100)
      .when(c > 1, 1)
      .otherwise(0)

When we supply a column, for example lit(1) we get the concise and clean plan:
CASE WHEN (1 IS NULL) THEN -1 WHEN (1 > 500) THEN 500 WHEN (1 > 100) THEN 100 WHEN (1 > 1) THEN 1 ELSE 0 END.

It would be much nicer to have a function that composes this same plan given a column and an arbitrary sequence of ordered integers instead of manually writing out the prior code for each sequence.
This lead me to write the following function:
val makeRange: (Column, Seq[Int]) => Column = (col: Column, range: Seq[Int]) => {
  val whenFunction = (c: Column, condition: Column, value: Int) =>
       c.when(condition, value)
  val reduced: Column => Column =
       range.map(i => (column: Column) => whenFunction(column, column > i, i))
            .reduce(_ compose _)
  reduced(when(col.isNull, -1)).otherwise(0)
}

This function maps each int to a when condition based on the column value being larger than than the int, so at least in theory it does the same operations as the manualAdjustment function above. However, the output of makeRange(lit(1), Seq(500, 100, 1)) is instead:
CASE WHEN (1 IS NULL) THEN -1 WHEN (CASE WHEN (1 IS NULL) THEN -1 END > 500) THEN 500 WHEN (CASE WHEN (1 IS NULL) THEN -1 WHEN (CASE WHEN (1 IS NULL) THEN -1 END > 500) THEN 500 END > 100) THEN 100 WHEN (CASE WHEN (1 IS NULL) THEN -1 WHEN (CASE WHEN (1 IS NULL) THEN -1 END > 500) THEN 500 WHEN (CASE WHEN (1 IS NULL) THEN -1 WHEN (CASE WHEN (1 IS NULL) THEN -1 END > 500) THEN 500 END > 100) THEN 100 END > 1) THEN 1 ELSE 0 END

This plan is at the least much more verbose than the other plan, but seems much less efficient as it (seemingly) has to calculate the same where conditions over and over again. My theory is that the when conditions are computed in place and applying further when conditions requires evaluating the former 'step' in the fold, which makes requires computing the same conditions over and over again.
Any insight into why this is happening, or how to write a function similar to makeRange that creates as simple of a plan as manualAdjustment?

A: This seems to create the same plan as your manualAdjustment:
val makeRange = (c: Column, range:Seq[Int]) =>
  range.foldLeft(when(c.isNull, -1))((acc: Column, curr: Int) => acc.when(c>curr,curr)).otherwise(0)

== Physical Plan ==
LocalTableScan [CASE WHEN (i IS NULL) THEN -1 WHEN (i > 500) THEN 500 WHEN (i > 100) THEN 100 WHEN (i > 1) THEN 1 ELSE 0 END#10]


text:
Q: How to pass string with \\ as string not hyperlink in python I am converting pandas dataframe to HTML table using python. But table data is having string which has \ in it so letters which are ahead of \ is getting converted into a hyperlink.
It's available in the table but as a hyperlink not string.
my string=testbackup(\\servernamenum)\folder1\scriptname.tar

in table
After bracket ( with both slash it's taking all string as a hyperlink.
e.g
database_backup (**\\servername)\2020-07-21_09-39-20_backup\Database\serv_backup.tar**
Please let me know if I need to add more information to get this clear

A: The backslash is used to escape the next character and to give format instructions, such as line feed, tab, or carriage return.
If you want to store a link with actual backslashes as characters, you need a double backslash:
my string="testbackup(\\servernamenum)\\folder1\\scriptname.tar"

This should do the trick.

A: try adding 'r' prefix.
string=r'testbackup(\servernamenum)\folder1\scriptname.tar'


text:
Q: Python script to move files I'm writing a script to organize files in a folder. If the files are in the root folder the script works fine, but when I add a line to run check for files within subfolders it's not working as expected
#!/usr/bin/env python3
import sys, glob, re, os, shutil
from termcolor import colored
#enconding: utf-8

dir_series = "/home/user/series/series/"
dir_temp = "/home/user/stuff/shared/temp/"

buscar = "*[sS][0-9][0-9]*"

for root, dirs, files in os.walk(dir_temp):
    for series in files:
        if series.endswith(('.mp4', '.srt', '.avi', '.mkv')):
            arch_encontrados = len(series)
            print(colored("\nArchivos encontrados:",'red', attrs=['bold'] ), colored(arch_encontrados, 'red', attrs=['bold'] ),'\n')
            print(*series, sep = "\n")

            for serie in series:

                #Extraer el nombre de la serie
                nombre = re.findall(r'.*[\. ][sS]\d', serie)[0]
                nombre_final = re.sub(r'[\. ][sS]\d','',nombre).replace('.',' ')
                #Extraer el número de la temporada
                season = re.findall(r'[\. ][sS]\d\d', serie)[0]
                season_final_numero = re.sub(r'[\. ][sS]','',season)
                season_final = ('season ' + season_final_numero)
                #Armar el directorio final
                for series_path in os.listdir(dir_series): #lista el contenido de /home/user/series/series/
                 if nombre_final.lower() == series_path.lower(): #compara el listado con la salida del nombre de la serie sin importar mayúsculas y minúsculas
                    for season_path in os.listdir(dir_series + series_path):
                     if season_final == season_path: #compara el listado de seasons contra season_final que tiene mayuscula
                        path = os.path.join(dir_series, series_path, season_final)
                        print(path)
                     else:
                        path = os.path.join(dir_series, series_path, 'Season ', season_final_numero)
                 else:
                    print(colored("\n\n*****************************************",'cyan', attrs=['bold']))
                    print(colored("** Directorio no encontrado, creándolo **",'cyan', attrs=['bold']))
                    print(colored("*****************************************\n",'cyan', attrs=['bold']))
                    path = os.path.join(dir_series, nombre_final, season_final)
                    print(path)
                    os.makedirs(path)

                #Mover el archivo
                print(colored('\nCopiando','green'), serie, colored('a', 'green'), path + '/' + serie)
                shutil.move(serie,path)

        else:
            print(colored('\nNo hay archivos para organizar.','green', attrs=['bold']))

            input(colored("\n\nPresione Enter para continuar ...", attrs=['blink', 'bold']))

When I do this in the root it works fine
dir_series = "/home/user/series/series/"

buscar = "*[sS][0-9][0-9]*"

series = [s for s in glob.glob(buscar) if s.endswith(('.mp4', '.srt', '.avi', '.mkv'))]
if series:
    arch_encontrados = len(series)
    print(colored("\nArchivos encontrados:",'red', attrs=['bold'] ), colored(arch_encontrados, 'red', attrs=['bold'] ),'\n')
    print(*series, sep = "\n")

Any ideas? thanks
/edit:
I believe I've fixed that. Now I'm getting another error, when trying to do the last shutil.move it says
print(colored('\nCopiando','green'), serie, colored('a', 'green'), path + '/' + serie)
NameError: name 'path' is not defined

New code:
#!/usr/bin/env python3
import sys, glob, re, os, shutil
from termcolor import colored
#enconding: utf-8

dir_series = "/home/user/series/series/"
dir_temp = "/home/user/stuff/shared/temp/"

buscar = "*[sS][0-9][0-9]*"

series = [os.path.join(root, s) for root, dirs, files in os.walk(dir_temp) for s in files if s.endswith(('.mp4', '.srt', '.avi', '.mkv'))]
if series:
   arch_encontrados = len(series)
   print(colored("\nArchivos encontrados:",'red', attrs=['bold'] ), colored(arch_encontrados, 'red', attrs=['bold'] ),'\n')
   for series_base in series:
      print(os.path.basename(series_base), sep = "\n")

   for serie in series:

    #Extraer el nombre de la serie
    nombre = re.findall(r'.*[\. ][sS]\d', os.path.basename(serie))[0]
    nombre_final = re.sub(r'[\. ][sS]\d','',nombre).replace('.',' ')
    #Extraer el número de la temporada
    season = re.findall(r'[\. ][sS]\d\d', serie)[0]
    season_final_numero = re.sub(r'[\. ][sS]','',season)
    season_final = ('season ' + season_final_numero)
    #Armar el directorio final
    coincidencia = False
    for series_path in os.listdir(dir_series): #lista el contenido de /home/user/series/series/
     if nombre_final.lower() == series_path.lower(): #compara el listado con la salida del nombre de la serie sin importar mayúsculas y minúsculas
        coincidencia = True
        coincidencia_season = False
        for season_path in os.listdir(dir_series + series_path):
         if season_final == season_path: #compara el listado de seasons contra season_final que tiene mayuscula
          coincidencia_season = True
          path = os.path.join(dir_series, series_path, season_final)
          print(path)
         if not coincidencia_season:
          path = os.path.join(dir_series, series_path, 'Season ' + season_final_numero)
          print(path)

    if not coincidencia:
     print(colored("\n\n*****************************************",'cyan', attrs=['bold']))
     print(colored("** Directorio no encontrado, creándolo **",'cyan', attrs=['bold']))
     print(colored("*****************************************\n",'cyan', attrs=['bold']))
     path = os.path.join(dir_series, nombre_final, season_final)
     print(path)
     os.makedirs(path)

    #Mover el archivo
    print(colored('\nCopiando','green'), serie, colored('a', 'green'), path + '/' + serie)
    shutil.move(serie,path)

else:
   print(colored('\nNo hay archivos para organizar.','green', attrs=['bold']))

   input(colored("\n\nPresione Enter para continuar ...", attrs=['blink', 'bold']))


text:
Q: How to add axios proxy? I'm trying to add a proxy to my application so when I make a query to my backend, instead of having to make a query to 'https://localhost:5000/api/users' I only have to make a query to 'api/users'. How would I go about doing this? Below is my package.json, I would really appreciate any direction on how to modify it to make this adjustment. Thank you!
{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject",
    "debug": "open 'rndebugger://set-debugger-loc?host=localhost&port=19001'"
  },
  "dependencies": {
    "@expo-google-fonts/quicksand": "^0.1.0",
    "@react-native-community/masked-view": "0.1.10",
    "@react-navigation/bottom-tabs": "^5.11.7",
    "@react-navigation/native": "^5.9.2",
    "@react-navigation/stack": "^5.14.2",
    "axios": "^0.21.1",
    "expo": "~40.0.0",
    "expo-app-loading": "^1.0.1",
    "expo-font": "~8.4.0",
    "expo-image-picker": "~9.2.0",
    "expo-status-bar": "~1.0.3",
    "moment": "^2.29.1",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-moment": "^1.1.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz",
    "react-native-dropdown-picker": "^3.8.0",
    "react-native-gesture-handler": "~1.8.0",
    "react-native-gifted-chat": "^0.16.3",
    "react-native-reanimated": "~1.13.0",
    "react-native-safe-area-context": "3.1.9",
    "react-native-screens": "~2.15.2",
    "react-native-web": "~0.13.12",
    "react-navigation": "^4.4.3",
    "react-redux": "^7.2.2",
    "react-router-dom": "^5.2.0",
    "redux": "^4.0.5",
    "redux-devtools-extension": "^2.13.8",
    "redux-thunk": "^2.3.0",
    "uuid": "^8.3.2"
  },
  "devDependencies": {
    "@babel/core": "~7.9.0"
  },
  "private": true
}

A: add the proxy option to your axios request, like so:
const res = await axios.get('/api/users', {
  proxy: {
    host: 'localhost',
    port: 5000
  }
});


text:
Q: Viewing and Opening recently viewed files and folders in unity launcher Is their a way to see and open recently viewed files and folders in unity launcher?
If you select files in third mouse key we will see a menu like this where it shows the default and book marked directory. I want to know whether recently viewed directories can also be viewed int this menu.

Similarly to directors, can recent files be also viewed/opened

eg: if we select gedit from launcher it shows this static menu. is it possible to view/open recently opened files in gedit launcher menu .


text:
Q: Is Schauder's conjecture resolved?
Schauder's conjecture: "Every continuous function, from a nonempty
compact and convex set in a (Hausdorff) topological vector space into
itself, has a fixed point." [Problem 54 in The Scottish Book]

I wonder whether this conjecture is resolved. I know R. Cauty [Solution du problème de point fixe de Schauder, Fund. Math. 170 (2001) 231–246] proposed an answer, but apparently in the international conference "Fixed Point Theory and its Applications" in 2005, T. Dobrowolski remarked that there is a gap in the proof.

A: There is  R. Cauty paper from 2012 titled 'Un theoreme de Lefschetz-Hopf pour les fonctions a iterees compactes' which from what I heard was reviewed to establish a  correct proof of Schauder's conjecture ( or rather a generalization for iterates of f ), and will appear in an international journal.
Edit: published: R. Cauty, J. Reine Angew. Math. 729 (2017), 1–27 DOI link

A: An old proof (by M. R. Taskovic) is here: Mathematica Moravica, volume 2, (1998).
Summary: " The most famous of many problems in nonlinear analysis is Schauder's problem (Scottish book, problem 54) of the following form, that if $C$ is a nonempty convex compact subset of a linear topological space does every continuous mapping $f : C → C$ has a fixed point? The answer we give in this paper is yes."
A new proof (by Mohamed Ennassik & Mohamed Aziz Taoudi
) is  here: Journal of Fixed Point Theory and Applications volume 23, 52 (2021).
Summary: "In this paper, we prove that every nonempty compact $s$-convex subset ($0<s\le 1$) of a Hausdorff topological vector space has the fixed point property. Our approach allows us to provide a simple alternative proof of Schauder's conjecture."

A: I have taken the following from the review of the following paper "Schauder's conjecture on convex metric spaces" written in 2010 :

One of the most resistant open problems in the theory of nonlocally convex linear metric spaces is:
Schauder's Conjecture. Let $E$ be a compact convex subset in a topological vector space. Then any continuous mapping $f:E\to E$ has a fixed point.
In this paper, the authors prove that it holds for convex metric spaces and consequently compact convex subsets of a $CAT(0)$ space have the fixed point property for continuous mappings.

So it seems that the problem in its general form is still open.

A: In Points fixes des applications compactes dans les espaces ULC published in in the arXiv in 2010 Robert Cauty wrote
il y a d'ailleurs une erreur dans la demonstration du
lemme 3 de [2], qu'il n'y a plus de raison de corriger, vu la superiorite de la
nouvelle approche
(there is, by the way, an error in the proof of lemma 3 from [2] for which there is no need for correction in view of the superiority of the new approach)
It seems thus that Cauty still (or again) claims that the Schauder conjecture is settled.
[2] is: R. Cauty. Solution du problème de point fixe de Schauder. Fund. Math. 170, 2001, 231-246.

Edit (August 2016). I was quite surprised that apparently there is no version of the mentioned 2010 arXiv article published in an international journal. While searching the web I learned that Robert Cauty died in 2013.


text:
Q: Is BitCoin a scam (Seeding Initial Wealth)? Hopefully You're aware of what BitCoin is (supposed to be)...

Seeding Initial Wealth
When the federal reserve "prints money", it doesn't just mail million-dollar checks to random Americans. It does one of two things. It either (a) purchases some other asset [generally us treasury bonds] on the free market, thereby injecting more cash into the system than there had been before, or (b), loans money to a bank, who will then loan it to other people who will then spend it.
Importantly, the people on the other end of those transactions did not just get free money. They either sold an asset for cash, or they borrowed cash that they will eventually repay (with interest).
Bitcoin does not have a central bank capable of printing and lending Bitcoin; it has an "algorithm" which through some convoluted mechanism allows Bitcoins to be "mined". Essentially it randomly allocates Bitcoin to early adopters. This is a very good system for early adopters (free money!) It is a nonsensical system for a real currency, not to mention being obviously unscalable (what happens when everyone tries to mine Bitcoin all day long?). To solve this second problem, the supply of Bitcoin is algorithmically limited, which is again good for early adopters.
So, is it a scam? Just a clever plan to enrich it's creators? (value of BitCoins is now (as of May 19th 2011) about 500 times higher than it was initially and is still growing as expected from the start mainly due to the built in deflation)


text:
Q: PowerApps Can't Patch Collection as Table I am running into issues with my patch function. The only error that I am seeing is that it's expecting a Record when I provided a Table. Is this because the collection is coming back as a table, and I need to iterate through the rows of the collection via ForAll? I had assumed the ForAll() in the collection itself would have done that. Any other ideas?
NOTE: My SharePoint List does have other columns in it, but I am only updating a few of them in this gallery.... Is this causing the issue?
// Create a collection to store updated values
ForAll(
    Filter(
        gal_EditableTable.AllItems,
        tog_isChanged.Value
    ) As ChangedRows,
    Patch(colUpdates,
    Defaults(colUpdates), {
        ID: ChangedRows.ID,
        ItemNumber: ChangedRows.txt_ItemNumber.Text,
        Description: ChangedRows.txt_Description.Text,
        Quantity: Value(ChangedRows.txt_Quantity.Text),
        Location: ChangedRows.txt_Location.Text
    })
);

// Update SharePoint with new values
Patch('Inventory Count', colUpdates);
Clear(colUpdates);

A: In order to Patch a collection directly to a Sharepoint list, the columns you are patching have to be exactly the same; names and data types.
Wonder if you could just do: (To add new records)
ForAll(
    Filter(
        Gallery1.AllItems,
        Toggle1.Value = true
    ) As ChangedRows,
    Patch('Inventory Count',
        Defaults('Inventory Count'),
        {
            itemNumber: ChangedRows.itemNumber,
            desc: ChangedRows.desc,
            qty: ChangedRows.qty
        }
    )
)

Or this: (To update existing records)
ForAll(
    Filter(
        Gallery1.AllItems,
        Toggle1.Value = true
    ) As ChangedRows,
    Patch('Inventory Count',
        LookUp('Inventory Count', id = ChangedRows.id),
        {
            itemNumber: ChangedRows.itemNumber,
            desc: ChangedRows.desc,
            qty: ChangedRows.qty
        }
    )
)


text:
Q: Simple implementation for detecting cycles in a directed graph in C# I wonder if you could help me with a simple implementation for detecting cycles in a directed graph in C#.
I've read about the algorithms but I'd like to find something already implemented, very simple and short.
I don't care about the performance because the data size is limited.

A: Check out QuickGraph - it has loads of the algorithms implemented and it's quite a nice library to use.

A: Run a DFS on G and check for backedges.
At every node you expand just check if it is already in the currrent path.


text:
Q: D3 can't render GeoJson file (Simple structure in Montreal, Canada) created in QGIS I am attempting to render SVG and attach it to a div with id="map". I can do this successfully with GeoJson which I acquired from this tutorial: http://maptimeboston.github.io/d3-maptime/#/1
Excerpt:
var neighborhoods_json = {
"type": "FeatureCollection",

"features": [
{ "type": "Feature", "properties": { "Name": "Roslindale", "density": 5.5800 }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -71.1259, 42.2720 ], [ -71.1257, 42.2723 ], [ -71.1256, 42.2724 ] etc...

I am rendering this using the following code:
var width = 960, height = 720;
var colors = d3.scale.category20();

var svg = d3.select('#map').append('svg')
  .attr('width', width).attr('height', height);

var albersProjection = d3.geo.albers()
  .scale(190000).rotate([71.057,0]).center([0, 42.313])
  .translate([width/2, height/2]);

var geoPath = d3.geo.path().projection(albersProjection);

svg.selectAll("path")
  .data(neighborhoods_json.features)
  .enter()
  .append('path')
  .attr('fill', function(d, i) {
  return colors(i);})
  .attr('d', geoPath);

This works great, as Boston is in the USA and Albers is an appropriate choice of projection.
The data which I need to render, however, is a simple movie theater traced over a location in Montreal, Canada using QGIS ( http://imgur.com/Dddkci2 ). I saved the layer as GeoJson using a setting of EPSG:4326, WGS 84. This results in the following file being added to my project:
var theater_json = {
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name":     "urn:ogc:def:crs:OGC:1.3:CRS84" } },

"features": [
{ "type": "Feature", "properties": { "id": 1, "d3Css": "l0r0" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -73.433681281940878, 45.445198056579976 ], [ -73.433681281940878, 45.445201593863992 ], [ -73.433916566065932, 45.445339547768 ], etc...

I am unable to render this in my project. The svg is appended, but regardless of whether I choose to append it as 'path' or 'polygon', the segments are all 0x0 and no visualization is created. I am confused whether or not a projection should be used, as I have seen suggestions of utilizing a projection of "null" in case the data was already outputted with a projection from QGIS. I have also seen suggestions that Canadian locations should use the mercator projection. In any case, here is how the code currently stands:
var svg2 = d3.select('#map').append('svg')
  .attr('width', width).attr('height', height);

var mercProjection = d3.geo.mercator();
var theaterPath = d3.geo.path().projection(mercProjection);

svg2.selectAll('path')
  .data(theater_json.features)
  .enter()
  .append('Polygon')
  .attr('fill', function(d, i) {
    return colors(i);})
  .attr('d', theaterPath);

Regardless of whether I use mercator, null, or any other variety of projection (stereographic, azimuthal equidistant, azimuthal equal area), I am never able to render any visualization. The paths/polygons, however, are still being created with segments of 0x0 in every case. Such an observation seems to suggest that the wrong projection is being chosen, as I observe the same behaviour when I choose the wrong projection for the Boston data.

A: Adjust the projection's scale since you're trying to show a small area.
Here's a polygon around Montreal:  https://gist.github.com/anonymous/302378c7c02cff2450231a77068c5870
Here's code to draw it with d3:  https://bl.ocks.org/swingley/9441b02dd565b6caa3b9f388cbd077bb
The relevant JS for defining the projection:
var mercator = d3.geo.mercator()
  .center([ -73.6, 45.5 ])
  .translate([ w * 0.5, h * 0.6 ])
  .scale([ w * 128 ]);

A: In case anyone is curious about what projection I ended up using for the data I was working with, it's this:
var mercator = d3.geo.mercator()
  .center([ -73.438, 45.447 ])
  .translate([ width * 0.1, height * 0.2 ])
  .scale([ 8000000 ]);


text:
Q: Do Command Blocks have character limits? I'm doing a lot of Big Commands in this map of mine and I was thinking that maybe, like chat Command Blocks might have a character limit.
Does anyone know the limit or if there isn't one?

A: According to the Minecraft Wiki, there is a limit, but it's a very large one.
See the Command Block page on the Minecraft Wiki:

The text limit for commands in a command block is 32,767 characters, but the text pane can only show a small portion of this amount at a time.

A: With client (32,500)
As of 1.9, the character limit when using the command block's interface has been reduced to 32,500 (down from 32,767). This change was to help circumvent crashes when exceeding the packet limit of 32,767 bytes, as more information than just the command is sent to the server when confirming changes (including the various options in the interface).
With server (2^31-1 or 65,535)
The command is stored by the server as an NBT string. Technically the character limit is as much as can fit in Java's String type, being Integer.MAX_VALUE (2^31-1).
However, when saving the string to, for example, a chunk file, a new character limit comes from Java's DataOutput.writeUTF() method:

If this number is larger than 65535, then a UTFDataFormatException is thrown.

If UTFDataFormatException is thrown, the chunk will fail to save. Therefore for map distribution, the character limit is 65,535. Since the client can only send 32,500 characters of a command, it will not be possible to modify the command block via the interface without trimming the command.
Example
One method to obtain a command block on a vanilla server that reaches the 65,535 limit is to use a loot table. Loot tables can create a command block item containing a preset command, which is all handled server-side (thus no client limit of 32,500).
With the following loot table located at WORLD/data/loot_tables/custom/limit.json: http://pastebin.com/8tmeeU4M
And the following command to create a chest containing the relevant command block:
/setblock ~ ~1 ~ minecraft:chest 0 replace {LootTable:"custom:limit"}

Placing and activating the command block will run a 65,535-character-long /say command, and you will see the final character of "1" in the chat (indicating the command was not trimmed). You can then exit the world and re-enter, and the command will still function.
Attempting to add more characters will still allow it to work while the chunk is loaded, but once you exit the world or otherwise unload the chunk, the chunk will fail to save with the following error:

[STDERR]: java.io.UTFDataFormatException: encoded string too long

A: Yes there is a character limit. You don't have to worry about it unless you are doing a one command creation. Also if it is in 1.9+ there is no character limit. Mojang got rid of it while developing 1.9


text:
Q: SQL Server : SELECT from a string I am struggling with this: I have two SQL statements that have 2 different sets of keywords. These are stored in temporary tables since I cannot update, delete or insert into a table.
How do I write a third SQL statement (limited on SQL characters in each statement) that says: "If 'pingu' and 'noot' is correct then true, otherwise if 'sponge' and 'bob' are true display results" (this works)? But then how do I say: "if 'pingu' and 'sponge' is selected then true, or 'bob' and 'noot' are selected then true", but keeping the 'pingu' and 'noot' as true if selected?
Example of keyword list 1: 'Pingu' and 'Noot'
DECLARE @teststring varchar(512) = '{KEYWORD}'
SELECT TOP 1 k.type
FROM (VALUES

('pingu', '66'), ('noot', '66'))

k(word,type) WHERE @teststring LIKE '%' + k.word + '%'

GROUP BY k.type
HAVING COUNT(1) >=2
ORDER BY COUNT(1) DESC;

Example of keyword list 2: 'Sponge' and 'Bob'
DECLARE @teststring varchar(512) = '{KEYWORD}'

SELECT TOP 1 k.type
FROM (VALUES ('sponge', '66'), ('bob', '66')) k (word, type)
WHERE @teststring LIKE '%' + k.word + '%'
GROUP BY k.type
HAVING COUNT(1) >= 2
ORDER BY COUNT(1) DESC;

A: What about combining the two source queries with a UNION ALL?
For example (adapting your original queries):
DECLARE @teststring varchar(512) = '{KEYWORD}';

WITH Keywords AS (
    SELECT *
    FROM (VALUES ('pingu', '66'), ('noot', '66')) k(word, type)

    UNION ALL

    SELECT *
    FROM (VALUES ('sponge', '66'), ('bob', '66')) k(word, type)
)

SELECT TOP 1 k.type
FROM Keywords k
WHERE @teststring LIKE '%' + k.word + '%'
GROUP BY k.type
HAVING COUNT(1) >=2
ORDER BY COUNT(1) DESC;

This returns a result row if at least two keywords, regardless of which source query the keywords come from, are found in @teststring.
Note: If your keywords lists are large, it may be worth reworking the query so that an index can be used to make processing the WHERE clause more efficient.


text:
Q: android nmea GPS Hi am using a locationManager with a Nmea listener. Everything seems to work fine but here is the issue.
I log out the messages in my logcat and i notice something very strange... The messages seems broken or lacking information
example from the logcat.
09-24 11:41:36.899: D/BLUE(3153): LocationManager $GPGGA,094138.0,,,,,0,,,,,,,,*7F
09-24 11:41:37.899: D/BLUE(3153): LocationManager $GPGGA,094139.0,,,,,0,,,,,,,,*7E
09-24 11:41:38.899: D/BLUE(3153): LocationManager $GPGGA,094140.0,,,,,0,,,,,,,,*70
09-24 11:41:39.899: D/BLUE(3153): LocationManager $GPGGA,094141.0,,,,,0,,,,,,,,*71
09-24 11:41:40.899: D/BLUE(3153): LocationManager $GPGGA,,,,,,0,,,,,,,,*66
09-24 11:41:42.899: D/BLUE(3153): LocationManager $GPGGA,,,,,,0,,,,,,,,*66
09-24 11:41:43.899: D/BLUE(3153): LocationManager $GPGGA,,,,,,0,,,,,,,,*66
09-24 11:41:44.899: D/BLUE(3153): LocationManager $GPGGA,,,,,,0,,,,,,,,*66
09-24 11:41:45.909: D/BLUE(3153): LocationManager $GPGGA,,,,,,0,,,,,,,,*66

As far as i know. The format of the GPGGA should be something like this
$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47

Now i tried other types like GLL and its the same issue. I also tried just reading the bytes directly with bluetooth but its the same thing.
Anyone have similair issues with Nmea messages?

A: It looks like the GPS does not have a fix. Are you certain you have a good enough signal? Please verify outdoors under an open sky.

A: Definitely the signal, wait 1 or 2 minutes and data will be completed


text:
Q: Prioritising certain tags For me, tags do not merely fall into 3 categories: favourite, not-favourite or do-not-want. Some tags are more interesting to me than others. I am a Scala developer; I don't develop in Java on a regular basis (or ever, really, any more). I do help answer Java questions because I know the language and many of them are not language-specific, and there aren't very many Scala questions by comparison to the number of Java questions.
But when a Scala question does appear, I'd like it to float to the top of the list.
There are one or two other "super-interesting" topics for which I feel the same.
Of course I can and do scan questions by eye, but I would like the site to help me out here.
Yes, I can subscribe to tags by email, and in the case of Scala, I can follow the Scala tag on Twitter. Nevertheless, I would appreciate being able to sort questions by how interesting their tags are to me.

A: Actually, I guess this Google Chrome extension which colour-codes questions by tag, would be a good enough workaround for now. It doesn't sort them, but it would make it easier to scan by eye.


text:
Q: mod_jk vs mod_cluster Can someone please tell me the pro's and con's of mod_jk vs mod_cluster.
We are looking to do very simple load balancing..  We are going to be using sticky sessions and just need something to route new requests to a new server if one server goes down.  I feel that mod_jk does this and does a good job so why do I need mod_cluster?

A: If your JBoss version is 5.x or above, you should use mod_cluster, it will give you a better performance and reliability than mod_jk. Here you've some reasons:

*

*better load balacing between app servers: the load balancing logic is calculated based on information and metrics provided directly by the applications servers (bear in mind they have first hand information about its load), in contrast with mod_jk with which the logic is calculated by the proxy itself. For that, mod_cluster uses an extra connection between the servers and the proxy (a part from the data one), used to send this load information.

*better integration with the lifecycle of the applications deployed in the servers: the servers keep the proxy informed about the changes of the application in each respective node  (for example if you undeploy the application in one of the nodes, the node will inform the proxy (mod_cluster) immediately, avoiding this way the inconvenient 404 errors.

*it doesn't require ajp: you can also use it with http or https.

*better management of the servers lifecycle events: when a server shutdowns or it's restarted, it informs the proxy about its state, so that the proxy can reconfigure itself automatically.

You can use sticky sessions as well with mod cluster, though of course, if one of the nodes fails, mod cluster won't help to keep the user sessions (as it would happen as well with other balancers, unless you've the JBoss nodes in cluster). But due to the reasons given above (keeping track of the server lifecycle events, and better load balancing  mainly), in case one of the servers goes down, mod cluster will manage it better and more transparently to the user (the proxy will be informed immediately, and so it will never send requests to that node, until it's informed that it's restarted).
Remember that you can use mod_cluster with JBoss AS/EAP 5.x or JBoss Web 2.1.1 or above (in the case of Tomcat I think it's version 6 or above).
To sum up, though your use case of load balancing is simple, mod_cluster offers a better performance and scalability.
You can look for more information in the JBoss site for mod_cluster, and in its documentation page.


text:
Q: Some characters stick to my colorized prompt in Python cmd I am using Python 2's cmd module to make a command line for a program.  Everything works nicely as long as I don't add color to my prompt.
Working code:
from cmd import Cmd

class App(Cmd):

    def __init__(self):
        Cmd.__init__(self)
        self.prompt = "PG ["+ (str('username'), 'green') +"@"+ str('hostname') +"]: "

    def do_exit(self, line):
        '''
        '''
        return True

App().cmdloop()

When I change my code as below, if I enter a long command or try to search in the command history, some characters stick to my prompt.
Problem code:
from cmd import Cmd

class App(Cmd):

    def __init__(self):
        Cmd.__init__(self)
        self.prompt = "PG ["+ self.colorize(str('username'), 'green') +"@"+ str('hostname') +"]: "

    colorcodes =    {'green':{True:'\x1b[32m',False:'\x1b[39m'}}

    def colorize(self, val, color):
        return self.colorcodes[color][True] + val + self.colorcodes[color][False]

    def do_exit(self, line):
        '''
        '''
        return True

App().cmdloop()

You can see this problem in asciicasts.  The problem also exists with the cmd2 module.

A: Just add markers to your color codes:
    colorcodes =    {'green':{True:'\x01\x1b[32m\x02',False:'\x01\x1b[39m\x02'}}
                                  # ^^^^        ^^^^         ^^^^        ^^^^

In your asciicast, you have problems when you leave i-search mode and the prompt is re-printed.  That is because Python doesn't know that the escape characters don't actually take up space on the screen.  Putting \x01 before each escape sequence, and \x02 after each escape sequence, tells Python to assume those characters take up no space, and so the prompt will be correctly reprinted.
This is the same solution as in this answer, which had the corresponding problem in a different context.  There is an open issue to mention this in the Python readline documentation, but I don't see that it has yet been done.
I tested the above colorcodes values with Python 2.7.12 on Cygwin, running in mintty.  In the prompt, username printed green and everything else printed the default (light gray).  I used the standard system cmd module, not cmd2 (which you linked).


text:
Q: Custom hook and dynamic useEffect dependency I'm using this useFetch custom hook in multiple components.

import {useState,useEffect} from 'react'
import {getToken} from './../services/token'

const useFetch = (url) => {

    const [data,setData]       = useState(null);
    const [error,setError]     = useState(null);
    const [loading,setPending] = useState(false);

    useEffect(() => {

        (async()=>{

          const abortCont = new AbortController();
          const token     = await getToken();

          try {

            setPending(true);

            const response = await fetch(url,{
              signal  : abortCont.signal,

              headers : {
                "Content-Type"  : "application/json",
                "Authorization" : "Bearer "+token
              }

            });

            const result    = await response.json();

            setData(result);
            setPending(false);

          } catch (err) {

            if(err.name === 'AbortError'){
                abortCont.abort();
                return;
            }

            setError(String(err));
            setPending(false);

          }

        })()

      }, [])

    return {data,error,loading}
}

export default useFetch;

And I import it in a users components as below.

const {data,error,loading} = useFetch('http://localhost:4040/users');

Normally I pass the second parameter of UseEffect like [users.length] to make the users data reactive but as this is a custom hook and being used in many components,
How can I make the users data to be reactive when users data was changed or updated?
Codesandbox Link

A: You can pass the dependency array as the optional parameter to your custom hook.
const useFetch = async (url, deps) => {

const [data,setData]       = useState(null);
const [error,setError]     = useState(null);
const [loading,setPending] = useState(false);

useEffect(() => {

    (async()=>{

      const abortCont = new AbortController();
      const token     = await getToken();

      try {

        setPending(true);

        const response = await fetch(url,{
          signal  : abortCont.signal,

          headers : {
            "Content-Type"  : "application/json",
            "Authorization" : "Bearer "+token
          }

        });

        const result    = await response.json();

        setData(result);
        setPending(false);

      } catch (err) {

        if(err.name === 'AbortError'){
            abortCont.abort();
            return;
        }

        setError(String(err));
        setPending(false);

      }

    })()

  }, deps || [])

    return {data,error,loading}
}

export default useFetch;

Then call it like
const {data,error,loading} = useFetch('http://localhost:4040/users', [users.length]);

EDIT
In your case you want to have some more control over the rendering. So i'll say you have to modify your hook to support setting data for your mounted component.
const useFetch = async (url, holded, setHolded) => {

const [data,setData]       = useState(null);
const [error,setError]     = useState(null);
const [loading,setPending] = useState(false);

useEffect(() => {

    (async()=>{

      const abortCont = new AbortController();
      const token     = await getToken();

      try {

        setPending(true);

        const response = await fetch(url,{
          signal  : abortCont.signal,

          headers : {
            "Content-Type"  : "application/json",
            "Authorization" : "Bearer "+token
          }

        });

        const result    = await response.json();

        setData(result);
        if(setHolded) {
            setHolded(result);
        }
        setPending(false);

      } catch (err) {

        if(err.name === 'AbortError'){
            abortCont.abort();
            return;
        }

        setError(String(err));
        setPending(false);

      }

    })()

  }, (holded && setHolded && [holded,setHolded,url]) || [url])

    return {data,error,loading}
}

export default useFetch;

Then call it like
const {data,error,loading} = useFetch('http://localhost:4040/users', users, setUsers);


text:
Q: Android Gradle annotationProcessor not available in parent module I'm having the following setup:
ProjectA build.gralde:
dependencies {
    compile (project(':ProjectB'))
}

ProjectB build.gradle:
dependencies {
    annotationProcessor 'com.ryanharter.auto.value:auto-value-parcel:0.2.5'
    compile "com.google.auto.value:auto-value:1.3"
    annotationProcessor "com.google.auto.value:auto-value:1.3"
}

And SomeClass in ProjectA that is implementing Parcelable
@AutoValue
public abstract class SomeClass implements Parcelable {
...
}

AutoValue won't generate any Parcelable related methods in AutoValue_SomeClass.
However, if I include auto-value-parcel annotationProcessor directly to ProjectA, the problem is resolved.
ProjectA build.gralde:
dependencies {
    compile (project(':projectB'))
    annotationProcessor 'com.ryanharter.auto.value:auto-value-parcel:0.2.5'
}

Can anyone explain how auto-value-parcel annotationProcessor is being excluded from ProjectA?

A: annotationProcessor dependencies are not exported to other projects. Also these are not exported with libraries.
AutoValue itself works, because you defined it with a compile dependency. This is something you should not do either. So an better dependency setup would look like...
ProjectB
dependencies {
    provided "com.jakewharton.auto.value:auto-value-annotations:$autoValueVersion"
    annotationProcessor "com.google.auto.value:auto-value:$autoValueVersion"
    annotationProcessor "com.ryanharter.auto.value:auto-value-parcel:$autoValueParcelVersion"
}

ProjectA
dependencies {
    compile project(':ProjectB')
    provided "com.jakewharton.auto.value:auto-value-annotations:$autoValueVersion"
    annotationProcessor "com.google.auto.value:auto-value:$autoValueVersion"
    annotationProcessor "com.ryanharter.auto.value:auto-value-parcel:$autoValueParcelVersion"
}

But not having annotationProcessor run on all projects would be even better.


text:
Q: Just insert a new key - value on a mysql json field on Laravel I work with Laravel and I try to add an entry to a MySQL field in JSON format ...
This field contains (for example), this:

        {
            "df2jay22p1f1nb31b161jf2jay22p5":
            {
                "type": "texte-image",
                "contenu": "Texte de test",
                "position": "2"
            },
            "df2jay1w251p1nb31a2f24f2jay1w256":
            {
                "type": "contenu-seul",
                "contenu": "Contenu de test",
                "position": "1"
            }
        }

My goal is to arrive at this:

            {
            "df2jay22p1f1nb31b161jf2jay22p5":
            {
                "type": "texte-image",
                "contenu": "Texte de test",
                "position": "2",
                "image": "/url/to/img.jpg"
            },
            "df2jay1w251p1nb31a2f24f2jay1w256":
            {
                "type": "contenu-seul",
                "contenu": "Contenu de test",
                "position": "1"
            }
        }

My controller works like this:
$page = new Page();
        $page->contenu = $request->input('composants'); // Json field
        $page->save();

        foreach($page->contenu as $i => $element){
            if ( $request->hasFile("composants." . $i . ".image") ){
                $image =  $request->file("composants." . $i . ".image");
                // ... image processing, save on directory, etc...
            }
        }

I would therefore like to take up the content of
$page->contenu

and add the value of "image" to it but I can't realize it ...
Thank you in advance :)

A: Here is an example that you can adapt to your code:
$json = '{
            "df2jay22p1f1nb31b161jf2jay22p5":
            {
                "type": "texte-image",
                "contenu": "Texte de test",
                "position": "2"
            },
            "df2jay1w251p1nb31a2f24f2jay1w256":
            {
                "type": "contenu-seul",
                "contenu": "Contenu de test",
                "position": "1"
            }
}';

$arr = json_decode($json, true);
$arr['df2jay22p1f1nb31b161jf2jay22p5']['image'] = "/url/to/img.jpg";
$json = json_encode($arr);
echo '<pre>';
print_r(json_decode($json, true));
echo '</pre>';


text:
Q: Unix scripting whoami/$USER not working as desired Hi I have the script as below.
if [[ 'whoami' -eq "test" ]]; then
    echo "test user"
else
    echo "Not a test user"
fi

This is returning test user even if my user is not text. It would be great if someone can pin point my silly mistake.

A: -eq is for integer testing.
e.g.:
kent$  [[ "a" -eq  "b" ]] && echo "y" || echo "n"
y
kent$  [[ 34 -eq  35 ]] && echo "y" || echo "n"
n

try:
kent$  [[ "a" == "b" ]] && echo "y" || echo "n"
n

A: You are using single quotes in place of backticks:
if [[ `whoami` -eq "test" ]]; then   # Not 'whoami'

For improved readability (and easier nesting, if applicable), use
if [[ $(whoami) -eq "test" ]]; then

instead.

A: Just like this:
if [[ `whoami` == "test" ]]; then  # Not 'whoami' -eq
    echo "test user"
else
    echo "Not a test user"
fi

don't use single quote and '-eq'


text:
Q: Is a high number of draw calls in Vulkan acceptable if there are no major state changes (eg. binding a new pipeline) between the calls? I'm making a 2d Space Invaders clone in Vulkan.
When I'm adding commands to my buffer, I insert a new push constant "Sprite" - which just contains a 2d position and a texture id - and then insert a draw call.
I add all the textures I'll be needing to a descriptor set when I'm building the pipeline, and then the Sprite's texture id is used to specify which texture is being used. As such, I don't need to bind a new pipeline between draw calls.
My code looks like this:
  for ( uint32_t i = 0; i < m_sprites.size(); i++ )
    {
        vkCmdPushConstants( blah,  &m_sprites[i]);
        vkCmdDrawIndexed( blah );
    }

I've set things up like this because I've read that "Draw calls themselves aren't really [expensive], it's the state changes surrounding them that make them expensive." https://www.reddit.com/r/vulkan/comments/g5bh31/why_are_drawcalls_setpass_calls_so_expensive/
Can anyone tell me if this is correct?

A: The answer to a question like this is almost invariably going to be "It depends".
Whether or not something is acceptable depends on if it meets your requirements on a target platform.  For a simple application like Space Invaders, having dozens or even hundreds of sprites on screen only translates into hundreds of calls, which on modern hardware is going to be trivial, especially if you're not doing any complex lighting.  As in, it's likely you're barely going to move the needle in terms of GPU usage.
That said, the kind of code you've written is literally the exact use case for doing vkCmdDrawIndexedIndirect.  Instead of pushing a constant for every call

*

*Push or update the entire m_sprites buffer onto the GPU.

*Bind it as a vertex attribute with VK_VERTEX_INPUT_RATE_INSTANCE input rate

*Use the instance id to access the m_sprites data in the shader array instead of via a push constant.

EDIT:
To answer your comment asking about why this would an indirect draw call might be more performant...  For one thing you're passing less information to the GPU.  For instance, if you want to draw 5000 sprites, then you have to record 10,000 commands. If you're using an indirect call you only have a single command.
What's more, because you're using push constants, every time any sprite changes, you're effectively copying the entirety of the m_sprites buffer every time AND you have to re-record the entire command buffer, right?  But if you're using an indirect call, you don't (necessarily) have to do that.  You can just keep using the same command buffer over and over, and only update the GPU copy of the m_sprites buffer with the elements that have changed.  So if only one sprite moved, you only have to update a tiny part of the buffer.  Obviously this kind of optimization means you have more complex code because you have to keep track of which parts of the buffer are "dirty" and need to be pushed to the CPU, but there are ways of wrapping that kind of stuff pretty easily.
In regards to parallelism of draw calls, I would read here about the strict ordering of some of the pipeline stages.


text:
Q: Number of solutions to $f(n) \equiv 0 \pmod{p}$ where $f$ is a cubic Let $f(x)$ be a cubic polynomial (not necessarily irreducible over $\mathbb{Z}[x]$). Fix a prime $p$. Are there any ways to tell when $f(n) \equiv 0 \pmod{p}$ has 3, 2, 1, or 0 solutions?

A: $\mathbb{F}_p$ is a field, so most stuff that works for reals works here too. You can look for Cardano's formula, but you end up taking roots. To see if there are repeat roots, compute $\gcd(p'(x), p(x))$ (the formal derivative is computed as for the reals, and as there any common factors between $p(x)$ and $p'(x)$ are for roots of multiplicity greater than 1). There are algorithms for factoring polynomials, symbolic mathematics packages like PARI/GP or SAGE probably include them.


text:
Q: Internet Explorer 11 automation VBA Document Empty I am just starting to learn Internet Explorer Automation using VBA and I am facing an issue.
The Document object is empty which prevents me from going further than just loading a page. I have been looking around the net for a solution to this and could not find anything working so here I am, asking for your help.
NB: My VBA level is intermediate
Windows 8.1 pro 64 bit
I wrote an example code

A: I had a the same issue (nothing in the .document) , with Internet Explorer 11.
I had to add the site to the Compatibility View list (gear, compatibility view, add)
Hopefully this will help someone avoid the time I spent looking for a solution.

A: This code works for me. It uses a loop to wait until navigation is complete.
Sub NavigateGoogle()
    Dim i As Long
    Dim ie As InternetExplorer
    Dim Googledoc As HTMLDocument

    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = True
        ie.navigate "www.google.com"
        Do
            DoEvents
        Loop While ie.Busy
    Set Googledoc = ie.document

    Debug.Print Googledoc.all(0).innerHTML

    Set ie = Nothing
End Sub


text:
Q: Check if table exists in created Database in U-SQL I am trying to check whether the table exists in database or not in U-SQL. Currently syntax is
DROP TABLE IF EXISTS Logs;
CREATE TABLE Logs (
    date DateTime,
    eventType int,
    eventTime DateTime,
    INDEX Index_EventType CLUSTERED (eventType ASC)
    DISTRIBUTED BY HASH(eventType) INTO 3);

In this example, I just want to check if table exists or not in current database, I don't want to drop the table if it exists.
Basically I want to add if..else statements in U-SQL script for Table.Such as below:
IF NOT EXISTS Logs
{
 //Create table here
}
else
{
 //Update table scripts
}

How to have this particular condition in U-SQL script?

A: Can you please file a feature request at http://aka.ms/adlfeedback for TABLE.EXISTS?
As a workaround, you could create a fake partitioned table that only contains a single partition, or use any of the workarounds maya specified in the comments to her answers.

A: You can specify IF NOT EXISTS within the CREATE statement to achieve such behavior:
CREATE TABLE IF NOT EXISTS Logs (
    date DateTime,
    eventType int,
    eventTime DateTime,
INDEX Index_EventType CLUSTERED (eventType ASC)
DISTRIBUTED BY HASH(eventType) INTO 3);


text:
Q: Spivak contradiction proof for Spivak problem?

Here is what I dont understand:
He says that $\alpha$ is an upperbound.  He says it is the least upperbound.
Then he finds that $x_1 \in A$
And that $x_1 > \alpha$
How does this contradict the fact that $\alpha$ is an upperbound? There can be infinitely many upperbounds as long as $x \le b$
$x +1$ is an upperbound,
$x+ \delta$ is an upperbound for any $\delta > 0$
Then how is this a contradiction that $\alpha$ is an upperbound?

A: The argument can be thought as the following:

*

*You assume the least upperbound $\alpha$ is such that $f(\alpha) < 0$.

*You use continuity to find an interval centered at $\alpha$ where $f$ is negative within that interval.

*You find a number $x_1$ that is greater than $\alpha$ and has the property that $f$ is negative.

*This new number $x_1$ is a number in the set considered that is greater than $\alpha$.

*If it is greater than $\alpha$ and is in the set, then $\alpha$ can't be an upper bound, can it? Remember that being an upper bound for $A$ means all $x$ in $A$ satisfy $x \leq \alpha$. You just found one $x_1$ in $A$ such that $x_1 > \alpha$.


text:
Q: shorthand syntax for c++ map in map If I have definitions like:
typedef map<string, Foo> Foo_map_1
typedef map<string, Foo_map_1> Foo_map_2
typedef map<string, Foo_map_2> Foo_map_3
typedef map<string, Foo_map_3> Foo_map_4
typedef map<string, Foo_map_4> Foo_map_5

Is there anyway I can generalize that so I could do, for example,
Foo_map<10>

and have a 10-fold nested map. I don't need something like boost::recursive_wrapper because the number of levels is always constant.

A: This is seems easy enough even for the limited C++ metaprogramming power:
#include <map>
#include <string>

template<int N, typename K, typename V>
struct NMap { typedef std::map<K, typename NMap<N-1, K, V>::type> type; };

template<typename K, typename V>
struct NMap<1, K, V> { typedef std::map<K, V> type; };

int main(int argc, const char *argv[]) {
    NMap<3, int, std::string>::type m;
    m[1][2][3] = "Test";
    return 0;
}

A: This works for me.
#include <iostream>
#include <string>
#include <map>
using namespace std;

struct Foo
{
   Foo() : _in(0) {}
   Foo(int in) : _in(in) {}
   int _in;
};

template <int N> struct Foo_map
{
   map<string, Foo_map<N-1> > foo_Map;
   Foo_map<N-1>& operator[](string const& key) { return foo_Map[key]; }
};

template <> struct Foo_map<1>
{
   map<string, Foo> foo_Map;
   Foo& operator[](string const& key) { return foo_Map[key]; }
};

int main()
{
   Foo_map<1> map1;
   map1["abcd"] = Foo(10);

   Foo_map<2> map2;
   map2["a"]["b"] = Foo(20);

   Foo_map<10> map10;
   map10["a"]["b"]["c"]["d"]["e"]["f"]["g"]["h"]["i"]["j"] = Foo(100);

   std::cout << map1["abcd"]._in << std::endl;
   std::cout << map2["a"]["b"]._in << std::endl;
   std::cout << map10["a"]["b"]["c"]["d"]["e"]["f"]["g"]["h"]["i"]["j"]._in << std::endl;
}

The output of running the program:

10
20
100


text:
Q: How to create a scroll able layout I am designing a screen for mobile devices (android), i wanted to display multiple text boxes and buttons on a screen.
Would someone please guide me how can i a make my screen scroll able so that all the text boxes and buttons can be created and viewed on same page.
I tried searching different postings also tried to find any property but couldn't get success.
Regards,
Gul

A: Use a  ScrollView. When he contents of a ScrollView cannot fit the allocated height it will become scrollable.
Note that a ScrollView can only contain a single direct child element so if you need multiple things to be scrollable, you need to wrap that content into a layout.
Here is an example
<ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

        <TextView
                android:id="@+id/tv_long"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="@string/really_long_string" >
        </TextView>

        <Button
                android:id="@+id/btn_act"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="View" >
        </Button>
    </LinearLayout>
</ScrollView>

A: Use ScrollView as the main parent layout. If you don't give the scrollview, then you can't scroll the page.
    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

    <LinearLayout

        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 1" />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 2" />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 3" />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 4" />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 5" />

        <ProgressBar
            android:id="@+id/progressBar1"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton 1" />

        <RadioButton
            android:id="@+id/radioButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioButton 2" />

        <ToggleButton
            android:id="@+id/toggleButton1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="ToggleButton" />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 6" />

        <SeekBar
            android:id="@+id/seekBar1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/button3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button 7" />

        <Button
            android:id="@+id/button4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button 8" />

        <CheckBox
            android:id="@+id/checkBox1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="CheckBox" />

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button 9" />

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button 10" />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button 11" />
    </LinearLayout>

</ScrollView>


text:
Q: Remove part of string after character in an array and remove repeated elements I'm trying to remove part of the value of an element in an array after '_' and once its done remove all repeated elements.
Array looks like
names =  ["ann_w", "james_q", "ann_q", "peter_p", "steve_q", "james_s"];

And I am trying to convert it into
names = ["ann", "james", "peter", "steve"];

Below code is returning undefined and cant figure it out how to remove all repeated elements.
for (i = 0; i < names.length; i++) {
   names[i] = names[i].substring(names[i].indexOf("_") + 1);
}

A: use Set & map:

var names =  ["ann_w", "james_q", "ann_q", "peter_p", "steve_q", "james_s"];

var unique_names = [ ...new Set(names.map(name => {
   return name.split('_')[0]
}))]
console.log(unique_names)

A: var names = ["ann_w", "james_q", "ann_q", "peter_p", "steve_q", "james_s"];

var tmp = names.map(function(n){
   return n.split("_")[0];
}).sort();

// tmp = ["ann", "ann", "james", "james", "peter", "steve"]

var result = [];

tmp.forEach(function(t){
    if(!result.includes(t))
        result.push(t);
});

console.log(result);

A: You can try using split on the string instead of doing the substring, then you'd get an array of strings, and since you only want the first name, you'd take array[0].
Also, you're getting back errors because you're trying to substring the entire array instead of a string.  You'd need to do names[i] = names[i].substring

A: You can do this: Use array#reduce and Object.keys.
reduce will create an object with name as keys and then you can get the key as an array via Object.keys().

var names =  ["ann_w", "james_q", "ann_q", "peter_p", "steve_q", "james_s"];

var obj = names.reduce(function(r,v) {
  var name = v.split('_')[0];
  if(!r[name]) {
    r[name] = 1;
  }
  return r;
}, {});

console.log(Object.keys(obj));

A: var names =  ["ann_w", "james_q", "ann_q", "peter_p", "steve_q", "james_s"];
var finalArray = [];
for (var i = 0; i <names.length; i++){
var substringArray = names[i].split("_");
if(finalArray.indexOf(substringArray[0]) == -1) finalArray.push(substringArray[0]);
}

https://jsfiddle.net/3z3naanb/9/

A: names =  ["ann_w", "james_q", "ann_q", "peter_p", "steve_q", "james_s"];

for (i = 0; i < names.length; i++) {
   names[i] = names[i].substring(0, names[i].indexOf("_"));
}

var unique = names.filter(function(item, i, names) {
    return i == names.indexOf(item);
});

console.log(unique)