text:
Q: OnDraw instead of spline, it draws circles /I got the following code:
public class SketchActivity extends Activity implements OnClickListener, OnSeekBarChangeListener {

private MyView myView;

private Button clearBtn;

private ToggleButton embossBtn, blurBtn, eraseBtn, srcaBtn;

private RelativeLayout layout, layout2;

private TextView penSizeTxt;

SharedPreferences pref;

private Preview preview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);

    init();
    preview = new Preview(this);

    layout2 = (RelativeLayout) findViewById(R.id.paint_layout2);
    layout = (RelativeLayout) findViewById(R.id.paint_layout);
    layout.addView(preview);
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            myView = new MyView(SketchActivity.this, layout.getWidth(), layout.getHeight());

            layout2.addView(myView);
            layout2.bringToFront();

        }
    }, 50);

    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(0xFF000000);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(5);

    mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);
    mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
}

private void init() {

    clearBtn = (Button) findViewById(R.id.clearBtn);

    embossBtn = (ToggleButton) findViewById(R.id.embossBtn);
    blurBtn = (ToggleButton) findViewById(R.id.blurBtn);
    eraseBtn = (ToggleButton) findViewById(R.id.eraseBtn);
    srcaBtn = (ToggleButton) findViewById(R.id.srcatopBtn);

    clearBtn.setOnClickListener(this);
    embossBtn.setOnClickListener(this);
    blurBtn.setOnClickListener(this);
    eraseBtn.setOnClickListener(this);
    srcaBtn.setOnClickListener(this);
}

private static Paint mPaint;

private MaskFilter mEmboss;

private MaskFilter mBlur;

public void colorChanged(int color) {
    mPaint.setColor(color);
}

private void setToggleOf() {
    embossBtn.setChecked(false);
    eraseBtn.setChecked(false);
    blurBtn.setChecked(false);
    srcaBtn.setChecked(false);
}

@Override
public void onClick(View v) {
    if (v.getId() == embossBtn.getId()) {

        if (mPaint.getMaskFilter() != mEmboss) {
            setToggleOf();
            mPaint.setXfermode(null);
            mPaint.setAlpha(0xFF);
            mPaint.setMaskFilter(mEmboss);
            embossBtn.setChecked(true);
        } else {
            mPaint.setMaskFilter(null);
            embossBtn.setChecked(false);
        }
    } else if (v.getId() == blurBtn.getId()) {

        if (mPaint.getMaskFilter() != mBlur) {
            setToggleOf();
            mPaint.setXfermode(null);
            mPaint.setAlpha(0xFF);
            mPaint.setMaskFilter(mBlur);
            blurBtn.setChecked(true);
        } else {
            mPaint.setMaskFilter(null);
            blurBtn.setChecked(false);
        }
    } else if (v.getId() == eraseBtn.getId()) {
        if (eraseBtn.isChecked()) {
            setToggleOf();
            eraseBtn.setChecked(true);
            mPaint.setMaskFilter(null);
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

        } else {
            mPaint.setMaskFilter(null);
            mPaint.setXfermode(null);
            mPaint.setAlpha(0xFF);

        }
    } else if (v.getId() == srcaBtn.getId()) {
        if (srcaBtn.isChecked()) {
            setToggleOf();
            mPaint.setMaskFilter(null);
            srcaBtn.setChecked(true);
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
            mPaint.setAlpha(0x80);
        } else {
            mPaint.setMaskFilter(null);
            mPaint.setXfermode(null);
            mPaint.setAlpha(0xFF);
        }

    }

    else if (v.getId() == clearBtn.getId()) {
        layout2.removeAllViews();
        myView = new MyView(SketchActivity.this, layout.getWidth(), layout.getHeight());
        layout2.addView(myView);
    }

}

public class MyView extends View {

    private static final float MINP = 0.25f;

    private static final float MAXP = 0.75f;

    private Bitmap mBitmap;

    private Canvas mCanvas;

    private Path mPath;

    private Paint mBitmapPaint;

    Bitmap bitmap;

    int x = 0;

    int y = 0;

    int r = 0;

    public MyView(Context c, int width, int height) {
        super(c);

        WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        int w = display.getWidth(); // deprecated
        int h = display.getHeight();
        // setFocusable(true);
        // setBackgroundResource(R.drawable.download);

        // setting paint
        mPath = new Path();
        mPaint = new Paint();

        mPaint.setAlpha(0);
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        mPaint.setAntiAlias(true);
        mPaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.NORMAL));
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);

        this.getContext().getResources();

        Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.smoke);
        Bitmap bm2 = getResizedBitmap(bm, h, w);

        // converting image bitmap into mutable bitmap

        bitmap = bm2.createBitmap(w, h, Config.ARGB_8888);
        mCanvas = new Canvas();
        mCanvas.setBitmap(bitmap); // drawXY will result on that Bitmap
        mCanvas.drawBitmap(bm2, 0, 0, null);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //mCanvas.drawCircle(x, y, r, mPaint);

        // canvas.drawBitmap(bitmap, 0, 0, null);
        canvas.drawBitmap(bitmap, 0, 0, mBitmapPaint);

        canvas.drawPath(mPath, mPaint);

        super.onDraw(canvas);

    }

    private float mX, mY;

    private static final float TOUCH_TOLERANCE = 4;

    private void touch_start(float x, float y) {
        mPath.reset();
        mPath.moveTo(x, y);
        // mPath.lineTo(x, y);
        // mCanvas.drawPoint(x, y, mPaint);
        mX = x;
        mY = y;

    }

    private void touch_move(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if ((dx >= TOUCH_TOLERANCE) || (dy >= TOUCH_TOLERANCE)) {
            mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
            mX = x;
            mY = y;
        }
        // invalidate();
    }

    private void touch_up() {
        mPath.lineTo(mX, mY);
        // commit the path to our offscreen
        mCanvas.drawPath(mPath, mPaint);
        // kill this so we don't double draw
        mPath.reset();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(x, y);

            invalidate();
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            touch_up();
            invalidate();
            break;
        }
        return true;
    }

    public Bitmap getImage() {
        return mBitmap;
    }
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    // TODO Auto-generated method stub
    penSizeTxt.setText(String.valueOf(progress + 2));

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    // TODO Auto-generated method stub

}

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // CREATE A MATRIX FOR THE MANIPULATION
    Matrix matrix = new Matrix();
    // RESIZE THE BIT MAP
    matrix.postScale(scaleWidth, scaleHeight);
    // RECREATE THE NEW BITMAP
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
    return resizedBitmap;
}

}

I want it to clear the second layout and show the content of the camera, on touch. So that if i make a curved line with my finger on the screen it would set those pixels to alpha, and see the camera from the back layout. The problem is that if for example, i make a curved line, the app erases the content of that curve too. So that if i would make a circle with my finger it would erase the content of the circle too, not only the margin.
A screenshot with how it looks: http://imgur.com/5gjNB

A: onCreate i had:
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFF000000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(5);

And then on my View i had:
 mPaint = new Paint();
 mPaint.setAlpha(0);
 mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
 mPaint.setAntiAlias(true);
 mPaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.NORMAL));

Overriding the mPaint, and that's what made it not work properly. By deleting the second:
 mPaint = new Paint();

I made it work


text:
Q: Open category filters by default in Magento 2 Is it possible to open category filters in the left pane by default in Magento 2 Luma theme.

A: Just copy
vendor\magento\theme-frontend-luma\Magento_LayeredNavigation\templates\layer\view.phtml

into
app\design\frontend\<your_company>\<your_theme>\Magento_LayeredNavigation\templates\layer\

and change the 'data-mage-init' attribute as follow:
<?php foreach ($block->getFilters() as $filter): ?>
    <?php if ($filter->getItemsCount()): ?>
        <?php if (!$wrapOptions): ?>
            <?php $collapsibleRange = implode(' ', range(0, $filter->getItemsCount())); ?>
            <?= /* @escapeNotVerified */ __('Shopping Options') ?>
            <div class="filter-options" id="narrow-by-list" data-role="content" data-mage-init='{"accordion":{"openedState": "active", "collapsible": true, "active": "<?= $collapsibleRange ?>", "multipleCollapsible": true}}'>
        <?php  $wrapOptions = true; endif; ?>

<?= /* @escapeNotVerified */ __($filter->getName()) ?>

<?= /* @escapeNotVerified */ $block->getChildBlock('renderer')->render($filter); ?>

    <?php endif; ?>
 <?php endforeach; ?>

A: I did not test it but I think if you change line 12 to true it should work.
https://github.com/magento/magento2/blob/077584c99ebb8007cad176c3b9a0144a05c259cd/app/code/Magento/Ui/view/base/web/js/lib/collapsible.js#L12
I don't know what the proper way to override js files in Magento 2 is yet. So you should look that up to do it the Magento way.

A: I acidentally found working code:

I don't know if this is proper solution, but all filters are open and collapsing working. Also mobile open filter button works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Function type with property in Kotlin I can specify this in TypeScript (thus can be done in JavaScript):
interface Foo {
  (arg: any): void
  foo: string
}

Can the same thing achieved in Kotlin?

A: This can be expressed in Kotlin, too:
interface Foo {
  fun funX(arg: Any): Unit
  val foo: String
}

Properties in Interfaces


text:
Q: Failed to locate a binder for interface Can anyone help. I am making a simple weather app in android. I know first two error,but don't know about last one.
10-25 16:44:11.666: E/ActivityThread(1448): Failed to find provider info for com.google.plus.platform
10-25 16:44:11.949: E/libEGL(1448): validate_display:255 error 3008 (EGL_BAD_DISPLAY)
10-25 16:44:12.379: E/chromium(1448): [ERROR:interface_registry.cc(99)] Failed to locate a binder for interface: autofill::mojom::AutofillDriver

A: Third error, possible due to the server being offline, therefore the URL not being loaded. Look at how you handle the WebView for that particular case. I might be wrong, ran into the same error a while ago, and I remember that's what it was.

A: Resolve this issue
    @Override
public void onPause() {
    super.onPause();
    webView.onPause();
    webView.pauseTimers();
}

@Override
public void onResume() {
    super.onResume();
    webView.resumeTimers();
    webView.onResume();
}

A: I start getting exactly same error when i updated sdk and play services version. App works fine but getting this error on logcat. I think its admob related but not really sure.

A: Try to use webView.getSettings().setDomStorageEnabled(true). In most of cases this helps.

A: Enable JavaScript in the webview. By default JavaScript is disabled in the webview. After enabling JavaScript problem solved for me.
WebSettings webSettings=webView.getSettings();
webSettings.setJavaScriptEnabled(true);

A: Error Solved: I had same error and it was caused closing the loading "Grade build running" before the Apk is installed on my Emulator....I tried everything to fix but failed until i created another project and transfered my files to the new project.Hope it works for you too.

A: I think that becouse you are using the Admobe test ID


text:
Q: Как данные за день продублировать на следующий день sql-запросом? (MsSql) Имеются данные в бд

Нужно скопировать эти данные но уже с датой следующего дня

A: Структура используемой таблицы:
CREATE table info(
    id int auto_increment  primary key,
    date DATETIME not null,
    _number INTEGER
);

Ее заполнение:
INSERT INTO info
(date, _number)
values
    ('1000-05-03 00:00:00', 1),
    ('2001-01-02 00:00:00', 3);

Вот, как можно прибавить n-ое кол-во дней к дате:
DATE_ADD('2008-01-02 13:38:50.02', INTERVAL n DAY)

Не составит труда теперь составить запрос:
INSERT INTO info
(date, _number)
SELECT
    DATE_ADD(date, INTERVAL 1 DAY) as date,
    _number
FROM
    info;

Если вызовем команду SELECT * FROM info, то получим вывод:

id, date, _number
'1', '1000-05-03 00:00:00', '1'
  '2', '2001-01-02 00:00:00', '3'
  '3', '1000-05-04 00:00:00', '1'
  '4', '2001-01-03 00:00:00', '3'


text:
Q: How can I do a bulk refactor in Visual Studio We are in the process of converting from Dynamics CRM 4.0 to Dynamics CRM 2011.  We have 100kloc+ written against auto-generated proxy classes (outputed by the crmsvcutil.exe program).
The new version of this utility changes the naming of proxy classes so this:
    var myEntity = new MyEntity();
    myEntity.MyField = 2;

Is now this:
    var myEntity = new new_myentity();
    myEntity.new_myfield = 2;

I can automate the matching of symbols so that I know the MyEntity is new_myentity, but now I need a way to update my code with all of the new symbols.


text:
Q: How to debug a specific binary using VS Code on Ubuntu I want to debug a Python binary which then calls scipy C++ modules (I want to step those) as suggested here. I can successfully do that with command line gdb using
gdb --args python runtests.py -g --python mytest.py

and I can do the same in eclipse by setting the binary as:
/usr/bin/python3

and debugger's arguments as
runtests.py -g --python mytest.py

Can I do this somehow in Visual Studio Code?

A: So I created a new launch configuration in launch.json file (by clicking on the Configure gear icon in the debugger), set program to
/usr/bin/python3

args to
runtests.py -g --python mytest.py

and added
"break" : "NI_ZoomShift"

to setupCommands. Then just run the new configuration which is in my case called (gdb) scipy and it works.

This link has been very helpful.


text:
Q: Debian 8(Jessie) started before DHCP server results in no network connection Recently we got a power outage and our debian 8 Raspberry Pi did not reconnect to the internet.
We noticed that our DHCP server was very slow to start > 5 min. In this time the Pi was already up and running, but without connection to the internet. 30 minutes later and still no attempt to make a connection to the internet, no entries from dhclient in syslog either.
If we just do ifdown eth0 && ifup eth0, it's fixed, but that's kind of hard when the device is somewhere remote and you rely on the interent to connect to it.
Our /etc/network/interfaces is very simple:
auto eth0
iface eth0 inet dhcp

Are there any solutions to this, other than writing a script that just constantly checks every x minutes if it can ping 8.8.8.8 and if it can't runs ifdown eth0 && ifup eth0?

A: If a host configured to use DHCP for IP address assignment is unable to contact a DHCP server, it will automatically configure itself for an address in the 169.254.0.0/16 CIDR block.  Naturally, this will not work for anything other than communicating with other hosts in the same state.  However, these self-assigned quasi leases have a short duration (often no more than five minutes) after which the host will attempt again to contact a DHCP server for configuration.  All you need to do is wait a short while and your device will be correctly set up as normal on the network.


text:
Q: Modal popup view like twitter and facebook in iPhone I want to create a modal popup view which contains some UIControls
like button, image, textfield etc.
Here is an example of what I want:

What should I use?
UIAlertView or UIView or something else ...?

A: you try use REComposeViewController
https://github.com/romaonthego/REComposeViewController

A: You should use UIView and just customize it. :)
UIAlertView has a default appearance.


text:
Q: Sub list items are not showing in C# I am trying to add a list inside a list. But I wasn't able to retrieve the items from the sub list. There is no error, but no data was retrieved from the sub list. Please focus on GenerateClue() I think the error is there.
When I'm trying to access the data using clueList[0][0], There is no data
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;

public class TrainingMode : MonoBehaviour {
    private List<int> answerKey;
    private List<int> clue;
    private List<List<int>> clueList;
    private int correct;
    private int wellPlaced;
    public Text answerKeyText;
    System.Random random = new System.Random();

    void Start () {
        answerKey = new List<int>();
        clue = new List<int>();
        clueList = new List<List<int>>();

        GenerateAnswerKey();
        GenerateClue();

        //CheckCorrectAndWellPlaced();

        answerKeyText.GetComponent<Text>().text = answerKey[0] + " "+ answerKey[1] + " "+ answerKey[2];
        foreach (List<int> arrClue in clueList)
        {
            foreach (int item in arrClue)
            {
                Debug.Log(item);
            }
        }
    }

    private void GenerateClue()
    {

        //Generate clue
        for (int j = 0; j <= 5; j++)
        {
            for (int i = 0; i <= 2; i++)
            {
                int randomNumber = random.Next(0, 9);
                if (clue.Contains(randomNumber))
                {
                    i--;
                }
                else
                {
                    clue.Add(randomNumber);
                }

                if (clue.Count == 3)
                {
                    clueList.Add(clue);
                    clue.Clear();
                }
            }
        }
    }

    private void CheckCorrectAndWellPlaced()
    {
        correct = 0;
        wellPlaced = 0;
        //Check for correct and wellplaced numbers
        for (int i = 0; i <= 2; i++)
        {
            if (answerKey.Contains(clue[i]))
            {
                correct++;
            }
            if (clue[i] == answerKey[i])
            {
                wellPlaced++;
            }
        }
    }

    private void GenerateAnswerKey() {
        //Generate answerkey
        for (int i = 0; i <= 2; i++)
        {
            int randomNumber = random.Next(0, 9);
            if (answerKey.Contains(randomNumber))
            {
                i--;
            }
            else
            {
                answerKey.Add(randomNumber);
            }
        }
    }
}

A: The problem is that when you add the clue to your clue list what it's actually doing is passing a reference because List<> is a class. So you end up having just 2 variables pointing to the same memory. One is your clue variable and the other is the clueList[X]. So when you call clue.Clear() you are clearing the clue list which is ACTUALLY the same memory than your clueList[X].
As as fix just change this:
if (clue.Count == 3)
{
    clueList.Add(clue);
    clue.Clear();
}

into this:
if (clue.Count == 3)
{
    clueList.Add(new List<int>(clue));
    clue.Clear();
}

A: Your problem is here :
if (clue.Count == 3)
{
    clueList.Add(clue);
    clue.Clear();
}

You're adding clue to the clueList and then clearing the clue which has the same "memory address" ( same object as in the clueList ).
So in general, you're filling the clue list with some random numbers and then you're clearing this up whenever it fills making it empty again.
Instead, try to create a new list of ints on the beginning of your first for-loop.
for (int j = 0; j <= 5; j++)
{
    var list = new List<int>();
    for (int i = 0; i <= 2; i++)
    {
        int randomNumber = random.Next(0, 9);
        if (list.Contains(randomNumber))
        {
            i--;
        }
        else
        {
            list.Add(randomNumber);
        }

        if (list.Count == 3)
        {
            clueList.Add(list);
        }
    }
}

A: You need to create a copy of the list, so to avoid the Clear() call to act on the element put in the clueList.
if (clue.Count == 3)
   {
       clueList.Add(clue.ToList());
       clue.Clear();
   }

But I also think that there can be cases when the list won't be inserted, because there can be cases when the random number it's always the same and you keep on going out the for loop.
for (int j = 0; j <= 5; j++)
        {
            for (int i = 0; i <= 2; i++)
            {
                int randomNumber = random.Next(0, 9);
                if (clue.Contains(randomNumber))
                {
                    i--;
                }
                else
                {
                    clue.Add(randomNumber);
                }

                if (clue.Count == 3) // EDIT: what if it never reaches 3 ?
                {
                    clueList.Add(clue.ToList());
                    clue.Clear();
                }
            }
        }


text:
Q: Setting variable to true on click - Doesn't seem to work I have a page with 2 simple tabs. The tabs are showing if disable_function = false.
At the end of the page I have a simple trigger which I want to set the variable disable_function = true so that the tabs won't work - when ever the trigger is ON.
I tried few ways but it didn't seem to work.
Here is a fiddle if you want to have a look of the code: http://jsfiddle.net/db7tK/
Thanks in advance.

A: you have disable_function defined in the scope of document.ready.
not as a global.
move it out of 'jQuery(document).ready(function(){'
EDIT:
<script>
var disable_function = false;
jQuery(document).ready(function(){....


text:
Q: Max chosen of first or last elements of array can u help me with this problem: :((
Given an array A[] have n positive numbers (n<=5000). Peter and Emma play a game chose number. When in turn of each person, they can choose the first or last elements of array then increase his/her score and remove that elements from array. Peter will play first.
You must find who can win and their score, and both Peter and Emma are the best players
Example:
A = {4,5,1,3}
At first turn, Peter can choose first number (4) or last number (3), so he choose 3 then remove it.
// A= {4,5,1}
At second turn, Emma can choose first number (4) or last number (1), so she choose 4 then remove it.
// A={5,1}
At third turn, Peter can choose first number (5) or last number (1), so he choose 5 then remove it.
// A={1}
At last turn, Emma only choose 1 number (1), then remove 1
Now array is empty so the game is over, Peter have 3+5=8 score; Emma have 4+1=5 score. So Peter win.
Explain why not Peter have 9 score (4+5) and Emma have 4 scores (1+3). Because they are both best player so when Peter remove the number 3, Emma will choose 4 instead of 1\
i have use backtrack but time limited

A: The basic idea is the following:
Let us call score(first, right) the best score that a player can get with remaining element from first to last element.
Then, if player A select the first element, then player B will gain score(first+1, last), and
player A will then gain sum - player B score.
The same logic is used if player A select the last element: player B will gain score(first, last-1)
This can be easily implemented in a recursive manner.
Memoization must be implemented to avoid repeating the same calculations.
Complexity: O(N^2).
#include <iostream>
#include <vector>
#include <numeric>
#include <tuple>

int sum;
int sum_left;
std::vector<std::vector<int>> mem;

int score_rec (const std::vector<int> &A, int first, int last) {
    if (mem[first][last] >= 0) return mem[first][last];

    sum_left -= A[first];
    int score1 = A[first] + sum_left - score_rec (A, first + 1, last);
    sum_left += A[first];

    sum_left -= A[last];
    int score2 = A[last] + sum_left - score_rec (A, first, last - 1);
    sum_left += A[last];

    int score = std::max (score1, score2);
    mem[first][last] = score;

    return score;
}

std::tuple<int, int> scores (const std::vector<int> &A) {
    int n = A.size();
    sum = std::accumulate (A.begin(), A.end(), 0);
    sum_left = sum;
    for (int i = 0; i < n; ++i) {
        mem.emplace_back (std::vector<int> (n, -1));
    }
    for (int i = 0; i < n; ++i) mem[i][i] = A[i];

    int scoreA = score_rec (A, 0, n-1);
    int scoreB = sum - scoreA;

    return {scoreA, scoreB};
}

int main () {
    std::vector<int> A = {4, 5, 1, 3};
    auto[scoreA, scoreB] = scores (A);
    std::cout << scoreA << " " << scoreB << std::endl;
    return 0;
}


text:
Q: lexical error at character '\DEL' when doing runhaskell Heres my code:
factorial :: Integer -> Integer
factorial n = product [1..n]

main = print(factorial 50)

I don't get any errors compiling, but when i run the compiled code
runhaskell test

I get this error:
test:1:1: lexical error at character '\DEL'

What is causing this? How do I solve the problem?
UPDATES
I did a hexdump of the file:
$ hexdump -x test.hs

and got
0000000    6166    7463    726f    6169    206c    3a3a    4920    746e
0000010    6765    7265    2d20    203e    6e49    6574    6567    0a72
0000020    6166    7463    726f    6169    206c    206e    203d    7270
0000030    646f    6375    2074    315b    2e2e    5d6e    6d0a    6961
0000040    206e    203d    7270    6e69    2874    6166    7463    726f
0000050    6169    206c    3035    0029
0000057

A: Make sure that you're using runhaskell with the source file test.hs rather than the compiled binary test.
If you've used something like ghc to create an executable file, you can just run that directly, with something like:
./test

Be aware that test is probably not a good name for an executable since it's a built-in command on some shells, something that's burnt me before when my test executable doesn't seem to do what I wanted :-)


text:
Q: Can this fluent interface be simplified? I am trying to implement a fluent interface that let's me specify a table with columns, where table and columns have properties. I want to able to initialize the table class like this:
var t = TableBuilder.Create()
                    .WithName("test")
                    .WithColumn("col1").WithType("Int32")
                    .WithColumn("col2").WithType("String")
                    .WithColumn("col3");

I came up with a solution, that works. My questions are, can the implementation be simplified or should I take a totally different approach? I've seen the usage of extension methods in similar cases, but I don't know if they would help me or how to use them in this case.
Here is the code (with some comments below):
interface ITable
{
    ITable WithName(string tableName);
    ITableAndColum<ITable, IColumn> WithColumn(string columnName);
}

interface IColumn
{
    IColumn WithType(string typeName);
}

interface ITableAndColum<TTable, TColumn>
    where TTable : ITable
    where TColumn : IColumn
{
    ITableAndColum<ITable, IColumn> WithColumn(string columnName);
    ITableAndColum<ITable, IColumn> WithType(string typeName);
}

class TableAndColumn : ITableAndColum<ITable, IColumn>
{
    public ITable Table { get; set; }
    public IColumn Column { get; set; }

    public ITableAndColum<ITable, IColumn> WithColumn(string columnName)
    {
        return Table.WithColumn(columnName);
    }

    public ITableAndColum<ITable, IColumn> WithType(string typeName)
    {
        Column.WithType(typeName);
        return this;
    }

    public override string ToString()
    {
        return Table.ToString();
    }
}

class Column : IColumn
{
    public string ColumnName { get; set; }
    public string TypeName { get; set; }

    public IColumn WithType(string typeName)
    {
        TypeName = typeName;
        return this;
    }
}

class TableBuilder : ITable
{
    public string TableName { get; set; }
    List<Column> Columns;

    TableBuilder() { Columns = new List<Column>(); }

    public static ITable Create() { return new TableBuilder(); }

    public ITable WithName(string tableName)
    {
        TableName = tableName;
        return this;
    }

    public ITableAndColum<ITable, IColumn> WithColumn(string columnName)
    {
        Column thisColumn = new Column() { ColumnName = columnName };
        Columns.Add(thisColumn);

        return new TableAndColumn() { Table = this, Column = thisColumn };
    }

    public override string ToString()
    {
        return TableName + "(" + string.Join(",", Columns.Select(c => (c.TypeName != null ? c.TypeName + " " : "") + c.ColumnName)) + ")";
    }
}

class Example
{
    public Example()
    {
        var t = TableBuilder.Create()
                            .WithName("test")
                            .WithColumn("col1").WithType("Int32")
                            .WithColumn("col2").WithType("String")
                            .WithColumn("col3");
        var tdef = t.ToString();
    }

}

There are the two interfaces ITable and IColumn with there implementations Table and Colum. They expose the appropriate methods which are specific to their type. The third interface ITableAndColumn combines the other interfaces and it's implementation TableAndColumn holds a reference to a Table instance and a Column instance. The Interface exposes selected methods of ITable and IColumn and calls the appropriate instance.
Is this approach to complicated? Would extension methods simply this in any way?

A: I'm not a huge fan of making TableAndColumn. Seems wrong, to me. They're distinct entities. I've taken a page out of KendoUI in terms of their fluent style:
TableBuilder.Create()
    .WithName("test")
    .WithColumn(c => c.WithName("col1").WithType("Int32"))
    .WithColumn(c => c.WithName("col2").WithType("String"))
    .WithColumn(c => c.WithName("col3"));

Note how we're configuring the columns via a lambda. This allows us to properly constrain what IColumn can expose.
Of course, you can change it to: WithColumn("col1", c => c.WithType("Int32")) and the overload .WithColumn("col3").
Implementation:
interface ITable
{
    ITable WithColumn(Action<IColumn> c);
    ITable WithName(string tableName);
}

interface IColumn
{
    IColumn WithName(string columnName);
    IColumn WithType(string typeName);
}

class TableBuilder : ITable
{
    public string TableName { get; set; }
    List<Column> Columns = new List<Column>();

    public static ITable Create() { return new TableBuilder(); }

    public ITable WithName(string tableName)
    {
        TableName = tableName;
        return this;
    }

    public ITable WithColumn(Action<IColumn> c)
    {
        Column thisColumn = new Column();
        c(thisColumn);
        Columns.Add(thisColumn);

        return this;
    }
}

class Column : IColumn
{
    public string ColumnName { get; set; }
    public string TypeName { get; set; }

    public IColumn WithName(string columnName)
    {
        ColumnName = columnName;
        return this;
    }

    public IColumn WithType(string typeName)
    {
        TypeName = typeName;
        return this;
    }
}


text:
Q: attach several images to post + gallery i'm wondering if its possible to attach several images to a post then display those images in a thumbnail/fading gallery?
By the way, the images should also be resized to a fixed size + thumbnail.
thanks

A: Yes, you can use the standard wordpress [gallery] shortcode, after having attacched the images to your post.
To attach images to your post, you can use the button "Upload Media".
Upload the image from your disk and the press "Save Changes". The image will be attached to your post.
Then use the gallery shortcode to insert the gallery in your post.


text:
Q: Regex PowerShell: Replace every comma with [blank] if it doesn't have a value in between a comma Regex PowerShell: Replace every comma with [blank] if it doesn't have a value in between a comma.
Raw Data:
Name 1,Exported,Exported,Exported,Exported,Exported,Exported,Exported
Name 2,Exported,Exported,Exported,Exported,Exported,Exported,
Name 3,Exported,Exported,,Exported,Exported,,

Expected Output:
Name 1,Exported,Exported,Exported,Exported,Exported,Exported,Exported
Name 2,Exported,Exported,Exported,Exported,Exported,Exported,[Blank]
Name 3,Exported,Exported,[Blank],Exported,Exported,[Blank],[Blank]

This is what I got so far:
```powershell
$data -replace ("(,\W)|(,\s)", ",[Blank],")

However, it doesn't work as intended.

A: As a pattern, you could use
(?m),[^\S\r\n]*(?=,|$)

Explanation

*

*(?m) Inline multiline modifier

*, Match a comma

*[^\S\r\n]* Match 0+ times a whitespace char without a newline

*(?=,|$) Positive lookahead, assert what is at the right is either a comma or the end or the line

And replace with
,[Blank]

.NET regex demo | Powershell demo

For example
$data=@'
Name 1,Exported,Exported,Exported,Exported,Exported,Exported,Exported

Name 2,Exported,Exported,Exported,Exported,Exported,Exported,

Name 3,Exported,Exported,,Exported,Exported,,
'@
$data -replace ("(?m),[^\S\r\n]*(?=,|$)", ",[Blank]")

Output
Name 1,Exported,Exported,Exported,Exported,Exported,Exported,Exported

Name 2,Exported,Exported,Exported,Exported,Exported,Exported,[Blank]

Name 3,Exported,Exported,[Blank],Exported,Exported,[Blank],[Blank]


text:
Q: Data Modeling: how to "normalize" same items identified to be different? Say I have as my input inventory of store items coming from different merchants. Further, say that some of these items may be the same between different merchants (e.g. 2 merchants sell Xboxes, but have different fields, ids, etc to describe the item). How do I model a database such that I know that my inventory item 1 is the same as Merchant 1's inventory item 255 is the same as Merchant 2's inventory item 45 is the same as ....?
I want my users to be able to indicate they are interested in my item 1 -- and I need to know how this translate to how the various merchants identify the same product.

A: You need and item_x_merchant table.
With columns my_id, merchant_id, merchants_item_id.


text:
Q: Java printf formatting to print items in a table or columns I am wanting to print things in a neat columns using printf.
happening       0.083333    [4]
hi              0.083333    [0]
if              0.083333    [8]
important       0.083333    [7]
is              0.250000    [3, 5, 10]
it              0.166667    [6, 9]
tagged          0.083333    [11]
there           0.083333    [1]
what            0.083333    [2]

I have this code System.out.printf("%s  %.6f  %s \n", word, web.getFrequency(word), loc);, but it prints out this:
happening  0.083333  [ 4 ]
hi  0.083333  [ 0 ]
if  0.083333  [ 8 ]
important  0.083333  [ 7 ]
is  0.250000  [ 3 5 10 ]
it  0.166667  [ 6 9 ]
tagged  0.083333  [ 11 ]
there  0.083333  [ 1 ]
what  0.083333  [ 2 ]

Any help would be appreciated.

A: I would use this:
System.out.printf ("%-30s %1.7f %s%n", word, etc, etc2);

A: You can get the max length of all the word strings, and store that length in a variable, max. Use a for loop to get that max, and then create a String that has the format with concatenating the normal printf format with the max variable to be used as the width. Additionally \t puts in a tab character.
int max = 0;
for (int ii = 0; ii < numberOfStrings; ii++)
{
   max = (word.length() > max) ? word.length() : max;
}
String format = "%" + max + "s\t%.6f\t%s \n";
System.out.printf(format, word, web.getFrequency(word), loc);

A: System.out.format("%-8s%-8s%-8s\n","a","b","pow(b,a)");
System.out.format("%-8d%-8d%-8d\n",1,2,1);
System.out.format("%-8d%-8d%-8d\n",2,3,8);
System.out.format("%-8d%-8d%-8d\n",3,4,81);
System.out.format("%-8d%-8d%-8d\n",4,5,1024);
System.out.format("%-8d%-8d%-8d\n",5,6,15625);

//the negative integer kinda sets it back to the number of space needed

A: input:
happening       0.083333    [4]
hi              0.083333    [0]
if              0.083333    [8]
important       0.083333    [7]
is              0.250000    [3, 5, 10]
it              0.166667    [6, 9]
tagged          0.083333    [11]
there           0.083333    [1]
what            0.083333    [2]

code:
import java.util.Scanner;
public class MyClass {
    private static final Scanner sc = new Scanner(System.in);
       public static void main(String args[]) {
            for(int i = 0 ; i < 9; i++){
                String str = sc.next();
                float f = sc.nextFloat();
                String str2 = sc.nextLine();
                System.out.printf("%-10s %f %s\n", str, f, str2);
             }
             sc.close();
      }
  }

output:
happening       0.083333    [4]
hi              0.083333    [0]
if              0.083333    [8]
important       0.083333    [7]
is              0.250000    [3, 5, 10]
it              0.166667    [6, 9]
tagged          0.083333    [11]
there           0.083333    [1]
what            0.083333    [2]

use - to make the string left aligned, use field width to align them properly.
In your case printf statement will be
System.out.printf("%-10s %.6f %s\n", word, web.getFrequency(word), loc);


text:
Q: Teamcity Multi Value Configuration Variables I want to utilize ConfParameters in Teamcity in a way that its value can be dynamic based on the environment specific value user selects.
Is this possible. I searched a lot, but I guess isn't supported.
Any help will be appreciated.
example:
if %env.val%="qa":
   dbuser="qauser"
else if %env.val%="stage":
   dbuser="stageuser"

.. and so on some logic
And I want this dbuser as a Conf parameter in Teamcity.

A: I think you could take this solution:
if %env.val%="qa":
   dbuser="qauser"
echo "##teamcity[setParameter name='env.dbuser' value='qauser']"
else if %env.val%="stage":
   echo "##teamcity[setParameter name='env.dbuser' value='stage']"

And after that you can use %env.dbuser% anywhere.


text:
Q: In a tabular, how to set a cell text aligned on the right and the text in the below cell aligned with the beginning of the above text I'd like to obtain a thing similar to the following image
As you see the word "Candidato:" is aligned with the beginning of the name "Giovanni Bianchi", While "Giovanni Bianchi" is aligned to the right.
Moreover I need to put the word "Relatori:" on the same line of "Candidato". "Relatori:" has to be aligned on the left side.
Thank you to everybody can respond to me.

A: I assume that you're typesetting this in some environment where \centering is in force.
You obtain the desired alignment by
\begin{tabular*}{\textwidth}{@{\extracolsep{\fill}}ll@{}}
\begin{tabular}[t]{@{}l@{}}
Relatori:\\
Prof.\ Mario Rossi\\
Ing.\ Pietro Verdi
\end{tabular}
&
\begin{tabular}[t]{@{}l@{}}
Candidato:\\
Giovanni Bianchi
\end{tabular}
\end{tabular*}

This is precisely what the frontespizio package does. It goes without saying that I recommend it.


text:
Q: Flutter - Automatically run the application when notification received from FCM (without clicking it) I'm developing a delivery app, when the client orders something i want the supplier app to open up on screen with 2 buttons to accept or decline the order.
its easy to do when the supplier clicks the notification (onLaunch and onResume configuration), but i want it to happen without their interaction.
Something like when someone calls you on whatsapp or FB messanger.
is this achievable ? couldnt find such a thing in flutter.

A: https://pub.dev/packages/flutter_local_notifications
      AndroidNotificationDetails(
                      'full screen channel id',
                      'full screen channel name',
                      'full screen channel description',
                      priority: Priority.high,
                      importance: Importance.high,
                      fullScreenIntent: true),

this will open app for android

A: Take a look at the firebase_messaging docs where it explains how to setup background messages on Optionally handle background messages

A: Note: This old way for implementing the the FCM Notification,
As for the the Documentation, Notification come your app, either it is in foreground or background.
But in these case of Background:  A notification is delivered to the device's system tray and the data payload is delivered in the extras of the intent of your launcher Activity.
Case of Foreground: You can navigate to any screen. with help of
final FirebaseMessaging fcmMessaging = FirebaseMessaging();

fcmMessaging.configure(

onMessage: (Map<String, dynamic> message) async {
            print("onMessage: $message");
        },

onLaunch: (Map<String, dynamic> message) async {
            print("onLaunch: $message");
            // your code
        },

onResume: (Map<String, dynamic> message) async {
            print("onResume: $message");

        },
);

New way : https://stackoverflow.com/a/73221621/5197656


text:
Q: How to communicate b/w chrome native messaging app( console ) and winforms I have created a chrome extension with native app messaging. The native app is written in (Winforms) c#. It starts as soon as we check on to the extension. I need to show the app only when the user clicks on .exe file. So my idea is to create a console application as an Native messaging application. When the user click on extension, the console app will run in background. When the user clicks on .exe
(winforms), the Winform app will launch and communicate with the console app.
Is it the best approach i can go with? And how can i establish the communication b/w console app and winforms?


text:
Q: Django Sessions: Correct way to get logged in user data from server? I have my API set up using SessionAuthentication. Once a user logs in, I redirect them to their profile page in React. Once they are redirected to their profile page, I want to make a REST call to retrieve their profile data and insert it in the proper location on the page. I see a couple ways I can do this:

*

*When a user logs in, put their User ID into the Response object (DRF) and then store that in the client somewhere (Redux store, session storage, or local storage). Then when they are redirected to the login page, make a REST call to /users/users_id.

*With Django sessions the logged in user is automatically tied to each request. So do I even need to follow Rest here? I can make a call to /users, and if the user is authenticated, return their data.

I would appreciate any help with this. Thank you.

A: With SessionAuthentication, after a successful login, the browser saves a sessionId cookie for that domain (or ip:port) automatically. Sending a request will send that cookie from the same domain no matter with Django or React, and authenticate the user, making your request.user a user.
You can check for the cookie when you inspect the page -> Application -> Cookies -> Your domain -> sessionId
Basically, you can login via Django and it will login you with React as well. No need to store anything manually. Just use the same domain for both.


text:
Q: Menu link not work properly I have problem with menu link. I use # in link. Using CMS - Wordpress. When i click on link mytournament i get only twiching. Other links works well.
Check here:http://fdsfd.5gbfree.com

    <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false">Primary Menu</button>

                Home

                My Tournaments

                Events

                Gallery

                Contact

A: The reason is that the link is #mytouranments but the section you are trying to link to is id="myt".
Change the link to #myt and it works.


text:
Q: Вывести таблицу по значениям из двух разных таблиц Подскажите. Необходимо вывести значения idParam только не одно а сразу несколько, 1438, 1439, 1440 и 55. то что написать в 4й строке?
Заранее благодарен.
select par.pRu, val.val
from Parameter par
left join VAL_2017 val on (par.Lid = val.Lid)
where idParam = 1438
and val.Lid = 10


text:
Q: Edit multiple records - asp.net MVC Been banging my head off the wall for a couple of days with this one and can't seem to figure it out or find an article that answers my question.
I'm working on a rota system for work, which is almost complete, but I'm stuck on this part in the admin area.
It will allow management to edit multiple rota entries for a given date range, for a given team.
It will eventually use a view model to pass in the dateFrom, dateTo, and Team (teamID) - I've just done it this way for now to try to get it working.
The rotas are stored in the Rotas table (see below.)
Rotas table
MorningShift and EveningShift (both FK's) store the employee's payroll number e.g. 123456.
The employee details are stored in the TeamMembers table (see below.)
TeamMembers table
The Username in the TeamMembers table is the employee's payroll number.
My issue is that I can't seem to get the currently entered value in the rotas table to display in the dropdown list in the view. It just has the first employee in the select list (Model.TeamMembers) displayed for all dropdowns.
My question is, how do I get the current value to display in each dropdown in the view?
I did try
    @Html.DropDownListFor(m => m.Rotas[i].MorningShift, Model.TeamMembers,
   Model.Rotas[i].TeamMember1.FirstName + " " + Model.Rotas[i].TeamMember1.Surname, null)

but while this shows the correct employee, it doesn't have a value set for the option, and obviously shows the employee's name again because that is in the selectlist.
What I have so far:
The controller:
    public async Task<ActionResult> ModifyRotas(DateTime? dateFrom,
            DateTime? dateTo, int? Team)
    {
        Auth auth = new Auth();
        bool isAdmin = auth.IsAdmin();

        if (!isAdmin)
        {
            return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
        }

        if (dateFrom != null && dateTo != null)
        {
            DateTime today = DateTime.Today;
            DateTime startDate = Convert.ToDateTime(dateFrom);
            DateTime endDate = Convert.ToDateTime(dateTo);

            // Make sure earlier shifts can't be modified
            if (startDate < today)
            {
                startDate = today;
            }

            // Verify the team exists
            Team teamDetails = await db.Teams.FindAsync(Team);
            if (teamDetails == null)
            {
                return HttpNotFound();
            }

            ModifyRotaVM vm = new ModifyRotaVM();

            // Get rotas for the team for the dates specified
            var rotas = await db.Rotas.Where(r => r.TeamID == Team && (r.ShiftDate >= startDate && r.ShiftDate <= endDate)).ToListAsync();

            vm.Rotas = rotas;

            // Generate the dropdown lists
            var teamMembers = db.TeamMembers.Where(m => m.TeamID == Team && m.Deleted == 0).Select(m => new SelectListItem() { Text = m.FirstName + " " + m.Surname, Value = m.Username });
            ViewBag.MorningShift = teamMembers;
            ViewBag.EveningShift = teamMembers;

            vm.TeamMembers = teamMembers;

            return View(vm);

        }

        // If we got here, something went wrong; redisplay the form
        return RedirectToAction("Modify");
    }

The VM:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    namespace TeamRota.Models
    {
       public class ModifyRotaVM
       {
          public List<Rota> Rotas { get; set; }

         public IEnumerable<SelectListItem> TeamMembers { get; set; }
       }
    }

The view:
    @model TeamRota.Models.ModifyRotaVM

    @{
       ViewBag.Title = "ModifyRotas";
    }

Modify Rotas

    @using (Html.BeginForm("RotaMod", "Rotas", new { area = "Admin" },
    FormMethod.Post))
    {
    // Being passed in so we can redirect back to the same page after the update
    @Html.Hidden("startDate", Request.QueryString["dateFrom"])
    @Html.Hidden("endDate", Request.QueryString["dateFrom"])
    @Html.Hidden("TeamID", Request.QueryString["Team"])

          Shift date
          Morning shift
          Evening shift

      @for (int i = 0; i < Model.Rotas.Count(); i++)
      {

               @Html.HiddenFor(m => m.Rotas[i].ID)
               @Html.DisplayFor(m => m.Rotas[i].ShiftDate)

            @Html.DropDownListFor(m => m.Rotas[i].MorningShift, Model.TeamMembers, Model.Rotas[i].TeamMember1.FirstName + " " + Model.Rotas[i].TeamMember1.Surname, null)
        @Html.DropDownListFor(m => m.Rotas[i].EveningShift, Model.TeamMembers, Model.Rotas[i].TeamMember.FirstName + " " + Model.Rotas[i].TeamMember.Surname, null)

    }

        <input type="submit" class="btn btn-success" value="Update" />

    }

Would really appreciate any help that anyone can offer.
Thanks.
Tom

A: I think you should try recreating your SelectList for the DropDownListFor.
var teamMembers = db.TeamMembers.Where(m => m.TeamID == Team && m.Deleted == 0).Select(m => new { Text = m.FirstName + " " + m.Surname, Value = m.Username });
ViewBag.TeamMembers = teamMembers

Then in your view, you just have to do this:
@Html.DropDownListFor(m => m.Rotas[i].MorningShift, new SelectList(ViewBag.TeamMembers, "Value", "Text", Model.Rotas[i].TeamMember1.Username), null)

@Html.DropDownListFor(m => m.Rotas[i].EveningShift, new SelectList(ViewBag.TeamMembers, "Value", "Text", Model.Rotas[i].TeamMember.Username), null)


text:
Q: How to install TCL packages: uuid,Itcl, html, tdom, tdom, tepam, math::bignum I need help to install  the following TCL packages:

*

*uuid

*Itcl

*html

*tdom

*tdom

*tepam

*math::bignum

A: uuid, html, tepam, and math::bignum all appear to be provided by package tcllib
/usr/share/tcltk/tcllib1.18/html/html.tcl
/usr/share/tcltk/tcllib1.18/math/bignum.tcl
/usr/share/tcltk/tcllib1.18/tepam/tepam.tcl
/usr/share/tcltk/tcllib1.18/tool/uuid.tcl
/usr/share/tcltk/tcllib1.18/uuid/uuid.tcl

specifically, in tcl8.6
% package require uuid
1.0.5
% package require html
1.4.4
% package require tepam
0.5
% package require math::bignum
3.1.1
%

tdom and itcl are provided by separate packages, namely
apt-cache show tdom
Description-en: fast XML/DOM/XPath/XSLT extension for Tcl written in C

apt-cache show itcl3
Description-en: [incr Tcl] OOP extension for Tcl - run-time files


text:
Q: ggplot2 legend entries change from posixct to integer when using scale_color_gradientn I'd like to make a path plot in ggplot2, with the path based on a timeseries, and a continuous color aesthetic to show this path. The legend should associate the color with timeseries. The legend is nice when the color aesthetic is defined in the original call to ggplot:
library(tidyverse)

times <- seq.POSIXt(from = as.POSIXct("2017-10-01 02:00:00"),
                    to = as.POSIXct("2017-10-03 12:34:00"),
                    by = "min")
values <- rnorm(length(times))

dat <- data.frame(times = times,
                  values1 = sin(values[order(values)]),
                  values2 = cos(values[order(-values)]))

ggplot(dat, aes(values1, values2, color=times)) +
  geom_path()

However, I want to use a different color scale than the default. When using scale_color_gradientn, or scale_color_continuous, the legend entries seem to get converted from POSIXct to integers:
ggplot(dat, aes(x = values1, y = values2, color = times)) +
  geom_path() +
  scale_color_gradientn(colors = rainbow(4))

How do I either (1) specify a custom color scale in the first plot, or (2) maintain POSIXct legend entries in the 2nd plot?

A: Looking at scale_colour_datetime() which is used by default, all it does is:
scale_colour_continuous(trans = "time")

So adding trans = "time" to your desired colour scale works:
ggplot(dat, aes(values1, values2, color=times)) +
    geom_path() +
    scale_color_gradientn(colors = rainbow(4), trans = "time")

Output:


text:
Q: Django and knockoutjs (foreach) In views:
 posts = Posts.objects.filter(...)
        template = loader.get_template('...')
        context = Context({
            'comments': comments,
            })
        return HttpResponseForbidden(template.render(RequestContext(request, context)))

In template:
 <script type="text/javascript">
    head.js('...');
    head.ready(function() {
        $(document).ready(function() {
            postModel = new postModel({
                posts: '{{ posts }}'
            });
            ko.applyBindings(commentModel, $('#posts')[0]);

        });
    });
    </script>
<ul data-bind="foreach: comments">
....
</ul>

In post.js
self.comments = ko.observableArray(ko.utils.parseJson(config.comments)); //error: Uncaught SyntaxError: Unexpected token &
self.comments = ko.observableArray(config.comments); //error: Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

How to convert the data type?
{{ posts}}
 [<Post: un posts!>, <Post: deux posts!>] to [{id:1, content:'un posts' etc},{...}]

A: in scripts:
postModel = new postModel({
                posts: '{{ posts.fields }}'
            });
            ko.applyBindings(postModel, $('#post')[0]);

it's work)
merci beaucoup)


text:
Q: Why are logarithms not defined for 0 and negatives? I can raise $0$ to the power of one, and I would get $0$. Also $-1$ to the power of $3$ would give me $-1$.
I think only some logarithms (e.g log to the base $10$) aren't defined for $0$ and negative numbers, is that right?
I'm confused because on all the websites I've seen they say "logs are not defined for $0$ and negative number". On one website it says "$\log_b(0)$ is not defined", then provides an example where the base is $10$.

A: You can define everything you want, but will this newborn object satisfy properties you want, depends on your definition. Assume, we do have logarithms for negative numbers and zero and all the properties of logarithms are preserved. Then we immediately obtain a contradiction. Here it is
$$
0=\log 1=\log(-1)^2=2\log (-1)
$$
so $\log(-1)=0$ and from the definition of logarithms we have $-1=10^0=1$. This is one of the reasons.
But if you still want to take logarithms of negative numbers, you must relax some requiremetns. The most reasonable is to make logarithms multivalued with values in $\mathbb{C}$. For more detailed description of such logarithms look  at Complex logarithm

A: No, that's not right: no matter what the base $b$, $\log_b x$ is not defined for $x\le 0$. Recall that $\log_b x=y$ means that $b^y=x$. If $b>0$ and $b\ne 1$, no power of $b$ is negative or $0$, so the equation $b^y=x$ has no solution for $x\le 0$. We don't define logs base $b$ for $b=1$ or $b\le 0$.
(I am assuming that you are working in $\mathbb{R}$, the real numbers; matters become much more complicated in $\Bbb{C}$, the set of complex numbers.)
Your comments that $(-1)^3=-1$ and $0^1=0$ suggest that you may actually want to ask why we don't define logs base $b$ for $b=1$ or $b\le 0$, though that's not the question that you actually did ask. A mathematically honest answer would be rather complicated, since it hinges on how one defines the logarithm function rigorously in the first place. Still, some difficulties are pretty easy to see. If $b$ is $1$ or $0$, there are very few values of $x$ for which the equation $b^y=x$ has a solution, so the notion of logs base $0$ or $1$ would obviously be pretty useless. What about something like $b=-2$? What would $\log_{-2}2$ be? If it's $y$, we have $(-2)^y=2$, so $-2=2^{1/y}$, which is impossible, since no power of $2$ is negative.


text:
Q: How to get flavor in buildType of build.gradle? I have my gradle file as below, where I sign my app as Debug in debug build, and Release in release build. It has two flavor i.e. Develop and Production.
buildTypes {
    debug {
        signingConfig signingConfigs.debug
    }
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.release
    }
}

productFlavors {
    develop {
        // Do something
    }
    production {
        // Do something
    }
}

However, I'm thinking of signing as Debug for Develop flavor (release) as well. How could I achieve that (i.e. access the flavor type variable in the buildType)?

A: As I understand your question you want something like this:
developDebug: signingConfigs.debug
productionDebug: signingConfigs.debug
developRelease: signingConfigs.debug
productionRelease: signingConfigs.release

You can achieve it this way:
android {
  productFlavors {
    develop {
        // Do something
    }
    production {
        // Do something
    }
  }
  buildTypes {
    debug {
        signingConfig signingConfigs.debug
    }
    // Make an unfinished release build type
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    // Finish the release build type flavor specific
    def runTasks = gradle.startParameter.taskNames.toString().toLowerCase()
    if (runTasks.contains("develop")) {
      release {
        signingConfig signingConfigs.debug
      }
    } else if (runTasks.contains("production")) {
      release {
        signingConfig signingConfigs.release
      }
    }
  }
}

A: Edit: I think this might be a cleaner solution
buildTypes {
    debug {
        signingConfig signingConfigs.debug
    }
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.release
    }
    release-develop {
        initWith buildTypes.release
        signingConfig signingConfigs.debug
    }
}

You could also use:
productFlavors.develop.signingConfig signingConfigs.debug

inside of your release build type.
Original Answer:
Something like this should do the trick.
The hierarchy goes buildTypes -> defaultConfig -> productFlavors
buildTypes {
    debug {
        signingConfig signingConfigs.debug
    }
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

defaultConfig {
    signingConfig signingConfigs.release
}

productFlavors {
    develop {
        signingConfig signingConfigs.debug
        // Do something
    }
    production {
        // Do something
    }
}

*

*developDebug: signed with debug key from debug variant

*developRelease: signed with debug key in develop flavor

*productionDebug: signed with debug key from debug variant

*productionRelease: signed with release key from defaultConfig since its not defined in release variant.


text:
Q: How do I rename a metadata term in C#? Can't find this documented anywhere. Do I just change the Term.Name and run a commit all on the term store?

A: Yes, that is the simplest way to do it.  I have only found two ways to rename a term programmatically:
1) Set the Name property and CommitAll on the Term Store:
    var site = SPContext.Current.Site;
    var taxonomySession = new TaxonomySession(site);
    var termStore = taxonomySession.TermStores[0];
    var termGroup = termStore.Groups[0];
    var termSet = termGroup.TermSets[0];
    var term = termSet.Terms[0];
    term.Name = "Test Update";
    termStore.CommitAll();

2) Create a new Term and then Merge it with the old one.
But you were on the right track.  Go with option 1.  Only thing to note is that it doesn't always update instantly.  It can take a few seconds for the change to be reflected when you try to retrieve the term again.


text:
Q: Excel - get range of data between two rows I have data in following pattern:

I want a formula to get the data between Content Start and Content End. The amount of content between the start and end is not just limited to 4 and can change.

A: You don't say what you want to do with this result.
I am assuming you can code the column in which your data is located.
The formula below will return those values as an array. e.g. with your data, the formula will return {1;2;3;4}
The values could be numeric or text.
How you want to handle those values is up to you.
=INDEX($A:$A,N(IF(1,ROW(INDEX($A:$A,MATCH("Content Start",$A:$A,0)+1,1):INDEX($A:$A,MATCH("Content End",$A:$A,0)-1,1)))))

EDIT: Here is an example of using that information to create a sparkline.  In this example, the formula above has been wrapped in TRANSPOSE and entered as an array formula in C1:I1.  The Sparkline has been entered in B1.  As with most charts, Excel is ignoring the #N/A errors.

And here is an example where the sparkline is in A1 and the transposed array is somewhere else, not in view, on the worksheet:

A: With Worksheets("Your Sheet").Range("A:A")
    Set c = .Find("Content Start", LookIn:=xlValues)
    Set d = .Find("Content End", LookIn:=xlValues)
    ActiveSheet.Range(Cells(c.Row + 1, c.Column), Cells(d.Row - 1, c.Column)).Select
End With

A: Probably multiple ways doing this, but if you prefer to do it without VBA you could use:

Formula used in B1 (allthough a bit lengthy):
{=INDEX($A$1:$A$10,SMALL((ROW($A$1:$A$10)>MATCH("Content Start",$A$1:$A$10,0))*(ROW($A$1:$A$10)<MATCH("Content End",$A$1:$A$10,0))*ROW($A$1:$A$10),SUM((ROW($A$1:$A$10)>MATCH("Content Start",$A$1:$A$10,0))*(ROW($A$1:$A$10)<MATCH("Content End",$A$1:$A$10,0)))+ROW(A3)))}

Notice it's an array formula entered through CtrlShiftEnter
Drag down....


text:
Q: Microsoft Word 2013 Template with Placeholders I need to create Microsoft Word document to be used as a template for generating other Microsoft Word documents based on template with placeholders replaced with actual values.
It must be like
Hello ##CUSTOMER_NAME##,

We want to offer you ##PRODUCT_NAME## for just $##PRODUCT_PRICE##

I know of document properties and "Insert\Quick Parts\Document Property". It is very close to what I want, except I have no idea how to add new property, because existing property set is not even close to my needs.

A: You want to use the mail merge feature in Word and select a data source. The data source can be another Word document, text file, Excel, Access, or any other data source that Windows (Admin Tools > Data Source) can process.
Press F1 in Word 2013 for Help. In the Help search screen, type "mail merge". There will be some steps and even videos on how to perform a mail merge.
There is also a Word for Dummies guide that will show how to perform mail merge as well:
http://www.dummies.com/how-to/computers-software/ms-office/Word/Word-2013/Mail-Merge.html
I am happy to provide steps, but since your question is very general, I will only provide exact steps if you state what your data source will be.


text:
Q: How to implement this kind of layout in new model? In
@dektrium/user/views/admin/_account.php
@dektrium/user/views/admin/_info.php
@dektrium/user/views/admin/_profile.php

there are
<?php $this->beginContent('@dektrium/user/views/admin/update.php', ['user' => $user]) ?>
'the rest codes'
<?php $this->endContent() ?>

and in @dektrium/user/views/admin/update.php there're

            <?= $content ?>

the $content will be replaced by code between 'beginContent' and 'endContent', how to implement this kind of layout in my new backend model 'Rayon'? I tried write a similar CRUD code, but keep getting an error 'Undefined variable content'.
Thank you for your help.

A: the row with code
 <?php $this->beginContent('@dektrium/user/views/admin/update.php', ['user' => $user]) ?>

tells to the "view" which is,  to take the code from the reference and add it to the place where the call is invoked ..
It performs an equivalent action to "include" within more the possibility of  pass the variables to use in the "content"
then you should create the part of view that you want to reuse .. and the views in which you want to call to add this type of call
You can  do something similar directly reusing the render () function inside de view and indicating which (other) view and which variables to use.
for (simple) example
view container_view.php  in yourapp/views

my container test

 <?= $content ?>

then
You want that the code in container_view is placed in a way that the code inside beginContent and endContent of the
create.php  in yourapp/views/ is place in the same place you have $content in the container
<?php $this->beginContent('yourapp/views/container_view.php', ['model' => $model]) ?>

this code is placed in $container

and the value of the var model is passed

 <?= $model->name '>
 <?php $this->endContent() ?>


text:
Q: How come my Discord bot (NodeJS) doesn't go online after a system reboot on a Raspberry Pi 4, with pm2? I am trying to host a Discord bot on a Raspberry Pi. I have gotten everything to work and I have a bot running on it. I also made it so the bot restarts on a system reboot. The bot logs in perfectly. However, I tried adding another bot and again, I made it so the bot restarts on system reboot. The bot restarts from what I can see when I use pm2 ls. However, the bot doesn't go online. I get this error in my logs as well:
HTTPError [FetchError]: request to https://discord.com/api/v9/gateway/bot failed, reason: getaddrinfo EAI_AGAIN discord.com

Also note that I can use pm2 start <process> and node <file> to start the bot. Does anybody know why this is happening?

A: It is an error relative to DNS. It tell you that getaddrinfo is in timeout (or delayed?) and that you should try again later.
Not enough information to be more specific. But if you start these two bots at the same time, perharps your DNS or Discords DNS don't like that. Try to start  bots one after the other (with minutes betwens starts) and see if problem persist or not.


text:
Q: Should exception check be explicitly done in public function if private function needs the same input The effective java makes it clear that an assert be used to verify parameters of a private function. If a method is a public method then the method should throw a NPE if a null is an invalid parameter.
Eg:
public void foo (Sting str) {
   char[] ch = str.toCharArray();
}

In the code above, we dont need an explicit check to ensure str is null, or not as null.toCharArray wil l throw the NPE
But what if the code changes to something like this:
   public void foo (String str) {
      List<String> strList = new ArrayList<String>();
      bar (str, strList);
   }

   private void bar(String str, strList) {
        assert strList != null;
        char[] ch = str.toCharArray();
        ... ... ..
   }

In such a code it falls on private function bar to throw a NPE. According to effective java a private code should only verify via an assert.
Will the following code be considered a better practice than code above ?
 public void foo (String str) {
          if (str == null)  throw NPE;
          List<String> strList = new ArrayList<String>();
          bar (str, strList);
       }

       private void bar(String str, strList) {
            assert str != null;
            assert strList != null;
            char[] ch = str.toCharArray();
            ... ... ..
       }

A: In your public method foo, you have the following
if (str == null) throw new NullPointerException;

This is often called guard clauses and is generally more readable than just letting a null pointer exception be thrown by not including anything.
Regarding assert, it generally as @Sotirios mentions is not used in production code.  Check out this answer for additional information:  Java assertions underused.
There is definitely some subjectivity here which is better, but from a readability viewpoint, the guard clause in the public method appears to more readable.  The assert provides no additional value especially if that private method is only called from that one public method.  The assert would never trigger.


text:
Q: REDCap API import records in Android I'm trying to use the REDCap API to import records using an Android app. How do I make a button in an activity run the code below when clicked in order upload the data into REDCap? If there is another way to code this, that would be just as helpful. I basically want to send the data in the JSON object into REDCap using their API token and URL that's already given to me.
package com.example.maciej.fuglmeyer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class MyClass
{
    private final HttpPost post;
    private final HttpClient client;
    private int respCode;
    private BufferedReader reader;
    private final StringBuffer result;
    private String line;

    @SuppressWarnings("unchecked")
    public MyClass(final Config c)
    {
        JSONObject record = new JSONObject();
        record.put("record_id", "3");
        record.put("first_name", "First");
        record.put("last_name", "Last");
        record.put("address", "123 Cherry Lane\nNashville, TN 37015");
        record.put("telephone", "(615) 255-4000");
        record.put("email", "first.last@gmail.com");
        record.put("dob", "1972-08-10");
        record.put("age", "43");
        record.put("ethnicity", "1");
        record.put("race", "4");
        record.put("sex", "1");
        record.put("height", "180");
        record.put("weight", "105");
        record.put("bmi", "31.4");
        record.put("comments", "comments go here");
        record.put("demographics_complete", "2");

        JSONArray data = new JSONArray();
        data.add(record);

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("token", "123423412342134"));
        params.add(new BasicNameValuePair("content", "record"));
        params.add(new BasicNameValuePair("format", "json"));
        params.add(new BasicNameValuePair("type", "flat"));
        params.add(new BasicNameValuePair("data", data.toJSONString()));

        post = new HttpPost("URLGOESHERE.com");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");

        try
        {
            post.setEntity(new UrlEncodedFormEntity(params));
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }

        result = new StringBuffer();
        client = HttpClientBuilder.create().build();
        respCode = -1;
        reader = null;
        line = null;
    }

    public void doPost()
    {
        HttpResponse resp = null;

        try
        {
            resp = client.execute(post);
        }
        catch (final Exception e)
        {
            e.printStackTrace();
        }

        if(resp != null)
        {
            respCode = resp.getStatusLine().getStatusCode();

            try
            {
                reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
            }
            catch (final Exception e)
            {
                e.printStackTrace();
            }
        }

        if(reader != null)
        {
            try
            {
                while((line = reader.readLine()) != null)
                {
                    result.append(line);
                }
            }
            catch (final Exception e)
            {
                e.printStackTrace();
            }
        }

        System.out.println("respCode: " + respCode);
        System.out.println("result: " + result.toString());
    }
}

A: 1) Create a simple Layout with a Button and a EditText for the data will be uploaded:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent_log"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="16dp"
    android:paddingEnd="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingStart="16dp"
    android:paddingTop="16dp">

    <EditText
        android:id="@+id/input_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="Exemplo: João da Silva"
        android:inputType="textPersonName" />

     <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CADASTRAR"
        android:id="@+id/uploadData"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="16dp"
        android:onClick="onClick" />

 </LinearLayout>

2) In onClick method on your Activity, get the data and call the Class Config and the ImportData (content in Java Examples on REDCap API)
public void onClick(View v) {
    String name = findViewById(R.id.input_name).getText().toString();

    Config config = new Config();

    //I have changed the constructor to send the only string that will be
    //uploaded, but you can send a context, array of strings, whatever...
    ImportRecords importRecords = new ImportRecords(config, name);
    importRecords.doPost();
}

3) On ImportRecords, class you posted, change the constructor (if you want) and here is an example of the code you can do
public class ImportRecords {
private final List<NameValuePair> params;
private final HttpPost post;
private HttpResponse resp;
private final HttpClient client;
private int respCode;
private BufferedReader reader;
private final StringBuffer result;
private String line;
private final JSONObject record;
private final JSONArray data;
private String recordID;
//private final SecureRandom random;

@SuppressWarnings("unchecked")
public ImportRecords(final Config c, String name) {
    //Create an id. Id is the record identifier
    //For example if you want get the record in the future, you'll need that
    Random r = new Random();
    int id = r.nextInt();

    record = new JSONObject();
    record.put("record_id", id);
    record.put("first_name", name);

    data = new JSONArray();
    data.add(record);

    params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("token", c.API_TOKEN));
    params.add(new BasicNameValuePair("content", "record"));
    params.add(new BasicNameValuePair("format", "json"));
    params.add(new BasicNameValuePair("type", "flat"));
    params.add(new BasicNameValuePair("data", data.toJSONString()));
    params.add(new BasicNameValuePair("forms", "pergunta"));

    //c.API_URL is the url found on your REDCap project - API
    post = new HttpPost(c.API_URL);
    post.setHeader("Content-Type", "application/x-www-form-urlencoded");

    try {
        post.setEntity(new UrlEncodedFormEntity(params));
    } catch (final Exception e) {
        e.printStackTrace();
    }

    result = new StringBuffer();
    client = HttpClientBuilder.create().build();
    respCode = -1;
    reader = null;
    line = null;
}

4) On Android, the method Post needs to run on background. I have created an AsyncTask for that
public void doPost() {
    new Task().execute();
}

public class Task extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected Boolean doInBackground(Void... params) {
        resp = null;

        try {
            resp = client.execute(post);
        } catch (final Exception e) {
            e.printStackTrace();
            return false;
        }

        if (resp != null) {
            respCode = resp.getStatusLine().getStatusCode();

            try {
                reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
            } catch (final Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        if (reader != null) {
            try {
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
            } catch (final Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        System.out.println("respCode: " + respCode);
        System.out.println("result: " + result.toString());
        if (respCode!=200)
            return false;
        return true;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if (aBoolean)
            Log.e("RESULT","The record was sent");
        else
            Log.e("RESULT","The record was not sent");
    }
}


text:
Q: Python 3, PyQt 4: split large class for GUI controls My class MainWindow(QMainWindow) for PyQt4 GUI has grown now and I want to split it somehow. The problem is that all numerous functions handling signals are very interconnected and influence other functions of the class. Is there any way to split it into several classes / files? Maybe separating all signals into one class? I don't really understand how to do that technically... I've also heard that there is some restriction from Qt (or PyQt) for multiple inheritance, which could solve the problem I guess (again, not obvious for me how exactly).
Just as an idea how it looks now (very very simplified, of course):
calss MainWindow(QMainWindow):
   ...
   def f1(self):
      if self.a1 == '...':
       ...
   def f2(self):
      if self.a2 == '...':
       ...
   def update(self):
      self.f3()
      self.f4()
      self.lineEdit.setText(self.a3)
      ...
   ...
   def on_radioButton_toggled(self):
      if self.radioButton.isChecked():
         self.a1 = '...'
   def on_comboBox_currentIndexChanged(self):
      if self.checkBox.isChecked():
         self.a2 = '...'
         self.f1()
      else:
         self.f2()
      self.update()
   ...

A: In my application I did it like this, there's the main window which contains child widgets (frames and stuff...), the main window does basically two things: initialize its children and connect the signals between them. Like this you have a hierarchy of views which is much simpler to handle that one big thing.
I think there isn't a painless move from your program to a more hierarchical one, I could say: you should have though of that earlier, but I don't. =P
To design the main window and its children QTdesigner comes in very handy.
And yes, AFAIK a class should not inherit form more than one PyQt class.


text:
Q: What is a security update?
*

*Why are some updates called Important security updates?

*How are they different from other updates?

*Is my system insecure, If I don't install them?

*How can there be very frequent security updates?

*Does it mean my Ubuntu is very unstable or insecure?

A: As the name says, security updates are important updates which will improve your security.
Some updates are only new versions of your applications with new features and some of them are bug fixes. Critical security bug fixes are included in "Important securty updates" in the update manager.
If you want your system to be secure you must install security updates as soon as possible. Without these updates, attackers may use vulnerabilities in your software to attack your system.
Also, it's a good idea to make Ubuntu check for updates daily and install security updates without confirmation:

Image source: Setup Ubuntu 10.10 Maverick Meerkat to Install Security Updates Automatically

A: What is a security update? How are they different from other updates?
Usually they are security-related bugs rather than new features or bug fixes. For example, it might fix a buffer overflow a developer found.
If I don't install them, is my system insecure?
Not necessarily, but there are exploits. If someone could manage to exploit them (which might not even be possible unless they have another exploit), it isn't totally compromised. However, you should assume that it is insecure, because if theres a slight chance that it is, for all purposes it is.
How can there be very frequent security updates? Does it mean my ubuntu is very unstable or insecure?
This comes into the differences between Linux and closed-source operating systems.
In Linux, security flaws are found much easier when they exist due to the code being open. Then the patch is immediately put upstream and onto your computer through the package update.
Whereas in a closed source system, often such flaws aren't found until exploitation. Its just a matter of when the security flaw is found, not the existence itself.


text:
Q: Show that $\cos x=x^3+x^2+4x$ has exactly one root in $[0,\frac{\pi}{2}]$ This is the section of the textbook on derivatives. I'm not sure if I should be using Rolle's Theorem or if Mean Value Theorem would be useful here. Intermediate Value Theorem?
I understand we can write this as $x^3+x^2+4x-\cos x=0$. We know this is uniformly continuous since it's just the sum of continuous functions on a compact domain. All the other benefits of working with a uniformly continuous function follow. I'm just not sure how to do this.
Maybe, we can write this as $f(x)=g(x)$ where $f(x), g(x)$ are differentiable and uniformly continuous on their domain. We can write $h(x)=g(x)-f(x)$ for all $x\in [0,\frac{\pi}{2}]$. I think we evaluate the endpoints of the interval, so $h(0)=-1$ and $h(\frac{\pi}{2})=\frac{\pi^3+2\pi^2+16\pi}{8}$. There's clearly a sign change, so by the IVT, somewhere in the interval, $h(x_0)=0$. Is that the end of the proof or do I have to show this $x_0$ is unique, how do I show it's exactly one?

A: Let $f(x)=-\cos(x)+x^3+x^2+4x$. Note $f(0)=-1<0$ and $f(\frac{\pi}{2})>0$. Therefore, by the Intermediate Value Theorem $f$ must admit a zero in $[0,\frac{\pi}{2}]$. If $f$ had another zero in $[0,\frac{\pi}{2}]$ then from Rolle's theorem $f'(x)=\sin(x)+3x^2+2x+4$ would admit a zero between those two zeros of $f$ but $f'$ is strictly positive in $[0,\frac{\pi}{2}]$. Therefore, $f$ only admits one zero on $[0,\frac{\pi}{2}]$.

A: Let $f_1(x) = \cos(x)$ and $f_2(x)=x^3+x^2+4x$. Note that, over $[0, \pi/2]$.
$$f_1'(x) =-\sin x < 0$$
$$f_2'(x) = 3x^2+2x +4 > 0$$
That is $f_1(x)$ strictly decreases and $f_2(x)$ strictly increases. Given that $f_1(0)=1$, $f_1(\pi/2)=0$ and $f_2(0) =0$, the two curves have to cross and cross once within $(0,\pi/2)$, hence having only one root.

A: Hint
$\cos x$ is concave and strictly decreasing and $x^3+x^2+4x$ is convex and strictly increasing, both over $\left(0,{\pi\over 2}\right)$


text:
Q: Como deixar parte do texto JLabel em negrito Há alguma forma de deixar apenas uma parte do texto em negrito de uma JLabel?
Por exemplo:
label.setText("apenas esta parte em negrito");

Porém esse trecho de código imprime o 'b' na tela também.

A: Você precisa envolver o texto todo entre as tags  e :
label.setText("apenas esta parte em negrito");

Entretanto, sugiro usar componentes alternativos, que permitem fazer isso sem sujar o código com esses trechos html's avulsos: JTextPane ou JEditorPane. Nesta resposta há um exemplo de uso de um destes componentes e do que eles são capazes de fazer.


text:
Q: How to count number of values within specific date interval from pandas dataframe values? I want to count and plot the number of 'payout' values by day for period 2018-04-01 to 2018-05-01 from this dataframe:
df['payout'].head(10)

0   2017-02-14 11:00:06
1   2015-03-14 11:00:06
2   2014-04-14 11:00:06
3   2017-11-14 11:00:06
4   2016-12-14 11:00:06
5   2018-04-10 11:00:06
6   2018-04-11 11:00:06
7   2018-04-12 11:00:06
8   2018-04-13 11:00:06
9   2018-04-14 11:00:06

I could obtain day-to-plot for the year 2018:
(df.loc[df['payout'].dt.year.between(2018, 2019), 'payout']
         .dt.to_period('D')
         .value_counts()
         .sort_index()
         .plot(kind="bar")
)

How do I shrink the plot to April 2018 only?
Thanks

A: Just check both month and year and use your current method
df.loc[(df.date.dt.month == 4) & (df.date.dt.year == 2018), 'payout']

A: You could use the same logic you were using, but use the datestrings you are interested in:
(df.loc[df['payout'].between('2018-04-01', '2018-04-30'), 'payout']
         .dt.to_period('D')
         .value_counts()
         .sort_index()
         .plot(kind="bar")
)

A: an other solution :
df[(df['date'] >= '2018-04-01') & (df['date'] < '2018-05-01')]['payout']

A: df.set_index('payout').loc['2018-04-01':'2018-04-30']

for your first line should do it.

*

*.set_index makes your payout column the index. This does not modify the original df. See the docs for details.

*Now that you have a DatetimeIndex, you can just use .loc to index with date strings directly. Note that unlike normal indexing, this will include all 24 hours of April 30.


text:
Q: Grid-like view in cocos2d I'm writing an app with a view that has a grid of images (3x3) and it needs to have infinite scroll per row and per column, very similar to the 'Design Museum Collection' app. How would I go about implementing this view? Is there a library that already supports this?  Can this be done in Cocos2d?  Here is a video of the 'Design Museum Collection' app (http://vimeo.com/39260302).
Thanks in advance.

A: The CCMenuAdvanced extension is a good place to start.  You can find it here:
https://github.com/cocos2d/cocos2d-iphone-extensions/tree/master/Extensions/CCMenuAdvanced


text:
Q: Chrome Apps Cordova webview shows a blank page It's quite a weird situation which I am in. I've recently found out about the Chrome Apps ability, you can port them automatically to iOs, Android and Windows. But I do have a problem, I've been writing the application in Javascript as a base and tested it with the Chrome Editor, worked fine in the windows mode.
I've been struggling on porting it to android and when it finally worked, my webview was empty. After 2 hours of trying, googling and messing around I decided to give up and just take a sample and work from there. But even the samples aren't giving me the webview.
The webview stays empty, all I can see is that I keep getting 4 errors which are not related to the script itself ( sychronous XMLHttpRequest, failed to load a css and a lost .html file from a chrome-extension ).
Debugging the app; text shows up, webview stays blank.
Anyone ever had the same problem?

The entire file contains the following code;

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>WebView sample</title>
    <link href="index.css" rel="stylesheet">
</head>
<body>

 <webview id="wv2" style="width:250px; height:200px;" src="http://google.com/"></webview>

    test

</body>
</html>

Another thing that caught my eye was the following two messages while deploying the application from the cca command line;
Permission not recognized by cca: pointerLock (ignoring)
Permission not recognized by cca: webview (ignoring)

A: After some digging I found out that the Webview tag is not supported on mobile devices by Chrome Apps. the Webview tag is a tag created by Cordova and will not work on mobile devices. Therefore you should consider using an iFrame instead.


text:
Q: How to select visitor counts by days I have this table from which I need to select visitors count by date.
CREATE TABLE `visitors` (
  `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `ip` VARCHAR(32) NOT NULL,
  `browser` VARCHAR(500) NOT NULL,
  `version` VARCHAR(500) NOT NULL,
  `platform` ENUM('w','l','m') NOT NULL,
  `date` DATE NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `person` (`ip`,`date`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

I try this:
SELECT DATE(`date`) AS `date`, COUNT(*) AS `visitor`
FROM `visitors` WHERE (`date` >= (NOW() - INTERVAL 7 DAY))
GROUP BY `date`;

Which returns this:
date         visitor
2015-12-19    2
2015-12-22    5

But what I really want is this:
date         visitor
2015-12-17    0        // Make 0 for the day which is not present
2015-12-17    0        // Make 0 for the day which is not present
2015-12-18    0        // Make 0 for the day which is not present
2015-12-19    2
2015-12-20    0        // Make 0 for the day which is not present
2015-12-21    0        // Make 0 for the day which is not present
2015-12-22    5

If I try with unions and get dates with this it is not problem with example 1 week. But what can I do if I need 1 year?

A: Use the sequence Engine. So you can generate date without a table
https://mariadb.com/kb/en/mariadb/sequence/
MariaDB [mysql]> SELECT date(now() - INTERVAL seq DAY) FROM seq_0_to_6;
+--------------------------------+
| date(now() - INTERVAL seq DAY) |
+--------------------------------+
| 2015-12-22                     |
| 2015-12-21                     |
| 2015-12-20                     |
| 2015-12-19                     |
| 2015-12-18                     |
| 2015-12-17                     |
| 2015-12-16                     |
+--------------------------------+
7 rows in set (0.00 sec)

This will work without a other Engine. You only must have a table with more Records as Days. The count of Days backwards is the LIMIT.
SELECT compare_date , count(v.`date`)
FROM (
    SELECT DATE(now() - INTERVAL @nr:=@nr+1 DAY)  AS compare_date
    FROM information_schema.COLUMNS, (SELECT @nr:=-1) AS tmp
    LIMIT 7
    ) AS d
LEFT JOIN  `visitors` v ON v.`date` = compare_date
GROUP BY compare_date;

Please tell this works for you.


text:
Q: How to set the alignment for the .data section? I defined the following variables in the .data section in NASM:
section .data
    var1       DD   12345    ; int (4 bytes)

    var2       DB   'A'      ; char (1 byte)

    padding1   DB   123      ; 1 byte padding
    padding2   DB   123      ; 1 byte padding
    padding3   DB   123      ; 1 byte padding

    var3       DQ   174.13   ; double (8 bytes)

In order for these variables to be correctly aligned, the .data section must be aligned to 8 bytes.
I believe that the alignment for the .data section is specified by the linker. I am using the Visual C++ 2010 linker, how can I set the alignment for the .data section using this linker?

A: The align directive works for data as well as code.
In the assembler's output file (an object file in the format the MSVC's linker can understand), it signals the required alignment of each section using metadata.
For example, if you use
section .data
align 1024*1024*2
foo: dd 1234
align 8       ; will assemble to 4 bytes of padding to reach the next multiple of 8
bar: dd 4567

The object file will have its required-alignment for that section set to 2MiB.  At least that works on Linux, where I think the section in the object file inherits the highest alignment requirement seen in the source file, so very high alignments are possible.
For win32 object files, NASM even has special syntax for section alignment:
section .data    data  align=16   like in the example in the manual. The default is align=4 for .data in win32/win64, apparently.  The maximum is 64.  I don't know if align directives inside a section can increase its alignment if none is specified for -f win32 / -f win64.  If not, as the manual cautions, you might be aligning wrt. the start of the section but not in an absolute sense.
ELF object files (Linux) work the same way, with each section having a required-alignment.
Your object file (hopefully) doesn't end up filled with up-to-2MiB of padding, but it might after linking if it links after something else that has a few bytes in a section that goes into the same segment as .data in the executable.
But still, knowing (or setting) the minimum alignment of the start of a section, the assembler can support align directives of any power of 2 at any point in the middle of any section.  The align directive doesn't have to be at the start of a section.