text:
Q: How to add express middleware at the end of the chain that gets invoked no matter what (OK/FAIL responses)? Is there a way to add middleware to the end of an express app or router chain that gets called to track whether or not the res / response was sent  or not?
I mean, regardless of if:

*

*A response is sent (string, JSON, etc.)

*A static served file.

*No file found in the static folder.

*A catch-all callback was reached.

*An error middleware was reached.

Example
For instance, if I wanted to log everything...
whether a response was successful or not, ie: it served a file via a express.static( ... ) middleware, some data fetched from a DB, or a custom middleware, or again... if it failed / threw an error...,
is there a way to invoke a callback at the very end?
So far from what I can understand, it seems like, by design, if a static file gets served successfully (via express.static), it doesn't call next(), so the chain stops there.
And for any custom-made middlewares using res.send(), you normally wouldn't want to call next() afterwards since it could cause some undesirable side-effects (errors with headers getting resent).
For error-handlers, that's easier since all unsuccessful responses can be caught here.
But how can it output both successful / unsuccessful responses? Could this be something that should be done without middlewares?

A: The solution I went with ended up being slightly different from this one by @idbehold, but in a nutshell, at the very top of the express app middleware chain, I had to hook a callback to the res Response object's finish event which gets triggered for most (all?) HTTP status-codes I needed to track a successfully served request.
app.use( ( req, res, next ) => {
    res.on( 'finish', () => {
        var codeStr = String( res.statusCode );
        codeStr = codeStr[res.statusCode < 400 ? 'green' : 'red'];
        var output = [req.method.green, req.fullUrl().green, codeStr];
        trace( output.join( ' ' ) );
    } );

    next();
});

I can now get things like:

EDIT
Alright! So provided you also have an error-handler at the "end" of your middleware chain that serves something with an error 404 code, that will trigger the finish event on the res object.
Example of such an error-handler:
app.use( ( err, req, res, next ) => {
    trace( "Error!".red );
    trace( err );

    res.status( 404 ).send(); // Triggers 'finish' on res.
})

A: There's a conceptual difficulty with the asynchronous architecture of node.js and Express for doing this.   I'll describe the general problem and then discuss a few possible work-arounds.
First, each Express handler can be asynchronous.  Thus, it gets called and returns pretty much immediately and nobody outside of that world knows whether it is still waiting for some asynchronous operation to finish before eventually sending its response or if it just failed to do anything.  You literally can't tell from the outside world.
Second, you can monitor a given request to see if it either calls an error handler or if it sends a response.  There is no way to monitor a request handler to see if it just failed to send anything because of the reason above - you have no way of knowing if its still waiting for some asynchronous thing to finish.
So, here's the best I could recommend:

*

*Hook res.end() to see when it gets called.  This is an indication that the response is now done (whether error or success).  You can see an example of doing that in the express-afterware module that Medet linked in an above comment.  The general idea is that you'd have your own middleware somewhere very early in the chain that overrides res.end() so you can see when its called.  That early middleware would just install the override and call next() to continue the handler chain.  Then, when the response is finished, your override would see that res.end() got called.  This should work for all cases where the response is sent.

*Then, you still need to handle cases where no response is sent (which is probably due to faulty code since all requests should get a response eventually).  The only way I know of to do that is to implement some sort of timeout for a request.  You can either use a built-in mechanism server.setTimeout() or you can implement your own inside your middleware (same middleware as describe in step 1).  Then, after some timeout that you specify, if no response has yet been sent, you would take over and send some error response.

*Install your own error middlewares early in the chain that will see and log all errors.  Note that res.end() will still be called so the behavior in step 1 will still be triggered even for errors (error responses still call res.end()).

A: You can trigger a piece of code at the end of a request by using the finish event of the response object. The finish event is emitted when the response has been sent to the client and all the data has been flushed to the network.
app.use(function(req, res, next) {
  res.on('finish', function() {
    console.log('Request finished');
  });
  next();
});


text:
Q: Using a Mirth Transformer to loop through multiple PID.3 Segments I have a message structure where I need to loop through multiple PID.3 segments, selecting one with a PID.3.5 == 'MR' and then replacing PID.3.4 with identifier.  I understand how to loop through multiple segments such as OBX, but not sub-segments.  I have some sample code (not correct) as a start.  Any guidance appreciated.
var pid = msg.PID;

for each (pid3 in pid[PID.3]) {
    if (pid3[PID.3.5] == 'MR') {
        pid3[PID.3.4] = 'IDENTIFIER';
    };
};

A: This seems to work
for each (pid3 in msg['PID']['PID.3']) {
    if (pid3['PID.3.5'].toString() == 'MR') {
        pid3['PID.3.4'] = 'IDENTIFIER';
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cs-cart category menu descriptions I am trying to show category description in category menu. Under each category link i would like to display a short description that is added through admin when creating the category.
This is the code in the tpl that displays the category menu:
{hook name="blocks:sidebox_dropdown"}{strip}
{assign var="foreach_name" value="item_`$iid`"}

{foreach from=$items item="item" name=$foreach_name}

{hook name="blocks:sidebox_dropdown_element"}

    {if $item.$childs}

        {hook name="blocks:sidebox_dropdown_childs"}

            {include file="blocks/sidebox_dropdown_chiled.tpl" items=$item.$childs separated=true submenu=true iid=$item.$item_id}

        {/hook}

    {/if}
    {assign var="item_url" value=$item|fn_form_dropdown_object_link:$block.type}

    {$item.$name}

{/hook}

{/foreach}
{/strip}{/hook}

A: It is not a right way to change the sidebox_dropdown.tpl file, because this file is used everywhere.
The right way is to create a new block template for categories.
Open this folder: /design/themes/[YOUR_SKIN]/templates/blocks/categories/
You will find (basically) 4 files:

*

*categories_dropdown_horizontal.tpl

*categories_dropdown_vertical.tpl

*categories_multicolumn_list.tpl

*categories_text_links.tpl

Create a new one and add any code you need. Put the sidebox_dropdown.tpl code inside your new file too.
After that just open Admin area -> Design -> Layouts. Open properties of the categories block and select your new file.


text:
Q: JAXB generated methods are not using generics I have a JAXB schema where one class contains a list of another class. The schema is given below.
But whenever I create the java classes from this schema , the method is not using generics so I have to use the casts just like pre java 5 way.
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:common="glodas.research">
    <xs:import namespace="glodas.research" schemaLocation="../common.xsd" />

    <xs:complexType name="DashboardStatType">
        <xs:complexContent>
            <xs:extension base="common:IndustryRegionType">
                <xs:sequence>
                    <xs:element name="ModuleStat" type="ModuleStatType"
                            minOccurs="0" maxOccurs="unbounded" />
                    <xs:element name="BitsCount" type="BitsCount"
                            minOccurs="0" maxOccurs="unbounded"/>
                    <xs:element name="AgeLimitViolation" type="AgeLimitViolation"
                            minOccurs="0" maxOccurs="unbounded"/>
                    <xs:element name="ModuleViolation" type="ModuleViolation"
                            minOccurs="0" maxOccurs="unbounded"/>
                </xs:sequence>

                <xs:attribute name="BrCode" type="xs:string" />
                <xs:attribute name="RegionDescription" type="xs:string" />
                <xs:attribute name="AverageAgeOfBits" type="xs:int" use="required"/>
                <xs:attribute name="NewestBitDate" type="xs:date" use="required"/>
                <xs:attribute name="OldestBitDate" type="xs:date" use="required"/>
                <xs:attribute name="ChapterCount" type="xs:int" use="required"/>
                <xs:attribute name="TriggerRulesCount" type="xs:int" use="required"/>
                <xs:attribute name="TriggerEventsCount" type="xs:int" use="required"/>
                <xs:attribute name="UnpublishedCount" type="xs:int" use="required"/>

            </xs:extension>
        </xs:complexContent>
    </xs:complexType>

    <xs:complexType name="ModuleStatType">
         <xs:sequence>
                    <xs:element name="ChapterStat" type="ChapterStatType"
                            minOccurs="0" maxOccurs="unbounded" />
                    <xs:element name="BitsCount" type="BitsCount"
                            minOccurs="0" maxOccurs="unbounded" />
                    <xs:element name="AgeLimitViolation" type="AgeLimitViolation"
                            minOccurs="0" maxOccurs="unbounded" />
                      <xs:element name="ChapterCountViolation" type="ChapterCountViolation"
                            minOccurs="0" maxOccurs="unbounded" />

        </xs:sequence>
        <xs:attribute name="ModuleDescription" type="xs:string" />
        <xs:attribute name="ModuleNumber" type="xs:int" use="required" />
        <xs:attribute name="AverageAgeOfBits" type="xs:int" use="required"/>
        <xs:attribute name="NewestBitDate" type="xs:date" use="required"/>
        <xs:attribute name="OldestBitDate" type="xs:date" use="required"/>
        <xs:attribute name="TriggerRulesCount" type="xs:int" use="required"/>
        <xs:attribute name="TriggerEventsCount" type="xs:int" use="required"/>
        <xs:attribute name="UnpublishedCount" type="xs:int" use="required"/>
    </xs:complexType>

     <xs:complexType name="ChapterStatType">
            <xs:sequence>
                <xs:element name="BitStat" type="BitStatType" minOccurs="0"
                    maxOccurs="unbounded" />
                <xs:element name="BitsCount" type="BitsCount"
                    minOccurs="0" maxOccurs="unbounded" />
                <xs:element name="AgeLimitViolation" type="AgeLimitViolation"
                    minOccurs="0" maxOccurs="unbounded" />
            </xs:sequence>

                <xs:attribute name="ChapterId" type="xs:int" use="required"/>
                <xs:attribute name="ChapterTitle" type="xs:string" use="required"/>
                <xs:attribute name="AverageAgeOfBits" type="xs:int" use="required"/>
                <xs:attribute name="NewestBitDate" type="xs:date" use="required"/>
                <xs:attribute name="OldestBitDate" type="xs:date" use="required"/>
                <xs:attribute name="TriggerRulesCount" type="xs:int" use="required"/>
                <xs:attribute name="TriggerEventsCount" type="xs:int" use="required"/>
    </xs:complexType>

    <xs:complexType name="BitStatType">
                <xs:sequence>
                <xs:element name="BitStat" type="BitStatType" minOccurs="0"
                    maxOccurs="unbounded"/>
                <xs:element name="BitAge" type="BitAge" minOccurs="0"
                    maxOccurs="unbounded"/>
                </xs:sequence>

                <xs:attribute name="WiId" type="xs:int" use="required"/>
                <xs:attribute name="Title" type="xs:string" use="required"/>
                <xs:attribute name="TriggerRulesCount" type="xs:int" use="required"/>
                <xs:attribute name="TriggerEventsCount" type="xs:int" use="required"/>
                <xs:attribute name="LastPublishedDate" type="xs:date" use="required"/>
    </xs:complexType>

   <xs:complexType name="ValidationMessage">
                <xs:attribute name="Text" type="xs:string" use="required"/>
                <xs:attribute name="Severity" type="xs:int" use="optional"/>
   </xs:complexType>

    <xs:complexType name="BitAge">
        <xs:sequence>
            <xs:element name="ValidationMessage" type="ValidationMessage"
                minOccurs="0" maxOccurs="unbounded" />
        </xs:sequence>
        <xs:attribute name="Age" type="xs:int" use="required" />
    </xs:complexType>

    <xs:complexType name="BitsCount">

        <xs:sequence>
            <xs:element name="ValidationMessage" type="ValidationMessage"
                minOccurs="0" maxOccurs="unbounded" />
        </xs:sequence>
        <xs:attribute name="Count" type="xs:int" use="required" />
    </xs:complexType>

    <xs:complexType name="AgeLimitViolation">
        <xs:sequence>
            <xs:element name="ValidationMessage" type="ValidationMessage"
                minOccurs="0" maxOccurs="unbounded" />
        </xs:sequence>
        <xs:attribute name="Count" type="xs:int" use="required" />
    </xs:complexType>

    <xs:complexType name="ChapterCountViolation">
        <xs:sequence>
            <xs:element name="ValidationMessage" type="ValidationMessage"
                minOccurs="0" maxOccurs="unbounded" />
        </xs:sequence>
        <xs:attribute name="Count" type="xs:int" use="required" />
    </xs:complexType>

    <xs:complexType name="ModuleViolation">
        <xs:sequence>
            <xs:element name="ValidationMessage" type="ValidationMessage"
                minOccurs="0" maxOccurs="unbounded" />
        </xs:sequence>
        <xs:attribute name="Count" type="xs:int" use="required" />
    </xs:complexType>

    <xs:element name="GetDashboardMonitorResponse">
        <xs:annotation>
            <xs:documentation>Response for DashboardMonitor.</xs:documentation>
        </xs:annotation>
        <xs:complexType>
            <xs:sequence>
                <xs:element type="DashboardStatType" name="DashboardStat" minOccurs="1"
                    maxOccurs="unbounded"></xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

</xs:schema>

... The method is generated like this
    java.util.List getBitAge();

I want the java method to be generated like this
java.util.List<BitAge> getBitAge();

A: Can you provide more details about your XML schema?  I have attempted to reproduce you issue with the following
nov30.xsd
I made a smaill change to the XML schema you provided since I do not have the source for common.xsd:

<xs:complexType name="DashboardStatType">

            <xs:sequence>
                <xs:element name="ModuleStat" type="ModuleStatType"
                        minOccurs="0" maxOccurs="unbounded" />
                <xs:element name="BitsCount" type="BitsCount"
                        minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="AgeLimitViolation" type="AgeLimitViolation"
                        minOccurs="0" maxOccurs="unbounded"/>
                <xs:element name="ModuleViolation" type="ModuleViolation"
                        minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>

            <xs:attribute name="BrCode" type="xs:string" />
            <xs:attribute name="RegionDescription" type="xs:string" />
            <xs:attribute name="AverageAgeOfBits" type="xs:int" use="required"/>
            <xs:attribute name="NewestBitDate" type="xs:date" use="required"/>
            <xs:attribute name="OldestBitDate" type="xs:date" use="required"/>
            <xs:attribute name="ChapterCount" type="xs:int" use="required"/>
            <xs:attribute name="TriggerRulesCount" type="xs:int" use="required"/>
            <xs:attribute name="TriggerEventsCount" type="xs:int" use="required"/>
            <xs:attribute name="UnpublishedCount" type="xs:int" use="required"/>

</xs:complexType>

XJC Call
xjc -d out nov30.xsd

BitStatType
The resulting list property still uses generics as expected:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.11.30 at 11:38:04 AM EST
//

package generated;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 *
Java class for BitStatType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="BitStatType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="BitStat" type="{}BitStatType" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="BitAge" type="{}BitAge" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *       <attribute name="WiId" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
 *       <attribute name="Title" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       <attribute name="TriggerRulesCount" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
 *       <attribute name="TriggerEventsCount" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
 *       <attribute name="LastPublishedDate" use="required" type="{http://www.w3.org/2001/XMLSchema}date" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BitStatType", propOrder = {
    "bitStat",
    "bitAge"
})
public class BitStatType {

    @XmlElement(name = "BitStat")
    protected List<BitStatType> bitStat;
    @XmlElement(name = "BitAge")
    protected List<BitAge> bitAge;
    @XmlAttribute(name = "WiId", required = true)
    protected int wiId;
    @XmlAttribute(name = "Title", required = true)
    protected String title;
    @XmlAttribute(name = "TriggerRulesCount", required = true)
    protected int triggerRulesCount;
    @XmlAttribute(name = "TriggerEventsCount", required = true)
    protected int triggerEventsCount;
    @XmlAttribute(name = "LastPublishedDate", required = true)
    @XmlSchemaType(name = "date")
    protected XMLGregorianCalendar lastPublishedDate;

    /**
     * Gets the value of the bitStat property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the bitStat property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getBitStat().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link BitStatType }
     *
     *
     */
    public List<BitStatType> getBitStat() {
        if (bitStat == null) {
            bitStat = new ArrayList<BitStatType>();
        }
        return this.bitStat;
    }

    /**
     * Gets the value of the bitAge property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the bitAge property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getBitAge().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link BitAge }
     *
     *
     */
    public List<BitAge> getBitAge() {
        if (bitAge == null) {
            bitAge = new ArrayList<BitAge>();
        }
        return this.bitAge;
    }

    /**
     * Gets the value of the wiId property.
     *
     */
    public int getWiId() {
        return wiId;
    }

    /**
     * Sets the value of the wiId property.
     *
     */
    public void setWiId(int value) {
        this.wiId = value;
    }

    /**
     * Gets the value of the title property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getTitle() {
        return title;
    }

    /**
     * Sets the value of the title property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setTitle(String value) {
        this.title = value;
    }

    /**
     * Gets the value of the triggerRulesCount property.
     *
     */
    public int getTriggerRulesCount() {
        return triggerRulesCount;
    }

    /**
     * Sets the value of the triggerRulesCount property.
     *
     */
    public void setTriggerRulesCount(int value) {
        this.triggerRulesCount = value;
    }

    /**
     * Gets the value of the triggerEventsCount property.
     *
     */
    public int getTriggerEventsCount() {
        return triggerEventsCount;
    }

    /**
     * Sets the value of the triggerEventsCount property.
     *
     */
    public void setTriggerEventsCount(int value) {
        this.triggerEventsCount = value;
    }

    /**
     * Gets the value of the lastPublishedDate property.
     *
     * @return
     *     possible object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public XMLGregorianCalendar getLastPublishedDate() {
        return lastPublishedDate;
    }

    /**
     * Sets the value of the lastPublishedDate property.
     *
     * @param value
     *     allowed object is
     *     {@link XMLGregorianCalendar }
     *
     */
    public void setLastPublishedDate(XMLGregorianCalendar value) {
        this.lastPublishedDate = value;
    }

}


text:
Q: Angular 2 app structure Angular 2 is pretty new to me and I need support to structure a project. I'm not sure what parts of the project to include in the Angular 2 app. The fist part of the app is a pure html welcome page with just a little interaction (user can also read about the business and so on). I want this page to load quickly since its the first impression for the user. This page have a simple form with 4 options and a button to move in to the real app and the app display data depending on the short form. Then the user can start to explore the data, sort and so on. This is where I see use of Angular. So the question is, should the welcome page be a part of the Angular app or should it be pure html delivered by the server (with some css and maybe jquery)? And the data delivered to the url or by cookie?
There is also an admin panel for this system.  Should that be in the same Angular app or should it be a different one? And how to do that?
Thanks!

A: The welcome page definitely could be part of your angular app, just load the app and then implement the logic to control when to show it or not, maybe using a modal popup (you may like to consider bootstrap or PrimeNG for this).
The admin module also can be included in the same app, you just have to validate against the user roles/permissions when to show it accessible. There's a menu module in PrimeNG that you can conditionally load options too.


text:
Q: Structured-data throws error for the publisher and image There is a parent span including two itemtypes as below:

        <meta itemprop="name" content="@Model.Brand.Name" />

            <link itemprop="url" href="@string.Format(Model.Brand.BrandAssetUrlPath+"{0}", "images/brand-logo-colored.png")" />

I am getting the errors for  LOGO and IMAGE which is : (MISSING_FIELD_WITHOUT_TYPE)
I thought it could be because of wrapping the whole code within
itemtype="http://schema.org/Organization"

I removed that from the parent span but still not working.


text:
Q: Upload File To Google Drive Using Google Apps Script Trying to created a Google Apps Script to prompt me to choose a file to upload to Google Drive as described here
But I am receiving an error

Uncaught ScriptError: TypeError: Cannot read property 'getAs' of
undefined

I have watched the YouTube video a couple of times now, but I don't see that I am doing anything incorrectly. Any ideas?
function doGet(){
  return HtmlService.createHtmlOutputFromFile("form.html")
}

function upload(e){
  // logic to upload the file
  var destination_id = 'enter your folder id here' //folder id
  var img = e.imageFile
  var contentType = 'img/png'
  var destination = DriveApp.getFolderById(destination_id)
  var img = img.getAs(contentType)
  destination.createFile(img)

}

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <form>
    <input type="file" name="imageFile"/>
    <input type="button" value="Upload" onclick="google.script.run.upload(this.parentNode)">

    </form>

  </body>
</html>

A: The code has an error
replace
var contentType = 'img/png'

by
var contentType = 'image/png'

Applyng the above fix, the code worked fine for me.
NOTE: While code doesn't throw any error using the default runtime (Chrome V8), the file was not correctly uploaded but using the old runtine (Mozilla Rhino) it works fine.
Regarding the specific error that you got, perphaps you didn't publish the code shown in the question as a new version of your web application. Try using the link to test the latest code.
Related

*

*Google Apps script web app automatically linked to latest code?


text:
Q: [BATCH / .Bat files]Help Toggling some option menus / toggle-able menus Another question about batch files
i know how choice works (also choice.com) but once in the back ive seen an option menu that would let you to toggle between options
like
something [ON] OFF and when toggled something ON [OFF] vice versa
i know 2 ways ..
which 1 way is to write both conditions and display the one needed ..
and the other is to toggle "[  ]" signs ...

i cant do the 2nd way and need some help..
also ive been looking at movement articles but they do not seem to have anything to help
thx for reading the passage and have a nice day :)

A: There are probably dozens of ways to accomplish this.  Here is one simple way, likely not the most elegant but it works:
@echo off

set _on=0

:top
cls

if %_on%==0 (set _nlb= &set _nrb= &set _flb=[&set _frb=]) else (set _nlb=[&set _nrb=]&set _flb= &set _frb= )

echo The '_on' flag is currently: %_nlb% On %_nrb%  %_flb% Off %_frb%
echo.
echo Press any key to toggle the '_on' flag
pause>nul

if %_on%==0 (set _on=1) else (set _on=0)
goto top


text:
Q: having a master database for a django project I have a small team of 5 and I need help finding resources or advice on how to have one centralized MySQL database. We all work virtual and host all the files on one github to centralize everything. So it would be a pain to have 5 local databases on different computers all with the same information as we work scripting logic from the models and etc that will be the same.
The github_cm_dev: is the main directory inside gitHub
venv: is the virtual environment (so anyone on the team can use and activate the environment easily)
indieitude-project/indieitude directory: Has all of my django applications and files
indieitude-project/indieitude/indieitude directory: has all the config files i.e. settings, urls.p etc
Any advice or thoughts on the matter?

A: Normally there is one master database -- the production DB. There are three general options here:
1) If the data isn't too sensitive and a dev doesn't need every last change, you can simply let each dev take a dump file from production and apply it to their machine.
2) If the data is sensitive (e.g. w/ user passwords), you can create a "dummy" version of the DB and use that as the canonical data for local dev and for testing.
3) If you need every change on each user's machine, then you can preload the entries you need with django fixture files. See https://docs.djangoproject.com/en/dev/howto/initial-data/  You can create a fixture file from a DB pretty easily. A fixture file is just text so you can put it in your  git repo.


text:
Q: JSF update component on every ajax request Hi i want to render the JSF messages as bootstrap alerts
<ui:repeat value="#{facesContext.messageList}" var="facesMessage">

        <button type="button" class="close" data-dismiss="alert">×</button>
        Warning! #{facesMessage.summary}

</ui:repeat>

in primefaces there is

means it is rerendered on every ajax request without explicit adding it to the render-attribute of a commandLink
is there a way to achieve this with plain JSF-ajax tags?

A: You might try something like this during your page load:
jsf.ajax.addOnEvent(autoRender);

And in autoRender you would be able to trigger a kind of action in order to render the target component. For instance:
function autoRender() {
    $(":form:autoRenderHiddenButton").click();
}

And in the button:

<h:commandButton id="autoRenderHiddenButton"
                 style="display: none">

    <f:ajax render="theComponentIdYouWantToRender"/>
</h:commandButton>

Or you can easily achieve the same behavior by using Omniface's commandScript:
<o:commandScript name="autoRender" render="theComponentIdYouWantToRender"/>


text:
Q: Need help with major category and permalink re-organization I would like to re-organize my categories and the permalink structure.
I want to rename and merge categories, make previous categories sub-categories and change the permalink structure from
/%postname%/
to
/%category%/%postname%/
The renaming and merging is not the problem, I am rather concerned about the resulting 404 errors.
How would you approach such a project?
Thanks,
Eddie

A: The canonical code within WordPress should actually already redirect those old posts to the new posts automatically. Have you tested that?


text:
Q: Angular 4-Add rows in table I have this service subscribtion
callSearchService($event) {
   this.searchService.searchUser(this.firstName,this.lastName).subscribe(
    data => {
        console.log("we got: ", data);
        this.isNull(data.firstName,data.lastName);
    },
    error => {
        console.log("Error",error);
    },
);

and also I have a table .

        #
        FirstName
        LastName

I am interested how to add rows dynamically to my table, when i get user info (firstname and lastname) from the callSearchService

A: something like this
users = []; //user array

        #
        FirstName
        LastName

<ng-container *ngFor="let user of users; let i=index;">

{{i}}
{{user.firstName}}
{{user.lastName}}

</ng-container>

when you receive new user just update array and remaining things will work fine
callSearchService($event) {
   this.searchService.searchUser(this.firstName,this.lastName).subscribe(
    data => {
        console.log("we got: ", data);
        this.isNull(data.firstName,data.lastName);
    this.users.push(data);
    },
    error => {
        console.log("Error",error);
    },
);

A: You can use ngFor.

suppose you are getting the results in userdetails[] variable.

              {{userdetail.firstName}}

              {{userdetail.lastName}}


text:
Q: Satallite orbiting the earth I need help understanding a question from my physics book.
It goes like this:

a communications firm wants to place a satellite in orbit so that it is always directly above the earth's 45th parallel (latitude 45 north). This means that the plane of the orbit will not pass through the center of the earth. Is such an orbit possible? Why or why not?

Can somebody help me answer this?

A: If we try to put a geosynchronous satellite above  latitudes other than equator then it won't be there for long as there will be a component of gravitational force acting downwards which will give some velocity to the satellite in that direction and it will deviate from it's geosynchronous position.


text:
Q: JSP function to get month from timestamp I have a time stamp column in cloud SQL database , Now i am trying to display a month wise graph on a JSP Page. Now for this graphical representation i need to extract month from the database time stamp column. Does anyone have a JSP function to extract month from the time stamp ?

A:
Does anyone have a JSP function to extract month from the time stamp ?

In JSP, you can use JSTL Formatting Tags that provides a set of tags for parsing and formatting locale-sensitive numbers and dates.
Steps to follow:

*

*first create a Date Object from Date String or long (time in milli seconds)

*extract the month from the Date Object

Sample code:
<c:set value="10/23/2014 - 15:15:22" var="dateString" />

<fmt:parseDate value="${dateString}" var="dateObject"
    pattern="MM/dd/yyyy - HH:mm:ss" />

<fmt:formatDate value="${dateObject}" pattern="MM" />

Read more at my another post to create a Date object from Date String and long (time in milli seconds).

*

*convert timestamp value in EL to date time in jsp

A: The excellent Joda DateTime library has a supplemental library for jsp tags which you could use.
Check them out here


text:
Q: How to add a  tag to currently opened page using Chrome extension? I want to add div tag to the currently open website when user clicks chrome extension Icon. This image should appear on the left top corner of the page. How can I achieve this goal?
The code below adds div tag to extension window.

    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Click Here

A: Presumably by icon you mean browserAction, the button on the right of the omnibox. Bind to the chrome.browserAction.onClicked event, and run executeScript on the current tab, injecting a script that adds a position: absolute; top: 0; left: 0; image to the DOM of the page.
Here's a good sample to get you started (changes the page color on clicking the browser action)

A: appending elements into DOM is fulfilled by content scripts, those scripts run after page load event. as you can see in the chrome extension documentations, so they won't affect already opened tabs.


text:
Q: add background image to asp.net master web page asp.net 4.0 and html5 Using ASP.NET, C#, HTML5 and CSS3. My MasterPage is not recognizing the background image I have set in my stylesheet. I found an answer from 2009 on the ASP.NET forums from an MSN developer and it is still not working. After checking the code, the answer is relevant to XHTML transitional, the default doctype for .NET in Visual Studio.
Any suggestions? Thank you in advance.

    <title></title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>

    <link href="../changes.css" rel="stylesheet" type="text/css" />
    <link href="../style.css" rel="stylesheet" type="text/css" />

    <form id="form1" runat="server">

    html, body {
    background-color: #000;
    background-image: url('../images/darker_wood_1600x1200.jpg');
    background-attachment: scroll;
    background-repeat: repeat-x;
            }

    <!DOCTYPE html>

<meta charset="utf-8" />

<title>

</title>
<link href="changes.css" rel="stylesheet" type="text/css" /><link href="style.css" rel="stylesheet" type="text/css" />

    <form method="post" action="Default.aspx" id="form1">

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTY1NDU2MTA1MmRkM1MGX8QufJ31wnSeINevDB81G3lHsitto4ucLAdg6zs=" />

Header here

Menu here

Sidebar here

Footer here

</form>

A: This code works for me, but I don't know if the code above is how it looks. Cause you post a stylesheet value in the middle of a div.
Also, if the page can't read the file. Try a different file or try changing the search path for the file. Maybe it can't read it because it's outside the server dir. Because the CSS code looks correct.
<!DOCTYPE html>

    <title></title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>

    <link href="../changes.css" rel="stylesheet" type="text/css" />
    <link href="../style.css" rel="stylesheet" type="text/css" />
    <link href="changes.css" rel="stylesheet" type="text/css" /><link href="style.css" rel="stylesheet" type="text/css" />

    <meta charset="utf-8" />

    <form method="post" action="Default.aspx" id="form1">

            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTY1NDU2MTA1MmRkM1MGX8QufJ31wnSeINevDB81G3lHsitto4ucLAdg6zs=" />

                Header here

                Menu here

                Sidebar here

                Footer here

    </form>


text:
Q: How to get the last accessed partitions from AWS Glue using Boto3 Im using the below function to get all partitions from AWS Glue catalog table. There are some tables in the database that has more than 50K partitions. Is it possible to get only the partitions based on the 'LastAccessTime' attribute. I know I can filter from the list of all partitions but I want to see if there is any possible way, using the 'Expression' property of the get_partitions or something so I can avoid scanning the entire catalog table
def get_glue_partitions(glue_client, database_name, table_name):
    """Grabs all partitions for a table, and iterates through pagination."""
    partitions = []

    next_token = ''
    while True:
        resp = glue_client.get_partitions(
            DatabaseName=database_name,
            TableName=table_name,
            NextToken=next_token)
        partitions += resp['Partitions']

        if 'NextToken' not in resp:
            break
        next_token = resp['NextToken']
    return partitions


text:
Q: spark create map of list columns I have a master table as
+-----------+----------+-------------+
|  Age      | Gender   | date        |
+-----------+----------+-------------+
|  [1,2]    |   M      |  2021-01-01 |
|  [11,13]  |   M      |  2021-01-10 |
|  [4,5]    |   M      |  2021-01-15 |
|  [3]      |   F      |  2021-01-30 |
|  [7]      |   F      |  2021-02-20 |
|  [2]      |   F      |  2021-02-30 |
|  [6]      |   M      |  2021-02-20 |

Output needed is

*

*map of date as key and values as list of age

*the values in map need to extracted for limited days, I have taken 15 days for a example. It could be anything like 60, 90, 30.

+-----------+----------+---------------------------------+
|  Age      | Gender   | date                            |
+-----------+----------+---------------------------------+
|  [1,2]    |   M      |  [2021-01-01-->[1,2,11,13,4,5]] |
|  [11,13]  |   M      |  [2021-01-10-->[1,2,11,13,4,5]] |
|  [4,5]    |   M      |  [2021-01-15-->[1,2,11,13,4,5]] |
|  [3]      |   F      |  [2021-01-30-->[3]]             |
|  [7]      |   F      |  [2021-02-20-->[7,2]]           |
|  [2]      |   F      |  [2021-02-30-->[7.2]]           |
|  [6]      |   M      |  [2021-02-20-->[6]]             |

I have tried spark.sql("""select Age,Gender,Map(date,age) as date from master""")
but not able to find out how to control out based on number of days

A: You can solve this by windowing the dataframe based on the date limits in your example this is 15 days, after windowing group rows which match the criteria then group based on Gender and window group to collect ages.
Working Example

*

*Imports and Dataframe setup

from datetime import datetime
import pyspark.sql.functions as F
from pyspark.sql import Window

data = [([1, 2], "M", datetime.strptime("2021-01-01", "%Y-%m-%d")),
 ([11, 13], "M", datetime.strptime("2021-01-10", "%Y-%m-%d")),
 ([4, 5], "M", datetime.strptime("2021-01-15", "%Y-%m-%d")),
 ([3], "F", datetime.strptime("2021-01-30", "%Y-%m-%d")),
 ([7], "F", datetime.strptime("2021-02-20", "%Y-%m-%d")),
 ([2], "F", datetime.strptime("2021-02-28", "%Y-%m-%d")),
 ([6], "M", datetime.strptime("2021-02-20", "%Y-%m-%d")), ]

df = spark.createDataFrame(data, ("Age", "Gender", "date"))

*Window defintion and acceptable condition to determine which rows can belong in the same group (acceptable_window variable in the code below captures this).

window_spec = Window.partitionBy("Gender").orderBy("date")
acceptable_window = 15
df1 = df.withColumn("date_diff", F.datediff(F.col("date"), F.lag("date").over(window_spec))).withColumn("date_group", F.when(F.col("date_diff").isNull(), 1).when(F.col("date_diff") > acceptable_window, 1).otherwise(0))

Contents of df1
+--------+------+-------------------+---------+----------+
|     Age|Gender|               date|date_diff|date_group|
+--------+------+-------------------+---------+----------+
|     [3]|     F|2021-01-30 00:00:00|     null|         1|
|     [7]|     F|2021-02-20 00:00:00|       21|         1|
|     [2]|     F|2021-02-28 00:00:00|        8|         0|
|  [1, 2]|     M|2021-01-01 00:00:00|     null|         1|
|[11, 13]|     M|2021-01-10 00:00:00|        9|         0|
|  [4, 5]|     M|2021-01-15 00:00:00|        5|         0|
|     [6]|     M|2021-02-20 00:00:00|       36|         1|
+--------+------+-------------------+---------+----------+

*From df1 determine which rows will fall into the same group, for this we sum date_group over our window.

df2 = df1.withColumn("date_window", F.sum(F.col("date_group")).over(window_spec))

Contents of df2
+--------+------+-------------------+---------+----------+-----------+
|     Age|Gender|               date|date_diff|date_group|date_window|
+--------+------+-------------------+---------+----------+-----------+
|     [3]|     F|2021-01-30 00:00:00|     null|         1|          1|
|     [7]|     F|2021-02-20 00:00:00|       21|         1|          2|
|     [2]|     F|2021-02-28 00:00:00|        8|         0|          2|
|  [1, 2]|     M|2021-01-01 00:00:00|     null|         1|          1|
|[11, 13]|     M|2021-01-10 00:00:00|        9|         0|          1|
|  [4, 5]|     M|2021-01-15 00:00:00|        5|         0|          1|
|     [6]|     M|2021-02-20 00:00:00|       36|         1|          2|
+--------+------+-------------------+---------+----------+-----------+

*Use the date_window to flatten and collect Age that fall within this window and create a mapping between date and collected ages.

df2.withColumn("date", F.create_map(F.col("date"), F.flatten(F.collect_list("Age").over(Window.partitionBy("Gender", "date_window"))))).select("Age", "Gender", "date").show(200, False)

Output
+--------+------+---------------------------------------------+
|Age     |Gender|date                                         |
+--------+------+---------------------------------------------+
|[3]     |F     |{2021-01-30 00:00:00 -> [3]}                 |
|[7]     |F     |{2021-02-20 00:00:00 -> [7, 2]}              |
|[2]     |F     |{2021-02-28 00:00:00 -> [7, 2]}              |
|[1, 2]  |M     |{2021-01-01 00:00:00 -> [1, 2, 11, 13, 4, 5]}|
|[11, 13]|M     |{2021-01-10 00:00:00 -> [1, 2, 11, 13, 4, 5]}|
|[4, 5]  |M     |{2021-01-15 00:00:00 -> [1, 2, 11, 13, 4, 5]}|
|[6]     |M     |{2021-02-20 00:00:00 -> [6]}                 |
+--------+------+---------------------------------------------+


text:
Q: How to transform dictionary in python How can modify the object A to look like Object B:
Obeject A:
{
  'first_name': {'
     'required': false,
     'enabled': false
  '},
  'last_name': {'
     'required': false,
     'enabled': false
  '}
}

Object(I want it look like this):
[
  {
   'name': first_name,
   'required': true,
   'enamble':false
  },
{
   'name': last_name,
   'required': true,
   'enamble':false
  }
]

A: A very simple thing to do is to use a for loop to iterate through the dictionary. When you do for variable in dict_A, what happens is that the variable iterates through all the keys in dict_A. So then you could use code that looks like
for key in dict_A:
    # the piece of code to change to dict_B,
    # where you use dict_A[key] to access the value for each
    # key stored in dict_A

Edit - And as a lot of comments have correctly pointed out, the dict_A in the question does not look like valid Python code.

A: You can use:
# Python >= 3.5
d = [{**{'name': k}, **v} for k, v in d.items()]

# Python >= 3.9
d = [{'name': k} | v for k, v in d.items()]
print(d)

# Output
[{'name': 'first_name', 'required': False, 'enabled': False},
 {'name': 'last_name', 'required': False, 'enabled': False}]

Input data:
>>> d
{'first_name': {'required': False, 'enabled': False},
 'last_name': {'required': False, 'enabled': False}}

A: Try something like this
Code
import json
b = {
  'first_name': {
     'required': "false",
     'enabled': "false"
  },
  'last_name': {
     'required': "false",
     'enabled': "false"
  }
}

output = []
for i in b:
  op = {}
  z = [d for d in b[i]]
  d = zip(z,[b[i][g] for g in z])
  op["name"] = i
  for x in d:
    op[x[0]] = x[1]

  output.append(op)

x = json.dumps(output, indent = 2)
print(x)

Output
[
  {
    "required": "false",
    "enabled": "false",
    "name": "first_name"
  },
  {
    "required": "false",
    "enabled": "false",
    "name": "last_name"
  }
]


text:
Q: Admob Native Expess Ads blocks while scrolling in UICollectionView I currently have an Admob Native Express Ad (GADNativeExpressAdView) configured in a UICollectionViewCell.

*

*I used the storyboard to set it up by adding an empty view and assigning the GADNativeExpressAdView class to it.

*Everything loads up fine and an ad appears every 10 cells for example.

Problem: The first time the user opens the app and starts scrolling down the list of cells, when they reach the Ad cell, the scrolling blocks until the Native Ad is "built". Once it's done, scrolling continues. The ad then might take a moment (1-2 seconds) to load up the ad request.

*

*The loading request does not seem to be the culprit.

*I've also setup the ad programmatically, and it seems to mainly hang when I add the ad view as a subview of the cell the first time.

Let's say an ad should appear in cell #20, #30, etc, the second time (and every other one after that), the scrolling is uninterrupted. It only happens for the first one.
Any ideas on how to fix this would be really appreciated. Is this a problem with GADNativeExpressAdView itself?
Thank you.
AdCollectionViewCell.Swift
class AdCollectionViewCell: UICollectionViewCell {

    @IBOutlet var intercellBanner: GADNativeExpressAdView!

    override func awakeFromNib() {
        super.awakeFromNib()

        let request = GADRequest()
        request.testDevices = [kGADSimulatorID]
        self.intercellBanner.loadRequest(request)
    }

    override func prepareForReuse() {
        super.prepareForReuse()

        let request = GADRequest()
        request.testDevices = [kGADSimulatorID]
        self.intercellBanner.loadRequest(request)

    }
}

A: I wrapped line where request is loading with GCD async block and it looks like this approach solved scrolling issue.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    view.nativeExpressAdView.loadRequest(request)
})

A: There is an open issue in the GitHub repo, no answers yet :S
https://github.com/googleads/googleads-mobile-ios-examples/issues/24


text:
Q: Firebase simple login for authentication with the REST api I want to create a web app with AngularJS and Firebase but only some parts of the app need the 3-way binding Firebase offers. The other parts would work just finding binding only once to the current data without constantly updating it. In other words, a normal REST API would suffice.
The Thinkster AngularJS-Firebase tutorial shows how to use $resource to access this Firebase REST API. This approach does not require to open a concurrent connection to your Firebase and only fetches the current data without updating:
app.factory('Post', function ($resource) {

return $resource('https://FIREBASE-URL.firebaseIO.com/posts/:id.json');
});

Would it be possible to do these kind of requests after logging in to Firebase using the simple login service, but without keeping a Firebase connection open. For example:
//Does this already open a connection to FireBase?
var ref = new Firebase('https://FIREBASE-URL.firebaseIO.com');

//Login to FireBase
ref.authWithPassword({
  email    : "bobtony@firebase.com",
  password : "correcthorsebatterystaple"
}, function(error, authData) {
  if (error === null) {
    // Can we close the connection now while still leaving the user authenticated?
    Firebase.goOffline();
  } else {
    console.log("Error authenticating user:", error);
  }
});

If I would make requests to the REST API now:

*

*Will Firebase recognize the auth variable?

*Does the authorization stay valid?

*Can I use this method to prevent the connection to stay open and use Firebase as a normal REST API?

To make things a little bit more clear:

*

*I do not need a real-time backend, a simple REST backend will suffice

*I would like to use Firebase because it provides easy authentication methods

*If possible, I want to avoid using the Firebase SDK and only interact with my Firebase using the REST API

In other words my question would be:
Is it possible to authenticate users client side to use the security rules of Firebase while using Firebase as a REST API without using the SDK?

A: This is a case of extremely premature optimization, and it's also detrimental more than helpful.
There's no advantage to using the REST API and SDK in tandem. If you already have the SDK downloaded and have already established a socket connection, it's going to be more efficient, cheaper, and less complex to re-use the existing connection. The SDK is also heavily optimized over the REST API and much better at dealing with temporary disconnections and networking errors. By utilizing the REST API, you'll essentially be making your life more difficult for zero gain.
If your goal is to download data exactly once without listening for updates, simply use once in place of on.
app.controller('ctrl', function($scope) {
  var ref = new Firebase('https://FIREBASE-URL.firebaseIO.com');
  ref.once('value', function(snap) {
     $scope.data = snap.val();
     $scope.apply();
  });
});

Creating a ref() does not immediately create a connection. The first time you authenticate, write, or read data, the connection is established.
Authenticating via the SDK does not help at all for REST queries. You need to pass ?auth=TOKEN into the URL, where TOKEN is an auth token that you create manually (not at all connected to the SDK simple login auth event).
If you don't want real-time capabilities, don't use the SDK at all. Simply utilize $http or $resource and connect via the .json URLs.


text:
Q: Getting response()->json() as undefined in console.log() in Laravel 5.8 I was working on overtrue/laravel-follow package and was using ajax call to follow a user and unfollow.
scripts file includes:
$(document).ready(function(){
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $('.btn-follow').click(function() {
        let user_id = $(this).data('id');
        let object = $(this);

        $.ajax({
            type: 'POST',
            url: '/follow',
            data: { user_id: user_id },
            dataType: 'json',
            success: function(data) {
                console.log(data.success);
            },
        });
    });
});

User Controller Follow method:
public function follow(Request $request)
    {
        $authUser = Auth::user();
        $user = User::findOrFail($request->user_id);

        if ($authUser !== null && $authUser instanceof User) {
            $response = $authUser->toggleFollow($user);
            return response()->json(['success' => $response]);
        }
    }

Routes:
Route::post('/follow', 'UserController@follow')->name('user.follow');

I'm getting undefined object in the console and no object with attached and detached.
What is the problem
PS: It is surprising that method is still working and follow unfollow is working behind the scene


text:
Q: Connections and metrics on Riemannian manifolds In a lecture on connections it was claimed that a manifold "attains a shape" when it is equipped with a connection while there were no mentions of a metric.
Is it correct to intuitively think that the connection determines the "shape" via how tangent spaces are "connected" or equivalently a rule how tangent vectors are moved in parallel manner between such spaces, while the metric only determines length of the same tangent vectors(and hence any curve).
And therefore the metric structure and connection structure is completely independent in general, i.e two completely separate things, unless your connection is defined in terms of the metric by kind of brute force as in the Levi-Cevita case, which is a very special case yet very meaningful.
Here's a link to the lecture https://www.youtube.com/watch?v=2eVWUdcI2ho. The discussion starts at around 5:30 and lasts until about 9:00.

A: This statement is only meant to provide intuition, since the notion of "shape" is undefined. A (Riemannian) metric structure and a connection are different things indeed, which is quite obvious once you look at their definitions. Few things to remember:

*

*An (affine) connection on a manifold need not preserve any Riemannian metric.

*Two different connections can correspond to the same Riemannian metrics.

*Two different Riemannian metrics can have the same Levi-Civita connection.

*An affine connection does determine a curvature tensor
$$
(X,Y,Z)\mapsto R(X,Y)Z,
$$
but in order to convert such tensors into functions (on the manifold or on some bundles over the manifold) you need an extra piece of data, which is usually taken to be a Riemannian (or semi-Riemannian) metric.

*There are connections on much more general bundles over manifolds (for instance, a bundle over a surface whose fibers are again surfaces); such connections, at the first glance, do not at all look like connections which are discussed in the lecture.
Edit. On the second thought, one way to interpret the notion of "shape" (say, for surfaces) is that "shape refers to the sign of curvature" (at a point or on some open subset). If your surface is (locally) isometrically embedded in $E^3$ then the sign of the curvature determines if the surface (locally) is "ellipsoidal-like" or "saddle-like", which one may think of as the shape of the surface. One can prove that the sign of the Gaussian curvature (say, at a point) is determined by the Levi-Civita connection. More precisely, if two metrics have the same connection, then they have the same sign of curvature. At the same time, a connection cannot determine the magnitude of the curvature. One can see this by multiplying the metric by a positive constant: Connection does not change, but the curvature does (unless it is zero, of course).
One can prove a similar statement about sectional curvature (in higher dimensions). In many ways, sign of the curvature is more important than the magnitude.


text:
Q: Revision control on a machine without root privileges I am using a computational server (Scientific Linux) that I don't have root privileges on. I want to keep track of changes I make to my code and any forking I do.
Subversion looks like a natural fit for this but I don't think I can set it up without root privileges. Does anyone know any simple revision control scripts I can use?
Edit:
Judging by the answer, I conclude that I wasn't clear about something. I don't want to upload my code to any other server. I simply want to copy it locally to a dedicated folder (or something similar). We do an hourly backup of the data on that machine.

A: Also Subversion can easily be used locally without root privileges. First create a local repository with
svnadmin create <repo_dir>

and then do a checkout with
svn checkout file:///<path_to_repo_dir> <checkout_dir>

Works like a charm without requireing any special privileges. You could even access the repository over svn+ssh if you have SSH access to that machine via
svn checkout svn+ssh://user@host/<path_to_repo_dir> <checkout_dir>

A: Most popular distributed version control systems can work without root privileges. The repository is entirely self-contained.
For example, the only command needed to convert the current directory into a Git or Hg (aka Mercurial) repository is git init and hg init respectively. All data stays within the same directory, although it's very easy to push to another server over SSH.

If the program is not installed yet, doing it yourself is possible – just download the source code, compile, and install somewhere in your home directory (for example, ~/usr or ~/.local). This works very well with Git; I have not tested yet with Hg.
Prepare (adjust $HOME/usr if wanted):
local="$HOME/usr"
export PATH="$local/bin:$PATH"

Install Git:
mkdir -p "$local"
wget https://git-core.googlecode.com/files/git-1.7.8.tar.gz -O - | tar xz
cd git-1.7.8
./configure --prefix "$local" && make && make install

To use, set PATH again as in the "Prepare" step.

A: Another DVCS worth to be considered (of course it will work as simple user) is fossil.
It has a ton of tempting features:

*

*single small-sized binary with no external dependencies

*works on all mainstream operating systems

*built-in web interface, tickets, wiki, blog (it's known as "github in a box")

*its "dad" is D. Richard Hipp - the author of sqlite


text:
Q: Changing prompts for loop I'm doing an exercise where I have to ask the user for 5 integer inputs and then print the total of the 5 numbers. I have to do this using a for loop. I know how to do this with a while loop but we're currently learning about for loops.
I have written the following code:
num = 0
count = 0

for i in range(num):
    while count < 5:
        num = getInteger("Please enter a number: ", format(num + 1))
        count += 1
        print(num)
    total = num + num
print(total)

Though I get so many errors because frankly, I don't know what I'm doing.

A: Try this:
total=0
for i in range(5):
   num = int(input(f"Please enter number {i+1}: "))
   total+=num
print(total)


text:
Q: HTML/Javascript - setTimeout issues My index.html:
<!DOCTYPE html>

<meta charset="UTF-8">

Hi, I already did some searches, but nothing satisfactory to fix the problem..
I would like some solution for this:

The onmouseover event is executed, and 1 second later, the
  onmouseout event is also called and setTime that was executed by the
  over function continues to count, reproducing a visual bug.

Is there any way to break the setTimer called by onmouseover event, when the onmouseout event is called?

A: Use clearTimeout

You can see a working example at w3wchools.com


text:
Q: Is it efficient to use UIBezierPath and CAShapeLayer to make curved edges on IOS? I have to make only top two corners curved for UILabel, so I have done like this after little exploration..
UIBezierPath *maskPath;

maskPath = [UIBezierPath bezierPathWithRoundedRect:label.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(8.0, 8.0)];

CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = label.bounds;
maskLayer.path = maskPath.CGPath;
label.layer.mask = maskLayer;

Is it efficient to do? In one forum they mentioned don't use this more than once for efficient purpose. If so what should I do? I need in few places. Thanx.

A: It's perfectly fine to do this - it's no more resource-intensive than creating a bitmap of comparable size and drawing a few curves on it. When they say not to use it more than once, they mean don't use it more than once within the lifespan of the object (i.e. call it just once when you load it). You could use this for every label in your app (in an override of initWithFrame:, for example) and you'd be fine.


text:
Q: Adding a progress bar to an existing Symfony2 entity form I've built a form which sends a video file to the server.
My client now wants a progress bar for some nicer UI.
Is it possible to drop in a JS script that can use the current form with no back end changes, or do I have to add some extra routes/methods for it to work?
This is what I've attempted.
Drop in the https://github.com/blueimp/jQuery-File-Upload plugin. This looks great, but I can't bind the form's submit button to the plugin, so the form just submits 'normally' and the plugin is not run (although the plugin is initializing OK).
I think the plugin wants to send the file on its own, but I need the whole form to be submitted.
Thanks in advance.

A: Try this bundle. It give you integration with really good amount of plugins and you can choose one of them.
Anyway if you want progress bar, file must be send via ajax. You can upload file first and then submit form.


text:
Q: Program that finds and prints all prime numbers 1-100 to a file I have a homework assignment and I'm stuck. the program compiles fine but when I run it, it only prints the number 1 into the file and ends. I've googled this problem dozens of times and all solutions involve try and catch statements which my professor will not accept because we haven't learned it in class yet.
Here is my code:
`import java.util.Scanner;
import java.io.*;
public class K_Topple_Chap5_Prime_NumList_Redo
{
  public static void main(String[] args) throws IOException
  {
    String filename; //filename used to open file
    boolean isPrime;
    int num1 = 1;

    Scanner keyboard = new Scanner(System.in); //needed for scanner class

    System.out.print("Enter a directory for a file: "); //asks user for name
of file
     filename = keyboard.nextLine(); //sets input equal to filename

    File file = new File(filename); //sets input filename = file variable
    Scanner inputFile = new Scanner(file); //opens file
    PrintWriter printWriter = new PrintWriter(file); //creates printwriter
for file

    for(num1 = 1; num1 <= 100; num1++) //for statement that runs 98 times to
test every number between 1-100 for primality
    {
      isPrime = isPrime(num1); //calls isprime method and tests primality
and sets isPrime to boolean value
      if(isPrime == true) //if isPrime is true then it prints that number to
the file
      {
        printWriter.println(num1 + " "); //prints num1 to file
      }
    }
    System.out.println("Done."); //when the for statement is done running it
prints done
    printWriter.close (); //closes file
  }

  /**This method tests if a number is prime
    * @param num1 holds the current number being tested
    * @return returns true or false if number is prime or not
    *
   */
  public static boolean isPrime(double num1) //isprime method used to test
if a number is prime
  {
    int i;
    for (i = 2; i <= num1; i++)
     {
      if (num1 % i == 0)
       {
        return false;
       }
     }
    return true;
  }
}
`

I tried putting comments in to make it easier for people to understand, any help is appreciated. Thanks.

A: Since every number is divisible by the number itself, you are getting false from the function. Just change the loop condition from i <= num1 to i < num1.
for (i = 2; i < num1; i++) {
    if (num1 % i == 0) {
        return false;
    }
}

A: this will return the correct flag..u can maintain a flag and based on that flag return true or false.
int i,flag=0;
for (i = 2; i <= num1/2; i++)
 {
  if (num1 % i == 0)
   {
     flag=1;
     return true;
   }
 }
if(flag==0)
return flase;


text:
Q: Force via "exchange particles" or "via field" More or less I have come across two concepts to explain non contact forces:

*

*FIELD CONCEPT: modification of space by the source which in turn produces force on the other (That is in my classroom course)

*EXCHANGE FORCE : which I recently read in wikipedia ( Infact just before writing this post)
After reading the concepts, it is quite expected that one would try to correlate them as both are true in their explanations (as far as I know, do let me know if it is the other way )
I was thinking that is it so that the source continuously emits the exchange particles (photon for em, gluon for quarks etc. ) to create the field around it which interacts with the other one.
I know it would come under the banner "generation of field" but the idea links both of them and as far as is the concern of description of generation of field my book is quite vague in that (high school)- it simply says that "source modifies the space around it"
But certain doubts arise in my mind ;

*

*Don't you find such creation quite weird that source continuously emits the exchange particles

*Secondly, continuous emission will create some impact over the source
Then, how are field generated?

A: Quantum fields interact in a quantum way ("digital" instaed of "analog"). Two charged particles both have quantum fields. These fields are NOT the electromagnetic field. Quantum fields are not real in the sense that they cannot be directly measured or observed. They represent the probability of the interaction. The fields don't constantly "feel" each other, do not constantly attract, repulse or interact in any way. Then at some random point (with the probablity defined by the fields) a momentary interaction happens, after which the fields again do not "feel" each other. This interaction tranfers energy, momentum, and certain quantum numbers (depending on the type of interaction this could be charge, "color", etc.). The values transferred by the interaction (except for the mass) look like they could belong to a particle, but this particle does not actually exist. Therefore, for simplicity, sometimes the interaction is viewed as an exchange of a virtual particle, where "virtual" as opposed to "real" emphasizes that this particle does not exist, but is just a way to combine the transferred values into a single hypothetical object.
Referring to your question, this interaction (or a "virtual particle", if you will) is an electromagnetic interaction and a part of the electromagnetic field. When you have many of such interactions, their quantum ("digital") nature averages out and you see a continuous ("analog") classical electromagnetic field. In the sense described above you can hypothetically say that the electromagnetic field consists of "virtual photons", as long as you remember that they don't actually exist, but are only a convenient way to decsribe how the quantum fields interact.
As you hopefully can see, virtual photons are not emitted constantly, but only "on demand" when the quantum fields of two particles "decide" to interact at a random point, but on average based on the probabilities defined by the intencity of the fields. Once again to emphasize, the quantum fields do not directly represent the electromagnetic field. The electromagnetic field is represented by a statistical sum of a large number of interactions between the quantum fields. And in a simplified way these interactions sometimes can be viewed as exchanges of "virtual particles", as long as we remember that they are not real and therefore do not actually exist. So in this view, one could say that the electromagnetic field consists of virtual photons as hypothetical objects representing quantum interactions between the quantum fields.
In contrast with the electromagnetic field, the electromagnetic wave can be viewed as consisting of real photons, but this is a different topic.


text:
Q: Setkey() and unique() for data.table in r 3.4.0 returns all rows in the data table not just the unique ones I recently downloaded this version of R:
R version 3.4.0 (2017-04-21) -- "You Stupid Darkness"
Copyright (C) 2017 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin15.6.0 (64-bit)library(data.table)
The behavior for setkey() and unique() on data tables has changed. Previous versions of R (3.3.3) would not return 7 rows in the following example since there are two rows with V2=="D".
This seems like a big change - is this intended?
library(data.table)
dt <- data.table(
+   V1=LETTERS[c(1,1,1,1,2,3,3,5,7,1)],
+   V2=LETTERS[c(2,3,4,2,1,4,4,6,7,2)]
+ )
setkey(dt, "V2")
unique(dt)

   V1 V2
1:  B  A
2:  A  B
3:  A  C
4:  A  D
5:  C  D
6:  E  F
7:  G  G
str(dt)
Classes 'data.table' and 'data.frame':  10 obs. of  2 variables:
$ V1: chr  "B" "A" "A" "A" ...
$ V2: chr  "A" "B" "B" "B" ...
- attr(*, ".internal.selfref")=<externalptr>
- attr(*, "sorted")= chr "V2"


text:
Q: Single table db architecture with AWS Amplify By default AWS Amplify transformers creating tables per each graphql type.
But according DynamoDB documentation it's best practice to

*

*Keep tables few as possible

*Keep often queried together entries within a same table

I have an impression Amplify way of doing things stays in contradiction with the statement above.
I am new to both NoSQL and Amplify
Can someone suggest ways to address those issues?

A: I think we're in a bit of a transition or gray area here.  I'm very new to Amplify and have been investigating moving to a single-table design as there are sources (below) that indicate that it's always be there but you'd have to write everything in VTL templates.  But in 2020 they released direct lambda resolver support: https://youtu.be/EOQqi6Yun7g?t=960 (clip)
However, it seems like you lose access to the @auth directive (and probably others because you're no longer going to use @model) along with a lot of the nice out-of-the-box functionality that's available with Amplify's multi-table approach.
At this point, being that I'm developing a new app, I'm going to stick with the default multi-table design to hasten the process of getting the app functional.
Trying to implement the single-table design seems to go against what the Amplify team recommends and requires more manual work. You'd have to manually create custom lambda functions (AppSync) and code queries to DynamoDb for each data access element and manage authorization through some other means which I'm not aware of at this time.  Maybe someone can chime in here...

Single table vs multi table info
Using Amplify with single table:
https://youtu.be/EOQqi6Yun7g
Single vs Multi Clip:

*

*https://youtu.be/1WF_wped808?t=1251 (clip)

*https://www.alexdebrie.com/posts/dynamodb-single-table/ (towards bottom)

*https://youtu.be/EOQqi6Yun7g?t=1288 (clip)

Example single table design by Alex Debrie:
https://gist.github.com/dabit3/96dc51e688b18a7d40fc534331758c56
More Discussion:
https://stackoverflow.com/a/56438716/1956540
Basic Setup steps
I setup a single table by following the below instructions.  Again, you don't use @models for this. Also, I think you have to include a type query {} in your schema for it to compile, but I could be wrong here.
So the basic steps are:

*

*Create a single table (amplify add storage)

*amplify push

*Create your schema in the schema.graphql file.

*Create supporting lambda function (amplify add function)

*

*Note: if you look at the example here, I believe you can create an entry point to routes to all other methods: https://gist.github.com/dabit3/96dc51e688b18a7d40fc534331758c56#lambda

*Add the DynamoDb query code in the function.

*amplify push

Complete steps for Setting up a single Table:
https://catalog.us-east-1.prod.workshops.aws/workshops/53b10bf8-2271-4ab4-bfd2-39e878a90dc8/en-US/lab2/1-vtl (both "Connecting to an existing DynamoDB table" and "Direct Lambda Resolver" steps)

Not trying to be negative about Amplify, it is awesome, I love what they are doing with this product.  I just think it's very new to everyone and I'm hoping this post is no longer valid next year and we continue to see great progress from the team.


text:
Q: laravel TokenMismatchException in ajax request i'm using resource group and use this filter to resolve TokenMismatchException problem:
Route::filter('csrf', function($route, $request) {
    if (strtoupper($request -> getMethod()) === 'GET') {
        return;
        // get requests are not CSRF protected
    }

    $token = $request -> ajax() ? $request -> header('X-CSRF-Token') : Input::get('_token');

    if (Session::token() != $token) {
        throw new Illuminate\Session\TokenMismatchException;
    }
});

my route :
Route::group(array('prefix'=> 'admin', 'before' => 'csrf'), function(){
    Route::resource('profile' , 'ProfileController', array('as'=>'profile') );
});

now. i get error to Ajax requests such as this code:

ERROR:
{"error":{"type":"Illuminate\\Session\\TokenMismatchException","message":"","file":"\/var\/www\/alachiq\/app\/filters.php","line":83}}

i think i'm must be sent _token in $.post. but i can not get input tag with name attribute. iget this error:
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.

A: There is a tip in the Laravel docs on how to do this.  This might not have been available at the time of the question, but I thought I would update it with a answer.
http://laravel.com/docs/master/routing#csrf-x-csrf-token
I have tested the meta tag method from the documentation and got it working.  Add the following meta tag into your global template
<meta name="csrf-token" content="{{ csrf_token() }}">

Add this JavaScript that sets defaults for all ajax request in jQuery.  Preferably in a js file that is included across your app.
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
})

This token can exist in the request header or the form.  This populates it into the request header of every ajax request.

A: You can as well add the url thats giving you the error inside the VerifyCsrfToken.php file in the
protected $except = [
    //
]

Let's say your route is post. You can just add in like this
protected $except = ['post',
    //
];`...

Hope this helps others.

A:

  <title>Ajax Example</title>
      <meta name="csrf-token" content="<?php echo csrf_token() ?>" />

This message will be replaced using Ajax.
     Click the button to replace the message.

  <?php
     echo Form::button('Replace Message',['onClick'=>'getMessage()']);
  ?>

and VerifyCsrfToken.php file add this function
protected function tokensMatch($request)
{
    // If request is an ajax request, then check to see if token matches token provider in
    // the header. This way, we can use CSRF protection in ajax requests also.
    $token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');

    return $request->session()->token() == $token;
}

A: You have to insert a hidden input with the _token and later get that value as you do to get the other form fields in your ajax post.
<input type="hidden" name="_token" value="{{ csrf_token() }}" />

An another method,
On your view you can set an object with the _token

and later on your ajax call you can get the _token from the object like this:
var token = _globalObj._token;

and include it on your ajax post.

A: Just do simple thing as i have shown in following code,
    $.ajax({
        type: 'POST',
        url: 'your-post-route-url',
        data: {
            "_token": "{{ csrf_token() }}",
            "form_data": $('#Form').serialize(),
        },
        success: function (data) {
            console.log(data);
        },
        error: function (reject) {
            console.log(reject);
        }
    });

I hope this one is the easiest way to solve this problem without any hidden field and it works for me in laravel 5.4 version :)
Hope it helps.


text:
Q: Implementing JsonSerializable by a Pure Enum According to the PHP manual

If a Pure Enum is serialized to JSON, an error will be thrown. If a Backed Enum is serialized to JSON, it will be represented by its value scalar only, in the appropriate type. The behavior of both may be overridden by implementing JsonSerializable

Let's try to implement JsonSerializable
enum Suit implements JsonSerializable
{
    case Hearts;
    case Diamonds;
    case Clubs;
    case Spades;

    public function jsonSerialize(): array {
        return [1, 2, 3, 4];
    }
}

echo json_encode(Suit::cases());

It prints:
[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]

Why [1,2,3,4] is duplicated 4 times?
How to control each case in an enum during serialization?

A: In an enum every case is an object instance of that enum. That means JsonSerializable is implemented by each one of them. Suit::cases()  will return a packed array of all cases in an enumeration (a.k.a objects) so jsonSerialize method will be called on each one of them hence the duplicated arrays.
How to control each case in an enum during serialization?
We can simply use a match expression
public function jsonSerialize(): string {
    return match($this) {
        Suit::Hearts => 'H',
        Suit::Diamonds => 'D',
        Suit::Clubs => 'C',
        Suit::Spades => 'S'
    };
}

It prints:
["H","D","C","S"]


text:
Q: "Condition expected" error when trying to nest CASE WHEN THEN statements The code before my changes (working perfectly well):
CASE WHEN b.EPIdentifier IS NOT NULL THEN b.EndTime

My changes when trying to implement some further nesting CASE WHEN THEN logic:
CASE WHEN b.EPIdentifier IS NOT NULL THEN
    CASE WHEN b.CancelEndTime IS NOT NULL THEN
        b.CancelEndTime
    ELSE CASE WHEN b.ExtendedEndDate IS NOT NULL THEN
        b.ExtendedEndDate
    ELSE CASE WHEN b.EndTime IS NOT NULL THEN
        b.EndTime
ELSE a.EndDate END EndDate

I get an error on the very last EndDate:

an expression of non-boolean type specified in a context where a condition is expected

I can't figure out why I'm getting the error. I've tried to put AS EndDate instead but I still get the same error. Have I messed something up with the nesting? I can't spot anything.

A: You have to put an END on every CASE WHEN. Your expression should be something like this:
CASE WHEN b.EPIdentifier IS NOT NULL THEN
    CASE WHEN b.CancelEndTime IS NOT NULL THEN b.CancelEndTime
    ELSE CASE WHEN b.ExtendedEndDate IS NOT NULL THEN b.ExtendedEndDate
         ELSE CASE WHEN b.EndTime IS NOT NULL THEN b.EndTime END
         END
    END
ELSE a.EndDate END EndDate

Anyway you can simplify your expression using COALESCE:
CASE WHEN b.EPIdentifier IS NOT NULL THEN COALESCE(b.CancelEndTime, b.ExtendedEndDate, b.EndTime)
ELSE a.EndDate END EndDate

From MSDN:

The COALESCE expression is a syntactic shortcut for the CASE expression. That is, the code COALESCE(expression1,...n) is rewritten by the query optimizer as the following CASE expression:

CASE

   WHEN (expression1 IS NOT NULL) THEN expression1
   WHEN (expression2 IS NOT NULL) THEN expression2
   ...
   ELSE expressionN
END

A:
END is the Part of CASE Statement, so you have to lookup for END.

SYNTAX FOR CASE Statement :
SQL CASE
Simple CASE expression:
CASE input_expression
     WHEN when_expression THEN result_expression [ ...n ]
     [ ELSE else_result_expression ]
END
Searched CASE expression:
CASE
     WHEN Boolean_expression THEN result_expression [ ...n ]
     [ ELSE else_result_expression ]
END


text:
Q: Override send() method in Request/Request.JSON to append defined data? My site makes use of ajax heavily for stuff like editing user details. I want to make an admin mode so that an admin can edit the user's details without having to log in as them (and so having to know their password.)
I plan to have all the user details pages on my site take the parameter id. If the page visitor is logged in as an admin, I want this id to be appended to the data of all ajax requests sent. So if the user is logged in as admin, I will inject some javascript into the page after the mootools library loads that forces the Request method to always carry this id when it makes requests.
How should I implement this?
This is the send method for the Request class:
send: function(options){
    if (!this.check(options)) return this;

    this.options.isSuccess = this.options.isSuccess || this.isSuccess;
    this.running = true;

    var type = typeOf(options);
    if (type == 'string' || type == 'element') options = {data: options};

    var old = this.options;
    options = Object.append({data: old.data, url: old.url, method: old.method}, options);
    var data = options.data, url = String(options.url), method = options.method.toLowerCase();

    switch (typeOf(data)){
        case 'element': data = document.id(data).toQueryString(); break;
        case 'object': case 'hash': data = Object.toQueryString(data);
    }

    //---------
    //LOOK HERE
    //---------
    if (this.options.format){
        var format = 'format=' + this.options.format;
        data = (data) ? format + '&' + data : format;
    }

    if (this.options.emulation && !['get', 'post'].contains(method)){
        var _method = '_method=' + method;
        data = (data) ? _method + '&' + data : _method;
        method = 'post';
    }

    if (this.options.urlEncoded && ['post', 'put'].contains(method)){
        var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
        this.headers['Content-type'] = 'application/x-www-form-urlencoded' + encoding;
    }

    if (!url) url = document.location.pathname;

    var trimPosition = url.lastIndexOf('/');
    if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition);

    if (this.options.noCache)
        url += (url.contains('?') ? '&' : '?') + String.uniqueID();

    if (data && method == 'get'){
        url += (url.contains('?') ? '&' : '?') + data;
        data = null;
    }

    var xhr = this.xhr;
    if (progressSupport){
        xhr.onloadstart = this.loadstart.bind(this);
        xhr.onprogress = this.progress.bind(this);
    }

    xhr.open(method.toUpperCase(), url, this.options.async, this.options.user, this.options.password);
    if (this.options.user && 'withCredentials' in xhr) xhr.withCredentials = true;

    xhr.onreadystatechange = this.onStateChange.bind(this);

    Object.each(this.headers, function(value, key){
        try {
            xhr.setRequestHeader(key, value);
        } catch (e){
            this.fireEvent('exception', [key, value]);
        }
    }, this);

    this.fireEvent('request');
    xhr.send(data);
    if (!this.options.async) this.onStateChange();
    if (this.options.timeout) this.timer = this.timeout.delay(this.options.timeout, this);
    return this;
}

At the place I have marked, the method seems to add some extra data to the requests. I thought that this would be a good place to add my code. I could overwrite the method to include something like this:
if (_USER_ID_TO_EDIT){
    var id= 'userIdToEdit=' + _USER_ID_TO_EDIT;
data = (data) ? id+ '&' + data : id;
}

However, this isn't a great solution because it means that if there is any changes to the send() function in the library, my code will become out of sync (I like to use the latest library version.)
Is there a better way to do this (and would my method here even work)? How can I add content to all requests sent by the Request class without changing ~20 .js files and ~100 uses of this class elsewhere on my site?

A: erm, I would question how trustworthy this practice would be but in any case, you can just use a special instance of Request for your admin:
Request.admin = new Class({

    Extends: Request,

    initialize: function(options) {
       this.parent(options);
    },

    send: function(options) {
        // example, add to the data being sent admin id and a delay
        options = Object.merge({
            data: {
                adminid: "foo",
                delay: 5 // testing with 5 sec delay
            }
        }, options || this.options);
        this.parent(options);
    }

});

new Request.admin({
    url: '/echo/html/',
    data: {
        html: "
original data here. foobar
"
    },
    method: 'post',
    onComplete: function() {
        document.id('target').set("html", this.response.text);
    }
}).send();

http://jsfiddle.net/dimitar/x2pBu/
I would consider this the better practice. You'd also need to override the .get method.
Another solution is to change the Request prototype itself by refactoring it, not editing it directly - you can use Class.refactor from mootools-more or Request.implement({send: ... }); so all subclasses of Request benefit from it (Request.HTML and Request.JSON and Request.Queue etc).
You can even do var orig = Request.prototype.send; Request.prototype.send = function() {... something to options; orig.call(this, options); } etc etc.
Downside to this kind of change is that you get unexpected behavior in your Request class (i.e. a mootools dev that expects certain things to happen will get caught out, data will go out w/o them knowing about it, validators may fail, etc etc). It may be difficult to debug. Having it as an implicit extended class makes sense from maintenance standpoint also, minimal abstraction.
don't worry too much about future compatibility - mootools 2.0 (aka MILK) will go the AMD way and old mootools code will be obsolete from compatibility standpoint, though the API will remain). There probably won't be many more releases in the 1.4 branch.


text:
Q: Getting 'LogicException: No such property: session' when i run phpunit test case in command prompt I was trying to run a phpunit test case of a controller. but am getting saying that
1) DefinerControllerTestCase::test_insertImageDetails
LogicException: No such property: session
/var/www/html/application/tests/_ci_phpunit_test/CIPHPUnitTestCase.php:44
/var/www/html/application/tests/controllers/DefinerControllerTestCase.php:33
My codegeniter verrsion is 3.1 and php unit version is 5.5.0
Here is my controller code
class Definer extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        date_default_timezone_set('Asia/Kolkata');
        $this->load->model("definer_model");
    }
    public function index()
    {

    }
    public function insertImageDetails()
    {
        $details['newImageName']=$this->session->userdata('newImageName');
        $data['imageOSName']=$this->session->userdata('imageOSName');
        $data['ImageReceipes']=$this->session->userdata("ImageReceipes");
        $data['imageOthers']=$this->session->userdata('imageOthers');
        $details['requirement']=json_encode($data);
        $details['defined_by_user']=$this->session->userdata('user_id');
        $details['defined_by_role']=$this->session->userdata('user_role');
        $details['date']=date('Y-m-d H:i:s');
        $details['status']='Y';
        $this->definer_model->addImageDetails($details);
        redirect(site_url('Definer/AddNewImage'));

    }

}

The test case code is here
class DefinerControllerTestCase extends TestCase
{
  public function __construct(){
  parent::__construct();

 $this->definer = new Definer();
 }

 public function test_insertImageDetails()
 {
 $_SESSION["newImageName"] ='TestSample';
     $this->session->set_userdata('newImageName', 'TestSample');
     $this->session->set_userdata('imageOSName', 'TestSample');
     $this->session->set_userdata('ImageReceipes', 'TestSample');
     $this->session->set_userdata('user_id', 'TestSample');
     $this->session->set_userdata('user_role', 'TestSample');
     $this->session->set_userdata('imageOthers', 'TestSample');
     $output = $this->request('GET', ['Definer', 'insertImageDetails']);
  if($output != "")
  {
   $this->assertContains('<title>Golden Image Managament System Dashboard</title>', $output);
  }
 }
}

Please help me on this....

A: i solved this issue by this following code.
public function test_insertImageDetails()
{
$this->request->setCallable(
function ($CI) {
$CI->session->newImageName = 'TestSample';
$CI->session->imageOSName = 'TestSample';
$CI->session->ImageReceipes = 'TestSample';
$CI->session->user_id = 'TestSample';
$CI->session->user_role = 'TestSample';
$CI->session->imageOthers = 'TestSample';
}
);

$this->request('GET', ['Definer', 'insertImageDetails']);
$this->assertTrue(true);

}


text:
Q: How To Hide Warning About Not Having Sufficient Privilege To Access Visualforce Page? I've selectively granted access to a Visualforce page embedded in a record detail page for only specific users. I used a permission set to achieve this. Now that I can selectively grant permission to the page and fields involved, I'm having to see a big warning about not being able to access the Visualforce page for users not given the permission set.

If possible, I would like this warning to not be displayed so that the users who don't have permission to use the feature don't even know that it's hidden from them. How might this be achieved?

A: You could make the VF page accessible to all, but create a Custom Permission.  Assign the Custom Permission in the Permission Set which is assigned to users who should see the VF page.
Then, in your VF page, render the full VF page for users who have the Custom Permission, and render a blank page, or some friendly boilerplate to those users who do not have the Custom Permission.
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_variables_global_permission.htm


text:
Q: Continue Shopping Button to category of product in same store view or same parent category There are answers all over the internet of how to alter the 'Continue Shopping' button to the last category.
However none of them take into consideration that the product may be in multiple categories or store views.
I've tried numerous ways to filter the below snippet to get the last category from either the current store or from a specific parent category, but nothing seems to work .
Any suggestions on how to refine the results further?
<?php
    $lastProductAddedToCartId = Mage::getSingleton('checkout/session')->getLastAddedProductId();
    if($lastProductAddedToCartId) {
        $productCategoryIdsArray = Mage::getModel('catalog/product')->load($lastProductAddedToCartId)->getCategoryIds();
        $continueShoppingCategoryUrl = Mage::getModel('catalog/category')->load($productCategoryIdsArray[0])->getUrl();
    }
?>

Reference:
https://stackoverflow.com/questions/12222601/make-magento-continue-shopping-button-redirect-to-the-last-added-to-cart-produ

A: Another approach to looking up the categories a product has is to store the url of the category a customer has last viewed into the session. This follows the assumption that most users would go to a category page > product page > cart.
An example of how to store and retrieve the url would be to add this to your catalog/category/view.phtml template
$currentUrl = $this->helper('core/url')->getCurrentUrl();
$session = Mage::getSingleton("core/session",  array("name"=>"frontend"));
$session->setData("last_category", $currentUrl);

Then on the cart page template (checkout/cart.phtml) you can retrieve the url like so:
$session = Mage::getSingleton("core/session",  array("name"=>"frontend"));
$lastUrl = $session->getData("last_category");

You may also want to take into account if they never visited a category page & provide fallbacks such as you stated in the question of using one of the categories of a last added product, or simply sending them back to the home page or a featured category page.
Update:
To get the a category URL of the last added product from the same store you can compare the path to the root category ID of the store:
$lastProductAddedToCartId = Mage::getSingleton('checkout/session')->getLastAddedProductId();
$continueShoppingCategoryUrl = Mage::getBaseUrl();
if($lastProductAddedToCartId) {
    $productCategorys = Mage::getModel('catalog/product')->load($lastProductAddedToCartId)->getCategoryCollection();
    $rootCatId = Mage::app()->getStore()->getRootCategoryId();
    foreach ($productCategorys as $category) {
        $regex = "/^[0-9]+\/". $rootCatId . "\/[0-9]+/";
        if(preg_match($regex, $category->getPath())){
            $continueShoppingCategoryUrl = $category->getUrl();
            break;
        }
    }
}


text:
Q: FakeS3 and Paperclip (on Rails) is still defaulting to HTTPS in URLs I'm using the configuration from this page: http://codesthq.com/blog/2015/gratuitious-development-with-aws-s3-and-paperclip.html
I can upload files to the local FakeS3 server, but when I generate a URL it returns a https:// link not https:// and I can't find a configuration option that changes it. I figure since the upload is working correctly, this is more likely a paperclip issue?
Here's my configuration:
config/initializers/aws.rb:
AWS::Rails.load_yaml_config

config/initializers/paperclip.rb:
paperclip_defaults = Rails.application.config_for :paperclip
paperclip_defaults.symbolize_keys!

Paperclip::Attachment.default_options.merge! paperclip_defaults

config/aws.yml:
development: &development
  access_key_id:       "abc"
  secret_access_key:   "abc"
  s3_endpoint:         "localhost"
  s3_port:             10001
  s3_force_path_style: true
  use_ssl:             false

test: *development

production: &production
  access_key_id:     <%= ENV["AWS_ACCESS_KEY_ID"] %>
  secret_access_key: <%= ENV["AWS_SECRET_ACCESS_KEY"] %>

staging: *production

config/paperclip.yml:
development:
    storage:       :s3
    bucket:        "development"
    s3_host_name:  "localhost"
    url:           ":s3_alias_url"
    s3_host_alias: "localhost:10001/development"
    s3_protocol:   'http'

test:
    storage:       :s3
    bucket:        "test"
    s3_host_name:  "localhost"
    url:           ":s3_alias_url"
    s3_host_alias: "localhost:10001/test"
    s3_protocol:   'http'

production: &production
    storage: :s3
    bucket:  <%= ENV["S3_BUCKET_NAME"] %>
    url:     ":s3_domain_url"

staging: *production

Versions installed:
$ bundle list | grep paperclip
  * paperclip (4.3.6)

$ bundle list | grep aws
  * aws-sdk (2.3.7)
  * aws-sdk-core (2.3.7)
  * aws-sdk-resources (2.3.7)
  * aws-sdk-v1 (1.66.0)

A: Doh, I was over-riding s3_protocol in the model's attachment configuration!


text:
Q: Making it so the first time you run the app you have to put in a code that can only be used once In trying to make a app and the first time you run it you would need to put in a code thats 12 digits I would have maybe 10000 diffrent codes but when someone uses a code it can not be used again
PS: The app is for android

A: Think of it as a Login.
When the application is started, show the PIN request to the user.
Then, validate his PIN and save it (database, shared preferences, server etc.). Let's say you decide to save it locally in SQLite.
The next time he opens the App, check if there is a PIN in the database and validate it again, if everything is alright, start the next Activity.

A: 1) Put all the codes in a server-side database
2) In the app, let the user enter a code and send it to your server
3) Validate the code. If successful, remove that code and generate and return a unique accesstoken.
4) Store the accesstoken in the app and validate it with the server on subsequent app usage to gain access.


text:
Q: How did John Carter send the letters to his nephew? Supposedly, John Carter wrote all the happenings on Mars and about the talisman and his body in the tomb so that his nephew can send him back to Mars. But how did John Carter have the time to write the letters and capability to actually send them, knowing he was unconscious on Earth after he got sent back to Earth from Mars? Does this make sense? If so, please let me know. In the meantime, I'll be watching it again.

A: From Wikipedia:

 On their first night, Carter decides to stay forever on Mars and throws away his medallion. Seizing this opportunity, Shang banishes him back to Earth. Carter then embarks in a long quest, looking for clues of the Therns' presence on Earth and hoping to find one of their medallions; after several years he appears to die suddenly and asks for unusual funeral arrangements—consistent with his having found a medallion, since his return to Mars would leave his Earth body in a coma-like state. He makes Burroughs his protector, giving him clues about how to open the tomb. The story reverts to the present, where Burroughs runs back to Carter's tomb and opens it only to find it empty. Shang, in the form of a butler, suddenly appears, having followed Burroughs. But as he prepares to kill Burroughs, Carter appears and kills Shang. He then tells Burroughs that he never found a medallion; instead, he devised a scheme to lure Shang out of hiding. Carter takes his medallion, whispers the code, and is then transported back to Barsoom.

In other words,

 Carter was never in the tomb. The whole business with the letters to Burroughs was a setup to lure the Thern assassin out into the open in order to get his hands on the medallion and return to Barsoom.

A: john carter was zapped back to earth at the end of the movie, upon this he had ten years to search and write..to come up with the idea  to set up the final meeting. his journal showed drawings and told of his tale on barsoom, while he was digging as his lawyer said to "ned". then he was off to java and such.