text:
Q: Store static data in Android - custom resource? I'm new to Android development, and I've been playing around with it a bit.  I was trying to create a program that has a small database-like collection of never-changing data.  In C#, my currently best language, I'd use a List of a custom class and serialize that to an xml file, then read that into my application at runtime.  I found the /xml resource folder in Android, but I'm not sure how I would go about doing what I'm envisioning. What would be the best way to go about doing this?
The data will never need to change.  Example:
Blob   | A  | B
----------------
Blob 1 | 23 | 42
Blob 2 | 34 | 21

I know that's laid out like a table, but using a database doesn't really make sense to me because the data will never change, and I would need a way to store it to initially populate the database anyway.
So basically I'm looking for a way to store somewhat-complex static data in my application.  Any ideas?
EDIT: I also saw the /raw folder.  So I could store things in /res/raw or /res/xml.  But I'm not sure what would be the best way to store/parse the data...

A: I have used Simple for xml parsing in the past. I think it has the least amount of code if you know what to expect in xml, which in your case you do.
http://simple.sourceforge.net/

A: According to the doc, /xml is the way to go.
Providing Resources
xml/ Arbitrary XML files that can be read at run-time by calling
Resources.getXML().

Various XML configuration files must be saved here, such as a searchable configuration.
Documentation for getXML()
I also made a working example:

*

*the XML structure:
<?xml version="1.0" encoding="utf-8"?>
<quizquestions>
    <quizquestion>
        <header_image_src>ic_help_black_24dp</header_image_src>
        <question>What is the Capital of U.S.A.?</question>
        <input_type>Radio</input_type>
        <answer correct="false">New York City</answer>
        <answer correct="true">Washington D.C.</answer>
        <answer correct="false">Chicago</answer>
        <answer correct="false">Philadelphia</answer>
    </quizquestion>

    <quizquestion>
        <header_image_src>ic_help_black_24dp</header_image_src>
        <question>What is the family name of the famous dutch painter Vincent Willem van .... ?</question>
        <input_type>EditText</input_type>
        <answer correct="true">Gogh</answer>
    </quizquestion>
</quizquestions>

*the Java class to hold parsed data:
public class QuizQuestion {
    private int headerImageResId;
    private String question;
    private String inputType;
    private ArrayList<String> answers;
    private ArrayList<Boolean> answerIsCorrect;
    private ArrayList<Integer> correctAnswerIndexes;

    /**
     * constructor for QuizQuestion object
     */
    QuizQuestion() {
        headerImageResId = 0;
        question = null;
        inputType = null;
        answers = new ArrayList<>();
        answerIsCorrect = new ArrayList<>();
        correctAnswerIndexes = new ArrayList<>();
    }

    public void setHeaderImageResId(int headerImageResId) {
        this.headerImageResId = headerImageResId;
    }

    public int getHeaderImageResId() {
        return headerImageResId;
    }

    void setQuestion(String question) {
        this.question = question;
    }

    public String getQuestion() {
        return question;
    }

    void setInputType(String inputType) {
        this.inputType = inputType;
    }

    public String getInputType() {
        return inputType;
    }

    void addAnswer(String answer, boolean isCorrect)
    {
        if (isCorrect)
            correctAnswerIndexes.add(answers.size());
        answers.add(answer);
        answerIsCorrect.add(isCorrect);
    }

    public ArrayList<String> getAnswers() {
        return answers;
    }

    public String getAnswer(int index)
    {
        // check index to avoid out of bounds exception
        if (index < answers.size()) {
            return answers.get(index);
        }
        else
        {
            return null;
        }
    }

    public int size()
    {
        return answers.size();
    }

}

*the parser itself:
/**
 * Created by bivanbi on 2017.02.23..
 *
 * class to parse xml resource containing quiz data into ArrayList of QuizQuestion objects
 *
 */

public class QuizXmlParser {

    public static String lastErrorMessage = "";

    /**
     * static method to parse XML data into ArrayList of QuizQuestion objects
     * @param activity is the calling activity
     * @param xmlResourceId is the resource id of XML resource to be parsed
     * @return null if parse error is occurred or ArrayList of objects if successful
     * @throws XmlPullParserException
     * @throws IOException
     */
    public static ArrayList<QuizQuestion> parse(Activity activity, int xmlResourceId)
            throws XmlPullParserException, IOException
    {
        String logTag = QuizXmlParser.class.getSimpleName();
        Resources res = activity.getResources();
        XmlResourceParser quizDataXmlParser = res.getXml(R.xml.quiz_data);

        ArrayList<String> xmlTagStack = new ArrayList<>();
        ArrayList<QuizQuestion> quizQuestions = new ArrayList<>();

        QuizQuestion currentQuestion = null;

        boolean isCurrentAnswerCorrect = false;

        quizDataXmlParser.next();
        int eventType = quizDataXmlParser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT)
        {
            //  begin document
            if(eventType == XmlPullParser.START_DOCUMENT)
            {
                Log.d(logTag,"Begin Document");
            }
            //  begin tag
            else if(eventType == XmlPullParser.START_TAG)
            {
                String tagName = quizDataXmlParser.getName();
                xmlTagStack.add(tagName);
                Log.d(logTag,"Begin Tag "+tagName+", depth: "+xmlTagStack.size());
                Log.d(logTag,"Tag "+tagName+" has "+quizDataXmlParser.getAttributeCount()+" attribute(s)");

                // this is a beginning of a quiz question tag so create a new QuizQuestion object
                if (tagName.equals("quizquestion")){
                    currentQuestion = new QuizQuestion();
                }
                else if(tagName.equals("answer"))
                {
                    isCurrentAnswerCorrect = quizDataXmlParser.getAttributeBooleanValue(null,"correct",false);
                    if (isCurrentAnswerCorrect == true) {
                        Log.d(logTag, "Tag " + tagName + " has attribute correct = true");
                    }
                    else
                    {
                        Log.d(logTag, "Tag " + tagName + " has attribute correct = false");
                    }
                }
            }
            //  end tag
            else if(eventType == XmlPullParser.END_TAG)
            {
                String tagName = quizDataXmlParser.getName();
                if (xmlTagStack.size() < 1)
                {
                    lastErrorMessage = "Error 101: encountered END_TAG "+quizDataXmlParser.getName()+" while TagStack is empty";
                    Log.e(logTag, lastErrorMessage);
                    return null;
                }
                xmlTagStack.remove(xmlTagStack.size()-1);
                Log.d(logTag,"End Tag "+quizDataXmlParser.getName()+", depth: "+xmlTagStack.size());

                //  reached the end of a quizquestion definition, add it to the array
                if (tagName.equals("quizquestion")){
                    if (currentQuestion != null)
                        quizQuestions.add(currentQuestion);
                    currentQuestion = null;
                }
            }
            //  text between tag begin and end
            else if(eventType == XmlPullParser.TEXT)
            {
                String currentTag = xmlTagStack.get(xmlTagStack.size()-1);
                String text = quizDataXmlParser.getText();
                Log.d(logTag,"Text: "+text+", current tag: "+currentTag+", depth: "+xmlTagStack.size());

                if (currentQuestion == null) {
                    Log.e(logTag,"currentQuestion is not initialized! text: "+text+", current tag: "+currentTag+", depth: "+xmlTagStack.size());
                    continue;
                }

                if (currentTag.equals("header_image_src"))
                {
                    int drawableResourceId = activity.getResources().getIdentifier(text, "drawable", activity.getPackageName());
                    currentQuestion.setHeaderImageResId(drawableResourceId);
                }
                else if (currentTag.equals("question"))
                {
                    currentQuestion.setQuestion(text);
                }
                else if (currentTag.equals("answer"))
                {
                    currentQuestion.addAnswer(text, isCurrentAnswerCorrect);
                }
                else if (currentTag.equals("input_type"))
                {
                    currentQuestion.setInputType(text);
                }
                else
                {
                    Log.e(logTag,"Unexpected tag "+currentTag+" with text: "+text+", depth: "+xmlTagStack.size());
                }
            }
            eventType = quizDataXmlParser.next();
        }
        Log.d(logTag,"End Document");
        return quizQuestions;
    }

}

*and finally, calling the parser:
//  read quiz data from xml resource quiz_data
try {
    quizQuestions = QuizXmlParser.parse(this,R.xml.quiz_data);
    Log.d("Main","QuizQuestions: "+quizQuestions);

} catch (XmlPullParserException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    quizQuestions = null;
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    quizQuestions = null;
}

if (quizQuestions == null)
{
    Toast.makeText(this,"1001 Failed to parse Quiz XML, sorry", Toast.LENGTH_LONG).show();
    finish();
}

A: I think this is the BEST solution and i am already using this one to store Static-data in my every project.
For that...
You can do one thing, make one xml file namely "temp.xml" ..and store the data in temp.xml as follows:
  <?xml version="1.0" encoding="utf-8"?>
<rootelement1>

    <subelement> Blob 1
     <subsubelement> 23 </subsubelement>
     <subsubelement> 42 </subsubelement>
    </subelement>

    <subelement>Blob 2
    <subsubelement> 34 </subsubelement>
    <subsubelement> 21 </subsubelement>
    </subelement>

    </rootelement1>

and then use XML PullParser technique to parse data.
You can have coding samples of PullParsing technique on Example , refer this example for better idea.
Enjoy!!

A: The best way is to use the Android Resource Heirarchy.
In the res/values/ directory, you can store any number of key-value pairs for several basic data types.  In your app, you would refer to them using an autogenerated resource id (name based on your resource's key).  See the link above for more documentation and details.
Android also supports raw datafiles.  You could store your data in the file directory under res/raw/yourfile.dat
You you create your data in whatever text based format you want and then read it on activity startup using the resource access apis.


text:
Q: display all Letter Tile Possibilities I was doing the leetcode problem Letter Tile Possibilities. Which is where you print out every possible sequence of a given string.
I have a working solution below. However, as a followup, I wanted to try and display all the sequences, but am having issues. Given string "AAB", it prints the correct number of sequences, but repeats several of the sequences, seen here:

note: B is a repeated sequence, and the sequence ABA never appears.
var numTilePossibilities = function (tiles) {
    let map = getTileMap(tiles);
    return helper(map, "");
};

function helper(map, currString) {
    let sum = 0;
    for (let character in map) {
        if (map[character] !== 0) {
            sum++;
            currString += character;
            map[character] = map[character] - 1;
            sum += helper(map, currString);
            map[character] = map[character] + 1;
            console.log('completed string: ', currString);
            currString = '';
        }
    }
    return sum;
}

I have found other solutions that I have edited to print out out all the sequences, and it prints correct, for example this c# solution:

But can't determine the difference between the solutions that is causing the sequences to print correctly.
How can I print out every string sequence for this problem?

A: Your problem is in the way that you modify currString after printing it. If you want to undo the appending of character, you should remove that character instead of setting the string to an empty string:
currString = currString.substring(0, currString.length - 1);

Perhaps it is better to leave currString as it is and create a new string only for the inner scope:
function helper(map, currString) {
    let sum = 0;
    for (let character in map) {
        if (map[character] !== 0) {
            let newString = currString + character;
            sum++;

            map[character] = map[character] - 1;
            sum += helper(map, newString);
            map[character] = map[character] + 1;

            console.log('completed string: ', newString);
        }
    }

    return sum;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Point inside Pie Piece I am writing an application in WPF and have come accross a problem. As seen in the picture below, I need an algorithm which determines whether or not a specified point P is inside the shaded region of the circle. The shaded region is just a portion of circle that has an orientation (where the shaded region is looking at) and an angle.

A: Maths first:
let v = p - c
  let u = (1,0)  : Using the geometry shown above
Check |v| < r
Angle = acos(v.u/|v|)
Check the angle is in range.
In WPF:
Vector v = p - (new Point(0,0));
if(v.Length > radius)
    return false;
double angle = -Vector.AngleBetween(v, new Vector(1,0));
...

Here's an untested class
class Pie
{
    public Point Center { get; set; }
    public double Radius { get; set; }
    public Vector ZeroDegrees { get; set; }
    public bool ClockwisePositive { get; set; }

    public double GetAngle(Point p)
    {
        if (ClockwisePositive)
            return (Vector.AngleBetween(p - Center, ZeroDegrees) + 360) % 360;
        else
            return (Vector.AngleBetween(ZeroDegrees, p - Center) + 360) % 360;
    }

    public bool Contains(Point p)
    {
        return (p - Center).Length <= Radius;
    }

    public class Slice
    {
        public Pie Parent { get; set; }
        public double DirectionDegrees { get; set; }
        public double SizeDegrees { get; set; }

        public bool Contains(Point p)
        {
            if (!Parent.Contains(p))
                return false;

            double angle = Parent.GetAngle(p);
            double minAngle = (DirectionDegrees - SizeDegrees / 2 + 360) % 360;
            double maxAngle = (DirectionDegrees + SizeDegrees / 2 + 360) % 360;

            if (minAngle < maxAngle)
                return minAngle <= angle && angle <= maxAngle;
            else
                return angle >= minAngle || angle <= maxAngle;
        }
    }
}

A: assuming you've first tested that P is inside the circle, and that you know the start and end angles for the pie piece
a. find the Orientation of the line segment CP (CPa) - this should be fairly basic trig
b. check if CPa is between the start and end angles for the pie piece


text:
Q: How to Add data to Database in Laravels I will to add data to database, but I have an error when I write the code to add data to array, and the error like this,

syntax error, unexpected '=', expecting ']'

I am using the follwing code:
Controller
<?php
namespace App\Http\Controllers;

use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BooksController extends Controller
{
    public function addBooks(Request $request)
    {
        $data = array([
            'name' = $request->input('bookName');
        'year' = $request->input('tahunT');
        'author' = $request->input('author');
        'summary' = $request->input('Summary');
        'publisher' = $request->input('publishers');
        'pageCount' = $request->input('pageCount');
        'readPage' = $request->input('ReadPage');
        'finished' = $pageCount == $readPage ? true : false;
        'reading' = $readPage > 0 ? true : false;
        'insertedAt' = new DateTime();
        'updatedAt' = $insertedAt;]);

        DB::table('books')->insert($data);
    }
}

Here's the view
<form class="row g-3" action="{{ route('addbook') }}" method="post">
    <input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">

        Nama Buku:
        <input type="text" class="form-control" name="bookName" id="bookName">

        Tahun Terbit :
        <input type="number" class="form-control" name="tahunT"  id="tahunT">

        Author :
        <input type="text" class="form-control" name="author" id="author">

        Publisher :
        <input type="text" class="form-control" name="publishers" id="publishers" >

        Page Count :
        <input type="number" class="form-control" name= "pageCount" id="pageCount">

        Read Page :
        <input type="number" class="form-control" name="ReadPage" id="ReadPage">

        Summary :
        <textarea class="form-control" name= "Summary" id="Summary"></textarea>

        <button type="submit" class="btn btn-primary">Add Book</button>

</form>

Here's the route
Route::post('/addbook', 'BooksController@addBooks')->name('addbook');

Do you have any solution to this? I have also tried:
'name' => $request->bookName

but that also gives an error.

A: You seem to have mixed the old array syntax array() and the new syntax []. Keep in mind each entry of the array has to end with an , instead of a ;.
You could use the following:
$data = [
    'name'=> $request->input('bookName'),
    'year'=> $request->input('tahunT'),
    'author'=> $request->input('author'),
    'summary'=> $request->input('Summary'),
    'publisher'=> $request->input('publishers'),
    'pageCount' => $request->input('pageCount'),
    'readPage'=> $request->input('ReadPage'),
    'finished' => $pageCount == $readPage ? true : false,
    'reading' => $readPage > 0 ? true : false,
    'insertedAt'=> new DateTime(),
    'updatedAt'=> $insertedAt
];

DB::table('books')->insert($data);


text:
Q: how to determine device orientation from the sensors My activity is locked on LANDSCAPE. But still I need to know the orientation of the device. So I have elected to use sensors. I have the following code
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
...
@Override
  public void onSensorChanged(SensorEvent event) {
    float[] values = event.values;

    // Movement
    float azimuth = values[0];
    float pitch = values[1];
    float roll = values[2];

    if ((-110 <= pitch && pitch <= -70) || (70 <= pitch && pitch <= 110)) {
      //PORTRAIT MODE
      portraitPitch = true;
      landscapePitch = false;
      Log.d(TAG, "portrait mode: pitch = " + pitch);
    } else if ((-20 <= pitch && pitch <= 20) || (-200 <= pitch && pitch <= -160) || (160 <= pitch && pitch <= 200)) {
      //LANDSCAPE MODE
      portraitPitch = false;
      landscapePitch = true;
      Log.d(TAG, "landscape mode : pitch = " + pitch);
    }

    if ((-20 <= roll && roll <= 20)) {
      //PORTRAIT MODE
      portraitRoll = true;
      landscapePitch = false;
      Log.d(TAG, "portrait mode: roll = " + roll);
    } else if ((-110 <= roll && roll <= -70) || (70 <= roll && roll <= 110)) {
      //LANDSCAPE MODE
      portraitRoll = false;
      landscapePitch = true;
      Log.d(TAG, "landscape mode : roll = " + roll);
    }

    if (portraitPitch && portraitRoll && !portrait) {
      portrait = true;
      landscape = false;
      rotateIconsToPortraitMode();
      Log.d(TAG, "portrait mode for icons: pitch = " + pitch + ", roll = " + roll);
    }

    if (landscapePitch && landscapeRoll && !landscape) {
      landscape = true;
      portrait = false;
      rotateIconsToLandscapeMode();
      Log.d(TAG, "landscape mode for icons: pitch = " + pitch + ", roll = " + roll);
    }
}

My code is not working reliably, in fact, the otateIconsToLandscapeMode() is never reached.
How do I use the information about azimuth, pitch, and roll to determine the PORTRAIT or LANDSCAPE orientation of the device?` I hope my question is specific enough to warrant a specific answer. Thanks.

A: In oncreate instantiate an OrientationEventListener
OrientationEventListener orientationEventListener = new OrientationEventListener(this)
    {
        @Override
        public void onOrientationChanged(int orientation)
        {
            Log.d(TAG, "orientation = " + orientation);
        }
    };

    orientationEventListener.enable();

Using the orientation value you can determine whether the device in in Portrait or Landscape.

A: If LANDSCAPE vs PORTRAIT orientation is all you need, then the pitch value should be sufficient. It may not be perfect depending on your specific needs. But from my understanding, you can simply use pitch. So you it exactly as you have it, just ignore roll.


text:
Q: Function to approach a number asymptotically I have a map that I can zoom in and out of. Gridlines display the latitude and longitude.
Right now I zoom in by shrinking the borders by a specific amount.
Say top edge is lat 30n, bot edge is lat 28n, left edge is lon -40w, right edge is lon -38w.
So for one zoom in, the new edges are 29.5n, 28.5n, -39.5w,-38.5 respectively.
Zooming in enough times would eventually make the opposite edges equal each other and then flip.
So next zoom in for top and bot edge would be 29n, 29n and then next 28.5n,29.5n which flips the orientation.
I'm looking for a function or a way that I can continuously zoom in, but never have the edges equal each other or flip. In others words something where I can get the edges to continuously get closer and closer to each other, but never touch.
So I have an idea that I'll need some function like
lim x-> infinity of x/(x+1) - 1 + midpoint of the two edges
which basically means, as I zoom in I will approach the midpoint.
If this is valid, I don't know how to implement limits in C++.
This is only one equation too. I have two edges on each axis and so I'd need two equations to approach the midpoint from both sides at an equal rate.


text:
Q: UITableView reloadRowsAtIndexPaths hides row I use UITableView with static cells.
If I use reloadData, than everything is OK.
If I try reloadRowsAtIndexPaths it hides row. Row appears if I drag tableView up-down(when cell is updated).

A: I had the same problem, it seems to be a bug. I experimented some and the problem doesn't occur when I set the animation option to UITableViewRowAnimationNone. Some other interesting stuff happens when you set that option to UITableViewRowAnimationTop, too.

A: If your table cells are static (i.e., you are using the same cell object to replace the one that's currently displayed), what you're seeing is an artifact of the transition animation.
Think of it this way. Lets say you set UITableViewAnimationOptionFade. When the cell is to be replaced, the cell it's to be replaced with (which in this case is the exact same object) has a fade-in animation added to it. Then, the cell that is being replaced (again, it's all the same object) has a fade-out animation added to it. At the end, the cell is actually there, but it's invisible because the fade-out animation has made that cell object invisible.
In a non-static tableview, one in which the replacement cell is a different object than the cell to be replaced, this isn't a problem, as the animations are added to two different objects.

A: I solved this by removing animation
tableView.reloadRows(at: [yourIndexPath], with: UITableView.RowAnimation.none)

Hope this helps to anyone searching for this.


text:
Q: Ignite cache expiry for multiple cahce I have 10 ignite cache but i want to set expiry policy for only 4 caches. I have googled for example but with no luck. I have prepared an code for but need expert's opinion. The XML is as below,
        <property name="cacheConfiguration">
        <list>
            <bean class="org.apache.ignite.configuration.CacheConfiguration">
                <property name="name">
                <list>
                <value>CACHE_L4_TRIGGER_NOTIFICATION</value>
                <value>CACHE_L2_COTH</value>
                <value>CACHE_L2_CVOC</value>
                <value>CACHE_L3_MSC</value>
                </list>
                </property>
                <property name="expiryPolicyFactory">
                    <bean class="javax.cache.expiry.CreatedExpiryPolicy" factory-method="factoryOf">
                        <constructor-arg>
                            <bean class="javax.cache.expiry.Duration">
                                <constructor-arg value="DAYS"/>
                                <constructor-arg value="3"/>
                            </bean>
                        </constructor-arg>
                    </bean>
                </property>
            </bean>
        </list>
    </property>

A: Rather than have a list of cache names, you define a list of CacheConfigurations:
    <property name="cacheConfiguration">
    <list>
        <bean class="org.apache.ignite.configuration.CacheConfiguration">
            <property name="name" value="CACHE_L4_TRIGGER_NOTIFICATION"/>
            <property name="expiryPolicyFactory">
                <bean class="javax.cache.expiry.CreatedExpiryPolicy" factory-method="factoryOf">
                    <constructor-arg>
                        <bean class="javax.cache.expiry.Duration">
                            <constructor-arg value="DAYS"/>
                            <constructor-arg value="3"/>
                        </bean>
                    </constructor-arg>
                </bean>
            </property>
        </bean>
        <bean class="org.apache.ignite.configuration.CacheConfiguration">
            <property name="name" value="CACHE_L2_COTH"/>
            <property name="expiryPolicyFactory">
                <bean class="javax.cache.expiry.CreatedExpiryPolicy" factory-method="factoryOf">
                    <constructor-arg>
                        <bean class="javax.cache.expiry.Duration">
                            <constructor-arg value="DAYS"/>
                            <constructor-arg value="1"/>
                        </bean>
                    </constructor-arg>
                </bean>
            </property>
        </bean>

...


text:
Q: How can we get project version from pom.xml in assembly plugin How can we get project version from pom.xml in assembly plugin, as {version} and {project.version} seem not working in assembly-plugin xml
<id>zip</id>
<includeBaseDirectory>true</includeBaseDirectory>

<formats>
    <format>zip</format>
</formats>
<fileSets>
    <fileSet>
        <directory>${project.basedir}/src/root/config</directory>
        <outputDirectory>{version}/config</outputDirectory>
    </fileSet>
    <fileSet>
        <directory>${project.basedir}/common/lib</directory>
        <outputDirectory>{version}/bin/JAVA</outputDirectory>
    </fileSet>
</fileSets>

A: ${project.version} worked, was missing $


text:
Q: pyrogram как скачать фото с сообщения, на которое был сделан ответ пользователем? Пытаюсь сделать демотиватор(цитата к фотографии, как в @super_rjaka_demotivator_bot) для юзербота телеграм, но столкнулся с проблемой, мне нужно скачать фото с сообщения на которое я сделаю ответ, а я не знаю как :(
помогите решить плиз
либа pyrogram

A: Client.download_media(message, file_name)

Подробнее: download_media()


text:
Q: Is there a way to be notified when a client has unsubscribe from server sent events? As I understand when a request to an event emitter on the server arrives, that request is never closed and you only need to res.write() every time you would like to send a message. However is there a way to be notified when the client that performed this request has left? Is there a property on the request object?
suppose I have the following route
app.get('/event',function(req,res){

//set response headers

//how do I check if req object is still active to send a message and perform other actions?

})

A: The basic sequence of events should be similar in other frameworks, but this example is Grails 3.3.
First set up endpoints to subscribe, and to close the connection.
def index() {
    // handler for GET /api/subscribe

    rx.stream { Observer observer ->

        // This is the Grails event bus. background tasks,
        // services and other controllers can post these
        // events, CLIENT_HANGUP, SEND_MSG, which are
        // just string constants.

        eventBus.subscribe(CLIENT_HANGUP) {String msg ->

            // Code to handle when the grails event bus
            // posts CLIENT_HANGUP
            // Do any side effects here, like update your counter
            // Close the SSE connection

            observer.onCompleted()
            return
        }

        eventBus.subscribe(SEND_MSG) {String msg ->

            // Send a Server Sent Event

            observer.onNext(rx.respond(msg))
        }
    }
}

def disconnecting()
{
    // handler for GET /api/disconnect
    // Post the CLIENT_HANGUP event to the Grails event bus

    notify(CLIENT_HANGUP, 'disconnect')
}

Now in the client, you need to arrange to GET /api/disconnect whenever your use-case requires it.  Assuming you want to notice when someone navigates away from your page, you could register a function on window.onbeforeunload.  This example is using Vue.js and Axios.
  window.onbeforeunload = function (e) {
    e.preventDefault()
    Vue.$http({
      method: 'get',
      url: 'http://localhost:8080/api/disconnect'
    })
      .then((response) => { console.log(response) })
      .catch(({error}) => { console.log(error) })
  }

In the case of Servlet stacks like Grails, I found that I needed to do this even if I had no housekeeping of my own to do when the browser went away.  Without it, page reloads were causing IOExceptions on the back end.


text:
Q: Java files instead of jar files in my downloaded java package? The joml java package I downloaded to import into eclipse to use in my project contains all java files instead of jar files. The problem is you cant import java files, you have to import jar files of course. Am I missing something important. I downloaded this package right off Github. I placed the java file I need which is (vector3f )into my library but still cant import it.
I've tried looking into the problem and found nothing. Ive leaned that a jar file is multiple java files put into one. I've also learned you cant make a jar file by compiling and running your project in cmd, but with this being a package they should already be jar files plus there is no public static void main to run it. Has anyone had this problem before


text:
Q: Filter dataframe on occurrence of same values across columns AND at column end I have a dataframe like this:
df <- data.frame(
  id = 1:19,
  Area_l = c(1,2,0,0,0,2,3,1,2,0,0,0,0,3,4,0,0,0,0),
  Area_r = c(3,2,2,0,0,2,3,1,0,0,0,1,3,3,4,3,0,0,0)
)

I need to filter the dataframe in such a way that all rows are omitted that fulfill two conditions:
(i): Area_l and Area_r are 0
(ii): the paired 0values in Area_l and Area_r are the last values in the columns.
I really have no clue how to implement these two conditions using dplyr. The desired result is this:
df
   id Area_l Area_r
1   1      1      3
2   2      2      2
3   3      0      2
4   4      0      0
5   5      0      0
6   6      2      2
7   7      3      3
8   8      1      1
9   9      2      0
10 10      0      0
11 11      0      0
12 12      0      1
13 13      0      3
14 14      3      3
15 15      4      4
16 16      0      3

Any help?

A: Reverse the order of the dataframe, filter with a cumany condition, then reverse it back.
library(dplyr)
df %>%
  map_df(rev) %>%
  filter(cumany(Area_l + Area_r != 0)) %>%
  map_df(rev)

output
# A tibble: 16 x 3
      id Area_l Area_r
   <int>  <dbl>  <dbl>
 1     1      1      3
 2     2      2      2
 3     3      0      2
 4     4      0      0
 5     5      0      0
 6     6      2      2
 7     7      3      3
 8     8      1      1
 9     9      2      0
10    10      0      0
11    11      0      0
12    12      0      1
13    13      0      3
14    14      3      3
15    15      4      4
16    16      0      3

A: We may use rle
library(dplyr)
df %>%
   filter(!if_all(starts_with("Area"), ~ .x == 0 &
     inverse.rle(within.list(rle(.x == 0), values[-length(values)] <- FALSE))))

-output
    id Area_l Area_r
1   1      1      3
2   2      2      2
3   3      0      2
4   4      0      0
5   5      0      0
6   6      2      2
7   7      3      3
8   8      1      1
9   9      2      0
10 10      0      0
11 11      0      0
12 12      0      1
13 13      0      3
14 14      3      3
15 15      4      4
16 16      0      3

Or another option is
df %>%
   filter(if_any(starts_with("Area"),
        ~ row_number() <= max(row_number() * (.x != 0))))

Or another option is revcumsum from spatstat.utils
library(spatstat.utils)
df %>%
    filter(!if_all(starts_with("Area"), ~ revcumsum(.x != 0) <1))


text:
Q: Finding duplicate entries in Spring Boot MongoDB? I'm new to Spring Boot and I've been trying to find out how you go about finding duplicates in MongoDB and reporting it.
For example each entry has an _id for database use, an entry name, and a barcode. All three of these need to be unique identifiers which can be searched.
For example. A user has created 100 entries a while back and for some reason has forgotten they've created a "Jaffa" entry with a barcode of 255.
Despite the app having a search function, the user neglects using it for what ever reason and they cannot find it the old fashioned way so tries to create a new "Jaffa" entry with the same barcode as above.
How do I get my app to look through the DB and report if the entry already exists or create otherwise either using the name or the barcode?
Thanks

A: You can use update with upsert option set to true. When you create a newEntry with whatever name, if it exists then it will update the existing entry data and if it doesn't exist then it creates a new document when no document matches the query criteria.
Here it is db.collection.update(query, update, options).
For ex:
db.collection.update({entryName: newEntry}, {$set: {entryName: newEntry: barcode: newBarCode}}, {upsert : true})


text:
Q: Python and Google App Engine access issue I followed the install for GAE and tried a tutorial. Getting:
The following error occurred while trying to extract file(s) to the Python egg
cache:

  [Error 5] Access is denied: 'C:\\Users\\User\\Documents\\app\\django\\pyyaml-3.10-py2.7-win32.egg-tmp\\_yaml.pyd'

The Python egg cache directory is currently set to:

  C:\Users\User\Documents\app\django

Perhaps your account does not have write access to this directory?  You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory.

PYTHON_EGG_CACHE is changed away from the AppData folder which was causing issues as per every other SO solution.
I checked permissions for the user and Admin, full control. I am running SDK as administrator.

A: The error is with pyyaml, to fix this uninstall pyyaml and reinstall with -Z
I did:
easy_install -Z pyyaml

Thanks to https://code.google.com/p/googleappengine/issues/detail?id=9069


text:
Q: Using a Button under the context:SecondActivity in a recyclerView For example:
This is my Button in SecondActivity.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapActivity">

        <Button
                android:id="@+id/Increase"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                android:text="Increase"/>

</androidx.constraintlayout.widget.ConstraintLayout>

I want to call this button in a FragmentClass but whenever I do the app crashes.
Increase= (Button)itemView.findViewById(R.id.Increase)

How do I use the button in other fragment class? Much appreciate

A: You should use getActivity() method.
Use this snippet with your fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
      View view = inflater.inflate(R.layout.fragment_item_select, container, false);
      yourButton = (Button) getActivity().findViewById(R.id.btn);
}

In that case you will be able to use the button from Activity in your Fragment.


text:
Q: Openweather API Refusing Connection I'm certain that this is something that I've missed when reading documentation for API's - I'm attempting to hard code a request in jquery to call the openweather API as the page is geographic specific:
console.log('Connected to Script.js');
$(document).ready(weatherSettings);
function weatherSettings () {
  var config =
  {
    url: 'https://api.openweathermap.org/forecast',
    data: {
      id:'7281804',
      appid: 'MYID'
    }
  };
  $.ajax(config).done(displayMelbourneData);
  function displayMelbourneData(callback) {
    console.log(callback);
  }
}

The error I am getting however is: net::ERR_CONNECTION_REFUSED and I cannot for the life of me figure out why.
Any help would be appreciated.

A: Just change your current URL to http://api.openweathermap.org/data/2.5/forecast and you should be fine.
You can try directly try this in your browser (remember to change YOURAPIKEY with your own API key)
http://api.openweathermap.org/data/2.5/forecast?id=7281804&appid=YOURAPIKEY
Below is a sample that I tried and worked. By the way don't forget to change YOURAPIKEY with your own API key.
<!DOCTYPE html>
<html lang="en">
<head>
  <title></title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
  <script>

    console.log('Connected to Script.js');
    $(document).ready(weatherSettings);
    function weatherSettings () {
      var config =
      {
        url: 'http://api.openweathermap.org/data/2.5/forecast',
        data: {
          id:'7281804',
          appid: 'YOURAPIKEY'
        }
      };
      $.ajax(config).done(displayMelbourneData);
      function displayMelbourneData(callback) {
        console.log(callback);
      }
    }
  </script>
</body>
</html>


text:
Q: Objective-c - failed to obtain a cell from its dataSource I try to add cell programmatically, and I have in my table the following
 if (indexPath.section == AST_SF_SECTION_DATES) {

        if (indexPath.row == AST_SECOND_1) {

            cellIdentifier = @"DemoCell";
            if (cell == nil) {
            DemoCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
            cell = [[MY_BUNDLE loadNibNamed:cellIdentifier owner:self options:nil] firstObject];
            cell.label.text = @"I'm a label";
            }

        }

Also I have xib with reuse identifier inside attributes inspector, .m and .h file.
and I tried
[_tableView registerClass:[DemoCell self] forCellReuseIdentifier:@"DemoCell"];

inside viewDidLoad of view controller with table, but error still there
log is following
*** Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3512.60.7/UITableView.m:7971
2016-06-11 13:55:13.768 SDKTemplate[14783:7920598] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView (<UITableView: 0x7ffb9c061c00; frame = (0 0; 375 667); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x7ffb9acab350>; layer = <CALayer: 0x7ffb9ac92450>; contentOffset: {0, -64}; contentSize: {375, 492.60000000149012}>) failed to obtain a cell from its dataSource (<ASTSearchForm: 0x7ffb9ac9f8f0>)'

What am I doing wrong?

A: as far as I know, if you want to add new cell programmatically, you should at first
[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];

second, in table view data source's cellForRowAtIndexPath, you should return new cell correctly

A: This line is incorrect, remove it:
cell = [[MY_BUNDLE loadNibNamed:cellIdentifier owner:self options:nil] firstObject];

dequeueReusableCellWithIdentifier:forIndexPathalways gives you a fully formed cell:

A UITableViewCell object with the associated reuse identifier. This method always returns a valid cell.
If you registered a class for the specified identifier and a new cell must be created, this method initializes the cell by calling its initWithStyle:reuseIdentifier: method. For nib-based cells, this method loads the cell object from the provided nib file. If an existing cell was available for reuse, this method calls the cell's prepareForReuse method instead.

So remove that, and if anything still goes wrong, it's your registration at fault. We'd have to look at the class code and/or nib to see what exactly. But very likely just use what dequeueReusableCellWithIdentifier gives you and you'll be good.


text:
Q: $U_q$ Quantum group and the four variables: $E, F, K, K^{-1}$ In Kassel's book on Quantum groups, it is defined that:
"We define $U_q=U_q(\mathfrak{sl}(2) )$ as the algebra generated by the four variables $E$, $F$, $K$, $K^{-1}$ with the relations
\begin{eqnarray*}
&&KK^{-1}=K^{-1}K=1\\
&&KEK^{-1}=q^2 E,\ KFK^{-1}=q^{-2} F\\
and &&[E,F]=\frac{K-K^{-1}}{q-q^{-1}}
\end{eqnarray*}"
May I ask if there is a way of understanding what are $E, F, K$ and $K^{-1}$? Are there matrix representations of them or anything like that?
Sincere thanks for any help.

A: On the one hand, I'd suggest taking that description of $U_q(\mathfrak{sl}_2)$ as a formal definition.  That is, think of $U_q(\mathfrak{sl}_2)$ as being the free associative algebra $k\langle E, F, K, K^{-1}\rangle$ modulo the relations you gave.  $E$, $F$, $K$ are just formal symbols.  You can just as well call them $x$, $y$, and $z$.  You can procede in this manner without losing any of the algebraic side of quantum groups.
On the other hand, it's helpful to know that $U_q(\mathfrak{sl}_2)$ is meant to be a one-parameter (that parameter is $q$) deformation of the enveloping algebra $U(\mathfrak{sl}_2)$ of the lie algebra $\mathfrak{sl}_2$.  Further, that as hopf algebras, $U(\mathfrak{sl}_2)$ and $SL(2)$ are dual to each other.  It is in this way that you can get some intuition behind the relations defining the quantum group.

A: The answer given by mebassett seems to take away the meaning of the elements $E,K,K^{-1},F$ and reduce them to formal symbols $x,y,z$ rather than providing meaning. That is one way to look at them of course; as formal symbols.
To get a better feeling of what these elements mean, you can turn to representation theory. Consider a finite-dimensional representation $V$ of $\mathfrak{U}_q(\mathfrak{sl}_2)$. If the highest weight $\lambda$ of $V$ is dominant integral, which just means $\lambda \in \mathbb{Z}^+$ for representations of $\mathfrak{U}_q(\mathfrak{sl}_2)$, the representation $V$ is the unique finite-dimensional irreducible representation $V_\lambda$ of dimension $\lambda+1$.
The representation $V_\lambda$ is given by the span of a highest weight vector $v_\lambda$ and all of its 'reductions' by the element $F$, i.e. $V_\lambda = \langle v_\lambda, F v_\lambda, F^2 v_\lambda, \dots, F^\lambda v_\lambda \rangle$. The weight of an element $F^k v_\lambda$ is $\lambda - 2k$. The actions of the elements $E,K,K^{-1},F$ on $V_\lambda$ are as follows:
$E v_\lambda = 0$
$E F^k v_\lambda = [k]_q [\lambda - k + 1]_q F^{k-1} v_\lambda$
$K^\pm F^k v_\lambda = q^{\pm(\lambda - 2k)} F^k v_\lambda$
$F F^k v_\lambda = F^{k+1} v_\lambda$
$F^{\lambda+1} v_\lambda = 0$
where $[k]_q = \frac{q^k - q^{-k}}{q - q^{-1}}$ is the $q$-analog of $k$.
As you see, the element $E$ moves an element of the representation up in weight, stopping at the highest weight $\lambda$. Similarly, the element $F$ moves an element of the representation down in weight, stopping at the lowest weight (which is $-\lambda$). The element $K$ acts with weight zero and simply 'registers' the weight of an element of the representation. In fact, $K = q^h$ where $h$ is the single element $\begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}$ that generates that Cartan subalgebra $\mathfrak{h}$ of $\mathfrak{sl}_2$. In the more general case of $\mathfrak{U}_q(\mathfrak{sl}_n)$, a generating element $K_i = q^{h_i}$ acts as
$q^{h_i} w = q^{\mu(h_i)} w$
on an element $w$ of weight $\mu$.


text:
Q: Is there a way to call an `async` python method from C++? We have a codebase in python which uses asyncio, and co-routines (async methods and awaits), what I'd like to do is to call one of these method from a C++ class which has been pulled into python (using pybind11)
Let's say there is this code:
class Foo:
  async def bar(a, b, c):
    # some stuff
    return c * a

Assuming that the code is being invoked from python and there is an io loop handling this, at some point, the code drops into C++ land where this bar method needs to be invoked - how does one await the result of this in C++?

A: This isn't pybind11, but you can call an async function directly from C.  You simply add a callback to the future using add_done_callback. I assume pybind11 allows you to call python functions so the steps would be the same:
https://github.com/MarkReedZ/mrhttp/blob/master/src/mrhttp/internals/protocol.c
result = protocol_callPageHandler(self, r->func, request))

Now the result of an async function is a future.  Just like in python you need to call create_task using the resulting future:
PyObject *task;
if(!(task = PyObject_CallFunctionObjArgs(self->create_task, result, NULL))) return NULL;

And then you need to add a callback using add_done_callback:
add_done_callback = PyObject_GetAttrString(task, "add_done_callback")
PyObject_CallFunctionObjArgs(add_done_callback, self->task_done, NULL)

self->task_done is a C function registered in python which will be called when the task is done.

A: It is possible to implement a Python coroutine in C++, but takes some work. You need to do what the interpreter (in static languages the compiler) normally does for you and transform your async function into a state machine. Consider a very simple coroutine:
async def coro():
    x = foo()
    y = await bar()
    baz(x, y)
    return 42

Invoking coro() doesn't run any of its code, but it produces an awaitable object which can be started and then resumed multiple times. (But you don't normally see these operations because they are transparently performed by the event loop.) The awaitable can respond in two different ways: by 1) suspending, or by 2) indicating that it is done.
Inside a coroutine await implements suspension. If a coroutine were implemented with a generator, y = await bar() would desugar to:
# pseudo-code for y = await bar()

_bar_iter = bar().__await__()
while True:
    try:
        _suspend_val = next(_bar_iter)
    except StopIteration as _stop:
        y = _stop.value
        break
    yield _suspend_val

In other words, await suspends (yields) as long as the awaited object does. The awaited object signals that it's done by raising StopIteration, and by smuggling the return value inside its value attribute. If yield-in-a-loop sounds like yield from, you're exactly right, and that is why await is often described in terms of yield from. However, in C++ we don't have yield (yet), so we have to integrate the above into the state machine.
To implement async def from scratch, we need to have a type that satisfies the following constraints:

*

*doesn't do much when constructed - typically it will just store the arguments it received

*has an __await__ method that returns an iterable, which can just be self;

*has an __iter__ which returns an iterator, which can again be self;

*has a __next__ method whose invocation implements one step of the state machine, with return meaning suspension and raising StopIteration meaning finishing.

The above coroutine's state machine in __next__ will consist of three states:

*

*the initial one, when it invokes the foo() sync function

*the next state when it keeps awaiting the bar() coroutine for as long as it suspends (propagating the suspends) to the caller. Once bar() returns a value, we can immediately proceed to calling baz() and returning the value via the StopIteration exception.

*the final state which simply raises an exception informing the caller that the coroutine is spent.

So the async def coro() definition shown above can be thought of as syntactic sugar for the following:
class coro:
    def __init__(self):
        self._state = 0

    def __iter__(self):
        return self

    def __await__(self):
        return self

    def __next__(self):
        if self._state == 0:
            self._x = foo()
            self._bar_iter = bar().__await__()
            self._state = 1

        if self._state == 1:
            try:
                suspend_val = next(self._bar_iter)
                # propagate the suspended value to the caller
                # don't change _state, we will return here for
                # as long as bar() keeps suspending
                return suspend_val
            except StopIteration as stop:
                # we got our value
                y = stop.value
            # since we got the value, immediately proceed to
            # invoking `baz`
            baz(self._x, y)
            self._state = 2
            # tell the caller that we're done and inform
            # it of the return value
            raise StopIteration(42)

        # the final state only serves to disable accidental
        # resumption of a finished coroutine
        raise RuntimeError("cannot reuse already awaited coroutine")

We can test that our "coroutine" works using real asyncio:
>>> class coro:
... (definition from above)
...
>>> def foo():
...     print('foo')
...     return 20
...
>>> async def bar():
...     print('bar')
...     return 10
...
>>> def baz(x, y):
...     print(x, y)
...
>>> asyncio.run(coro())
foo
bar
20 10
42

The remaining part is to write the coro class in Python/C or in pybind11.

A: For things like this, if I don't want to delve too deep into CPython API, I just write my stuff in Python, and call that using pybinds Python interface.
An example:
https://github.com/RobotLocomotion/drake/blob/a7700d3/bindings/pydrake/init.py#L44
https://github.com/RobotLocomotion/drake/blob/a7700d3/bindings/pydrake/pydrake_pybind.h#L359
Rendering onto this use case, perhaps you can do:
# cpp_helpers.py
def await_(obj):
    return await obj

py::object py_await = py::module::import("cpp_helpers").attr("await_");
auto result = py::cast<MyResult>(py_await(py_obj));

However, this will very likely be less performant than the above solutions.


text:
Q: Blue/green deployment, canary releases and database consistency There is a few techniques to ensure new changes doesn't break the system, like mentioned above blue-green or canary deployment. Both means applying changes partially (change only part of infrastructure, or run new version in parallel with old one).
However I don't get how to keep data consistency if any major changes comes in data structure (let's say, you made changes for GDPR - pretty possible case, huh?).
Even on NoSQL based solutions it may cause issues (as I imagine it). I've tried to look for solutions, but the problem is only widely mentioned, but rarely addressed.
How is it possible to introduce such techniques and keep data consistency? How does it achieved normally in real life applications?

A: If I understand your question correctly you're talking about the Expand-Contract pattern in which you change your system to support multiple data structures during an update.
You would do multiple expand-contracts for a large data structure change that couldn't be done in one deployment.
Also known as Parallel Change.
https://martinfowler.com/bliki/ParallelChange.html


text:
Q: Given any two points $x, y \in X$ there exists connected set $A$ such that $x, y \in A$. Then $X$ is connected. Let $X$ be a (metric) space such that given any two points $x, y \in X$ there exists connected set $A$ such that $x, y \in A$. Then $X$ is connected.
Let us consider a continuous function $f : X \to \{-1,+1\}$. We first choose $p \in X$. With out loss of generality we consider $f(p) =1$. If $x \in X$ then by hypothesis there exists a connected subset $A$ in $X$ such that $x,p \in A$. Since $A$ is connected $f(x) = 1$. Since $x$ is arbitrary in $X$ so the function $f$ is constant proving the fact that $X$ is connected.
Is the proof correct?


text:
Q: Nanobox multiple https certificates I just deployed my side project and I'm adding the HTTPS certificates.
I was able to setup the certificate for the root domain but it looks like it's impossible to add it to my subdomain www - The UI's dashboard only let you setup one domain.
I ask that since I need two certificates - WWW and NON-WWW - to be able to redirect the WWW to NON-WWW.

A: You can create another certificate with a different domain, then create and activate a bundle for it as well. Nanobox doesn't limit the number of certificates you can add to any of your apps.
The process of adding a certificate is a bit involved, whether Nanobox is in the loop or not:

*

*The first step is to create a certificate signing request (CSR), essentially a certificate with all the information about your domain (including the public encryption key), but no security. Nanobox refers to this as "creating a certificate", a process that starts every time at the "SSL/TLS Certificates" screen of your app's Admin tab.

*The next step is to get that CSR signed, which is where all the security is layered in. Nanobox refers to this as "generating a bundle", since it pulls in the certificate used to sign yours, as well as any ancestor certs that may have.

*The final step is to actually load that collection of certificates, also called a "chain of trust" or just "certificate chain", onto your server, where your site can use it to secure communications with itself. Nanobox calls this "activating the bundle", and it involves passing the certificate chain (the "bundle") to the app's load balancer, and telling it which domain to use that particular bundle for.
Here's where things get the most confusing the most often for most users with this question. The UI at this point mentions that "Only one bundle can be activated at a time" – it doesn't clarify that it means "one bundle at a time per certificate". Since you could, hypothetically, sign the same CSR multiple times with multiple Certification Authorities (CAs; LetsEncrypt is the most common CA for Nanobox apps), Nanobox supports loading multiple chains for a single CSR (or, to use the Nanobox naming, multiple bundles for a single certificate). But since SSL doesn't support multiple chains per request, you have to select a bundle to serve for the associated certificate, and that's all that bit means.
To add another certificate/bundle, go back to the "SSL/TLS Certificates" screen, by clicking that button on the left side of the page, then choose "New SSL/TLS Certificate" under any existing certificate(s) you've already added. The rest is the same process you already followed, above.
The workflow to add new certificates in Nanobox isn't the most friendly or obvious, though there are probably ways to improve on that, but hopefully that makes a bit more sense, now.


text:
Q: what is the difference between ${10 \choose 2}$ and ${10 \choose 1}\times{9 \choose 1}$? I'm not able to understand the difference between these two.
Don't both just give the number of ways of selecting $2$ objects from a total of $10$?
Maybe the difference is that ${10 \choose 2}$ gives the number of ways of selecting $2$ distinct objects from a total of $10$, but ${10 \choose 1}$ gives the number of ways of selecting $1$ object from a total of $10$, but ${9 \choose 1}$ gives the number of ways of selecting $1$ object from a possible $9$ left options, so shouldn't multiplying ${10 \choose 1}$ with ${9 \choose 1}$ give the same result logicaly?

A: The difference is the duplication of pairs you get from 10C1 followed by 9C1.
For example, if the set you are choosing from is {a, b, c, d, e, f, g, h, i, j}
Then the choices for 10C1 followed by 9C1 will include (a, b) and (b, a) whereas the choices for 10C2 will include only one of the two.

A: $10C_2$ means selecting $2$ items from a set of $10$ items.
$10C_1\cdot9C_1$ means selecting $1$ item from $10$ and then selecting $1$ item from the rest $9$.
Though you are eventually selecting a total of $2$ items, you should also take a note the parent set from which you are selecting is different in both the cases.

A: One way of seeing the difference is this.
Suppose you are to pick from the set of integers $\{1,2,3,4,5,6,7,8,9,10\}$.
For $\binom{10}{2}$ you choose two elements
"at the same time", that is, picking $2$ and $3$ is the same
as picking $3$ and $2$.
But for $\binom{10}{1}\binom{9}{1}$ the elements are picked in a definite
sequence, that is, picking $2$ the first time and $3$ the second time
is counted separately from picking $3$ the first time and $2$ the second time.
Often $\binom{10}{2}$ is called the number of combinations of $2$
elements you can pick from a set of $10$ elements.
If you are counting permutations of $2$ elements out of $10$
rather than combinations, that is, it matters in what order the elements
are placed rather than just what elements are in the selected subset,
then in fact $\binom{10}{1}\binom{9}{1} = 10\cdot 9$
is exactly the right number of permutations.

A: The number $\binom{10}{2}$ is the number of ways we can select a subset of two elements from a set with ten elements.  Assuming you are making both selections from the same set, the number $\binom{10}{1}\binom{9}{1}$ is the number of ways we can select a subset of one element from a set of ten elements and then choose a subset of one element from the remaining nine elements of the ten element set.  That is, $\binom{10}{1}\binom{9}{1}$ represents the number of ways we can make an ordered selection of two elements from the ten element set. If we are just interested in which elements we have selected, selecting $0$ and then $1$ is the same as selecting $1$ and then $0$.  Using $\binom{10}{1}\binom{9}{1}$ counts them separately, so $$\binom{10}{2} = \frac{1}{2!}\binom{10}{1}\binom{9}{1}$$
because there are $2! = 2$ orders in which we can select the same two elements.

A: No because the product
$${10 \choose 1}\times{9 \choose 1}$$
does not account for inter-dependencies as the direct calculation (else everything could be reduced, see it as such)
$${10 \choose 2}$$
The inter-dependencies are counted by a convolution-like identity (which is indeed an identity of the binomial coefficients)

For your example the inter-dependencies would be the duplication of pairs you get from ${10 \choose 1}$ followed by ${9 \choose 1}$ (as already mentioned), plus the ordering.
One can easily validate this by direct calculation of the two terms and see if they are equal.


text:
Q: Synchronize Sorted ListViewItems in View to ObservableCollection in ViewModel I'm using C# WPF following the MVVM design pattern. Currently my View has a ListView which contains several columns and rows ( i.e. ListViewItems ).
The ViewModel exposes an ObservableCollection<Person> collection ( as shown below ) which the View binds to.
public ObservableCollection<Person> People
{
    get
    {
        return _people;
    }
    set
    {
        // new value?
        if( value != _people )
        {
            // Set
            _people = value;

            // Notify
            OnPropertyChanged( "People" );
        }
    }
}

and here is the binding snippet
<ListView ItemsSource="{Binding People}" ... >
    <!-- Omitted -->
</ListView>

In the View the user may click on  a column header and the ListView will sort itself accordingly. The problem is  that some of the logic and commands in the ViewModel are sensitive to the order of elements and when the ListView is sorted on a particular column the underlying People collection in the ViewModel doesn't reflect the order the user is seeing.
Any clue on how to synchronize the sorted ListViewItems in the ListView with the underlying ObservableCollection<Person>?
Edit Already tried Mode=TwoWay on the ListView ItemsSource, that didn't work.

A: The problem is (as you yourself stated) that some of the logic and commands in the ViewModel are sensitive to the order of elements. In short, they shouldn't be; if the reason is actually reordering the items (just about the only one I can imagine where the order would be important), then the view shouldn't be sortable by columns. Otherwise you need to find ways to make the order irrelevant - perhaps you could give an example of an action that depends on the order of items? That way we could suggest a real solution.
Also wanted to clarify that the order of the items in the view has no relation to their order in the source ObservableCollection. Generally the ItemsControls automatically create an ICollectionView that is sorted independently. Edit: yeah well not an actual ICollectionView, it's a more complicated mechanism (what the ItemCollection does in conjunction with the ItemContainerGenerator) but you get the picture.


text:
Q: Is there any Google OAuth2.0 Scope present which can tell me when the user access his account last time I know google provides lot of apis/scopes which we can use to manage google account (similar to this https://developers.google.com/gmail/api/reference/rest?apix=true). I am looking for an scope which can tell me when did user last accessed his/her account. Accessing account means checking email, playing YouTube video, anything.

A: You can review the login api, using this API  you can verify the last time of a sucessfull login for a Workspace account.
A sample output were the time of the loggin is visible :
{
  "kind": "admin#reports#activities",
  "etag": "\"REDACTED\"",
  "items": [
    {
      "kind": "admin#reports#activity",
      "id": {
        "time": "2021-05-28T19:30:23.868Z",
        "uniqueQualifier": "REDACTED",
        "applicationName": "login",
        "customerId": REDACTED"
      },
      "etag": "REDACTED"",
      "actor": {
        "email": "user@domain.com",
        "profileId": "11111111111111111111"
      },

*

*Please note that this report will log each time a user logs in with google, however if the user already has an active session and access to a google service this action will not be logged.


text:
Q: Custom deserialiser using the universal Kafka ingest Following on from this (apologies, had a different user): Kafka Key access on Ingress of a Python Flink Stateful function
Our use case is that we make use of the Kafka headers as a means of tracing and lineage as well as required metadata. Looking at this:
https://github.com/apache/flink-statefun/blob/master/statefun-flink/statefun-flink-io-bundle/src/main/java/org/apache/flink/statefun/flink/io/kafka/binders/ingress/v1/RoutableKafkaIngressDeserializer.java#L45-L61 It looks like using the standard deserializer, the headers are dropped.
Effectively what I'd want, is a way to inject my own deserializer that would return a message containing this and any other metadata from the record. I'd want to add something like the UniversalKafkaIngress so that I could configure it using a remote module.
Looking at the code, I can see that I could register a new ExtensionModule, and replace the deserializer (and create a custom kind). Is this recommended? If so - are there any docs on this (if not, how could I configure statefun to pick this up)?
Or, is there another preferred method?
Thanks again...

A: Ah - found out where I was going wrong.
You can load a ExtensionModule using the standard module SPI process - and therefore register it as a new 'universal' ingress, so that it can be loaded remotely. I had a typo - which is why I battled.
There are a few gotchas - and I'll post a gist a little later to show how it can be done.


text:
Q: mysql database event (like insert update delete) tracking for all table using node.js I am new in node.js. I was just trying to build a module to track a record for all MySQL database activity with details using node.js.
as I want like someone insert/update/delete in MySQL db then data will show in our node console.
example- database my_work insert a row with value (......) when I hit a insert command in MySQL workbench.


text:
Q: Node not added to tree I've been trying to create a integer binary search tree with Java and for some reason, I've been going wrong with adding new nodes to the tree.
Here is the NODE class.
class NODE
{
    NODE left = null, right = null;
    int info;
    public NODE(int x)
    {
        info = x;
    }
}

and here's the BST(Binary Seatch Tree) class with the insert() method.
class BST
{
    NODE tree = null;
    public void insert(int x)
    {
        NODE node = new NODE(x);
        NODE temp = tree;
        while(true)
        {
            if(temp == null)
            {
                temp = node;
                break;
            }
            else if(temp.info > x) temp = temp.left;
            else temp = temp.right;
        }
    }
    //other methods present here
}

For reasons that I could not figure out, the  insert() method is going wrong.
The object tree carries null in it even after the insert() method is called.
Can you find something spotty in the code?
Thanks!

A: Use a recursive insert method in the NODE class (instead of utilizing an infinite loop as you did):
public void insert(int x) {
        if(x < this.info) {
            if(this.left == null)
                this.left = new NODE(x);
            else
                this.left.insert(x);
        }
        else {
            if(this.right == null)
                this.right = new NODE(x);
            else
                this.right.insert(x);
        }
    }

And your BST class would have the following insert method (simply calls the other insert method):
public void insert(int x) {
    if(tree == null)
        tree = new NODE(x);
    else
        tree.insert(x);
}

The main insert method is in the NODE class because it must recursively call itself on nodes within the tree.

A: Of course tree remains null - you don't assign anything to this field.
After temp = tree; and temp = node; only temp is changed, not tree.

A: The insert() method should insert the child of a node into the tree, calling an already declared Node as a parameter.  e.g.:
//Returns true/false depending on whether the insert is successful
public boolean insert(int x, Node node, boolean leftChild) {
    if (node == null) return false;
    Node child = new Node(x);
    if (leftChild) {
        if (node.left != null) return false;
        node.left = child;
    } else {
        if (node.right != null) return false;
        node.right = child;
    }
    return true;
}


text:
Q: Extract 3 numbers from string and put them into variables I'm trying to extract 3 numbers from string and put them into variables
This is the html
Click Me

I got the href string with jQuery
$('a').attr('href')

and the result is
javascript:theNumbers( 09222004, 05232015, '4815162342' );

I want to extract each value (09222004 and 05232015 and 4815162342) to variable so I can use each number in different process

A: Click Me

to  get value
var numbers =$('a').attr('data-numbers').split(',');

this return an array
['09222004', '05232015', '4815162342']

A: Take a look at this, i hope it helps:

$(document).ready(function(){
  // get href text attribute
  var mString = $('a').attr('href');
  // get the text between ()
  var mResult = mString.match(/\((.*)\)/);
  // split mResult
  var numbers = mResult[1].split(',');
  // show the result
  for(var i = 0; i < numbers.length; i++){
    $("#numbers").append('Number ' + i + ' is ' + numbers[i] + '
');
  }
});

Click Me

A: String.prototype.split() str.split([separator[, limit]]) will help you here, brackets then commas.
Parse the elements of the array of size 3 you end up with

A: Just for the record, the accepted answer doesn't fulfill the requirement to return usable numbers. In fact the accepted answer (method A below) doesn't work at all as already noted by OP. The answer given in the fiddle (method B) is better, but still returns the wrong data, i.e., parseInt(s) = NaN.
However, one could return a clean set of data by simply removing non-numeric characters and splitting on commas:
href.replace(/[^0-9,]/g,'').split(',');

Run the snippet to compare the output of the various methods:

<xmp id="stdout" style="background-color:black; color:lime;padding:1em;"></xmp>


text:
Q: DiscordJS embeds not adding fields properly I am programming my discord bot to work with google calendar. I've managed to get this code almost working https://pastebin.com/DRT83kcr, but there is a problem with that embed, it doesn't add these field into it. Why ? It logs them and values are right, but when it logs the embed, there are no fields. Can you please help me ?
// Funkce na vypisování skautských událostí
function listEvents(auth) {
  var fields = [];
  const embded = new Discord.MessageEmbed() // Vytvoření embedu
          .setColor("#0ddede")
          .setThumbnail("https://medvediberoun.eu/wp-content/uploads/2020/10/znak_oddilu.jpg") // Skautské logo
          .setTitle("Skaut")
          .setDescription("4 Nadcházející akce ve skautském kalendáři")
          .setTimestamp()
          .setAuthor('Medvědi Beroun', 'https://medvediberoun.eu/wp-content/uploads/2020/10/znak_oddilu.jpg', 'https://medvediberoun.eu/')
          .setFooter('https://www.skaut.cz/', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.U8-xvll_vFXoDUbWx7AxCAHaHa%26pid%3DApi&f=1')
          .setURL("https://skaut.cz/");
  const calendar = google.calendar({version: 'v3', auth}); // Něco od googlu
  calendar.events.list({
    calendarId: 'primary',
    timeMin: (new Date()).toISOString(),
    maxResults: 4,
    singleEvents: true,
    orderBy: 'startTime',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const events = res.data.items;
    if (events.length) {
      events.map((event, i) => {
        const start = event.start.dateTime || event.start.date;
        fields.push([parseISOString(start).toDateString(),event.summary]);
      });
      console.log(fields);
      printEmbded(fields);

    } else {
      console.log('No upcoming events found.'); // Žádné eventy
    }
  });
}

function printEmbded(fields) {
  var fields = getAkce();
  console.log(fields);
  for(var index = 0; index < fields.length; index++){ // Procházení všech eventů
        console.log(fields[index][0] + " " + fields[index][1] + " " + index ); // Zpracování jednotlivých eventů
        if(index == 0){ // Jestliže je první
          embded.addFields({name: fields[index][0], value: fields[index][1], inline: false}, {name: '\u200B', value: '\u200B'}); // Vypsání samostaně
        } else {
          embded.addField(fields[index][0], fields[index][1], true); // Vypsání ostatních eventů
        }
      }
  console.log(embded);
  client.channels.cache.get(ids.skautAnouncements).send(embded);
}

A: Do you have any error ?
I think it's because you don't add your embded variable inside your printEmbded() function.
You should try :
// Funkce na vypisování skautských událostí
function listEvents(auth) {
  var fields = [];
  const embded = new Discord.MessageEmbed() // Vytvoření embedu
          .setColor("#0ddede")
          .setThumbnail("https://medvediberoun.eu/wp-content/uploads/2020/10/znak_oddilu.jpg") // Skautské logo
          .setTitle("Skaut")
          .setDescription("4 Nadcházející akce ve skautském kalendáři")
          .setTimestamp()
          .setAuthor('Medvědi Beroun', 'https://medvediberoun.eu/wp-content/uploads/2020/10/znak_oddilu.jpg', 'https://medvediberoun.eu/')
          .setFooter('https://www.skaut.cz/', 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.U8-xvll_vFXoDUbWx7AxCAHaHa%26pid%3DApi&f=1')
          .setURL("https://skaut.cz/");
  const calendar = google.calendar({version: 'v3', auth}); // Něco od googlu
  calendar.events.list({
    calendarId: 'primary',
    timeMin: (new Date()).toISOString(),
    maxResults: 4,
    singleEvents: true,
    orderBy: 'startTime',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const events = res.data.items;
    if (events.length) {
      events.map((event, i) => {
        const start = event.start.dateTime || event.start.date;
        fields.push([parseISOString(start).toDateString(),event.summary]);
      });
      console.log(fields);
      printEmbded(fields, embded);

    } else {
      console.log('No upcoming events found.'); // Žádné eventy
    }
  });
}

function printEmbded(fields, embded) {
  var fields = getAkce();
  console.log(fields);
  for(var index = 0; index < fields.length; index++){ // Procházení všech eventů
        console.log(fields[index][0] + " " + fields[index][1] + " " + index ); // Zpracování jednotlivých eventů
        if(index == 0){ // Jestliže je první
          embded.addFields({name: fields[index][0], value: fields[index][1], inline: false}, {name: '\u200B', value: '\u200B'}); // Vypsání samostaně
        } else {
          embded.addField(fields[index][0], fields[index][1], true); // Vypsání ostatních eventů
        }
      }
  console.log(embded);
  client.channels.cache.get(ids.skautAnouncements).send(embded);
}


text:
Q: BouncyCastle - Generate certificate file that MS Windows understands I'm using Java and BouncyCastle to generate a CA certificate, the CA issues several user Certificates, these Certificates are stored on a Data Base with their private key. How can I generate a certificate file that can be installed by Windows in which the operating system recognizes the private key and the certificate details ?
If I save the certificate details from X509Certificate class to PEM file the certificate details are recognized but without the private key.
Any help ?
Thanks.

A: Normally you generate a private key and a certificate signing request, you send the csr to the CA, and the CA issues the certificate. Finally you can generate a keystore and store the private key and the certificate together on it. So I don't understand how is your CA storing the private key in a data base since the private key is not send to the CA.
Omitting this information (maybe you've a selfsigned CA for infrastructure purposes, data base it's not safe to store privateKeys, etc), the thing is; to load a private key and a certificate on windows you need a keystore file (typically for windows a pfx or pkcs12) instead of only a certificate. To do so using java and bouncycastle as you ask you can use the follow sample code (as you said I suppose that you have the certificate and the private key):
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class Sample {

    public static void main(String[] args) throws Exception {

        // generate your certificate
        CertificateFactory cf = CertificateFactory.getInstance("X509", new BouncyCastleProvider());
        Certificate yourCert = cf.generateCertificate(new FileInputStream("C:/your_certificate_path"));
        // here you can add also the issuer of your cert
        Certificate[] certChain = { yourCert };
        // depending on your private key format you've a different
        // ways to parse its
        Key privatekey = null;//...
        String alias = "yourKSEntry";
        // generate the keystore
        KeyStore ks = KeyStore.getInstance("PKCS12", new BouncyCastleProvider());
        // necessary to init a new keystore
        ks.load(null, null);
        String keyPass = null;// your key pass or null if the key file has no password
        // adds the key and cert to the keystore
        ks.setKeyEntry(alias, privatekey, null, certChain);
        // save to file in order that then you
        // can install on windows keystore
        ks.store(new FileOutputStream("C:/where_save_your_keystore.p12"), "your_keystore_pass".toCharArray());

    }
}

Hope this helps,


text:
Q: jQuery: Separate values with comma? I am aware with jQuery append method to extend something after text.
I was actually thinking about extending some special characters dynamically.
I want-
I have two text boxes with display:inline. One is for Basic phone Number and another is for Mobile number. I am getting all this information as summary after submitting with button.
I wanted to separate these two numbers with , separator.
One way I could do this, By separating these with static method.
<input type="number" data-id="#Basic_phone#" /> , <input type="number" data-id="#Mobile_phone"/>

It looks like- 1234569119,9119119119
But it looks bad when there is no value in database for any one input box. Then I need to type numbers, But sometimes I don't have value for one of input boxes.
then I get only (space),(space) or 1234569119,(space) or (space),1234569119.
I want to get comma only when both numbers are there. Sorry I don't have any idea for doing it.

A: Try this Demo as given example
function abc(){
 var str="";
 if($("#Basic_phone").val().length>0)
   str=$("#Basic_phone").val();
 if(str.length>0 && $("#Mobile_phone").val().length>0 )
   str=str+",";

str=str+$("#Mobile_phone").val()

alert(str);
}

<input type="number" id="Basic_phone" /> , <input type="number" id="Mobile_phone"/>
<input type="button" value="hello" onclick="abc()"/>

A: You can use a conditional statements to append Comma(,), like the below one
     if(phoneNo != "" && mobileNo != "" ){
      //do the append code here
     }else{
        print the phone No
      }

A: How are you populating the two inputs?
If with server-side code, then just check the value before outputting the comma and second value:
if(Mobile_phone is not empty)
 show <input type="number" data-id="#Basic_phone#" /> , <input type="number" data-id="#Mobile_phone"/>
else
 show <input type="number" data-id="#Basic_phone#" />


text:
Q: Introductions to Grothendieck I'm an applied mathematician, computer scientist, physicist. I have some basic knowledge of algebraic geometry. Books like this: https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/ crop up every now and again with Grothendieck's inevitably influences on these subjects.
When I come across them/need to top up, I think "I should just learn from the master himself". Unfortunately, almost everything he's written is 10,000 pages long or in French or... :) Whilst on the other hand a textbook on algebraic geometry/category theory, may be in the same field, but have ultimately none of 'his' ideas as such (even if they are built on his foundations).
Have there ever been introduction books (grad level) that basically are able to walk us through specifically his maths/ideas? It is also hard to see with such a large landscape where one should begin with Grothendieck. What is the best way to learn directly from Grothendieck's ideas?


text:
Q: How to prevent the browser cache interfering with NSURLCache? I am trying to achieve the following on iOS:

*

*Always load local files to a UIWebView for static assets (.html, .js, etc.)

*Allow an update protocol such that after some period of time we can return a different set of static assets for the same URLs

Download link for minimal example.
I have this working but it seems the NSURLCache is sometimes completely missed (reproducible) and the only reliable way to fix this has been to use nasty cachebusting tricks on the page being loaded. Another equally nasty hack is to destroy the UIWebView and create another.
As an example of this we have three versions of our webapp (red, blue and green for v1, v2 and v3 respectively):

Each screen is made up of a single HTML and JS file.
index.html
----------

<!DOCTYPE html>

app.js
------
var label = document.getElementById('label');
label.innerHTML = 'red';

Every 2 seconds the following happens:

*

*We change what files the NSURLCache will return to make it return the different versions (note we implement this by overriding cachedResponseForRequest: rather than storeCachedResponse:forRequest:)

*The UIWebView loads a dummy page "http://www.cacheddemo.co.uk/index.html"

The NSURLCache logic is implemented simply as a rotating NSMutableArray:
@implementation ExampleCache

- (id)init
{
    self = [super initWithMemoryCapacity:8 * 1024 * 1024 diskCapacity:8 * 1024 * 1024 diskPath:@"webcache.db"];
    if(self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(swapCache:) name:@"swapCache" object:nil];
        self.cache = [@[@{@"index.html":@"index1.html", @"app.js":@"app1.js"},
                       @{@"index.html":@"index2.html", @"app.js":@"app2.js"},
                       @{@"index.html":@"index3.html", @"app.js":@"app3.js"}] mutableCopy];
    }

    return self;
}

- (void)swapCache:(NSNotification *)notification
{
    [self.cache addObject:self.cache[0]];
    [self.cache removeObjectAtIndex:0];
}

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
    NSString *file = [[[request URL] pathComponents] lastObject];
    NSString *mimeType;

    if([file hasSuffix:@".html"]) {
        mimeType = @"text/html";
    } else if([file hasSuffix:@".js"]) {
        mimeType = @"application/javascript";
    }

    if(mimeType) {
        NSString *cachedFile = self.cache[0][file];
        NSUInteger indexOfDot = [cachedFile rangeOfString:@"."].location;

        NSString *path = [[NSBundle mainBundle] pathForResource:[cachedFile substringToIndex:indexOfDot] ofType:[cachedFile substringFromIndex:indexOfDot + 1] inDirectory:@"www"];
        NSData *data = [NSData dataWithContentsOfFile:path];

        if(data.length) {
            NSLog(@"Response returned for %@", file);

            NSURLResponse *urlResponse = [[NSURLResponse alloc] initWithURL:[request URL] MIMEType:mimeType  expectedContentLength:data.length textEncodingName:nil];
            NSCachedURLResponse *response = [[NSCachedURLResponse alloc] initWithResponse:urlResponse data:data];
            return response;
        }
    }

    NSLog(@"No response for %@ - %@", file, request);
    return nil;
}

The view controller logic uses GCD to reload the UIWebView after the delay:
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    [self.webView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];
    [self.webView setDelegate:self];
    [self.view addSubview:self.webView];

    [self loadContent];
}

- (void)loadContent
{
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%d", @"http://www.cacheddemo.co.uk/index.html", arc4random()]]]];
//    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cacheddemo.co.uk/index.html"]]];

    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"swapCache" object:nil];
        [self loadContent];
    });
}

The part I can not understand here is that adding the query string will make the page reloading work flawlessly (loads R - G - B - R - G - ...) - this is the uncommented line:
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@?%d", @"http://www.cacheddemo.co.uk/index.html", arc4random()]]]];

Once we get rid of the query string the NSURLCache stops being hit other than the first request so it just stays on the R page:
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cacheddemo.co.uk/index.html"]]];

The fact that the query string causes the NSURLCache to act as it is supposed to indicates to me that the browser cache is interfering in some way. In my head I figure the caching levels work as so:

*

*Check browser cache

*If nothing returned so far - check NSURLCache

*If nothing returned so far - check proxy server cache

*Finally attempt to load the remote resource

How can we disable the browser cache entirely so we can completely control caching behaviour for UIWebView. Unfortunately I do not see an option to set the Cache-Control header in NSURLCache - I already tried returning a NSHTTPURLResponse with the headers set but this seems to be ignored.

A: I am not sure I understand correctly, but the cache-control has to be set on server side, with something like no-cache, expires and so on, and not on iOS side.
Second, by modifying the query string i.e. www.mysite.com/page?id=whatever..., iOS and any browser think the request is not the same, if you have opened the cache itself with some db editor, you should have seen one request, which is one database entry, for each changed query.
This trick of adding a random query string is quite useful for avoiding the browser to cache javascript file.
I hope I understand correctly your question.

A: The browser does appear to have its own "cache" above the networking layer's cache (i.e. NSURLCache).
Not sure if setting the cache control headers will solve it but if you want to try that you can do so in your code for cachedResponseForRequest. Where you create an NSURLResponse object you can use initWithURL:statusCode:HTTPVersion:headerFields: to set the header fields (including the cache control headers). In your cache control header you can try using both no-store and no-cache (e.g. http://blog.55minutes.com/2011/10/how-to-defeat-the-browser-back-button-cache/ ). If you try this please let us know if it does or does not work.
However, in practice I think the most pragmatic and maintainable solution will be to the use a number on the URL (i.e. cache busting). BTW instead of a random number you can use a simple increment that gets reset whenever the webview is allocated.


text:
Q: mssql nodejs trustedSecurity So I've been trying to connect to my SQL database using a trusted connection (Windows authentication) using mssql in nodejs but to no luck so far.
I have following config:
var express = require('express');
var config = {};

config.mssql = {
    server: 'CLT-GFI-0278',
    database: 'Interview',
    options: {
        trustedConnection: true
    }
};

module.exports = config;

Having this in config.js I proceeded to integrate this in the file I want to             use mssql in:
var express = require('express');
var router = express.Router();
var sql = require('mssql');

var config = require('./../config');
sql.connect(config, function (err) {
    console.log(err);
});

router.get('/getYear/:year', function (request, response) {
    sql.Request()
        .query('select * from SomeTable')
        .then(function(recordsets) {
            console.dir(recordsets);
        })
        .catch(function(err) {
            console.log(err.message);
        });
    response.send();
});

module.exports = router;

But when I run the app I get following response:

Is there anyone who can guide me in a direction where the trustedConnection would work? I do know that I can create a user and grant it permissions but I would like to get it running like so. Many thanks in advance

A: I struggled with same problem and read somewhere that

It's impossible to use Windows Authentication by default.

You have to login with a login/password combination or use edge package.
https://github.com/tjanczuk/edge
https://github.com/tjanczuk/edge-sql
Example:
var edge = require('edge');
var params = {
    connectionString: "Server=YourServer;Database=YourDB;Integrated Security=True",
    source: "SELECT TOP 20 * FROM SampleData"
};
var getData = edge.func( 'sql', params);

getData(null, function (error, result) {
    if (error) { console.log(error); return; }
    if (result) {
        console.log(result);
    }
    else {
        console.log("No results");
    }
});


text:
Q: puppeteer - centos7 - symbol not found Hi I have a super simple Dockerfile to run puppeteer in Docker:
FROM node:12.2.0-alpine

RUN apk update && apk upgrade && \
  echo @edge http://nl.alpinelinux.org/alpine/edge/community >> /etc/apk/repositories && \
  echo @edge http://nl.alpinelinux.org/alpine/edge/main >> /etc/apk/repositories && \
  apk add --no-cache \
  bash=4.4.19-r1 \
  git=2.20.1-r0 \
  openssh=7.9_p1-r5 \
  chromium@edge \
  nss@edge \
  freetype@edge \
  harfbuzz@edge \
  ttf-freefont@edge \
  sudo=1.8.25_p1-r2

ADD https://github.com/Yelp/dumb-init/releases/download/v1.2.0/dumb-init_1.2.0_amd64 /usr/local/bin/dumb-init
RUN chmod +x /usr/local/bin/dumb-init
ENTRYPOINT ["dumb-init", "--"]

ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD true

WORKDIR /app

COPY package.json .

RUN npm install --quiet -g pm2@^3.5.1 && \
    npm install puppeteer@1.19.0 && \
    npm install --quiet

COPY app.js ./app.js

RUN addgroup -S pptruser && adduser -S -g pptruser pptruser \
  && mkdir -p /home/pptruser/Downloads \
  && chown -R pptruser:pptruser /home/pptruser \
  && chown -R pptruser:pptruser /app

USER pptruser

EXPOSE 1337

CMD [ "pm2-runtime", \
    "start", "app.js", \
    "-i", "max", \
    "--max-memory-restart", "1700M", \
    "--cron", "0 */12 * * *" \
]

This was a working solution until now wehn I have run yum update on my centos7 host machine. Right after that, the app refuses to work properly generating the following error:
Error: LAUNCH_BROWSER
    at /app/node_modules/async/dist/async.js:171:65
    at processTicksAndRejections (internal/process/task_queues.js:89:5)
Error: Failed to launch chrome!
Error relocating /usr/lib/chromium/chrome: _ZNSt7__cxx1118basic_stringstreamIcSt11char_traitsIcESaIcEEC1Ev: symbol not found
Error relocating /usr/lib/chromium/chrome: _ZNSt7__cxx1119basic_ostringstreamIcSt11char_traitsIcESaIcEEC1Ev: symbol not found
Error relocating /usr/lib/chromium/chrome: _ZNSt19_Sp_make_shared_tag5_S_eqERKSt9type_info: symbol not found

I have failed to find a solution so far to put it back in order :-( Any advice appreciated.

A: There is currently a problem with the recent Chromium version on alpine. See these two issues on github for more information:

*

*Issue on the alpine-chrome repository (opened 3 days ago) with your exact error message

*Issue on the puppeteer repository (opened 9 Aug)

Solution
The solution for now is to downgrade the Chromium version to version 72. Some users also reported that version 73 worked for them. You could also give that a try (chromium@edge=73.0.3683.103-r0).
In addition to downgrading Chromium, you also need to downgrade puppeteer to the corresponding version. For Chromium 72 you need to use version 1.11.0. (more information on how to detect the Chrome version to use with puppeteer)
The changed Dockerfile:
RUN apk update && apk upgrade && \
  ...
  chromium@edge=72.0.3626.121-r0 \
...

RUN ...
    npm install puppeteer@1.11.0 && \


text:
Q: Redirect Specific URL if Loaded in UIWebview iOS I'm trying to detect if a specific url is being loaded in a uiwebview and if so redirect the webview to a different url. So far I've got the following code which should seem to work for me but no luck so far, anyone know what I'm doing wrong:
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

    if(request.URL == [NSURL URLWithString:@"https://cheese.com/"])
    {
        NSURL *url = [NSURL URLWithString:@"https://example.com/"];
        [self.webView loadRequest:[NSURLRequest requestWithURL:url]];

    } else {

    }

    return  YES;
}

A: if([request.URL.relativeString isEqualToString:@"https://cheese.com/"]) {

}


text:
Q: Tail projections of conditional expectation Let $\Omega$ be a set, $\mathbb{P}$ a probability measure on $\Omega$, and $\Sigma_0\subset \Sigma$ be finite $\sigma$-algebras on $\Omega$ on which $\mathbb{P}$ is defined.  Let $X$ be a Banach space, $1\leqslant p<\infty$, and let $L_p(X)$ denote the Banach space of (equivalence classes) of Bochner $p$-integrable $X$ valued functions on $\Omega$ strongly measurable with respect to $\Sigma$. Let $L_p(X, \Sigma_0)$ be defined similarly. Let $Z$ denote the subspace of $L_p(X, \Sigma)$ consisting of those $f\in L_p(X, \Sigma)$ such that $\mathbb{E}(f|\Sigma_0)=0$. Then $f\mapsto f-\mathbb{E}(f|\Sigma_0)$ is a projection onto $Z$. Standard facts yield that $f\mapsto \mathbb{E}(f|\Sigma_0)$ is a norm $1$ projection of $L_p(X, \Sigma)$ onto $L_p(X, \Sigma_0)$, so the complementary projection $f\mapsto f-\mathbb{E}(f|\Sigma_0)$ of $L_p(X, \Sigma)$ onto $Z$ is norm at most $2$.
What is the exact norm of $f\mapsto f-\mathbb{E}(f|\Sigma_0)$?


text:
Q: Is there a way to Chrome command-line argument that it will use a local file as a CA (cert authority) for that session only? Let's say I've created a local private CA (with OpenSSL) (eg. https://stackoverflow.com/a/60516812/8679778).  I can use it from a client application that uses https to a server running on the same computer, using a cert from the same locally created CA.
But what if I want Chrome to have the same capability.   I know I can register the CA with the local root store, but I don't want to affect the entire system -- just a specific invocation of the browser.


text:
Q: STS + Roo maven fail I can't run any of the "perform" commands from the STS Roo Shell.
I keep getting:
~.web roo> perform package
error=2, No such file or directory

If I go to a non-STS shell, everyting works properly.
OS: Mac OSX 10.10
STS: 3.6.1.RELEASE
ROO: 1.2.5.RELEASE [rev 8341dc2]

A: Make sure that you have Maven installed correctly on your machine. Open terminal then mvn -v to test Maven installation.


text:
Q: Debian source control and bug tracking server - what's a good backup plan? I run a subversion source control server from my house on a debian machine.  I will be setting up Jira for bug/project tracking very soon so I now have the necessary motivation to put a proper backup plan in place.  The current hard drive in my server is going on probably 10 years (an old 80GB IBM deskstar) so I'm looking at picking up a couple of 250GB WDs from newegg and see these options so far for my backup:
1) Setting up a RAID1 array

*

*I have never setup a RAID
configuration before

*My gumption is that this is more
robust, but does that come at a cost
of    complexity?

*How difficult is it to replace a drive that goes bad in RAID1 configuration?

*I do not need instant access to my
data, 24 hour replacement is good
enough - so RAID may not be the best option

2) Setup a nightly diff backup

*

*Is this simpler to setup and maintain?

*Are there any good free linux diff
backup programs?

I also plan on using something like Jungledisk/AmazonS3 for offsite backup.  I welcome thoughts on the above 2 options, and any alternative solutions.

A: Raid is not a backup option. Please repeat that out loud at least ten times. Do not rely on it for data integrity, you will get burned.
The purpose of raid is to have less time where your data is unavailable due to mechanical failures. (and to increase throughput)
The complexity of raid1 depends a little on the controller. The way your setup sounds, it could be a good idea to use linux soft raid. Use the 'new' drive to create a degraided raid array, move all the data to it (no need to reinstall, you could move the OS with a live-cd if you want to), then wipe the old drive and attach it to the raid. Do this after you have proper backups. Replacing a drive is as simple as that.
rdiff-backup is my tool of choice in a lot of situations (don' forget to clean up old data), you may also like rsnapshot. Any backup storage to different machine, preferably on a different location is a good one, if it comes down to JD/S3 I have no preference.
Make sure to take dumps of both the svn repos and the database and include them in the backups. (do not believe that about svn fsfs backends not needing this)
Check your backups once in a while, and check your backup process daily. Do this is a way it requires least effort; routine chores lapsing can give you a false sense of (data)security, with a nasty wakeup later (don't ask...)
Last but not least: make sure you have checked out redmine before you settle on jira; it's a matter of taste, of course.
Bonus points for running 10 years on a single deathstar