Django static files not serving when running inside Docker container

Question: I have a django application thats is rendering the static files when run outside docker container. I added a Dockerfile so that I can run it in a container. However, the static files are not getting served when running in the container
The sample app that I have used can be found here
I have added the following Dockerfile at the root level
FROM python:3.8

#add project files to the usr/src/app folder
ADD . /usr/src/app

#set directoty where CMD will execute
WORKDIR /usr/src/app/wisdompets
COPY requirements.txt ./

# Get pip to download and install requirements:
RUN pip install --no-cache-dir -r requirements.txt

# Expose ports
EXPOSE 8000

# default command to execute
CMD exec gunicorn wisdompets.wsgi:application --bind 0.0.0.0:8000 --workers 3

And the requirements.txt file at root level as below
django==3.0.3
gunicorn==20.0.4

The static files settings in my settings.py is as follows
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]

Please let me know if there's something wrong with my configuration
Answer: You are missing collectstatic command which will package static files alongside the app.
Check this link for reference.
Comment: Where did you add it? If you are running it before creating a Docker container, did you create `volume` for sharing static files from your file system to the container?
Comment: I followed the link you gave. They are doing that in the docker entrypoint script which is invoked when the container is started
Answer: Revisa keeps you configured.
STATIC_ROOT

You should have no problems when you run the command.
python manage.py \
        collectstatic \
        --verbosity 0 \
        --noinput \
        --clear

If it's fine but still doesn't render the statics.
Check the gunicorn documentation.
I recommend you to use uwsgi is much more elegant.
https://uwsgi-docs.readthedocs.io/en/latest/


Variance of the Square

Question: Suppose $X_1, \cdots, X_n$ are a sample of independent variables taken from a normally distributed population with mean $\mu$ and variance $\sigma^2$.
I would like to determine the variance of the squares $X_1^2, \cdots, X_n^2$.
From a Monte Carlo simulation it seems that when $\mu$ is large enough, it is close to $\operatorname{Var}(X^2)= (2\mu\sigma)^2$, but I have no proof, and I'm struggling to come up with one. I understand it has to do with the Chi-Square distribution, but I have not connected the dots.
Answer: $Var(X^2)=E(\{X^2\}^2)-[E(X^2)]^2=E(X^4)-[E(X^2)]^2$
Wikipedia has the non-central moments of a normal distribution.
$$E(X^4)=\mu^4+6\mu^2\sigma^2+3\sigma^4, E(X^2)=\mu^2+\sigma^2$$
Thus$$\begin{align}Var(X^2)&=\mu^4+6\mu^2\sigma^2+3\sigma^4-(\mu^2+\sigma^2)^2\\&=\mu^4+6\mu^2\sigma^2+3\sigma^4-\mu^4-2\mu^2\sigma^2-\sigma^4\\&=4\mu^2\sigma^2+2\sigma^4\end{align}$$
A circuitous answer involving the chi-squared distribution with one degree of freedom:
$$\left(\frac{X-\mu}{\sigma}\right)^2\sim \text{Chi Squared}(1)$$
The variance of a chi-squared random variable with 1 df is $Var(\chi^2_{1})=2$ so $$\begin{split}2&=\frac 1 {\sigma^4}Var(X^2-2X\mu+\mu^2)\\
2\sigma^4&=Var(X^2)+4\mu^2Var(X)-4\mu Cov(X^2, X)\\
&=Var(X^2)+4\mu^2\sigma^2-4\mu\left(E(X^3)-E(X^2)E(X)\right)\\
&=Var(X^2)+4\mu^2\sigma^2-4\mu(2\mu\sigma^2)\end{split}$$
and so $Var(X^2)=2\sigma^4+4\mu^2\sigma^2$.
Answer: $$var(x) = E(x^2) - E(x)^2 = \sigma^2$$
$$ E(x^2) = \sigma^2 + \mu^2$$
$$var(x^2) = E(x^4) - E(x^2)^2$$
$$= [\mu^4 + 6 \mu^2 \sigma^2+ 3 \sigma^4 ] - [\sigma^2 + \mu^2]^2 $$
$$ \mu^4 + 6 \mu^2 \sigma^2 + 3 \sigma^4 - \sigma^4 - 2\sigma^2 \mu^2 - \mu^4 = 4\sigma^2 \mu^2 +2 \sigma^4   $$

Variance of the Square


Read/write as3 zip using fzip

Question: I'm creating a custom file type in AIR, which is a zip file under a different extension. I've been trying a few libs out, and settled on Fzip. This is to house my apps project files.
The tests seem to run OK, apart from occasionally getting 'Unknown record signature' Error.
I'm wondering if I'm missing something, and perhaps someone can shed some light. First time I've attempted something like this.
It seems to occur randomly, I have a basic app which allows you to add new files at runtime. Contents display in a list and upon select you view the text content.
From time to time when adding a new file, saving, then reopening I get this unknown record error. The main functions which could be the cause
<code>    private function openComplete( event:Event ):void {
        _zipFile.loadBytes( _file.data );
        dispatch( new ZipServiceEvent( ZipServiceEvent.CONTENTS_CHANGE ) );
    }
    public function saveFile( event:Event=null ):void {
        if( _file.isDirectory ) {
            browseForSave();
            return void;
        }
        if ( _file.extension != _ext )
            _file = new File( _file.nativePath + _ext );
        var stream:FileStream = new FileStream();
        stream.open( _file, FileMode.WRITE );
        _zipFile.serialize( stream );
        stream.close();
    }
    public function getFile( name:String ):FZipFile {
        return _zipFile.getFileByName( name );
    }

    public function addFile( name:String, contents:ByteArray ):void {
        _zipFile.addFile( name, contents );
    }
    private function saveFileHandler( event:Event ):void {
        var contents:ByteArray = new ByteArray();
        contents.writeMultiByte( view.filecontents.text, 'utf-8' );
        model.addFile( view.filename.text, contents );
    }
</code>
Comment: So did you solved this issue?
Answer: I would need to test you class to look for errors… I wont have time to check it but in the meanwhile I´ll post an Util class I created for this purpose. It´s not very extensive, it was just for a small project but it may help you…
<code>package com.models
{
    import com.events.AppEvent;

    import deng.fzip.FZip;

    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.IEventDispatcher;
    import flash.utils.ByteArray;

    public class ZIPEncoder extends EventDispatcher
    {
        private var _zip:FZip;
        private var _compressedBytes:ByteArray = new ByteArray();

        public function ZIPEncoder(target:IEventDispatcher=null)
        {
            super(target);
        }

        public function newZip(name:String = ""):void
        {
            if(_zip) _zip = null;
            _zip = new FZip();
            _zip.addEventListener(Event.COMPLETE, onZipComplete);
        }

        public function newEntry(name:String, bytes:ByteArray):void
        {
            if(_zip == null)
            {
                throw(new Error("No zipOutput initialized. Call newZip() to initialize a new ZipOutput object before creating entry instances"));
                return;
            }
            _zip.addFile(name, bytes);
        }

        public function compress():void
        {
            _zip.serialize(_compressedBytes, false);
            dispatchEvent(new AppEvent(AppEvent.ZIP_ENCODED, _compressedBytes));
        }

        private function onZipComplete(event:Event):void
        {
            dispatchEvent(new AppEvent(AppEvent.ZIP_ENCODED, _compressedBytes));
        }
        //public function get zip():ZipOutput { return _zip; }
    }
}
</code>
hope it helps…
Comment: Thanks for your reply, I'll test it out. I can see you're serializing to bytearray where as Im passing a file stream. I'll test serializing to byte array before writing.
Comment: Nope regardless of Stream or ByteArray random errors seem to occur. I can't quite put my finger on what it is. All the logic seems sound. Since it's an air app, i'm going to try out native process and 7zip/p7zip

Read/write as3 zip using fzip


popup menu not launching new activity

Question: My pop up menu displays with these options:
New Contact
Share
Settings

When 'New Contact' is clicked it should open the activity Make_a_contact. But nothing happens - the pop up menu just closes down, like nothing is supposed to happen. Any ideas? They'd be much appreciated. The code I have at present is:
In my Manifest:

<uses-sdk
    android:minSdkVersion="11"
    />

<uses-permission android:name="android.permission.READ_CONTACTS"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

    <activity
        android:name=".thisisatest"
        android:label="@string/title_activity_thisisatest">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Make_a_contact"
        android:label="@string/title_activity_make_a_contact" >
    </activity>
</application>

In my thisisatest.java:
    package com.example.chris.omgandroid;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SimpleCursorAdapter;

public class thisisatest extends ListActivity {
    @Override
    public long getSelectedItemId() {
        return super.getSelectedItemId();
    }
@Override
public int getSelectedItemPosition() {
    return super.getSelectedItemPosition();
}

ListView lv;
Cursor cursorl;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_thisisatest, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    //noinspection SimplifiableIfStatement
    if (id == R.id.New_Contact) {

        Intent intent = new Intent(this, Make_a_contact.class);
        startActivity(intent);

        return true;
    }
    return super.onOptionsItemSelected(item);
}

public void Show_Settings(View v){

    PopupMenu popup = new PopupMenu(this, v );
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.menu_thisisatest, popup.getMenu());
    popup.show();
}
}

My menu looks like:
   <menu 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"
    tools:context="com.example.chris.omgandroid.thisisatest">

<item
    android:id = "@+id/New_Contact"
    android:title = "New Contact"
/>

    <item
        android:id = "@+id/Share"
        android:title = "Share"
    />

    <item
        android:id = "@+id/Settings"
        android:title = "Settings"
    />
</menu>

Make_a_contact class:
package com.example.chris.omgandroid;

import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class Make_a_contact extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_make_a_contact);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_make_a_contact, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
Edit Note: Thanks to Greg below I now know the problem is with setOnMenuItemClickListener But how do I implement this to get my popupmenu to work? I am obviously missing code somewhere. In thisisatest.java I have modified the public void Show_Settingsnethod so it now reads:
   public void Show_Settings(View v){

        PopupMenu popup = new PopupMenu(this, v );
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.menu_thisisatest, popup.getMenu());

        PopupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(getApplicationContext(),item.toString(),Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        popup.show();
    }

When I build the project I get the error:
Error:(91, 18) error: non-static method setOnMenuItemClickListener(OnMenuItemClickListener) cannot be referenced from a static context

Comment: post the `Make_a_contact` class and also change the name of your class, you should follow the `naming convention for class`
Comment: He is telling you not to use underscores in your activity names, which is true, but it wouldn't cause the problem
Comment: posted my Make_a_contact class. What's wrong with the name?
Answer: You need to set a click listener on the popup menu using setOnMenuItemClickListener and handle the click there.
The onCreateOptionsMenu/onOptionsMenuSelected calls are used for showing action bar items in your activity toolbar, completely different thing from your popup menu.
Comment: No problem, you just need to reference your instance of the popup menu. Instead of `PopupMenu.setOnMenuItemClickListener(...)` it should be `popup.setOnMenuItemClickListener(...)`
Comment: Thanks, but I have little knowledge of how to implement this, as I'm new to Android. If you could develop on what I have at present I'd be grateful. I've edited and added code to my original question.

popup menu not launching new activity


How to deal with vimeo iframe and position fixed elements?

Question: My site: dwapotwory.com uses embed vimeo videos. In Safari (Mac) and sometimes on Chrome (both Win/Mac) when the iframe is loaded every single element that has position: fixed (header and left/right button divs) crashes.
Without iframe in Safari everything is fine: http://dwapotwory.com/1.html
With iframe in Safari...: http://dwapotwory.com/2.html
I have the iframe wrapped in div and set to scale when scalling the browser window but it's not causing the problem (I've tried a few responsive embed vimeo solution and it didn't make any difference).
Comment: I have something similar going on, only on Safari (Desktop) with the video tag. Basically all the elements *before* the video tag go absolute where as the ones *after* get correctly positioned (fixed). In my case the parent is fixed, and the child elements absolute.
Answer: So I run into this question because I have a similar problem with videos (just video tags, not actual iframes etc.) and fixed-positioned containers.
The Safari issues seems to be quite random, in my case I fixed it by adding -webkit-transforms to the fixed container, but in yours it can apparently be solved simply by setting a z-index to the absolute container of the frames, i tried by manipulating your DOM directly in the inspector and it seems to work.


How can I correct a crowned floor joist?

Question: In my son's bedroom there is a raised spot in the floor along one of the joists. I went into the crawlspace with a level and that joist is bowed up about 3/4" to 1" compared to the other joists on either side of it.
Best I can tell, this may have been like this when the subfloor went down as the subfloor is well attached to the joists in this area. Also, the blocking isn't flush with the bottom of the crowned joist where it peaks. Everything else around this one joist looks okay and I'm not noticing any signs of settling in the drywall inside or the brick outside.
I noticed the raised spot shortly after we bought the house a few years ago, but recent furniture placement has made it incredibly obvious. I don't think it has gotten any worse since then. Is there anything else I need to look for that might indicate a serious problem?
If the problem is just this one joist being bowed up as I suspect, what are my options to remedy the situation? Is there any way that I can pull it down from below?
EDIT
After thinking about this some, would it be possible to attach a piece of steel angle or t bar to the crowned joist with lag bolts and use the joists on either side to pull it down?
Comment: My first thought: assuming you can get at the joist from underneath, first draw a level line at the top of the joist. What's above this line is the part to be removed. Then use a reciprocating saw to cut out this part. I would use a metal cutting blade because you'll likely cut through nails too. Next, if necessary to re-anchor the sub-floor (in your judgement), I would drill pilot holes through the joist at angles. Then, with someone standing on the floor to push it down onto the joist, attach the joist to the sub-floor with decking screws.
Comment: how long is the bowed floor joist? You are certain this is the only joist with the problem?
Comment: @shirlockhomes The joist is bowed for most of it's length. It tapers from peak over about 4' on either side. This joist is the next to last one from the outside wall. The joists on either side plus the next two towards the middle of the house line up.
Comment: @getterdun The length of the crown is pretty long. I think I would need to do this from above to make a decent cut.
Answer: Pretty simple to fix if you have access from underneath. I would start by adding a couple of 2x4 with screws underneath several of the joists on each side of the problem joist.
Next, cut the joist vertically at the location where the bump is. This will let the joist sag down on top of the 2x4 braces that you added.
Finally add a sister next to the joist that you cut. The simplest thing to do is to use a piece of wood of equivalent size as the existing joist. It is glued onto the existing joist with construction adhesive and then bolted together securely with closely-spaced bolts.
Comment: +1 Good idea, I wished I thought of it. Actually the 2X4s could be added after the notch is made and the glue and 8 ft. long joist is applied. Then use screws to draw down the crown, then set the splicing joist in tight. The joists that is cut, will stay crowned unless acted upon by an outside force, though it may drop a teensy bit... not enough for concern. With a little forethought it can be assembled in such a way that one 2X4 is placed loosely to make it easy to slide the splice in place before the other 2X4s are added.
Comment: How long should the sister be?
Comment: @ josh, 8 ft long with construction adhesive and 2 1/2 or 3 inch screws
Answer: I was thinking along the line of the steel angle too, but do it in at least 2 places if not 3, where they are spaced 2 to 4 ft. apart depending on how long the span, the idea would be to break it up in thirds, the mid third is where the steel would be, then split that up into equal spaces for the placement of the angles or Kendorf track is what I was going to suggest. Not lag bolts either, they will pull through with enough force drawn on them. My idea was to use a tightly bent 1/2" all thread, or a long 1/2" bolts the correct length, with the head welded to the head of another 1/2"bolt the right length to go through the joist a few inches below the top of the joist. The short bolt is drilled through the joist and set with washers and a nut snugly, and the long bolt is ran through the metal that is under the joist and set with a washer and nut too. Tighten down in stages, the joist will not want to go straight in one setting. It will take 2 or 3 tightening to get it straight, with a week or longer between each tightening. Alternate the placement of the bolts so all are not pulling to the same side, trying to twist the joist.
Comment: In my opinion the joist should be cut down from the top, I had to do that in my home, it takes a couple of hours once the flooring is gone, of course, that is the trouble, the flooring. Mine was easy I had new carpet coming in the next day. I noticed the high joist when I removed the old carpet. I cut out a span of plywood over 3 joists total, the high one in the center, planed it down with my electric planer and was able to reset the same subfloor I cut out. I pulled all the nails first then cut the path the nails were on with a saw set to depth of the subfloor.


Mounted Combat: How to manually choose side to attack

Question: Is there any way how to override the side where I'm going to swing with the weapon? Sometimes, especially when charging a group of enemies, I want to choose the target myself.
Sub-questions for bonus points :-)

difference between fast and strong attack when mounted? (I didn't find any)
using horse's kinetic energy to inflict damage possible? (doesn't seem so)
Answer: You cannot choose manually, it will always be based on target selected. However, you can lock onto the enemy and swap between who is selected and ride to whichever side you prefer. Not sure of your system, but on PS4 you can click in the right(?) stick and flick left and right to swap.
As far as your other 2 questions, I believe there is no difference in attack type (from what I can tell, although I don't have proof at the moment). And you will do different damage on horseback, but the speed of the horse doesn't come into play (from personal experience). I've simply walked Roach in and it does the same damage and a full gallop. Roach also doesn't appear to damage enemies by physically colliding with them.
Comment: I'm only "pretty sure" about the PS4 control I mentioned. I haven't played recently so my memory *might* be a tad fuzzy...
Comment: I have PC, but play with a Logitech controller with x360ce and yeah, it's right-stick-press to lock onto enemy and flick it to swap. Actually, what I meant with the horse speed is whether the horse itself does damage when it hits an enemy, but I don't think that's the case (would make mounted combat too easy).
Comment: Ah! I will edit my answer to reflect that as well. But no, I don't notice any collision events between Roach and enemies... Roach's collisions with enemies/objects aren't the greatest part of this game in my opinion... Hope my answer helped anyway!
Comment: In my experience, a correctly executed charge attack will always one-shot a human enemy, even one of a significantly higher level than Geralt.
Comment: I have to strongly disagree here. Playing on Death March, I've definitely had "trouble" with human enemies despite being on horseback.


How to get the URL of the currently executing PHP script?

Question: How do I get the URL of the currently executing PHP script?
For example, the URL http://www.domain.com/folder/script.php sends a request to /var/www/domain/folder/script.php.
In script.php, I want to echo http://www.domain.com/folder/ (not /var/www/domain/folder/, not http://www.domain.com/folder/script.php). What is the simplest way to do this?
Answer: A simple Google search would have answered your question. Here's the result.
http://php.about.com/od/learnphp/qt/_SERVER_PHP.htm
Comment: $_SERVER['PHP_SELF'], $_SERVER['REQUEST_URI'] and $_SERVER['SCRIPT_NAME'] return path with script file name instead of the path alone. I want to know if there is a variable set to the path alone.
Comment: See solution by Mihai Iorga below. PHP doesn't come with that function out of the box, but with about half a minute of time, you can get the desired functionality. That takes less time than posting on SO.
Answer: It is not that sophisticated, but here it goes:
<?php
    $scriptFolder = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';
    $scriptFolder .= $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);
    echo $scriptFolder;
?>

Comment: A better solution might use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['REQUEST_URI']. And what about "https://"?
Comment: @powerboy: did you read the PHP documentation pertaining to $_SERVER? I believe php.net and its comments cover everything you're asking.
Answer: I was looking for an answer for this question, it seems there isn't an easy one.
Then it hit me: it is because it is not always possible to get the current script url.
PHP can include a file anywhere in the file system, as long as the user running the process has access to it, it will work. But then, that means it is possible to include scripts outside the webserver's root directory - hence impossible to have a url. I believe that is the reason there is not straight forward function to do that.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/13920864)
Comment: Well, it is a question without an answer, and I explain why I think it is the case.


Can lack of sponsored content reduce trust in a list/ranking?

Question: We've been doing some research on a website of ours. On this website we help the user pick the cheapest product for what they are searching for (example: TV / Smartwatch etc).
In the heatmaps we see that if there is no sponsored content, most of the users click the second option. While if we do show sponsored content, most of the users select the first non-sponsored option. The sponsored content is, in all cases, clearly marked paid content.

While doing user interviews (for general research) we noticed that a lot of users say they do not trust 'websites that compare stuff' because they do not know if the content is sponsored or not.
In the user interviews after a usertest the user says they picked the second option in the non sponsored list because it looked the best for them. Users that had sponsored content also picked the second one and gave the somewhat the same reply.
However in the sponsored list the 3rd option would be the same option as the 2nd in the non sponsored list.
So my question is as followed, would showing sponsored content increase the trust of the list because it is clearly marked? And when there is no sponsored content, would the user pick the second because they maybe assume the first is sponsored content?
Note: The usertests were qualitative and not quantitative
Comment: https://www.nngroup.com/articles/banner-blindness-old-and-new-findings/

I'd say the most obvious answer is that we've been so accustomed to seeing ads that we see then even when they aren't there.
Comment: Examining more in detail why user chose second option would be good. Assumption can be also that they skip first option as they thinks it's an Ad. More metrics in Qualitative research would help you. Also if you google "banner blindness" and check in details how it works you can see if that's it. Google adwords banner blindess is probably most learned UI pattern for that.
Comment: Very good question.
Comment: @xul Indeed, In my case the sponsored content is marked as paid content the design is somewhat different. If the 'second non paid' option would be better for the user it should show in both heatmaps in my opinion. I edited my post somewhat.
Comment: "Why did you picked the second option", "What do you think about first option".. You can always ask that.. Without its just a guessing game. But very interesting, would love to hear outcomes
Comment: It may be that users under test are behaving differently to how they would if in a comfortable environment browsing at their own pace. Is your list ordered in any way other than having sponsored content at the top (if present)?
Answer: There are clearly some additional complexities and contexts that might explain the observations made, but if we look at the key aspects of trust it might be possible to try and tease out what are the most important factors in this particular context.

Trust can come from familiarity, and this is certainly a common
psychological behaviour which can be reinforced over time but also
taken away very suddenly with some potentially disastrous results.
Trust can also come from social proof, especially when there are
brands or influencers (including subject matter experts) to provide
objective and impartial value to the users.
Trust can also come from personal biases of individual users and
groups that are established and not susceptible influences other than
those that are from within the group.

As was mentioned in the question, the results are qualitative and not quantitative, so the degree to which these different factors that influence trust are at play here requires more investigation, but that would be outside the scope of this question in terms of whether the sponsored content can reduce trust. In other circumstances it can also increase the level of trust.


Exclude results from array that contains ONLY the sent query. MongoDB

Question: I'm trying to build a Query that excludes results from an Array when it only contains the String sent in the Query.
I have these two Arrays
Array 1
[ { _id :'first', subCategory : '5K'}, { _id : 'second', subCategory : '10K'}]

Array 2
[ { _id :'first', subCategory : '5K'}]

I want to exclude JUST the second one, so I can't use
query.$and.push({ subCategory: { $nin: '5K }});

I tried this, but it didn't work either :
query.$and.push({ subCategory : { $elemMatch : { $nin : '5K' }}});

Thank you for your time!!
Answer: Ok, I solved it.
query.$and.push({ array : { $all : [{ $elemMatch : { subCategory : { $nin : '5K' }}}]}});


Add SameSite Attribute to Passport.js Session Cookie

Question: I am authenticating against an OIDC service using Passport.js with the OAuth2Strategy strategy. The application makes some cross-domain requests to services that need the connect.sid cookie that is set by Passport.  Chrome is promising to stop supporting these requests unless the SameSite attribute of the cookie is set to "Lax".
I'm not sure how to do that as the setting of the cookie is internal to Passport.  Any suggestions?  Below is the relevant function call that lives in the callback route given to the OIDC service.
  passport.authenticate("oauth2", function (err, user, info) {
    if (err) {
      req.flash('error', err);
      res.redirect('/login_error/');
    }
    else if (!user) {
      req.flash('error', 'Unable to locate user account.');
      res.redirect('/login_error/');
    }
    else {
      req.logIn(user, (err) => {
        if (err) { return next(err); }
        return res.redirect('/user_profile/);
      });
    }
  })(req, res, next);

Comment: The upcoming Chrome changes will mark cookies as `SameSite=Lax` by default unless otherwise stated, so if you're not relying on cross-site POST requests this should continue working. What backend service are you using? It may be possible to reach out and get them to update their cookies.
Comment: Thanks for the clarification, Rowan -- much appreciated. I'm using Express.js on the backend.
Comment: @sean_x Did you get any solution for this?
Answer: Answer: Try using href. Or set-up proxy on the client app to the server app.
I had faced the same issue. Have researched far and wide. Summary below.
Use-case and tech-stack: Using Passport.js to implement Google OAuth authentication with React and Express. Using CORS in express. Also, set-up a middleware in Express to add Access-Control-Allow-Origin, Access-Control-Allow-Headers and Access-Control-Allow-Credentials to each response. Still did not work.
Solution: Only solution that seems to work is to use an href from the front-end to call the authentication URL (e.g. /auth/google). Or to set-up a proxy from the client to redirect requests to the server (Have not tried or tested this yet).
Long-term solution: Passport.js needs to add same-site=none to the cookie it sends to the client for chrome to allow redirecting the requests with fetch.
Core issues: axios doesn't work due to redirect issue. OAuth API need to redirect to client URL after authentication. Fetch doesn't work due to Chrome same-site=lax cookie issue. XHR faces issues as well. Perhaps a combination of redirect, cookies and CORS challenges.
P.S. Also learned that setting res.header('Access-Control-Allow-Origin', '*') in Express doesn't work for axios. axios seems to require a specific domain
Comment: PassportJS already supports changing the `sameSite` and `secure` fields for the cookies it sets; however, these settings are controlled by the specific session middleware that PassportJS employs, rather than configurable through PassportJS itself. See here for an example (with the [cookie-session](https://github.com/expressjs/cookie-session) package): https://stackoverflow.com/a/69207405/2441655


socket.io, node.js forwarding image from server to client

Question: I want to receive an image via socket.io on node.js and would like forward it to a client (browser), but the image sent via the message to the browser is not recognised and therefore not show.
However, when I save the message/image first on the node.js server and load the saved file again to forward the image it works fine. I can also open the jpeg file on the server from the file system without a problem. Sending a different jpeg directly from the server works also as expected.
socket.on('image', function(msg) {
        var fileName = 'clientImage.jpg';

        // First save the file
        fs.writeFile(fileName, msg.buffer, function() {});

        // reload the image and forward it to the client
        fs.readFile(__dirname +'/clientImage.jpg', function(err, buf){
            socket.emit('serverImage', {image: true, buffer: buf});
        });
    }

If I simplify the function to forward the message (msg) received without the "fs" workaround, like:
socket.emit('serverImage',  {image: true, buffer: msg.buffer});

or in the simples expected way
socket.emit('serverImage',  msg);

the message will not be recognised as an image on the browser and the client does not fire the "onload" event for the Image.
Client code (works with jpeg files fine):
socket.on('serverImage', function(msg) {
    var blob = new Blob([msg.buffer], {type: 'image/jpeg'} );
    var url = URL.createObjectURL(blob);
    var limg = new Image();
    limg.onload = function () {
        console.log(' -- image on load!');
        rcontext.drawImage(this, 0, 0);
        URL.revokeObjectURL(url);
    };
    limg.src = url;
});

Is there a way that the message can be adopted/converted somehow i.e. encoding, to be recognised directly without the "fs" library, or any other suggestions?
many thanks!
Answer: Many thanks for the responses,
I did further tests and found a workaround / solution by using an additional buffer variable specifying the type in front of the socket.emit :
var nbuffer = new Buffer(msg.buffer,'image/jpeg');
socket.emit('serverImage',  {image: true, buffer: nbuffer});

with this additional step, the browser recognises now the message as image.
Many thanks for your help!
Answer: writeFile is asynchronous. It takes time to write a file to the disk. You passed it a callback function, but it's empty. Re-read the image inside that callback function.
// First save the file
fs.writeFile(fileName, msg.buffer
    , function() { // When writing is done (that's the important part)
       // reload the image and forward it to the client
       fs.readFile(__dirname +'/clientImage.jpg', function(err, buf){
            socket.emit('serverImage', {image: true, buffer: buf});
        });
});

Comment: Many thanks for your response. But this would still need to save and reload the message to disk! Would like to forward without fs activities.
Comment: Why don't you just send back `msg.buffer` then?


Cannot POST to Trello API even when authenticated

Question: I've been trying to get a Google Apps Script up and running to move spreadsheet entries into a Trello board each time a form is completed. I'm testing the OAuth1 flow, but regardless of how I authenticate, I cannot POST anything (GET requests have worked so far on everything except cards). I've confirmed the apps have the necessary read/write permissions in my account settings.
For testing purposes, I used the Single Use Token option in Trello via the following URL:
https://trello.com/1/authorize?name=SingleUseTesting&expiration=never&scope=read,write&key=MYKEY
Authorizing showed that the app had permission to read and write to my account.
Authorization showed up in my account dashboard as read/write enabled.
I can get a response for my cards from:
https://api.trello.com/1/lists/LIST_ID/cards
When I try to POST via the API URL using the following:
https://api.trello.com/1/lists/57a0b90f8b1740162702fa22/cards?&name=testing&due=null&key=MYKEY&token=MYTOKEN
I get an error saying the token is invalid. I even went so far as to revoke access to all other apps to see if it was checking the wrong token for some reason, but with no change in result.
I need to make sure the POST URI works to send the payload object from Google Apps Scripts successfully, but I can't get beyond this step. Any insight on where I'm going wrong?
Answer: The solution isn't in the Trello documents (that I can find), so I'm posting it here in case others run into the same problem.
Since Google has dropped the OAuth1 library objects and methods, it's much easier to request a perpetual token for your Trello API key through a URL. But, in order for that to work, you have to set the request_type to token in the URL.
The authorization request should look like this:
https://trello.com/1/authorize?key=YOUR_APP_KEY&name=APP_NAME&scope=read,write&expiration=never&response_type=token
The returned page has a string which is included in the payload to authenticate the write request for the API key.
A full, working code example can be found in this GitHub Gist.
Answer: A bit late, but here's what I found.
If you have your application working with GET requests, you should have a fetch URL that looks something like this:
var url="https://api.trello.com/1/boards/MY_BOARD_ID/lists";

Unless you specify otherwise, GET requests are the default method in Trello API.
For the other three types (PUT, POST and DELETE) you need to pass the request method as parameter.
Here's how it's coded on my script:
var url="https://api.trello.com/1/cards/MY_CARD_ID/pos?value=top";
var options={"method":"put"};
var response=service.fetch(url,options);

As you can see on this snippet of code, the actual request parameters are passed through the URL and the method inside the options variable. My guess is that you can also send it via payload object inside the options variable, but I'm too lazy to test it right now.
The methods to be used with each request are described on Trello API documentation:
https://developers.trello.com/advanced-reference
I hope it helps.


Complex continuous run vs easier single junction boxes

Question: I am currently in the process of finishing my basement and I am doing the electrical wiring of all my rooms. The work will be checked by my electrician before he connects everything to the electrical panel.
For all of my electrical outlets and other appliances, I have used a continuous circuits that have no unnecessary junction box. The junctions take place from one outlet to another, etc.
However, for my light and my heating circuits (one of each), I am considering using two single junction boxes at the center of my basement that would have 4 load romex going out to each of the rooms of my basement. That would save me from using a continuous circuit that would require hundreds of feet of cabling passing through weird places (under sheetrock ceiling, around staircases, etc.) instead of going through the middle of the main room that has dropped ceilling for easy access. Also, if I want to add lights in the future, I would be able to just add a cable to this 4x4 junction box.
I know that the use of junction box is frown upon, but since they would be under a drop ceiling (easy access), would you consider that this design is justifiable?
Also, I know having a single light circuit is not ideal, but that would power a few low wattage LED and won't utilize 10% of this 15 amp circuit. Again, having a center junction box could enable the addition of another 15 amp circuit load line, but I highly doubt this would be required.
Comment: Junction boxes are not frowned upon, they are quite normal.. They do need to be accessible.
Comment: Where are you located? Depending on country/state, etc, answers may vary.
Comment: My location is in Canada.
Answer: It seems the heart of your question is topology. "Bus" topology is what you have for your outlets, in which power comes from the distribution panel to one outlet, then to the next, and so on like a chain. "Star" topology is one in which power comes from the distribution panel to a central point and then branches out in multiple directions. It sounds like this is what you're entertaining for the lighting.
Both bus and star are acceptable. Wire sizing, demand calculations, and so on are the same regardless of the topology.
As for the junction box at the heart of the star topology: it needs to be in an accessible place, and it needs to be sized appropriately to contain the wires.
"Accessible" means it can be reached without removing any part of the building. Drop-in ceiling tiles seem to be accepted as "accessible" virtually everywhere, so if you make the junction in a box (don't forget the cover) and put it above a drop-tile ceiling that'll be fine.
Junction box sizing is determined with an exercise called "box fill calculation." It considers the number and gauge of conductors being joined or merely passing through, any devices like switches or outlets also in the box, etc. Boxes are marked with their cubic inch volume; the box fill calculation tells you the minimum number of cubic inches needed.
Comment: @jay613 -- see [this Q/selfA of mine](https://diy.stackexchange.com/questions/177103/what-are-the-legalities-associated-with-mounting-splicing-wire-connectors) if you want to know the gory details of the situation
Comment: If you use a big hub box with 5 or more spokes consider something more structured than many daisy-chained wire nuts inside to connect it all together.   Wago has a 5-lever connector with a carrier that you can mount in the box.  You could create a nicely organized and easily maintainable system, and daisy-chain them to get up to 8 spokes with 2 connectors each for L,N,G mounted on three sides of the box.  I don't however understand how this would consume much less cable than just chaining from switch to switch in the usual way.
Comment: @jay613 -- the issue with the Wago carriers is that they wind up becoming a terminal block when in their carriers, and terminal blocks can't carry a UL *listing*, only *component recognition*, which isn't so helpful for us as it puts us far more at the mercy of one's AHJ.  Of course, outside of N. America, it's a whole another ballgame as terminal blocks are an accepted part of IEC-style mains wiring
Comment: Good reference article.   Skip the carrier.   I suppose with solid conductors arranged nicely the carrier doesn't add much anyway.
Answer: What Greg Hill says about topology.
You can branch out anywhere you want.  It's not down to only 2 choices of "string" vs "hub and spoke".  Each outlet on a circuit can simply go to the nearest and most convenient outlet that has already been reached.  Or to a junction box you choose to create somewhere.
The only thing you have to watch for is junction box size, as Greg discusses.  "Octagon boxes" (round boxes) intended for lamps are the most troublesome here.
For very large boxes, use 4-11/16" square deep boxes, with an appropriate 1-gang, 2-gang or round mud ring or domed cover.
You seem to be in North America, so this answer is based on that.
Comment: @TobySpeight Note that StackExchange is a Q&A site.  As such, the answer exists in the context of the question.  (and in this case, Greg Hill's answer).  Were the breaker 16A or 32A, I am sure my answer would be different.
Comment: @TobySpeight alright this time, but I'm not into disclaimerism.  It's not for me to tell OP whether they're from US or Canada.


Riemann integrability on open subset of $\mathbb{R}$

Question: Let $f:\mathbb{R}\to \mathbb{R}$ be a continuous function such that $f$ is Riemann integrable over $\mathbb{R}$.
Is it true that $f$ is Riemann integrable over any open subset $A\subset \mathbb{R}$??
Comment: What do you mean by $f$ is Riemann integrable over $\mathbb{R}$? You might find your answer there.
Comment: What is your definition of integrable?
Comment: I mean improper integral as defined here https://en.m.wikipedia.org/wiki/Improper_integral
Comment: A function which has an improper integral restricts to an integrable function on any *closed* interval, and thus restricts to an integrable function on a closed interval that contains $A$, but as RRL points out this may not work for open intervals depending on how you define the integral.
Comment: I understand. But It works on open subsets whose boundary have measure zero like $(0,+\infty)$, right?
Comment: True as long as you are talking about an improper integral on $(0,+\infty)$ not the Riemann integral.
Answer: Assuming you mean Riemann integrable on any closed, bounded interval and you have defined the Riemann integral over an arbitrary open set using the characteristic function, the answer is no.
We can construct an open set $A \subset [0,1]$ whose boundary does not have measure zero. Take $f(x) = 1$.
Then the Riemann integral
$$\int_A f := \int_0^1 f(x) \chi_A(x) \, dx $$
does not exist
Construction of $A$
Let $\{r_i\}$ be an enumeration of the rational numbers in $(0,1)$. This is a countable set. We can take intervals such that $r_i \in(a_i,b_i) \subset (0,1)$ and $\sum_{i \geqslant1} (b_i - a_i) < 1$.  The union
$$A = \bigcup_{i \geqslant 1}(a_i,b_i)$$
is an open set with boundary $\partial A= [0,1] \setminus A$ since the rationals are dense in $[0,1]$. However, $m(\partial A) = m([0,1]) - m(A) > 1 - \sum_{i \geqslant 1}(b_i-a_i)> 0$.
Comment: @MonstrousMoonshiner: That is how an improper Riemann integral over an open set in $A \subset \mathbb{R}^n$ can be defined. It requires that the function be Riemann integrable over those closed subintervals.  But existence of an improper integral does not mean the function--  in this case $\chi_A$ -- is Riemann integrable over $A$. I will elaborate in the anser about the construction of this pathological set $A$.
Comment: See also "fat Cantor set".
Comment: See Spivak, Calculus on Manifolds, problem 3-11 where a non-rectifiable set in $\mathbb{R}$ is constructed. Then the characteristic function is discontinuous on a set of non-zero measure so it is not Riemann integrable.
Comment: In $\mathbb{R}^n$ where $n$ may be $1$, Riemann integrals are defined on rectangles (intervals) first and then exptended to arbitrary sets using the characteristic function.  If the boundary is not of measure $0$, then the integral will not exist unless the function approaches $0$ at every boundary point -- and this can't happen for the function $f(x) = 1$.
Comment: @TonyPiccolo: The above construction of an open subset of $[0,1]$ that is not rectifiable is a standard example found in Munkres, Spivak, etc.  The characteristic function of this set is not Riemann integrable.  It is constructed as a union of countably many intervals that overlap.  However as an open set in $\mathbb{R}$ it must also be a countable union of pairwise disjoint intervals. It seems to contradict theorem 3.2,  asserting that the characteristic function of a countable union of pairwise disjoint intervals is discontinuous only at countably many endpoints -- hence, Riemann integrable.
Comment: I would say the theorem in the paper is incorrect -- missing such pathological examples of bounded open sets with boundaries of non-zero measure. Perhaps an analogous situation where intuition fails is the Cantor set which includes points like $1/4$ that are not endpoints of the countably many removed intervals.
Comment: This is interesting, care to elaborate? Namely, how do you construct such an open set, and how do you show that the Riemann integral does not exist?
Comment: Perhaps a better way to define the integral over such an open set would be to take a limit of integrals over unions of closed intervals contained in the open set. Would not the limit be defined in this case, or would this fail for similar reasons?
Comment: In fact I have seen fat Cantor sets; it just didn't occur to me that they could provide the sort of counterexample necessary here. I've even seen the example you mentioned in the update before, but that one didn't occur to me either. Real analysis is weird.
Comment: Curious to know your comment on theorem 3.2 in this [paper](http://marathwadamathsociety.org/vol14-1/6june13divate1.pdf)


Scope Variable in Unit Tests

Question: I am unit testing with karma/jasmine and am having errors with unit testing my controller.
Controller code:
angular.module('app.controllers', [])
    .controller('myctrl1',[function($scope){
        $scope.test = "this worked";
    }])

Unit Test Code:
describe('Controllers', function(){ //describe your object type
    beforeEach(module('app.controllers')); //load module

    describe('Running Test for :',function(){ //describe your app name

        var myctrl;
        beforeEach(inject(function($controller){ //instantiate controller using $controller service
            myctrl = $controller('myctrl1');
        }));
        it('Test scope var', function(){  //write tests
            expect($scope.test).toBe('this worked'); //pass
        });
    });
});

I am getting the following error:
TypeError: Cannot set property 'test' of undefined
ReferenceError: $scope is not defined

Answer: Modify your test to:

angular.module('app.controllers', ['ngMockE2E'])

.controller('myCtrl1', function($scope) {
  $scope.test = "this worked";
});

describe('Main Controller test suite', function() {

  describe('myCtrl1', function() {
    var $scope;

    beforeEach(module('app.controllers'));

    beforeEach(inject(function($rootScope, $controller) {
      $scope = $rootScope.$new();
      $controller('myCtrl1', {
        $scope: $scope
      });
    }));

    it('Test scope var', function() {
      expect($scope.test).toBe('this worked'); //pass
    });
  });
});
<!DOCTYPE html>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.min.css" />

Angular controller test with Jasmine

Reference: https://docs.angularjs.org/guide/unit-testing#testing-a-controller
Comment: TypeError: Cannot set property 'test' of undefined
ReferenceError: $controller is not defined

Scope Variable in Unit Tests


Can someone please explain why my code is not executing without error? I've done research but i can't see where i made a mistake

Question: Trying to create roles in SQL and assign them permissions. After i creating the roles i want to create new users to assign to role
Create Role Sales_Person
    Grant Insert on Northwind.dbo(Customers, Orders, OrderDetails)
    To Sales_Person
    Grant Select, Update on Northwind.dbo.Customers(CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax)
    To Sales_Person
Create Role Sale_Manager
    Grant Insert, Delete on Northwind.dbo(Customers, Orders, OrderDetails)
    To Sale_Manager
    Grant Select, Update on Northwind.dbo.Customers(CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax)
    To Sale_Manager
Create Role HR_Person
    Grant Insert on Northwind.dbo.Employees
    To HR_Person
    Grant Select, Update on Northwind.dbo.Employees(LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate, Address, City, Region, PostalCode, HomePhone, Country, Extension, Notes, ReportTo)
    To HR_Person
Create Role HR_Manager
    Grant Insert, Delete on Northwind.dbo.Employees
    To HR_Manager
    Grant Select, Update on Northwind.dbo.Employees(LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate, Address, City, Region, PostalCode, HomePhone, Country, Extension, Notes, ReportTo)
    To HR_Manager
Create User Jane1 Without Login
    Grant Sales_Person to Jane1
Create User Joan1 Without Login
    Grant Sale_Manager to Joan1
Create User Joe1 Without Login
    Grant HR_Person to Joe1
Create User James1 Without Login

Error message saying "Msg 1020, Level 15, State 1, Line 0
  Sub-entity lists (such as column or security expressions) cannot be specified for entity-level permissions."
Comment: which line is giving the error message ?
Comment: What happens if you remove the column names as the error implies?
Comment: Start by ending the statements with semicolons.
Answer: Try breaking out the tables, it looks to be reading them as columns for some of the insert and delete parts. Permissions for insert and delete must be done at table level, not column.
Create Role Sales_Person
    Grant Insert on Northwind.dbo.Customers
    To Sales_Person
    Grant Insert on Northwind.dbo.Orders
    To Sales_Person
    Grant Insert on Northwind.dbo.OrderDetails
    To Sales_Person
    Grant Select, Update on Northwind.dbo.Customers(CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax)
    To Sales_Person
Create Role Sale_Manager
    Grant Insert, Delete on Northwind.dbo.Customers
    To Sale_Manager
    Grant Insert, Delete on Northwind.dbo.Orders
    To Sale_Manager
    Grant Insert, Delete on Northwind.dbo.OrderDetails
    To Sale_Manager
    Grant Select, Update on Northwind.dbo.Customers(CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax)
    To Sale_Manager
Create Role HR_Person
    Grant Insert on Northwind.dbo.Employees
    To HR_Person
    Grant Select, Update on Northwind.dbo.Employees(LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate, Address, City, Region, PostalCode, HomePhone, Country, Extension, Notes, ReportTo)
    To HR_Person
Create Role HR_Manager
    Grant Insert, Delete on Northwind.dbo.Employees
    To HR_Manager
    Grant Select, Update on Northwind.dbo.Employees(LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate, Address, City, Region, PostalCode, HomePhone, Country, Extension, Notes, ReportTo)
    To HR_Manager
Create User Jane1 Without Login
    Grant Sales_Person to Jane1
Create User Joan1 Without Login
    Grant Sale_Manager to Joan1
Create User Joe1 Without Login
    Grant HR_Person to Joe1
Create User James1 Without Login


How to hide and replace navbar-toggler-icon in Bootstrap 4?

Question: How do you hide and replace the navbar-toggler-icon in Bootstrap 4? Right now the code below just puts the 'X' below the hamburger menu.

  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse"
  data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false"
  aria-label="Toggle navigation">

  </button>

     <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse"
  data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false"
  aria-label="Toggle navigation">
    X
  </button>

Comment: Can you explain a little better what you're trying to accomplish?
Comment: I wanted to toggle X and hamburger, so when menu is open I get an X when X is clicked menu closes and hamburger is back using Bootstrap only.
Answer: The code you have now has 2 togglers, but I'm not sure why. You just need to replace the normal navbar-toggler-icon with an X..

    <button class="navbar-toggler navbar-toggler-right py-2" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
       X
    </button>
    Brand

Link

EDIT To toggle between the hamburger toggler icon and a close X, you'd need have both the X and hamburger icon inside the navbar-toggler. Add some CSS to handle the collapsed state of the navbar.
.navbar-toggler>.close {
    display:inline;
}
.navbar-toggler.collapsed>.close, .navbar-toggler:not(.collapsed)>.navbar-toggler-icon {
    display:none;
}

http://www.codeply.com/go/fgHv33Q6UM

Update Bootstrap 4.2
The original question/answer is for Bootstrap 4 alpha. Once Bootstrap 4 was in beta, the navbar-toggleable-* classes changed to navbar-expand-* which effect the navbar breakpoint. Here is an updated example for Bootstrap 4.2...
https://www.codeply.com/go/9AQ4AsYUph
Comment: It is not working for Bootstrap 4. As "X" is appeared first as after page loaded even though navbar is not collapsed. I toggle once then everything got fixed as hamburger sign appear before toggle and "X".after toggle.
Comment: @MuhammadYasir - Of course the original answer is for v4 alpha. You need to update the Navbar markup for whatever version you're using (the latest is 4.2). But the concept is still the same for the toggler to X icon.
Comment: I wanted to toggle hamburger icon with X and vice versa that's why I had two.
Comment: codeply is working, but when I tried exactly as shown hamburger and X showing at the same time inline
Comment: It works and answers your question. Follow the codeply example, exactly make sure you include the CSS too.
Answer: If the close button appears at beginning, try this one
HTML

    <button class="navbar-toggler navbar-toggler-right collapsed" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
       X

    </button>
    Brand

Link

Link

Link

CSS
.navbar{
  button[aria-expanded="true"] > span.close {
    display: inline;
    color: #fff;
    opacity: 1;
  }

  button[aria-expanded="true"] > span.navbar-toggler-icon {
    display: none;
  }

  button[aria-expanded="false"] > span.close {
    display: none;
  }
}

Comment: If you're using bootstrap 5. Use this.


DocumentDB REST API: PartitionKey extracted from document doesn't match

Question: I'm trying to insert a JSON document into DocumentDB via REST, using PHP (which lacks an official API wrapper). Now, it seems that a partition key has become mandatory for any collection in DocumentDB, but i cannot find the REST API documented.
I get the following error in return:
PartitionKey extracted from document doesn't match the one specified in the header

The JSON document I'm trying to insert looks as follows:
{ id:"1", ... "domain":"domain.com" }

In Azure, I have defined the collection with the following partition key:
/domain

And when sending the REST request, I send along the following header:
x-ms-documentdb-partitionkey: [ "domain" ]

What am I missing here?
Comment: Clarification: Partition keys are required for *partitioned collections*, not for single-partition collections.
Comment: You would need to specify the partition key value and not the attribute i.e. you would write `x-ms-documentdb-partitionkey: [ "domain.com" ]`. Please try with this.
Comment: It worked!! Thanks a lot! (Please add your reply as an answer - not comment - so I can set accepted/solved)
Answer: For x-ms-documentdb-partitionkey value you would need to specify the partition key value ("domain.com") and not the partition key attribute ("domain").
x-ms-documentdb-partitionkey: [ "domain.com" ]
Once you do this, documents matching this partition key value will be returned.


Wordpress post tags are not working

Question: I ma fetching post and tags manually and forming tags url properly but still tags link not working. On click In Browser inspect network tab sending ajax request to admin-ajax.php automatically.
if (is_array(get_the_tags($post->ID)) || is_object(get_the_tags($post->ID))) :
   foreach(get_the_tags($post->ID) as $tag)
    {
      echo '
term_id) . '" title="'.$tag->name.'" class="'.$tag->slug.'">' . $tag->name . '
 ';
     }
endif;

Links to verify; http://220.127.116.11/fow/
Html Formed :
Startup

Answer: Try using this:
$post_id = get_the_ID();

if (is_array(get_the_tags($post_id)) || is_object(get_the_tags($post_id))) :
   foreach(get_the_tags($post_id) as $tag)
    {
      echo '
term_id) . '" title="'.$tag->name.'" class="'.$tag->slug.'">' . $tag->name . '
 ';
     }
endif;

Comment: Both looks same apart storing post id on separate variable
Comment: post values static set and check
Comment: post values static set and check   ex:  $post_id=118
Comment: Display link . Didn't get please explain.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/162798/discussion-between-tarang-koradiya-and-krishnaisdinesh).

Wordpress post tags are not working


Type checking: an iterable type that is not a string

Question: To explain better, consider this simple type checker function:
from collections import Iterable
def typecheck(obj):
    return not isinstance(obj, str) and isinstance(obj, Iterable)

If obj is an iterable type other than str, it returns True.  However, if obj is a str or a non-iterable type, it returns False.
Is there any way to perform the type check more efficiently?  I mean, it seems kinda redundant to check the type of obj once to see if it is not a str and then check it again to see if it is iterable.
I thought about listing every other iterable type besides str like this:
return isinstance(obj, (list, tuple, dict,...))

But the problem is that that approach will miss any other iterable types that are not explicitly listed.
So...is there anything better or is the approach I gave in the function the most efficient?
Comment: It's not inefficient. You likely have more important things to worry about.
Comment: @thefourtheye - Because sometimes you need to check if something is iterable but isn't a string.  An example could be a function that flattens a nested list.  You don't want the strings in it flattened as well.
Comment: @aIKid - Yea, I didn't like the `isinstance(obj, (list, tuple, dict,...))` solution too much either.  I was just curious if there was any way to do this without calling `isinstance` twice.  But now I'm beginning to think that that _is_ actually the best way.
Comment: @iCodez: But you want the dicts flattened? Or the files? In this specific case, it seems more reasonable to specifically check for lists. That said, there are legitimate use cases where you want to accept either a string or a sequence of strings, and you want to distinguish between the two.
Comment: If you exclude str, usually you should exclude unicode and buffer too
Comment: Just curious. Why do you consider string as a non-iterable?
Comment: Something like `return isinstance(obj, (list, tuple, dict,...))` will be far more inefficient since it has to check all the types, isn't it?
Comment: TBH, I think you're already on the right track.
Comment: It *is*. It has to check it only twice, for each types. No solution can do it better.
Answer: In python 2.x, Checking for the __iter__ attribute was helpful (though not always wise), because iterables should have this attribute, but strings did not.
def typecheck(obj): return hasattr(myObj, '__iter__')

The down side was that __iter__ was not a truely Pythonic way to do it: Some objects might implement __getitem__ but not __iter__ for instance.
In Python 3.x, strings got the __iter__ attribute, breaking this method.
The method you listed is the most efficient truely Pythonic way I know in Python 3.x:
def typecheck(obj): return not isinstance(obj, str) and isinstance(obj, Iterable)

There is a much faster (more efficient) way, which is to check __iter__ like in Python 2.x, and then subsequently check str.
def typecheck(obj): return hasattr(obj, '__iter__') and not isinstance(obj, str)

This has the same caveat as in Python 2.x, but is much faster.
Comment: @tripleee - `isinstance(u'foo', basestring)` does the trick in Python 2.x (both `unicode` and `str` subclass `basestring`)
Comment: There is still the distinct problem that `isinstance(u'foo', str)` returns `False` and so you end up with the same conundrum as explicitly listing all the types which are *not* string types.  As a quick hack, I came up with checking `hasattr(thing, 'lower')` but it's obviously too obscure.


Find all the documents that has same subdocuments mongoose

Question: I have postSchema which references the tagsSchema.
 var tagsSchem = new Schema({
    name: {
        type: String,
        required: true
    }
}, {
    timestamps: true
});

// create a schema
var postsSchema = new Schema({
    title: {
        type: String,
        required: true,
        unique: true
    },
    mainImage: {
        type: String
    },
    category: {
        type: String,
        required: true
    },
    body: {
        type: String,
        required: true
    },
    postedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    tags: [tagsSchem]
}, {
    timestamps: true
});

One post can contain any no. of tags. So if a post has 3 tags then I want to get all the posts with those 3 tags without querying it multiple times. Is it possible?
Comment: all the posts that has **one** of these three tags or **all** three tags together?
Answer: When you perform find, you can use the $in option to find values that are in your array. For example:
posts.find({tags:{$in:{["tag1","tag2","tag3"]}}, function(err,data) {
... //Your code here
}

This will take all the posts that contains one of the three tags. It's important you have to pass an array in the $in option. This should work.
Comment: Suppose if I just have the post id and not all the tags. Is it possible?
Comment: I believe it will return nothing
Comment: should I use the tag id's or the names in $in array
Comment: It depends of what you have as reference in the post schema. If you are persisting the ids, you should search for ids, if you are persisting the names, you should search for the names.
Comment: So If i just have postId there is no way to get all the related posts without the above solution?
Comment: If you have only the postId, how would relate it to other posts?
Comment: Just by tagsSchema
Comment: So, you have a postId, then you'll retrieve the tagIds from this post and then search by the tagIds, right?
Comment: Yes, From the postId I will get the Post then the tags. If it's not possible I will do this way only


convert sql from server syntax to absolute database

Question: This is the original code that worked with SQL Server using Unidac components :
In the SQL (TStrings) of the uniQuery I had :
 use HIS
    DECLARE @StartDate  DATETIME,
            @EndDate    DATETIME,
            @RoomType   VARCHAR(6)
    ;

     SELECT @StartDate  = '2011-04-15',
            @EndDate    = '2011-04-26',
            @RoomType   = 'DBLMS'
    ;
    WITH
    cteStayDates AS
    (
     SELECT RoomType  = Room_Type,
            StartDate = CASE WHEN Rate_Start_Date < @StartDate THEN @StartDate ELSE Rate_Start_Date END,
            EndDate   = CASE WHEN Rate_End_Date   > @EndDate   THEN @EndDate   ELSE Rate_End_Date   END,
            Rate
       FROM dbo.Room_Rates
      WHERE @RoomType  = Room_Type
        AND @StartDate < Rate_End_Date
        AND @EndDate  >= Rate_Start_Date
    )
     SELECT RoomType, StartDate, EndDate, Rate,
            Days = DATEDIFF(dd,StartDate,EndDate)
                 + CASE WHEN EndDate = @EndDate THEN 0 ELSE 0 END
       FROM cteStayDates
      ORDER BY StartDate
    ;

On Button click I had :
procedure TForm1.Button1Click(Sender: TObject);
//uniQuery1.SQL.Add('SET DATEFORMAT DMY');
begin
uniQuery1.Close;
uniQuery1.SQL.Clear;
uniQuery1.SQL.Add('DECLARE @StartDate  DATETIME,');
uniQuery1.SQL.Add('@EndDate    DATETIME,');
uniQuery1.SQL.Add('@RoomType   VARCHAR(6);');
uniQuery1.SQL.Add('SELECT @StartDate  = :a2,');
uniQuery1.SQL.Add('@EndDate    = :a3,');
uniQuery1.SQL.Add('@RoomType   = :a1;');
uniQuery1.SQL.Add('WITH');
uniQuery1.SQL.Add('cteStayDates AS');
uniQuery1.SQL.Add('( SELECT RoomType  = Room_Type,');
uniQuery1.SQL.Add('StartDate = CASE WHEN Rate_Start_Date < @StartDate THEN @StartDate ELSE Rate_Start_Date END,');
uniQuery1.SQL.Add('EndDate   = CASE WHEN Rate_End_Date   > @EndDate   THEN @EndDate   ELSE Rate_End_Date   END,');
uniQuery1.SQL.Add('Rate');
uniQuery1.SQL.Add('FROM dbo.Room_Rates');
uniQuery1.SQL.Add('WHERE @RoomType  = Room_Type');
uniQuery1.SQL.Add('AND @StartDate < Rate_End_Date');
uniQuery1.SQL.Add('AND @EndDate  >= Rate_Start_Date)');
uniQuery1.SQL.Add('SELECT RoomType, StartDate, EndDate, Rate,');
uniQuery1.SQL.Add('Days = DATEDIFF(dd,StartDate,EndDate)');
//uniQuery1.SQL.Add('+ CASE WHEN EndDate = @EndDate THEN 0 ELSE 0 END');
uniQuery1.SQL.Add('FROM cteStayDates  ORDER BY StartDate;');
uniQuery1.Params.ParamByName('a1').AsString := cxTextEdit1.Text;
uniQuery1.Params.ParamByName('a3').AsDate := cxDateEdit2.Date; // end date
uniQuery1.Params.ParamByName('a2').AsDate := cxDateEdit1.Date; // start date
uniQuery1.Open;

end;

Now I am trying to port this code to absolute database (table fields are the same) but can not get it to work. Can someone help me with this ?
I also tried putting this query in the SQL text of the ABSQuery1:
SELECT RoomType, StartDate, EndDate, Rate,
            Days = DATEDIFF(dd,StartDate,EndDate)
                 + CASE WHEN EndDate = EndDate THEN 0 ELSE 0 END
  RoomType  = Room_Type,
            StartDate = CASE WHEN Rate_Start_Date < StartDate THEN StartDate ELSE Rate_Start_Date END,
            EndDate   = CASE WHEN Rate_End_Date   > EndDate   THEN EndDate   ELSE Rate_End_Date   END,
            Rate
       FROM Room_Rates
      WHERE RoomType  = Room_Type
        AND StartDate < Rate_End_Date
        AND EndDate  >= Rate_Start_Date      ORDER BY StartDate
    ;

But I can not retrieve fields so it does not wok. Really dont know why. Connection is set up properly. When I try and retrieve the fields I get :
Comment: @user763539 Pro oriented? That's like saying the dictionary is only for people that can read.
Comment: Presumably it creates some kind of error. What is that error? A guess would be that it has issues with the CTE and/or DATEDIFF. The CTE can be rewritten as a sub-query and if DATEIFF is the issue you have to check the documentation for Absolute database to see what you can do instead.
Comment: Absolute Database does not support `Common Table Expressions` (`CTEs`). For the appropriate syntax to use, see the Absolute documentation.
Comment: Documentation is pro oriented, not suitable for beginners.
Comment: You could remove the `datediff` and do the calculation on the client instead. Also your first `CASE` does not seem to ad much value here.
Comment: how would you write it ?
Comment: Did your query work if you remove `DATEDIFF`?
Comment: I think I must rewrite this query from scratch .... Perhaps one option is to add a calculated field to the query representing stay_dates ...
Comment: easy for you to say.... I learn by real world examples :)
Comment: Yes I think you are correct. You should rewrite the query starting with something that works and add new features untill you find what parts does not work in Absolute database.
Answer: Common Table Expressions (with cteStayDates as (..)) are a SQL Server feature that are probably not in absolute. You could try something like:
 use HIS
    DECLARE @StartDate  DATETIME,
            @EndDate    DATETIME,
            @RoomType   VARCHAR(6)
    ;

     SELECT @StartDate  = '2011-04-15',
            @EndDate    = '2011-04-26',
            @RoomType   = 'DBLMS'
    ;
     SELECT RoomType, StartDate, EndDate, Rate,
            Days = DATEDIFF(dd,StartDate,EndDate)
                 + CASE WHEN EndDate = @EndDate THEN 0 ELSE 0 END
  RoomType  = Room_Type,
            StartDate = CASE WHEN Rate_Start_Date < @StartDate THEN @StartDate ELSE Rate_Start_Date END,
            EndDate   = CASE WHEN Rate_End_Date   > @EndDate   THEN @EndDate   ELSE Rate_End_Date   END,
            Rate
       FROM dbo.Room_Rates
      WHERE @RoomType  = Room_Type
        AND @StartDate < Rate_End_Date
        AND @EndDate  >= Rate_Start_Date      ORDER BY StartDate
    ;

Comment: Absolute database it seems does not support: USE or DECLARE.


Gas line pressure testing, is there an acceptable limit for losses?

Question: Last week I finished installing the gas home runs in a house I'm working on.  Never really done this before, but I figured I'd take a shot at it since it was only 20 ft of pipe.
Last Saturday, with all valves open except the main and the last valve before the appliance, I pressurized the line to 15PSIG.  When I left that night, still at 15.  Monday morning it was at 14.  Tuesday evening it was at 11.  Today it was down to 5.  Obviously, I don't want gas issues, but nothing is going to stay pressurized forever without maintenance.  Is there a rule of thumb, practical limit?
Comment: Best rule of thumb: **any leak will only get worse** so fix it.
Answer: You have a leak, and given that it's gas piping, you need to fix it.
For an air compressor, you might live with that sort of leak, but you don't have to.
For gas, it's unacceptable.
"Nothing is going to stay pressurized forever without maintenance" - for adequate values of forever, sure, the pipe will rust away. My "properly assembled" portable air tank, with a gauge and a quick-disconnect and a hose left on the quick disconnect with another quick-disconnect and a tire chuck holds pressure for (at least) months. If your gas piping won't hold pressure for a week, that's going to be a problem.
Small variations (which can go up as well as down) may be seen due to changes in temperature. I very much doubt that's the case for your pipe. Add more pressure, get out the soapy water (plus glycerine if you can find some, or buy "leak detector fluid" if you like - or just bubble solution for blowing bubbles) and start checking every joint. At least one is bubbling and needs to be remade properly.


Captain form saving form input in a database

Question: i have a question regarding a Wordpress plugin for building forms. It is called Captain Form. It saves all the submitted user input in the form on a cloud/their own databases.
Is it possible to make a script, that when someone clicks on submit, the information is stored in another database on the server, where the site is stored?
Comment: Yes it is. Where are you stuck?
Comment: In the process of thinking if it even matters actually... I saw that with the free version you can't even send autorespond mails, which is too limited for me. :/
Answer: With CaptainForm, if you have your own database you can create a custom script and using Webhooks you can have all submissions sent to your own private database.
Hope it helps!
Comment: It does healp a little bit, thank you;) I will have to check out the webhooks a bit more...


What does "region to be shaded" mean in the PCF paper?

Question: I am reading the percentage closer filtering (PCF) paper by Reeves, W. et al. (https://graphics.pixar.com/library/ShadowMaps/paper.pdf).
At at section 3.2, it mentioned that "each shading calculation represents some region on a surface". And "each region to be shaded is mapped to a region in the shadow map".
For my understanding, using Opengl fragment shader, for each shading calculation, we just operate on each pixel. We do the shadow calculation on each pixel in the camera image.
Can anyone explain what does that "region to be shaded" mean? Thanks!
Answer: Texture mapping is the process of providing a mapping from the surface to a location on the texture. That is, given a particular point on a surface, you can find a specific point in a texture that corresponds to it. Giving positions a UV texture coordinate is a common means of defining a texture mapping, but you can use a function of arbitrary complexity.
Texture mapping is at least theoretically reversible. That is, given a particular texel, you can use the texture mapping to determine where on an object that texel appears. Of course, not every texture mapping is reversible. Some mapping cause a texel to be used in multiple locations on a surface, and not every mapping uses every texel in the texture.
But the important part of the reverse mapping operation is this: a texel maps to some area of the surface, not a single point.
Shadow mapping is a form of texture mapping. It defines a mapping from the scene to a texture by performing perspective projection of the points in the scene onto the surface of a texture, based on a light position.
If you reverse this mapping, a texel in the shadow map maps to an area in the scene. This is the "region in the scene".
Comment: Thanks for your explanation! I think I got what you mean. So, for PCF, we first map a pixel in the camera image to a region in the scene, and then we map that region onto the shadow map. I think this is a quite complicated operation... Maybe not worthwhile to do it I guess.


Truncate all tables in MySQL database that match a name pattern

Question: I need to clear all my inventory tables.
I've tried this:
SELECT 'TRUNCATE TABLE ' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'inventory%'

But I get this error:
Truncated incorrect DOUBLE value: 'TRUNCATE TABLE ' Error Code 1292

if this is the correct way, then what am I doing wrong?
Comment: You realize that won't *run* the truncate statements, just create them as strings in a result set?
Comment: The `+` syntax isn't valid with MySQL.  You have to use the concat function.
Answer: Use concat:
SELECT concat('TRUNCATE TABLE `', TABLE_NAME, '`;')
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'inventory%'

This will of course only generate SQL which you need to copy and run yourself.
Comment: You might also want to add `AND TABLE_SCHEMA = 'mydatabase'` to ensure you're only operating on a particular database.  Also, adding `INTO OUTFILE 'c:\\script.sql'` will prevent you from having to copy & paste anything; instead, just run the script.
Comment: ok so I copied the result, pasted it in the query browser, hit CtrlEnter and boooom!!!!   nothing happended, tables still with data =(
Comment: it seems that I have to execute each line in the query browser, well at least I don't have to write all the lines, just pres CtrlEnter on each one o.O
Comment: must a function of your mysql client. ';' should work as a statement separator in most clients
Comment: Little trick to have the whole query on 1 line : `SELECT group_concat(a.c SEPARATOR ' ') FROM (SELECT concat('TRUNCATE TABLE ', TABLE_NAME, ';') AS c FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'inventory%') a;`
Answer: I know it's an older post already but maybe the following example is helpful for someone who needs to truncate multiple tables from linux command line or from within a shell script:
mysql -p<secret> --execute="SELECT concat('TRUNCATE TABLE ', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '<database>' AND FIND_IN_SET(TABLE_NAME,'your_table_a,your_table_b,your_table_c')" | sed 1d | mysql -p<secret> <database>

Given that you need to replace the strings in brackets with your own values it was working for me. Also replace the 'your_table_a,your_table_b,your_table_c' with a comma-separated list of your tables. ;)
Comment: If you happen to need to flush all your cache tables because you setup a solution like memcache here's a useful command:

    mysql -uroot -proot --execute="SELECT concat('TRUNCATE TABLE ', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'db_name' AND TABLE_NAME LIKE 'cache%'" | sed 1d | mysql -uroot -proot db_name ... just update the db_name and user credentials.
Answer: SELECT 'SET FOREIGN_KEY_CHECKS = 0;'
UNION
SELECT DISTINCT concat( "TRUNCATE TABLE ", TABLE_NAME, ";" )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'mydbname'
UNION
SELECT 'SET FOREIGN_KEY_CHECKS = 1;'

Comment: This answer too will generate a string of SQL statements separated with ; But the key thing here is that it will turn of the foreign_key checks for you before truncating and later turn on the check again. This is needed if your tables have foreign_key pointing to each other. If you have a row in a table with a foreign_key to a table that you truncate you'll break the reference and mysql will throw an error.
Answer: If you are using command line, you might want to try something like this.
mysql -u [user] -p[password] -e 'use [database]; show tables' | perl -lane 'print "truncate table $F[0]" if /^inventory/i' > [database].sql

Answer: Here is a little improvement on the above SQL statement.
SELECT DISTINCT concat("TRUNCATE TABLE ", TABLE_NAME, ";")
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE "cache%"

Notice the DISTINCT command in the beginning. This will make the SELECT result show only once the the tables that match your LIKE criteria.
Comment: Are you accessing table from more than one db on the server?
Answer: If you have more than one database on your server, you may want to specify the db as well.
e.g. to clear Drupal cache tables
SELECT DISTINCT CONCAT(
    "TRUNCATE TABLE ",
    TABLE_SCHEMA,
    ".",
    TABLE_NAME,
    ";" )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE  "cache_%"
AND TABLE_SCHEMA = 'dbname';

This results in sql like...
TRUNCATE TABLE dbname.cache_admin_menu;
TRUNCATE TABLE dbname.cache_block;
etc.

Giving two advantages,

You can run this sql anywhere regardless of the currently selected
database.
You'll be sure that you're truncating the tables on the
correct database.

See @falperez answer if foreign key checks get in the way of your mass truncate, (although of course they won't for drupal cache clearing)
Answer: Try this statement, It will give you single line of all tables and you can copy that statements and run to execute all:
SELECT DISTINCT REPLACE(GROUP_CONCAT("TRUNCATE TABLE ", TABLE_NAME, ";"), ',', '')
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE "cache%";

Comment: I like the idea.  However mysql client is trimming the results, so it gets cut off.  Anyone know how to prevent it from doing that?
Comment: The query is not working correctly.  It returns table names like "cache_SOMETHING", where SOMETHING is a table, but cache_SOMETHING is not.
Comment: Replace `GROUP_CONCAT` with Only `CONCAT` function it will give you each `TRUNCATE TABLE TABLE_NAME;` in each row then you can copy each row and run it as you expect.
So, now your MySQL Client will not trimming the results.
Answer: SELECT CONCAT('TRUNCATE TABLE ',TABLE_NAME)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'inventory%'

You should then take every row of the result set and call it as the SQL statement. You can do it by coping and pasting the separated results to the command window.
But much better solution is to write some program which will make the query above and loop through the results and make every query.
Use PHP for that or any other scripting language. Many examples even here on SO.
Answer: SELECT REPLACE(GROUP_CONCAT("TRUNCATE TABLE ", TABLE_NAME, ";"), ',', '')
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME LIKE "cache%";

This is based on AshwinP's answer.  I had to remove DISTINCT and add WHERE TABLE_SCHEMA=DATABASE() for it to work for me.
The command does not truncate tables, but returns a one-liner that will.  Copy and paste the one-liner into the mysql client.
Answer: Late answer... But better later, than never. To avoid unnecessary copying and pasting or additional shell scripting, the most agnostic approach -- at least with respect to MySQL and MariaDB -- to truncating a set of tables in a database or matching a pattern is via a stored procedure.
The following is a script used regularly to truncate all tables in the current database. The SELECT statement can be tailored to match patterns if more precise control is required.
DROP PROCEDURE IF EXISTS truncate_tables;

DELIMITER $$
CREATE PROCEDURE truncate_tables()
BEGIN
  DECLARE tblName CHAR(64);
  DECLARE done INT DEFAULT FALSE;
  DECLARE dbTables CURSOR FOR
    SELECT table_name
    FROM information_schema.tables
    WHERE table_schema = (SELECT DATABASE());
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN dbTables;
  SET FOREIGN_KEY_CHECKS = 0;

  read_loop: LOOP
    FETCH dbTables INTO tblName;
    IF done THEN
      LEAVE read_loop;
    END IF;

    PREPARE stmt FROM CONCAT('TRUNCATE ', tblName);
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
  END LOOP read_loop;

  CLOSE dbTables;
  SET FOREIGN_KEY_CHECKS = 1;
END
$$

CALL truncate_tables();
DROP PROCEDURE IF EXISTS truncate_tables;

This example drops the store procedure after it is used. However, if this is a regular task, then it is better to just add it once by running everything before the $$ delimiter and executing
CALL truncate_tables();

on the target database.
Answer: mysql -uuser -ppass --execute="SELECT concat('TRUNCATE TABLE ', TABLE_NAME, ';') FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'db' AND TABLE_NAME LIKE 'cache%'" | sed 1d | mysql -uuser -ppass db

..this worked for me.. replace user, pass and db with your own.
Answer: very nice example of generating and executing statements USING concat I just read minute ago:
http://www.mysqltutorial.org/mysql-drop-table
-- set table schema and pattern matching for tables

SET @schema = 'classicmodels';
SET @pattern = 'test%';

-- build dynamic sql (DROP TABLE tbl1, tbl2...;)

SELECT CONCAT('DROP TABLE ',GROUP_CONCAT(CONCAT(@schema,'.',table_name)),';')
INTO @droplike FROM information_schema.tables WHERE @schema = database()
AND table_name LIKE @pattern;

-- display the dynamic sql statement

SELECT @droplike;

-- execute dynamic sql

PREPARE stmt FROM @dropcmd;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Comment: It's not possible to run multiple statements in one prepared statement according to: http://stackoverflow.com/questions/20371677/execute-multiple-semi-colon-seperated-query-using-mysql-prepared-statement
Comment: The above script works for ``DROP TABLE`` since it can accept multiple table names. The same is not true for ``TRUNCATE``.


Display time differs from actual solving time taken in Minizinc model

Question: I wrote a large minizinc model including var variables with int_search statement for proper ordering. It contains output statement in which I use fix(var variables) statements to output the variable values and it contains some functions which use built-in functions sum, bool2int, etc.
Now when I run the model it displays on the screen after a very long time ( say, 5-6 minutes) but runtime/solvetime (by default print information of solver) shows only 20 seconds.
Why is this strange thing happening? Is it because output statement also consumes time? But the variables got fixed at that time, then why so?
Answer: The extra time is probably due to the first step in the process: i.e. converting the MiniZinc (.mzn) file to FlatZinc (.fzn); this is the "flattening step". The time the solver shows is from when it start to read the FlatZinc file.
Large models might require considerable time to flatten, as you've witnessed here.
Comment: @RajatGupta, To reduce the flattening time, annotations won't make a difference. It is the  number of variables, constraints, and level of reifications. You can try to reduce this or try the `--no-optimise` flag. This might result in worse Flatzinc, but should improve flattening time. If you are running the same instance multiple time, you can run `mzn2fzn` seperately and safe the flat model.
Comment: Thanks, but is there any particular way to reduce that? Because I am wasting a lot of time there almost 15 times as solving. My model contains lots of annotations also, that also contributes to considerable time while flattening?
Comment: @RajatGupta, The flattening time will depend a lot on your model and the solver library that you are targeting. Usually it's the solvers using the `linear` library that take a lot of time, like Gurobi, CBC, or CPLEX.
Comment: Heyy!! I have tried the commands separately, mzn2fzn but it takes almost 2-3s to complete. But when I tried fzn-gecode with passing .ozn file or without passing .ozn file. It takes a huge time when run with passing .ozn file. So the main culprit is .ozn file. How can this happen? I think output param variables(var variables those get fixed after solving) can never be issue. There is function overloading inside it also, and builtin sum function. Still I am not able to find what causes output to slow at such a huge rate.
Comment: passing .ozn file means I am using solns2out, this is taking the main time. But not able to figure out the reason.
Comment: @RajatGupta, Can you post you're output statement? I'm afraid we won't be able to diagnose the problem without it
Comment: I found out the problem in solns2out, I was passing large arrays in a function to print the strings. Currently it is a open issue on GitHub about solns2out that it takes so much memory for this case and never free it. Link is https://github.com/MiniZinc/libminizinc/issues/145       There is no solution to this issue yet.


How can I use my own diff tool with `add --patch` and the like?

Question: I use an offbeat diff tool called diffr, like this:
diffr="diffr \
      --colors removed:background:00:foreground:01 \
      --colors refine-removed:background:0:foreground:124 \
      --colors added:background:0:foreground:10 \
      --colors refine-added:background:0:foreground:35:intense \
      | less -R"

git config --global pager.diff "$diffr"
git config --global pager.show "$diffr"
git config --global pager.log "$diffr"

My normal workflow also commonly makes use of the --patch and --interactive flags when adding and checking out code.
However, the --patch switch appears to use the default (colordiff?) and not diffr.
How can I coerce diffr as the diff tool in this context (and any others I may not be thinking of)?
Answer: Sometimes all you have to do to find the answer is ask the question.
The solution is:
git config --global interactive.diffFilter "$diffr"

Comment: An explanation would however be welcome, or at least just a link to the [doc](https://git-scm.com/docs/git-config#Documentation/git-config.txt-interactivediffFilter).


Spring-batch step not re-executed (cache)

Question: I'm working on a project that includes Spring batch, before copying the code snippets, I'm going to summarize easily how the job works with a cron.

the cron calls a rest API on my project (@PostMapping("/jobs/external/{jobName}"))
in the post method, I get the job and execute it.
in each execution, I'm supposed to run a step.
the step contains a reader (external rest call to elastic API to get documents) and a processor.

now my problem: in the catalina.out, I'm able to see the rest call from the cron every 10 minutes as configured in my cron. BUT, the step doesn't seem to make that call to elastic every 10 minutes, the batch process always has the same set of data, which is fetched one time when the batch is called during tomcat restart.
job rest api :
@PostMapping("/jobs/external/{jobName}")
@Timed
public ResponseEntity start(@PathVariable String jobName) throws BatchException {
    log.info("LAUNCHING JOB FROM EXTERNAL : {}, timestamp : {}", jobName, Instant.now().toString());
    try {
        Job job = jobRegistry.getJob(jobName);
        JobParametersBuilder builder = new JobParametersBuilder();
        builder.addDate("date", new Date());
        return Optional.of(jobLauncher.run(job, builder.toJobParameters()))
            .map(BatchExecutionVM::new)
            .map(exec -> ResponseEntity
                .ok()
                .headers(HeaderUtil.createAlert("jobManagement.started", jobName))
                .body(exec))
            .orElseGet(() -> ResponseEntity.badRequest().build());
    } catch (NoSuchJobException aEx) {
        log.warn(JOB_NOT_FOUND, aEx);
        throw new BatchException();
    } catch (JobInstanceAlreadyCompleteException | JobExecutionAlreadyRunningException | JobRestartException aEx) {
        log.warn("Job execution error.", aEx);
        throw new BatchException();
    } catch (JobParametersInvalidException aEx) {
        log.warn("Job parameters are invalid.", aEx);
        throw new BatchException();
    }
}

job configuration :
@Bean
public Job usualJob() {
    return jobBuilderFactory
        .get("usualJob")
        .incrementer(new SimpleJobIncrementer())
        .flow(readUsualStep())
        .end()
        .build();
}

@Bean
public Step readUsualStep() {
    // TODO: simplifier on n'a pas besoin de chunk
    return stepBuilderFactory.get("readUsualStep")
        .allowStartIfComplete(true)
        .<AlertDocument, Void>chunk(25)
        .readerIsTransactionalQueue()
        .reader(rowItemReader())
        .processor(rowItemProcessor())
        .build();
}
@Bean
public ItemReader<AlertDocument> rowItemReader() {
    return new UsualItemReader(usualService.getLastAlerts());
}
@Bean
public UsualMapRowProcessor rowItemProcessor() {
    return new UsualMapRowProcessor();
}

i don't know why usualService.getLastAlerts() is called just once and not every 10 minutes.
Comment: because your `rowItemReader` bean is a singleton and not job or step scoped.
Comment: i'm sorry but i really don't master spring batch. a singleton means one instance for me, but this instance should make calls every 10 minutes no ?
Comment: No. This instance will be created once and reused every 10 minutes. The configuration is loaded once not every 10 minutes. Hence you need to make your bean step of job scoped so that for each time it executes it recreates that bean and thus executes the request.
Comment: THANK YOU M. Deinum, i annotated my steap bean with @StepScope and it worked.
Answer: thanks to M. Deinum, this is basically the solution :
    @Bean
@StepScope
public ItemReader<AlertDocument> rowItemReader() {
    return new UsualItemReader(usualService.getLastAlerts());
}

annotating the step bean with stepScope annotation will make it reinstantiate every step.


In minecraft, how to make everyone in gamemode 1 except yourself gamemode 2

Question: I'm trying to make a minecraft map and to prevent cheating i want to run a command on a clock that sets everyone in creative mode except myself back to adventure mode.
Comment: I don't think you actually need to use the scoreboard (although it would definitely be easier and more flexible).
Answer: How to do it
The command you are looking for is
/gamemode 2 @a[name=!You,m=!2]

The m=!2 part makes it so that people in adventure mode are not redundantly put into adventure mode again. Or, more flexibly, create a dummy scoreboard objective (let's call it canCreative) and set it's score to 1 for people allowed in creative mode. Then use:
/gamemode 2 @a[score_canCreative_min=1,m=!2]

(Starting with 1.9, using a scoreboard tag is more appropriate for this.)

Why you shouldn't do it
That said, I strongly advise against doing this. It takes away player agency, with no actual benefit to anyone.
Yes, it does ensure that no-one can use creative mode to cheat, but not only is that of little use in and of itself, since every real benefit of being in creative mode (advanced movement skills, invulnerability, access to blocks, placement of blocks) can be replicated by other commands, e.g. tp, effect, give, setblock, and so on.
But it's not only ineffective at deterring people from cheating, it can also be detrimental to the non-cheating players' fun. No matter how well-designed your map is, chances are someone will somehow break it at some point. If that point is 2 hours into playing your 2.5 hour map, that is frustrating in and of itself.
However, normally, access to creative mode (or spectator mode) offer solutions when you are stuck, by breaking down a door whose mechanism broke, or by manually triggering that mechanism, or even just looking at the mechanism to figure out what you are missing.
At such a point, without access to creative, I personally would just quit and never come back, no matter how amazing your map was before I got stuck. And I don't think I'd be alone in that.
Comment: 1.13 syntax: `/gamemode adventure @a[name=!You,gamemode=!adventure]`/`/gamemode adventure @a[scores={canCreative=1..},gamemode=!adventure]`
Comment: Also, the implementation of the `canCreative` objective is backwards, because it changes the gamemode of all players who have at least one point on that scoreboard.