text:
Q: Yii2 testing environment guidelines for extension development I am developing an Yii 2 public (MIT) extension to change some of the yii\web\View behaviours (minify, combine and many other optimizations).
I can do it easily. But I really want to write as many tests (codeception) as possible for it. This is where I am very confused.
I already have some unit tests (for example: testing a specific minifing, or returning combined minified result). But I would like to test the entire result and the final integration between my extension and the Yii2 web application using it.
I just would like some guidelines for this process:

*

*Should I have a real (complete) app inside my extension for testing purposes? If so, should it be 'installed' inside tests dir?

*Would you use functional testing ? (I think so because the View will find files in AssetBundles, combine and minify them, publish the result as a single file and replace the assets' urls by new url (i.e., the optimized asset url) inside the view;

*Could you provide some very basic examples/guidelines?
I just would like to highlight that I dont intend you do my testing job, I really want to learn how to do it. This is why I really would be very grateful for any tips.
Thank you so much.

A: My Own Guidelines
Ok, I've found my way based on tests inside yii2-smarty.
So, these are the guidelines for testing your own Yii2 extension development using phpunit:
1) The tests/bootstrap.php:
// ensure we get report on all possible php errors
error_reporting(-1);

define('YII_ENABLE_ERROR_HANDLER', false);
define('YII_DEBUG', true);

$_SERVER['SCRIPT_NAME'] = '/' . __DIR__;
$_SERVER['SCRIPT_FILENAME'] = __FILE__;

require_once(__DIR__ . '/../vendor/autoload.php');
require_once(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');

//optionals
Yii::setAlias('@testsBasePathOrWhateverYouWant', __DIR__);
Yii::setAlias('@slinstj/MyExtensionAlias', dirname(__DIR__));

2) Create a tests/TestCase base class extending \PHPUnit_Framework_TestCase:
namespace slinstj\MyExtension\tests;

use yii\di\Container;

/**
 * This is the base class for all yii framework unit tests.
 */
abstract class TestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * Clean up after test.
     * By default the application created with [[mockApplication]] will be destroyed.
     */
    protected function tearDown()
    {
        parent::tearDown();
        $this->destroyApplication();
    }

    /**
     * Populates Yii::$app with a new application
     * The application will be destroyed on tearDown() automatically.
     * @param array $config The application configuration, if needed
     * @param string $appClass name of the application class to create
     */
    protected function mockApplication($config = [], $appClass = '\yii\console\Application')
    {
        new $appClass(ArrayHelper::merge([
            'id' => 'testapp',
            'basePath' => __DIR__,
            'vendorPath' => dirname(__DIR__) . '/vendor',
        ], $config));
    }

    protected function mockWebApplication($config = [], $appClass = '\yii\web\Application')
    {
        new $appClass(ArrayHelper::merge([
            'id' => 'testapp',
            'basePath' => __DIR__,
            'vendorPath' => dirname(__DIR__) . '/vendor',
            'components' => [
                'request' => [
                    'cookieValidationKey' => 'wefJDF8sfdsfSDefwqdxj9oq',
                    'scriptFile' => __DIR__ .'/index.php',
                    'scriptUrl' => '/index.php',
                ],
            ]
        ], $config));
    }

    /**
     * Destroys application in Yii::$app by setting it to null.
     */
    protected function destroyApplication()
    {
        Yii::$app = null;
        Yii::$container = new Container();
    }

    protected function debug($data)
    {
        return fwrite(STDERR, print_r($data, TRUE));
    }
}

3) Create your testSomething classes extending TestCase:
namespace slinstj\MyExtension\tests;

use yii\web\AssetManager;
use slinstj\MyExtension\View;
use Yii;

/**
 * Generated by PHPUnit_SkeletonGenerator on 2015-10-30 at 17:45:03.
 */
class ViewTest extends TestCase
{

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        parent::setUp();
        $this->mockWebApplication();
    }

    public function testSomething()
    {
        $view = $this->mockView();
        $content = $view->renderFile('@someAlias/views/index.php', ['data' => 'Hello World!']);

        $this->assertEquals(1, preg_match('#something#', $content), 'Html view does not contain "something": ' . $content);
    }

    //other tests...

    /**
     * @return View
     */
    protected function mockView()
    {
        return new View([
            'someConfig' => 'someValue',
            'assetManager' => $this->mockAssetManager(),
        ]);
    }

    protected function mockAssetManager()
    {
        $assetDir = Yii::getAlias('@the/path/to/assets');
        if (!is_dir($assetDir)) {
            mkdir($assetDir, 0777, true);
        }

        return new AssetManager([
            'basePath' => $assetDir,
            'baseUrl' => '/assets',
        ]);
    }

    protected function findByRegex($regex, $content, $match = 1)
    {
        $matches = [];
        preg_match($regex, $content, $matches);
        return $matches[$match];
    }
}

That is all! This code skeleton is highly based in the yii2-smaty/tests code. Hope to help you (and me in further needs).

A: this approach works, but i had to make some small adjustments:

*

*if you are developing an extension (in /vendor/you/extension directory) and the bootstrap.php file is inside a test-directory, the paths for autoloader and yii base class are most likely wrong. Better is:
require_once(__DIR__ . '/../../../autoload.php');
require_once(__DIR__ . '/../../../yiisoft/yii2/Yii.php');

*i have tested an validator class which needed an application object. i have simply created an console application inside the bootstrap file (append to end of file):
$config = require(__DIR__ . '/../../../../config/console.php');
$application = new yii\console\Application($config);


text:
Q: How to code a for or while loop which prints list's values from a initial index value to an end one? I would like to print a specific range of a list's number using for or while loop.
For example:
li = [1,2,3,4,5,6,7,8,]

from li.index[3] to li.index[7]
Output: 3,4,5,6,7

I've tried things like:
for i in listName in range(listName.index(3), listName.index(7),1):

A: You can use range
for num in range(2,7):
    print(li[num])

or just array slicing
for num in li[2:7]:
    print(num)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nesting INNER JOINs with UNION calls in SQL - quite lost I have a friends table: id, fid1, fid2 which represents a friendship between two users (bidirectional).
and a users table: fid,name
I'd like to make a function or query that takes

*

*User id

and returns

*

*list of friends (users.fid, users.name) which represent all of the friends which are friends with original user id

I'm having trouble with nesting JOINs and UNIONs. I need the UNION to make sure that I get all friendships (but also don't get duplicates). This is what I've got so far:
SELECT fid1 as friends FROM friendships WHERE fid2 = 123456
INNER JOIN users
ON friendships.fid1 = users.fid

UNION ALL (

SELECT fid2 as friends FROM friendships WHERE fid1 = 123456
INNER JOIN users
ON friendships.fid2 = users.fid
)

which is an error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN users ON friendships.fid1 = users.fid UNION ALL ( SELECT fid2' at line 2

in general I'm having trouble with commands because I don't understand how SQL treats results - in normal programming languages I'd pass the result of the INNER JOINs to  the UNIONs and then apply that function. But I'm getting a bit lost here. Any thoughts?

A: Your WHERE needs to go after the JOIN
SELECT f.fid1 AS friends
FROM friendships AS f
INNER JOIN users AS u ON f.fid1 = u.fid
WHERE f.fid2 = 123456

UNION ALL

SELECT f.fid2 AS friends
FROM friendships AS f
INNER JOIN users AS u ON f.fid2 = u.fid
WHERE f.fid1 = 123456

Visual article on Joins
Information on MySQL SELECT syntax
As you can see from the SELECT syntax, you join all of your tables together, then apply the filters (WHERE clauses).  This creates one result set.  You can then UNION that to another result set of the same format (Same number of columns, same data types).
A UNION will return all distinct records, and a UNION ALL will return the first record set, then the second record set, maintaining order.
Option 2
SELECT CASE
          WHEN t.fid1 != 1 THEN t.fid1
          ELSE t.fid2
       END AS Friends
FROM
(
   SELECT DISTINCT f.fid1, f.fid2
   FROM friendships AS f
   LEFT JOIN users AS u ON f.fid2 = u.fid
   WHERE f.fid1 = 1 OR f.fid2 = 1
) AS t

Option 3
SELECT DISTINCT
   TRIM(CASE
           WHEN f.fid1 = 1 THEN ' '
           ELSE f.fid1
        END +
   CASE
      WHEN f.fid2 = 1 THEN ' '
      ELSE f.fid2
   END) AS Friends
FROM friendships AS f
LEFT JOIN users AS u ON f.fid2 = u.fid
WHERE f.fid1 = 1 OR f.fid2 = 1

I am not sure which will perform better for you, may want to test it out under your real-world conditions, mine showed all three performed similarly, but I have very little data, and no indexes for my testing.


text:
Q: SonarQube is not analysing all the bugs I am using SonarQube for analysing my windows form .NET project but from the past few days for my certain projects SonarQube is behaving strangely it is not capturing all the errors but the line of code count is correct. On one form it is treating a certain code as a bug and on another page it is showing it as a bug. To confirm this I have created a bug explicitly but SonarQube is not showing that peice of code as error but SonarLint is working fine it is showing that as an error.
I am using VS2015 so in my errorlist all the sonar errors are listed as warnings but these errors are not on my dashboard there are only very few errors are listed on my dashboard previously it was working fine and I have also not made any changes.
Configuration details are as follow:
SonarQube - 5.3
MSBuild.SonarQube.Runner - 2.0
C# plugin - 4.5
.NET framework - 4.6
Windows Forms application
Please help and let me know if you require any more details.
Thanks & Regards,
Nikhil Gupta

A: I too face these kind of issues.
Solution:
This is because of having single file for both .cs file and .designer.cs file (which is auto generated code), so sonar excluding this auto generated files.
If you split this file to 2 separate files as .cs file and .designer file, it will not excluded by sonar and it will analyse all winform files as well.


text:
Q: Recurring events on a calendar are changed to incredibly long multiday events? If you guys could point me somewhere I can look, that'd be great.
The problem is local to one site inside a site collection.
Recurring events worked fine; one user had an event marked every other Monday and Friday. He created a multiday event, and now recurring events appear as one single event with an end date exactly 998 recurrence-lengths forward (e.g. an event created 5 Aug, 2013 that recurs once weekly would end 20 Sept, 2032, 998 weeks later). No workflows or custom code are associated with this calendar, and new calendars on this same site experience the issue while calendars on other sites do not.
A similar problem is described in Recurring Events in SharePoint 2010 - Incorrect "Duration" where it is suggested that it may be a SP2010 bug.
If I can provide more info, please let me know.

A: this is an error that I believe was fixed by SP 1.
The workaround is to modify the view.  you don't even need to change any settings, just go into the settings page and click OK.
this is generally related to sites that are created from a template.


text:
Q: How to make Xephyr to hide its background (rootless mode like in Cygwin/X) Cygwin/X and Xming can run in "rootless" mode that seamlessly integrates "inner" windows to the host environment.
Is there similar mode for Xephyr or some equivalent program? I want Xephyred windows to be like usual windows, but without ability to lock screen or generate keystrokes or mess with other windows.


text:
Q: Laravel Href to external site from database link I have created a blade.php file that creates a list of customers(with their names, social media accounts, date added, etc.) from my database. I am having trouble being able to click on the social media icons and have it take you directly to their social media pages. I am looking to have an href on the icon that directs you to their page depending on the person. Any idea as to how to take the url from the database for each person and use it as the href on the social media icon. I currently can send them to the main social media account page(facebook, twitter, linkedin) but I cant get it to send them directly to the persons page.

A: Bind the href html attribute to the lead values with v-bind:href or simply :href:


text:
Q: How to add two Fonts to java swing components, and make them automatically switch when user switches keyboard input language? I'm working on an app where User should be able to input some text which contains both English and Persian(Same as Arabic: almost same characters and written from right to left ).
Currently i'm using fonts like Courier New which supports both languages but it looks really Ugly. I Want to use some better looking fonts, but these fonts only support one of these languages and show nonsense characters for the other language. So i need to use them based on text language.
So generally how can I make Java components (especially swing.JTextField, swing.JListBox and swing.JTextComponent) accept two fonts and switch appropriately to have a good looking GUI?
Edit: Here is an example of what i need. Let say user should input something like (FPGA استفاده از ) and all of it in a single swing.JTextField. It means (Using FPGA) and FPGA is an abbreviation, so there is no Persian translation. I need to set a font with a better look and all fonts which support Unicode are ugly for the Persian part.
Now if I set font to something like Times New Roman ,which only supports Latin, then Persian characters would show as empty squares. also if i set font to something like B Nazanin ,which only supports Persian, then Latin characters would show as empty squares. How can I have both fonts in a single Java component in the same time.

A: InputContext context = InputContext.getInstance();
if(context.getLocale().toString().equals("en_GB")){
    .setFont(*font for english keyboard*);
}
else if(context.getLocale().toString().equals("fa_IR")){
    .setFont(*font for persian keyboard*);
}


text:
Q: Mercurial Editor: "abort: The system cannot find the file specified" I have a problem getting Mercurial to recognise my editor. I have a file, c:\windows\notepad.exe and typing "notepad" at the command prompt works. I can commit by using the "-m" argument to supply the commit title. But a simple "hg commit" brings up the error.
A call to "hg --traceback commit" brings up:
Traceback (most recent call last):
  File "mercurial\dispatch.pyc", line 47, in _runcatch
  File "mercurial\dispatch.pyc", line 466, in _dispatch
  File "mercurial\dispatch.pyc", line 336, in runcommand
  File "mercurial\dispatch.pyc", line 517, in _runcommand
  File "mercurial\dispatch.pyc", line 471, in checkargs
  File "mercurial\dispatch.pyc", line 465, in <lambda>
  File "mercurial\util.pyc", line 401, in check
  File "mercurial\commands.pyc", line 708, in commit
  File "mercurial\cmdutil.pyc", line 1150, in commit
  File "mercurial\commands.pyc", line 706, in commitfunc
  File "mercurial\localrepo.pyc", line 836, in commit
  File "mercurial\cmdutil.pyc", line 1155, in commiteditor
  File "mercurial\cmdutil.pyc", line 1184, in commitforceeditor
  File "mercurial\ui.pyc", line 361, in edit
  File "mercurial\util.pyc", line 383, in system
  File "subprocess.pyc", line 470, in call
  File "subprocess.pyc", line 621, in __init__
  File "subprocess.pyc", line 830, in _execute_child
WindowsError: [Error 2] The system cannot find the file specified
abort: The system cannot find the file specified

I've tried setting the HGEDITOR environment variable, setting "visual =" and "editor =" in the Mercurial.ini file. I tried full path as well as command only. I also tried copying the notepad.exe file into both the current folder as well as the mercurial folder.
Ideally I would like to use the editor at this location "C:\PortableApps\Notepad++Portable\Notepad++Portable.exe", but at this stage I would be happy with any editor!
HG debugconfig output:
c:\wamp\www\SiteAB.com\web>hg debugconfig
bundle.mainreporoot=c:\wamp\www\SiteAB.com\web
ui.username=killroy
ui.shell=true
ui.verbose=true
ui.visual="C:\PortableApps\Notepad++Portable\Notepad++Portable.exe"
ui.editor="C:\PortableApps\Notepad++Portable\Notepad++Portable.exe"

A: That editor = notepad didn't work suggests something is wrong with your environment.  Since running notepad from the command line works, I wonder if maybe the problem is with your python installation.  Your backtrace makes me think you're running hg 1.5 which was current when you posted.  While I don't believe it should make a difference, it couldn't hurt to update to 1.5.4.
You're running Notepad++Portable from your C: drive.  Usually one installs PortableApps to a removable drive.  Are you sure hg should look at C:?  I understand sometimes it can be handy for unpriviledged users to install them locally.  Notepad++Portable won't play particularly nice with hg.  You'll need to have npp completely closed and spawn it from hg or commits won't work.  If you can, I'd try running the full version of Notepad++ instead.  Here's what I use:
[ui]
editor = "C:\Program Files\Notepad++\notepad++.exe" -multiInst -nosession

-multiInst tells npp to open a new instance just for hg.  That way it won't interfere with any npp windows you already have open.  This does not work with the PortableApps version.
-nosession tells npp not to open any files you previously had open, speeding startup times and reducing clutter.  When I'm writing a commit message, I want to focus on my message, and not be distracted by a bunch of unrelated tabs.

A: When you set editor = in the Mercurial.ini file, you're doing it within the [ui] section, right?
After doing that maybe provide the output of hg debugconfig ?


text:
Q: Nest an entire CSS to only target a single div I have a fairly complex CSS file that a co-worker has written for a single server monitoring page. The monitoring page looks great BUT it calls out element tags and other proprietary tags that conflict with my existing css- im trying to absorb the server monitoring page into a larger pre-existing page without breaking EVERYTHING AND without re-designing an entire CSS. There has to be a way to nest an entire css so that it only looks at a single div or attribute....right?
Ive tried something similar to this:
#server_mon ~ {
   {#cssrule1}
   {#cssrule2}
}

Where #server_mon is the div that the monitoring table lives in...this doesn't work. I understand the basics of nesting but nesting an entire css...hmmm any thought or approaches to this? THANK YOU- this will save me a ton of work.


text:
Q: How to launch combined app without seperation I've combined two apks. One of them runs only on background. So I thought that It must have been easy to do. But I have a problem. After I install my signed apk I see two of them on the menu. Why are they seperated? How can I make them run together? Here is the activity part which causes the problem.
<activity android:label="@string/app_name" android:name=".MainActivity" android:theme="@android:style/Theme.NoDisplay">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity>
<activity android:configChanges="orientation" android:label="@string/app_name" android:name=".FreeMemoryRecover">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
</activity>

A: You're defining both of them as launcher activities, which is a perfectly legitimate thing to do, just not what you want.  Define only one as a launcher activity, and have it launch the other in a new task.
Note that you cannot launch an activity into the background, only launch an activity over the current one.  And there is no guarantee that an activity will continue to exist once it's in the background or even in the backstack of the same task.  It sounds like you should convert one of your activities to a Service.


text:
Q: Endnote is duplicated in all the empty istances I was trying to place multiple footnotes level inside a minipage I came up with a solution using endnotes which allows me two footnotes level in a minipage. However, when I have some unexpected behaviour, the endnote of one minipage is copied on the others.

\documentclass{book}

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{endnotes}
\usepackage{marginnote}
\usepackage{setspace}
\usepackage[para]{footmisc}

\renewcommand*{\enoteheading}{}

\newcommand{\ent}[3]{
\begin{minipage}{\textwidth}
\vspace{5pt}
\marginnote{#1}
\textit{#2}\\
\onehalfspacing
#3
\vspace{5pt}
\setcounter{endnote}{0}
\theendnotes
\end{minipage}
}

\begin{document}
This is a test for the rest of the document:\\
\ent{III 250-1}{ sdfg sdfg sdfgs rwr wrt.}{wertwertt\footnote{footnote A } \footnote{footnote B)}}
\ent{III 252}{\dots Cyrene \dots}{Cyrene condita est a Theraeis\footnote{footnote C }. some text goes here. \endnote{The only endnote is dublicated}}
\end{document}

A: I solved the problem using an if statement \if\theendnote0 if the number of endnotes is zero do not print the endnotes:
\newcommand{\ent}[3]{
\begin{minipage}[t]{\textwidth}
\marginnote{#1}
\textit{#2}\\
#3
\if\theendnote0
\else
\setcounter{endnote}{0}
\theendnotes
\fi
\end{minipage}
}}


text:
Q: Create installer with HM NSIS edit, "fail to execute main script" So I create a simple tkinter app.
I create a .exe with pyinstaller.
I create a .nsi which can create Install.exe
I can give anyone Install.exe, it will install my project.
Problem:

The installation works. If you check "Lancer RT Forms 1.0" the application will compile perfeclty.
BUT
if you try to launch it after, it will always show you this error message.

Someone know from where it comes from ? any advice on how to debug ? Where can I find explicit error message ?


text:
Q: Is there a Batcave under Arkham Asylum in any version of the comic? In the videogame Arkham Asylum, the Joker get captured by Batman and sent into Arkham Asylum. But this is all a trap, as the Joker planned to take over Arkham Asylum and use its infamous inmates to fight Batman.
At some point, Batman needs supplies and decides to enter an annex of the Batcave that was built in case someone went wrong in Arkham (crazily prepared vigilante!).
Of course, this is really convenient in the setting of the game, since it allows the appearance of the Batcave without having Batman leave Arkham's island.
But, as someone who mostly knows about Batman through the movies and the animated series, this really surprised me.
Does Batman have a Batcave under Arkham Asylum in some version of comics?

A: What is commonly identified with the term Batcave is the cave below Wayne Manor, but in reality Batcave is the name of a complex of different caves/areas placed all around (well, below, actually) Gotham City. The one below Arkham Asylum is just one if many of those areas, it's called "Northwest Batcave" and first appearance I can remember of it is in No Man's Land.


text:
Q: Detect if a key should be treated as a style or attribute I have the following function :
var applyStyling = function (element, object) {
    return _.each(object, function (value, key) {
       // determine whether the key should be treated as an attribute or style
         if(style)
            element.style.key = value
         element.setAttribute(key, value)
    })
}

An example use would be something like
applyStyling('some dom element', {'id' : 'someID', 'zIndex' : 10})

How can I detect if the key should be treated as a style or attribute? I could only find how to check if attribute/style has been set on an element.

A: var applyStyling = function (element, object) {
    return _.each(object, function (value, key) {
       // determine whether the key should be treated as an attribute or style
         if(element.hasAttribute(key))
             element.setAttribute(key, value)
         else if (element.style.hasOwnProperty(key))
             element.style[key] = value
    })
}

Edit: modified answer based on OP comment
var applyStyling = function (element, object) {
    return _.each(object, function (value, key) {
       // determine whether the key should be treated as an attribute or style
         if (element.style.hasOwnProperty(key))
             element.style[key] = value
         else
             element.setAttribute(key, value)
    })
}

A: I´m afraid there is no quick answer. You can list/check already defined properties. But how could you pre-list user-defined properties on DOM elements or browser-defined properties like style ones.
You can even use the same name for both ( with reserve ), setting element.zIndex and element.style.id would do no wrong.
Nice Hack. pre-list for your use and abuse.

A: var applyStyling = function (element, object) {
  for(var key in object) if(object.hasOwnProperty(key)) {
    if(element.style[key] !== void 0)
      element.style[key] = object[key];
    else
      element.setAttribute(key, object[key]);
  }
}

var applyStyling = function (element, object) {
  for(var key in object) if(object.hasOwnProperty(key)) {
    if(element.style[key] !== void 0)
      element.style[key] = object[key];
    else
      element.setAttribute(key, object[key]);
  }
}
applyStyling(document.documentElement, {
  color: 'red',
  title: 'tooltip'
});
Some text


text:
Q: Share global variables between aspx and Vue pages Before anybody starts screaming at me for using global variables, I have a few things to say:

*

*This is only for one variable and will only be used temporary (my estimates says that it will be gone within one year)

*I'm open for suggestions on how to solve this a better way

Our project has a bit of a unusual setup. We have an old ASP.Net website, that we are slowly converting to VueJs, page by page. Due to this, we are using UMD
Currently Vue is used for the menu, showing content, etc. When showing an old aspx page, we are using iframe. My goal is for my Vue to be able to catch events thrown from the open aspx page
For this I thought the mitt emitter would be perfect for the job. I'm using it in my Vue project already
On the code side of things, I have the following:
I have a Toolbox.js file, where I try to keep my global variable
var emitter;

async function ClickFromOldPage()
{
    emitter.emit('test');
}

In mounted in my vue file (the first thing that opens) I'm setting the global variable
mounted()
{
    window.emitter = window.mitt();

    window.emitter.on('test', this.Test);
},

And then I have an aspx page that calls ClickFromOldPage
Both the vue file and aspx file is loading Toolbox.js like this
<script src="../Vue3/Javascript/Toolbox.js"></script>

From what I could gather around the net, this should do it, but emitter is undefined when calling Toolbox from the aspx page
Another way was by using top to set/get variables, but this gives the same result
I also tried localStorage, but this can't handle complex objects like the emitter
The only other way to handle this challenge I can think of, is by using cookies or localStorage, where the aspx page writes 'Clicked' (or whatever), then have a function in Vue that checks for said data every second or so. This doesn't sound like a good solution, but the only solution I can come up with
Any other ideas?


text:
Q: Remap data structure to list of objects from totals My data is currently:
var data = [
  {"date":"01/2020", "x":1, "y":3, "z":4},
  {"date":"02/2020", "x":2, "y":4, "z":6},
  ...
];

My desired output is:
var data2 = [
  {date:"01/2020", type:"x"},
  {date:"01/2020", type:"y"},
  {date:"01/2020", type:"y"},
  {date:"01/2020", type:"y"},
  {date:"01/2020", type:"z"},
  {date:"01/2020", type:"z"},
  {date:"01/2020", type:"z"},
  {date:"01/2020", type:"z"},
  {date:"02/2020", type:"x"},
  {date:"02/2020", type:"x"},
  {date:"02/2020", type:"y"},
  {date:"02/2020", type:"y"},
  {date:"02/2020", type:"y"},
  {date:"02/2020", type:"y"},
  {date:"02/2020", type:"z"},
  {date:"02/2020", type:"z"},
  {date:"02/2020", type:"z"},
  {date:"02/2020", type:"z"},
  {date:"02/2020", type:"z"},
  {date:"02/2020", type:"z"},
  ...
];

Essentially I'm aiming to unpack the totals in data and configure them into an object format such that the number of objects equals the number of totals. For instance if y=3 in January then we have three occurrences of {date:"01/2020", type:"y"} in data2.
I'm not quite sure how to achieve that. I only was able to expand one measily type, in a crude / unscalable way:
var data2 = d3.range(3).map(()=>({"type":"y"}));

Question
How can I frame the logic for populating my new array with objects based on totals from the original array?

A: You can use Array.reduce on your data array, processing each object and pushing the date and each of the other key values as an object into your output array, where you push each object the number of times specified by the value associated with the key:

var data = [
  {"date":"01/2020", "x":1, "y":3, "z":4},
  {"date":"02/2020", "x":2, "y":4, "z":6}
];
var data2 = data.reduce((c, { date, ...rest }) => {
  Object.entries(rest).map(([type, v]) => {
    for (let i = 0; i < v; i++) {
      c.push({ date, type });
    }
  });
  return c;
}, []);

console.log(data2);

A: You could use .flatMap() to iterate your data array. For each object in the data array, you can take the entries of the object excluding the date property (this object is stored in r, and is obtained via destructuring assignment), and map through those to return a new array of the length of each value. Using this new array, you can fill it with {date, type} objects. We're using .flatMap() here as it allows us to flatten/concatenate the returned results into one resulting array:

const data = [{"date":"01/2020", "x":1, "y":3, "z":4}, {"date":"02/2020", "x":2, "y":4, "z":6},];

const data2 = data.flatMap(({date, ...r}) => Object.entries(r).flatMap(
  ([type, length]) => Array.from({length}, _ => ({date, type}))
));

console.log(data2);
.as-console-wrapper { max-height: 100% !important;} /* ignore */

A: You can do the following,

var data = [

{"date":"01/2020", "x":1, "y":3, "z":4},
{"date":"02/2020", "x":2, "y":4, "z":6},
];

res = data.reduce((prev, curr) => {
  Object.keys(curr).forEach(key => {
    if(key !== 'date') {
      for(let i = 0; i<curr[key]; i++) {
        prev.push({ date: curr.date, type: key});
      }
    }
  });
  return prev;
}, []);

console.log(res)


text:
Q: Facebook SDK loginViewShowingLoggedInUser not getting called I'm new to iOS and trying to implement Facebook login and after login is successful I want it to go to another view. I've done everything that the documentation shows but I can't get the delegate to be called. I have seen people questions but I tried all of them. Nothing worked not sure if I miss something obvious.
This is my LoginViewController.h
#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>

@interface LoginViewController : UIViewController <FBLoginViewDelegate>

@end

This is my LoginViewController.m file
#import "LoginViewController.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        NSLog(@"Starting");
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    FBLoginView *loginView = [[FBLoginView alloc] init];
    loginView.delegate = self;

    return YES;
}

-(void)loginViewShowingLoggedInUser:(FBLoginView *)loginView {
    NSLog(@"You're logged in");
    [self performSegueWithIdentifier:@"segueToAnotherView" sender:self];

}

-(void)loginViewShowingLoggedOutUser:(FBLoginView *)logoutView {
    NSLog(@"Logged out");
}

@end

I also have this in my AppDelegate.m
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {

    // Call FBAppCall's handleOpenURL:sourceApplication to handle Facebook app responses
    BOOL wasHandled = [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];

    // You can add your app-specific url handling code here if needed

    return wasHandled;
}

When the app comes back I don't see the log "You're logged in" or even "Logged out" at all. I can only see the Logout button from Facebook. Also, the two view controllers are connected by a segue.

A: Checkout the following code to log in from facebook
#define PERMISSION @"publish_actions",@"email",@"public_profile"

@property (strong, nonatomic) FBSession *session;

NSArray *permissions = [[NSArray alloc] initWithObjects:PERMISSION,nil];

    self.session = [[FBSession alloc] initWithPermissions:permissions];

    [FBSession setActiveSession:self.session];

    // if the session isn't open, let's open it now and present the login UX to the user
    [self.session openWithCompletionHandler:^(FBSession *session,
                                                              FBSessionState status,
                                                              NSError *error) {

        if (!error) {

          //Handle code for success

        } else {

           //Code for failure
        }

    }];

A: You are going to want to add your app to Facebook, Download the Facebook SDK and add some values to your plist. There is a lot more you're going to need to do here and I suggest you read Facebook SDK Documentation If you need more help, I am brand new to iOS as well and just implemented my own Facebook login (I guess you could call it custom) and it works smoothly.


text:
Q: How to display Images from internet in a windows phone 7 app? I am making an application which gets urls of images by parsing an RSS feed.I want to diplay that images in the application one after another when tapped on screen .How can i do it? Is it required to download all images before displaying? Please explain.
Thanks and regards
vaysage

A: Maybe I don't understand your question correctly but you should be able to set the Source of an Image element directly to an URI specified in your RSS feed item.
<Image x:Name="m_Image" Source="http://www.microsoft.com/silverlight/images/ms-silverlight-logo.png"/>

When changing item (by tapping) you can easily swap the source of the image from your code.
Uri uri = new Uri("...", UriKind.Absolute);
ImageSource imgSource = new BitmapImage(uri);
m_Image.Source = imgSource;

Using LowProfileImageLoader (as mentioned by Thomas Joulin and Mick N) is a good way to load images in the background and keep the UI responsive.

A: *

*Parse you're RSS Feed to get the images URL's (using for exemple HTTPWebRequest)

*Set the binding for the source of each of you images (since it's web based, I recommend LowProfileImageLoader which will load images in the background.

*Create a SlideShow.xaml view, based on a pivot. Dynamically add Pivot items

*On tap on a thumbnail, launch the SlideShow.xaml, at the specified index

A: You will need to get the images download in some form.
You might find these posts an interesting read.
Keep a low profile [LowProfileImageLoader helps the Windows Phone 7 UI thread stay responsive by loading images in the background] - Delay's Blog
**There's no substitute for customer feedback! [Improving Windows Phone 7 application performance now a bit easier with LowProfileImageLoader and DeferredLoadListBox updates] - Delay's Blog


text:
Q: Implementing Two Level Aggregate in PostgreSQL using Sequelize Function for NodeJS App Hello guys please bear with me here. I'm using PostgreSQL, Sequelize, Express, and NodeJS to create a backend. I'm wondering if these lines of raw query code can be implemented using Sequelize Model findAll function.
First of all, what I am trying to do here is to calculate the total score of these students. Here are some tables and their relations.
                 Student                               Level
| student_id |    name    | level_id |       | level_id | level_name |
|:----------:|:----------:|:--------:|       |:--------:|:----------:|
|      1     |    John    |     1    |   >   |     1    |   Rookie   |
|      2     |    Jane    |     2    |       |     2    |   Expert   |

                    v

              StudentQuiz
|   quiz_id  | student_id |   score  |
|:----------:|:----------:|:--------:|
|      1     |      1     |    40    |
|      1     |      1     |    100   |
|      2     |      1     |    80    |
|      1     |      2     |    100   |
|      2     |      2     |    100   |

If I run line of codes below.
   SELECT table2.student_id,
          s.canvasser_name,
          l.level_name,
          table2.total_score
   FROM (SELECT table1.student_id,
                sum(table1.max_score) total_score
         FROM (SELECT sq.student_id,
               max(sq.score) max_score
               FROM public.StudentQuiz sq
               GROUP BY sq.quiz_id, sq.student_id) table1
         GROUP BY table1.student_id) table2
   INNER JOIN public.Student s
           ON s.student_id = table2.student_id
   INNER JOIN public.Level l
           ON l.level_id = s.level_id
   ORDER BY table2.total_score DESC
   LIMIT 10;

I will get something like this.
| student_id |    name    |  level   |   total_score  |
|:----------:|:----------:|:--------:|:--------------:|
|      1     |    John    |  Rookie  |       180      |
|      2     |    Jane    |  Expert  |       200      |

Please note that I'm selecting the highest score if more than one quiz with the same id found.
Anyway, I want to implement it using sequelize built in function. What I've been trying to do is something like this.
    const result = await StudentQuiz.findAll({
      attributes: ['studentId', [sequelize.fn('sum', sequelize.fn('max', sequelize.col('score'))), 'totalPrice'], 'quizId'],
      group: 'studentId',
      include: [
        {
          model: Student,
          include: [{
            model: Level
          }],
        },
      ],
      offset: 0,
      limit: 10
    });

The code above throws an error message which is "aggregate function calls cannot be nested".
Any kind of help will be appreciated. Thank you.
P.S. I know i can use sequelize.query() function to use the first code block shown, but that's not the point.

A: Sequelize is not intended to work with complex aggregations using models. Its primary goal is to provide CRUD operations with models.
To use models in such scenario you can use a model definition to get a schema, a table name and fields to build a query dynamically not knowing exact field names.

A: I find the solution without using any raw query, though I need to get two tables, that is StudentQuiz and Student that coupled by Level. Here is my answer.
    // Finding maximum score and group it based on studentId and quizId
    const maxScoreList = await StudentQuiz.findAll({
      attributes: ['studentId', 'quizId', [sequelize.fn('max', sequelize.col('score')), 'maxScore']],
      group: ['studentId', 'quizId'],
      order: ['studentId', 'quizId'],
      raw: true
    });

    // Calculating total score for the same student for each quiz recorded
    const scoreArray = [maxScoreList.shift()];
    let index = 0;
    const unfilteredStudentId = maxScoreList.map((item) => {
      if (scoreArray[index].studentId !== item.studentId) {
        scoreArray.push(item);
        index += 1;
      }
      scoreArray[index].maxScore += item.maxScore;
      return item.studentId;
    });

    // Filtering studentId that show up more than one time
    const extractedStudentId = [...new Set(unfilteredStudentId)];

    // Finding student based on studentId inside extractedStudentId array
    const student = await Student.findAll({
      where: { id: extractedStudentId },
      attributes: ['id', 'canvasserId', 'canvasserName', 'canvasserImageUrl'],
      include: {
        model: Level,
        attributes: [['level_name', 'level'], ['icon_url', 'level_image_url']]
      },
      order: ['id'],
      raw: true,
      nest: true
    });

    // Combining total score list to student list
    const rankList = student.map((item, idx) => ({ ...item, totalScore: scoreArray[idx] }));

With this much complexity, I agree that using raw query by far the best approach for this case.


text:
Q: Calculating thermal force generated Let's say you have a car that weights 1000kg traveling at 25m/s that slams into a brick wall and stops immediately.  Using (F) = 1/2 (m)(v)^2, where m is 1,000 kg and v is 25, the car generates 312,500J of thermal force (kinetic energy transforms to thermal energy via friction, right?).
My question is what happens if you have 2 cars, both traveling in the opposite direction slamming into each other head on and stopping immediately.  How would you calculate the total amount of thermal energy created (/transformed).  Would it be:
A) M = 1000kg, V = 50, F = 1,250,000J
Double the velocity as the 2 cars are traveling in the opposite direction but leave the mass the same.
B) M = 2000kg, V = 25, F = 625,000J
Double the mass as 2 cars are involved but leave the velocity the same.
C) M = 2000kg, V = 50, F = 2,500,000J
Double the mass as 2 cars are involved and double the velocity as they are both traveling 25 m/s in the opposite direction.
I believe the correct answer would be C but could you please double check.

A: The car alone does not produce thermal energy in the idealised case, because all the energy is used to keep the mass in motion. Now we assume that the two cars are in a closed system, so the cars can neither create nor destroy energy, i.e. they drive towards each other at a constant speed. With these assumptions, we set up this equation, where $ \Delta U $ is the internal energy in the form of, for example, thermal energy.
$$ \sum E_{kin} = \sum E_{kin}' + \Delta U $$
$$ \frac{m_1 v_1^2}{2} + \frac{m_2 v_2^2}{2} = \frac{(m_1 + m_2) v'^2}{2} + \Delta U $$
As both cars come to an immediate stop, the end speed $ v' $ equals zero and since $ m = m_1 = m_2 $ and $  v = v_1 = v_2 $, $ \Delta U $ can be calculated using
$$ \Delta U = m v^2 = 1000\,\text{kg} \times \left(25\,\frac{\text{m}}{\text{s}}\right)^2 = 625\,000\,\text{J}. $$


text:
Q: 'Unauthorized' error when requesting 'https://graph.microsoft.com/v1.0/me/joinedTeams' from Microsoft Graph I am trying to access https://graph.microsoft.com/v1.0/me/joinedTeams in postman with Authorization and I'm getting the response as
{   "error": {
"code": "Unauthorized",
"message": "Unauthorized",
"innerError": {
"date": "2020-08-01T09:39:59",
"request-id": "d906f428-ffcd-4821-9153-f9b1976e74c1"
}   } }
As mentioned in the documentation, I have set the scopes Team.ReadBasic.All TeamSettings.Read.All TeamSettings.ReadWrite.All User.Read.All User.ReadWrite.All Directory.Read.All Directory.ReadWrite.All Group.Read.All Group.ReadWrite.All ChannelMessage.Send
In the Enterprise applications, I'm having Microsoft teams installed
I have added the API permissions for type Delegated
But I can access the profile and groups. whenever I try to access teams API, I'm always getting Unauthorized message. Can anyone tell me, What am I missing?

A: I notice that you haven't granted admin consent for your tenant. You should use an Azure AD admin account to do this. The the Status will become "Granted for {your tenant}".

You should refer to Get access on behalf of a user to get the access token by using auth code flow.


text:
Q: Glue secret manager integration: secretId is not provided I am running the glue pyspark script from my local machine using the GlueETL library.
When creating a dataframe from glue catalog,
dyf_user_book_reading_stat = glueContext.create_dynamic_frame.from_catalog(
    database="xxx-db",
    table_name="xxx_table"
)

I'm getting this error

GlueContext: Glue secret manager integration: secretId is not
provided.

What is the secretId that it is asking for and how to provide it?


text:
Q: Does Java compiler recognize byte and short as literals? What I actually meant to ask is, if I write :
byte b=13;
short s=14;

Then values on the right-hand side i.e., 13 and 14 respectively are treated as byte and short Or is just read as an int type by the compiler.
If they are read as bytes and shorts respectively then why,
byte b1=13;
byte b2=23;
byte b3=b1+b2;

And
short s1=14;
short s2=24;
short s3=s1+s2;

are invalid statements(short s3=s1+s2; and byte b3=b1+b2;) in java even if the the precision is not compromised in bothe the cases.
And if they are just read as int types by the compilers, then how their identity is maintained by the compiler for being byte or short types?

A: Java doesn't have byte or short literals. What it does have is an implicit assignment conversion from int to byte, char and short when the int is a compile time constant and in range for the target type.
So, this is OK:
byte b = 13+14; // implicit conversion

But this is not:
void method(byte b) {}

method(13);

Nor this:
byte b = 13+nonConstant;

A: You hav to cast the result of + which is an int.
byte b1 = 13;
byte b2 = 23;
byte b3 = (byte) (b1 + b2);

short s1 = 14;
short s2 = 24;
short s3 = (short) (s1 + s2);

A: This is because integer literals (and more generally constant expressions of type int) are handled specially by the compiler. When you assign an integer literal to a byte or short, the compiler checks if it is in the range of the target type and then allows the assignment without a cast.


text:
Q: Custom django auth backend not logging the user with base login view I am writing a custom django auth backend that sends a post request with just the username and password info to a server, the server replying with some data about the user if the login/password couple is correct (403 response otherwise)
The code works fine, create the user if it doesn't already exists, then returns the user (made unit tests that are passing). However, the default login view doesn't log the user in.
Here's the code for the backend :
from django.contrib.auth import get_user_model
import requests

User = get_user_model()

class CustomAuthBackend():
    def authenticate(self, username, password):
        response = requests.post(
            LOGIN_SERVER_URL,
            data={'username': username, 'password': password}
        )
        if response.status_code == 200:
            try:
                return User.objects.get(username=username)
            except User.DoesNotExist:
                user = User.objects.create_user(
                    username=username,
                    password=password
                )
                user_data = response.json()['user']
                user.last_name = user_data['last_name']
                user.first_name = user_data['first_name']
                user.email = user_data['email']
                user.save()
                return user

    def get_user(self, username):
        try:
            return User.objects.get(username=username)
        except User.DoesNotExist:
            return None

And the call for the login view (the custom form is just to have placeholders on the form):
from django.conf.urls import url
from django.contrib.auth.views import logout, login
from accounts.forms import CustomAuthenticationForm

url(
        r'^login$',
        login,
        {
            'template_name': 'login.html',
            'authentication_form': CustomAuthenticationForm
        },
        name='login'
    ),

I have spent a fair amount of time tracking down why the user isn't logged in, without any success.
Is there anyone to enlighten me on this issue ? Thanks !

A: According to the docs, the get_user method should take the primary key of the model as the argument:
def get_user(self, user_id):
    try:
        return User.objects.get(pk=user_id)
    except User.DoesNotExist:
        return None


text:
Q: Node.js calling a callback function inside a callback I started learning node.js by reading Node JS in Action book recently. This is probably a newbie question, but after reading several posts of callback functions and javascript scope of variables, I still have problem understand the idea behind this code in chapter 5 of the book.
function loadOrInitializeTaskArray(file, cb) {
  fs.exists(file, function(exists) {
    var tasks = [];
    if (exists) {
      fs.readFile(file, 'utf8', function(err, data) {
        if (err) throw err;
        var data = data.toString();
        var tasks = JSON.parse(data || '[]');
        cb(tasks);
      });
    } else {
      cb([]);
    }
  });
}

function listTasks(file) {
  loadOrInitializeTaskArray(file, function(tasks) {
    for(var i in tasks) {
      console.log(tasks[i]);
    }
  });
}

It includes three callback functions divided in two functions. listTasks(..) is called first and it calls loadorInitializeTaskArray(.. ) later. My problem starts here, how is this call handle by node? loadOrInitializeTaskArray takes two arguments and the second one is the callback function which shouldn't accept any parameters according to is signature but it does!!
when does cb(..) get called in loadorInitializeTaskArray and what is that (the same function that calls helper function)?
"tasks" is an array declared inside function loadOrInitializeTaskArray, how do we have access to it in listTasks(..) function?
I know in Javascript, scope of a variable is inside the function it define and all nested functions. But I have a hard time understanding it here. So can someone explain what is going on here?
Thank you

A: You really are having a hard time in understanding the scope of variable inside the nested functions. So, lets start with it.
Let's consider this code
function foo(){
  var a = 3;
  function bar(){
    console.log(a);
  }
  return bar;
}
var baz = foo();
baz(); // the value of a i.e 3 will appear on console

If you know langauges like C, C++... Your brain would be interpreting this code like this. If you don't know any of them just ignore thiese points.

*

*When foo() is called, variable a will be declared and assigned value 3.

*When foo is returned the stack containing a will be destroyed. And hence a would be destroyed too.

*Then how in the world baz() is outputting 3. ???

Well, in javascript when a function is called the things that happen are different than in C. So, first let your all C things go out from your mind before reading further.
In javascript scope resolution is done by travelling down a chain of objects that defines variables that are "in scope" for that code. Let's see how?

*

*When you declare a global JavaScript variable, what you are actually doing is defining a property of the global object.

*In top-level JavaScript code (i.e., code not contained within any function definitions), the scope chain consists of a single object, the global object.

*In a non-nested function, the scope chain consists of two objects. The first is the object that defines the function's parameters and local variables, and the second is the global object.

*In a nested function, the scope chain has three or more objects. When a function is defined, it stores the scope chain then in effect. When that function is invoked, it creates a new object to store its local variables, and adds that new object to the stored scope chain to create a new, longer, chain that represents the scope for that function invocation.

So, when foo() is executed. It creates a new object to store it's local variables. So, variable a will be stored in that object. And also, bar is defined. When bar is defined it stores the scope chain in effect. So, the scope chain of bar now contains the object that has variable a in it. So, when bar is returned it has a reference to it's scope chain. And hence it knows a.
So, I guess it answers your question how node handles the code.
You wrote:

loadOrInitializeTaskArray takes two arguments and the second one is the callback function which shouldn't accept any parameters according to is signature but it does!!

The callback function is
function(tasks) {
    for(var i in tasks) {
      console.log(tasks[i]);
    }
}

And it accepts an argument tasks. So, you are wrong here.
And When loadOrIntializeTaskArray is called cb refers to this call back function. And cb(arg) basically does this tasks = arg where tasks is the argument in callback function.
I guess you still will be having a lot of questions. Let me know in comments. And I highly recommend you to go through the Core Javascript before diving into node.

A: I'm not sure what you mean by "the second one is the callback function which shouldn't accept any parameters according to is signature". The callback signature (function(tasks)) certainly does expect an argument (tasks).
cb is the callback function that was passed in. In this case it is literally the anonymous function:
function(tasks) {
  for(var i in tasks) {
    console.log(tasks[i]);
  }
}

tasks is the name of two different variables (but they point to the same object because arrays are passed by reference) in different scopes. One is defined in loadOrInitializeTaskArray() as you noted, the other is a parameter for the callback passed to loadOrInitializeTaskArray().
Also, on an unrelated note, typically callbacks follow the "error-first" format. This allows for handling of errors upstream. Modifying the code to follow this convention would result in:
function loadOrInitializeTaskArray(file, cb) {
  fs.exists(file, function(exists) {
    var tasks = [];
    if (exists) {
      fs.readFile(file, 'utf8', function(err, data) {
        if (err)
          return cb(err);

        var data = data.toString();

        // JSON.parse() throws errors/exceptions on parse errors
        try {
          var tasks = JSON.parse(data || '[]');
        } catch (ex) {
          return cb(ex);
        }

        cb(null, tasks);
      });
    } else {
      cb(null, []);
    }
  });
}

function listTasks(file) {
  loadOrInitializeTaskArray(file, function(err, tasks) {
    if (err) throw err;
    for (var i in tasks) {
      console.log(tasks[i]);
    }
  });
}

A: First, there is not really any such thing as a function signature in javascript. You can pass as many or as few arguments to a function as you like. The second argument to loadOrInitialiseTaskArray is simply assigned to the local variable cb when the function is called. The line cb(tasks) then invokes this value, so the second argument had better have been a function.
When you call loadOrInitializeTaskArray from listTasks, the second argument is indeed a function, and the first argument to this function is named tasks in its own scope. It isn't reaching into loadOrInitializeTaskArray and using the variable declared in that function's scope. You explicitly passed in that value when you invoked cb.
The code would work the same and perhaps be easier to understand if we renamed the variables:
function loadOrInitializeTaskArray(file, cb) {
  fs.exists(file, function(exists) {
    var taskArray = [];
    if (exists) {
      fs.readFile(file, 'utf8', function(err, data) {
        if (err) throw err;
        var data = data.toString();
        var taskArray = JSON.parse(data || '[]');
        cb(taskArray);
      });
    } else {
      cb([]);
    }
  });
}

function listTasks(file) {
  loadOrInitializeTaskArray(file, function(listOfTasks) {
    for(var i in listOfTasks) {
      console.log(listOfTasks[i]);
    }
  });
}


text:
Q: SQL WITH statement I have the query below. How come with the invoice_dt set between 1/1/2021 - 5/31/2021... the output display ALL date ranges. How would I set it to look for dups based on pay_cte within the date range?
with pay_cte( vendor_id,invoice_id, pay_amt,pay_cnt ) as (
select vendor_id,invoice_id, pay_amt,count(*)
from ps_voucher
where invoice_dt between '01-Jan-2021' and '31-May-2021'
group by vendor_id,invoice_id, pay_amt
having count(*)>1)
select t.vendor_id, t.voucher_id,t.INVOICE_ID,t.gross_amt, t.INVOICE_DT
from ps_voucher t
join pay_cte p on t.vendor_id=p.vendor_id and t.invoice_id = p.invoice_id
and t.gross_amt=p.pay_amt

A: The reason your query is returning all dates is due to the fact that your actual select statement that uses the WITH clause does not have any filtering for dates. It is likely that your ps_voucher table has records in it that have INVOICE_DT values that are out of the range of dates about which you are curious.
There are two ways you can filter results; the first is in the (inner) JOIN clause, and the second is by adding a WHERE clause in the query.
Option 1:
with pay_cte( vendor_id,invoice_id, pay_amt,pay_cnt ) as (
    select
        vendor_id,
        invoice_id,
        pay_amt,
        count(*)
    from ps_voucher
    where
        invoice_dt between '01-Jan-2021' and '31-May-2021'
    group by
        vendor_id,
        invoice_id,
        pay_amt
    having
        count(*)>1
)
select
    t.vendor_id,
    t.voucher_id,
    t.INVOICE_ID,
    t.gross_amt,
    t.INVOICE_DT
from ps_voucher t
join pay_cte p
    on t.vendor_id = p.vendor_id
    and t.invoice_id = p.invoice_id
    and t.gross_amt=p.pay_amt
    and t.INVOICE_DT between '01-Jan-2021' and '31-May-2021'

Option 2:
with pay_cte( vendor_id,invoice_id, pay_amt,pay_cnt ) as (
    select
        vendor_id,
        invoice_id,
        pay_amt,
        count(*)
    from ps_voucher
    where
        invoice_dt between '01-Jan-2021' and '31-May-2021'
    group by
        vendor_id,
        invoice_id,
        pay_amt
    having
        count(*)>1
)
select
    t.vendor_id,
    t.voucher_id,
    t.INVOICE_ID,
    t.gross_amt,
    t.INVOICE_DT
from ps_voucher t
join pay_cte p
    on t.vendor_id = p.vendor_id
    and t.invoice_id = p.invoice_id
    and t.gross_amt=p.pay_amt
where
    t.INVOICE_DT between '01-Jan-2021' and '31-May-2021'

A: You have to change your date for this format "yyyy-mm-dd"


text:
Q: How to get image path from id using SQL I want to use a SQL query to get some random users and display an advanced custom fields profile image. Currently with this query I get the image ID back but I somehow from that need to get the url for the image.
global $wpdb;
$users = $wpdb->get_results(
"SELECT id
, (SELECT MAX(meta_value) FROM wp_usermeta WHERE ID = wp_usermeta.user_id AND meta_key = 'first_name') first_name
, (SELECT MAX(meta_value) FROM wp_usermeta WHERE ID = wp_usermeta.user_id AND meta_key = 'last_name') last_name
, (SELECT MAX(meta_value) FROM wp_usermeta WHERE ID = wp_usermeta.user_id AND meta_key = 'profile_image') profile_image
FROM wp_users ORDER BY RAND() LIMIT 25"
);
return $users;

Perhaps a join on the wp_postmeta table on the _wp_attached_file field?
UPDATE. Okay, I got it working thanks to the function suggestions:
foreach ($users as $user) {
     $image_attributes = wp_get_attachment_image_src( $attachment_id = $user->profile_image );
    $user->avatar = $image_attributes[0];
}

return $users;


text:
Q: asp.net making a gridView column invisible This is a Master-Detail form. Master is a GridView. And, the Detail is a DetailsView.
The entire thing is achieved programmatically.
As you can see from the code, DetailsView is using the Master-objects's ID to retrieve the Detail items.
I need to make the ID column of the Master-GridView invisible. Coz, it is irrelevent for the user of the page. But it must not harm the page logic.
But the code-line, GridView1.Columns[1].Visible = false; is generating an exception.
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

How should I solve this problem?
public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
            }
        }

        protected void BindData()
        {
            List<Order> orders = Order.Get();

            GridView1.DataSource = orders;
            GridView1.DataBind();

            // This is giving Error...............!!!
            GridView1.Columns[1].Visible = false;

            // At first, when the page first loads,
            //      GridView1.SelectedIndex == -1
            // So, this is done to automatically select the 1st item.
            if (GridView1.SelectedIndex < 0)
            {
                GridView1.SelectedIndex = 0;
            }

            int selRowIndex = GridView1.SelectedIndex;

            int selMasterId = Convert.ToInt32(GridView1.Rows[selRowIndex].Cells[1].Text);

            Order master = Order.Get(selMasterId);

            labItemsCount.Text = master.Items.Count.ToString();

            DetailsView1.DataSource = master.Items;
            DetailsView1.DataBind();
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
        {
            DetailsView1.PageIndex = e.NewPageIndex;

            BindData();
        }
    }

A: Have you considered using the DataKeyNames property of the gridview? This way you can remove the 'id' column from the GridView bu still access the 'id' value in the Page_Load.
DataKeyNames = "id"

Then you can get the value of the id like this.
int selRowIndex = GridView1.SelectedIndex;
int selMasterId = Convert.ToInt32(GridView.DataKeys[selRowIndex].Value);
Order master = Order.Get(selMasterId);

Alternately, you could try changing the visibility of the column in the OnRowBound event of the GridView.
protected void GridView_RowDataBound(object sender,   GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header ||
        e.Row.RowType == DataControlRowType.DataRow ||
        e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[1].Visible = false;
    }
}


text:
Q: Finding estimators for $n$ and $p$ for a binomial distribution Say I am given a data-set generated from $Binomial(n, p)$, and these values are: $$5, 6, 2, 6, 3, 6, 8$$I am not given any information about the parameters $n$ or $p$.
First off, I need to set up an estimator $\hat{n}$ for $n$, for which I used: $$\hat{n}=\max{x_i}$$ So in this case $\hat{n}$ would be $8$. Is this considered to be a good estimator for n? Are there any others I could consider?
Also, since I only have an estimated value for $n$, am I correct to say that $$\hat{p}=\dfrac{X}{\hat{n}k}$$ where k is the number of tests (in this case 7), is a biased estimator? This estimator value for the above data-set would be: $$\hat{p}=\frac{5+6+2+6+3+6+8}{8\cdot7}\approx0.643$$

A: Why not use maximum likelihood estimators? For $N$ i.i.d. observations $x=(x_1,\ldots,x_N)$ with mean $$\bar x=\frac1N\sum_{k=1}^Nx_k$$ the likelihood of the sample $x$ with respect to the binomial $(n,p)$ distribution is $$L(n,p)=c_n(x)p^{N\bar x}(1-p)^{nN-N\bar x}$$ where $$c_n(x)=\prod_{k=1}^N{n\choose x_k}$$
Optimizing $L(n,p)$ with respect to $p$ yields $$\hat p=\frac{\bar x}n$$
hence one is left with optimizing $L(n,\hat p)={\bar x}^{N\bar x}\ell(n)$ over $n$, with $$\ell(n)=c_n(x)n^{-nN}(n-\bar x)^{nN-N\bar x}$$
which can be maximized numerically.
For $x=(5,6,2,6,3,6,8)$, one gets $$N=7\qquad\bar x=\frac{36}7$$ and the plots of $\ell(n)$ shown below indicate a maximum located at $n=14$.
This points at selecting the binomial distribution $(n,p)$ with $$n=14\qquad p=\frac{18}{49}\approx0.367$$ rather than your suggestion $n=8$ and $p\approx0.643$, for a reduced likelihood $\ell(14)=1.392\cdot10^{-32}$ rather than $\ell(8)\approx6.77\cdot10^{-33}$.


text:
Q: Send email to multiple people based on common cell value using Excel VBA I would like to add multiple recipients and attachments to one email message dictated by the value in a column.
I need to have people update their resumes, which will be attached, but I would like to group the emails by manager. The # of people under each manager ranges from 1-14.
The columns I have are:
B: Mgr Email address
C: Mgr last name
D: Employee email
E: Emp first name
F: Emp last name
G: Status of resume
I created a macro that will loop through and create an email with proper attachment for each entry.
I'd like to switch this to groups of employees by the value in column C or B. I have an inkling this will include arrays. I am a VBA novice.
What I have so far (with specific paths/emails renamed for privacy):
Sub Test2()
Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range
Dim sSourcePath As String
Dim flpath As String
flpath = "C:\Resumes\"

Application.ScreenUpdating = False
Set OutApp = CreateObject("Outlook.Application")

On Error GoTo cleanup
For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
    'XYZ email address was hardcoded for testing purposes, but should also loop
    If cell.Value = "XYZ@gmail.com" And _
       Cells(cell.Row, "G").Value = "4. Need Update" _
       Then

        Set OutMail = OutApp.CreateItem(0)
        sSourcePath = Dir(flpath & Cells(cell.Row, "E").Value & " *.docx")

        On Error Resume Next
        With OutMail
            .To = cell.Value & ", " & Cells(cell.Row, "D").Value
            'cced address is static
            .CC = "ZZZ@gmail.com"
            .Subject = "Resume needed"
            .body = "Howdy!" _
                  & vbNewLine & vbNewLine & _
                    "Body text"

            .attachments.Add flpath & sSourcePath
            .Display  'Or use Display

        End With
        On Error GoTo 0
        Set OutMail = Nothing
    End If

Next cell

cleanup:
    Set OutApp = Nothing
    Application.ScreenUpdating = True
End Sub

A: If I'm guessing correctly at what you want, here's a way that uses a collection of e-mails by manager. They are created as you go, and then when you're finished, you can do whatever you want to the messages in the collection.
Dim allMessages as Collection
Dim currMessage as Object
Set allMessages = New Collection

For Each cell In Columns("B").Cells.SpecialCells(xlCellTypeConstants)
    If Cells(cell.Row, "G").Value = "4. Need Update"
        ' Find the e-mail for the present manager
        For Each currMessage in allMessages
            If currMessage.CC = cell.Value Then
                Exit For
            End If
        Next currMessage

        ' Create it, if it wasn't found
        If currMessage Is Nothing Then
            Set currMessage = OutApp.CreateItem(0)
            allMessages.Add currMessage
            With currMessage
                .CC = cell.Value
                .Subject = "Résumé Needed"
                .Body = "Howdy!" & vbNewLine & vbNewLine & "Body text."
            End With
        End If

        ' Add the Message Recipient and Attachment
        sSourcePath = Dir(flpath & Cells(cell.Row, "E").Value & " *.docx")
        With currMessage
            .To = .To & Iif(Len(.To) > 0,";","") & _
                  cell.Value & ", " & Cells(cell.Row, "D").Value
            .Attachments.Add flpath & sSourcePath
        End With

        Set currMessage = Nothing

    End If
Next cell

' Now do something with the messages.
For Each currMessage In allMessages
    currMessage.Display
End If

Set currMessage = Nothing
Set allMessages = Nothing

Caveat: Given that I don't have your data and don't use Outlook presently, I have not tested the above code snippet. The snippet primarily replaces your For...NextLoop, with an additional loop and clean up at the end, some declarations at the beginning. Let me know if it gives you problems, and I'll try to fix this answer based on what you tell me.


text:
Q: How to make text block fixed and not overlap above other elements? I am developing a new page on Wordpress, it is more or less completed now but I have one problem.
I need the text on the left-hand side of the page properly fixed but it keeps going above the footer once you scroll to the bottom.
I want it to remain fixed but not go past the last box on all screen sizes, how would I do that?
I have tried the following CSS:
position: fixed;
width: 20% !important;
float: left !important;

Here is a link to the page - https://marketing.feedinfo.com/recruitment-2/

A: Add to your footer css
position: relative
z-index: 1000

A: please try this solution.
in this solution text will not hide.

#left-col {
    position: sticky;
    /* width: 20% !important; */
    float: left !important;
    z-index: 1;
    top: 190px;
}


text:
Q: Tensorflow unicode text encoding-decoding I just started working with cyrillic text. Cannot properly print russian text after text preprocessing. How can I set encoding during text loading?
import pathlib
text = pathlib.Path('rus.txt').read_text(encoding='utf-8')

lines = text.splitlines()
pairs = [line.split('\t') for line in lines]
inp = [inp for targ, inp, tag in pairs]
targ = [targ for targ, inp, tag in pairs]
inp[:20]

Output1:
['Марш!',  'Иди.',  'Идите.',  'Здравствуйте.',  'Привет!',  'Хай.',
   'Здрасте.',  'Здоро́во!',  'Приветик!',  'Беги!',  'Бегите!',...

Creating dataset:
BUFFER_SIZE = len (inp)
BATCH_SIZE = 64

dataset = tf.data.Dataset.from_tensor_slices((inp, targ)).shuffle(BUFFER_SIZE)
dataset = dataset.batch(BATCH_SIZE)

for example_input_batch, example_target_batch in dataset.take(1):
  print(example_input_batch[:5]) --Russian input
  print()
  print(example_target_batch[:5]) --English target
  break

Output2:
 tf.Tensor(
    [b'\xd0\xa2\xd0\xbe\xd0\xbc \xd0\xbf\xd0\xbe\xd1\x81\xd1\x82\xd1\x83\xd0\xbf\xd0\xb8\xd0\xbb \xd1\x85\xd0\xbe\xd1\x80\xd0\xbe\xd1\x88\xd0\xbe.'
     b'\xd0\xa2\xd1\x8b \xd1\x81\xd0\xb4\xd0\xb5\xd0\xbb\xd0\xb0\xd0\xbb\xd0\xb0 \xd1\x8d\xd1\x82\xd0\xbe \xd1\x81\xd0\xbf\xd0\xb5\xd1\x86\xd0\xb8\xd0\xb0\xd0\xbb\xd1\x8c\xd0\xbd\xd0\xbe.'
     b'\xd0\xa2\xd0\xbe\xd0\xbc \xd0\xb5\xd1\x89\xd1\x91 \xd0\xbd\xd0\xb5 \xd0\xbc\xd0\xbe\xd0\xb6\xd0\xb5\xd1\x82 \xd1\x85\xd0\xbe\xd0\xb4\xd0\xb8\xd1\x82\xd1\x8c \xd1\x81\xd0\xb0\xd0\xbc.'
     b'\xd0\x94\xd1\x83\xd0\xbc\xd0\xb0\xd1\x8e, \xd0\xbf\xd0\xbe\xd1\x80\xd0\xb0 \xd0\xbc\xd0\xbd\xd0\xb5 \xd0\xbf\xd0\xbe\xd0\xb3\xd0\xbe\xd0\xb2\xd0\xbe\xd1\x80\xd0\xb8\xd1\x82\xd1\x8c \xd0\xbe\xd0\xb1 \xd1\x8d\xd1\x82\xd0\xbe\xd0\xb9 \xd0\xbf\xd1\x80\xd0\xbe\xd0\xb1\xd0\xbb\xd0\xb5\xd0\xbc\xd0\xb5 \xd1\x81 \xd0\xbd\xd0\xb0\xd1\x87\xd0\xb0\xd0\xbb\xd1\x8c\xd0\xbd\xd0\xb8\xd0\xba\xd0\xbe\xd0\xbc.'
     b'\xd0\xaf \xd0\xbc\xd0\xbe\xd0\xb3\xd1\x83 \xd1\x8d\xd1\x82\xd0\xbe \xd1\x83\xd0\xbb\xd0\xb0\xd0\xb4\xd0\xb8\xd1\x82\xd1\x8c.'], shape=(5,), dtype=string)

tf.Tensor(
[b'Tom did a good thing.' b'You did that on purpose.'
 b"Tom can't walk on his own yet."
 b"I think it's time for me to talk to the boss about this problem."
 b'I can arrange that.'], shape=(5,), dtype=string)

Can you please advise what is the problem here with printing russian text? English text prints ok.

A: The strings that appear like nonsense are actually UTF-8 encoded.  See this post for more details.
For example, the first string in the tensor
\xd0\xa2\xd0\xbe\xd0\xbc \xd0\xbf\xd0\xbe\xd1\x81\xd1\x82\xd1\x83\xd0\xbf\xd0\xb8\xd0\xbb \xd1\x85\xd0\xbe\xd1\x80\xd0\xbe\xd1\x88\xd0\xbe.

is this garbage
Том поÑÑÑпил ÑоÑо

which can actually be decoded correctly, like this:
s = '\xd0\xa2\xd0\xbe\xd0\xbc \xd0\xbf\xd0\xbe\xd1\x81\xd1\x82\xd1\x83\xd0\xbf\xd0\xb8\xd0\xbb \xd1\x85\xd0\xbe\xd1\x80\xd0\xbe\xd1\x88\xd0\xbe.'
decoded = bytes(s, encoding='latin').decode()
print(decoded)

Output:
Том поступил хорошо.

I'm not sure exactly how to do this with Tensorflow, but perhaps tf.strings.unicode_decode can help.

A: I used tf.strings.unicode_decode() function which converts encoded '\xd0\xa2\xd0\xbe\xd0\xbc' like value into a tensors of integers like [1053, 1077,   32, 1076,... . I have also converted the result into numpy array to make it applicable for chr() function which converts the unicode integer into unicode symbols.
def decode_string(ints):
  strs = [chr(i) for i in ints]
  joined = [''.join(strs)]
  return joined

decoded = tf.strings.unicode_decode(example_input_batch[:5], 'utf-8').numpy()
decoded_list = [decode_string(ex) for ex in decoded]
print(decoded_list)

The result is:
[['Том был окружён дельфинами.'], ['Бразилия была колонией Португалии.'], ['Скажи Тому, чтобы поторопился.'], ['Я слишком многого прошу?'],...


text:
Q: Only variables can be passed by reference $explode2 = @end(explode('.', $fetched_delete_data['image']));
$explode3 = @explode('.', $fetched_delete_data['image']);

Есть вот такой код, при анализе кода IDE'шкой, выходит ошибка "Only variables can be passed by reference", связанная с этим кодом. Вопрос, как исправить данную ошибку?, и если я её исправлю, то другой код возможно связанный с этим местом, не сломается ли?
P.S - Версия в IDE - PHP 5.6/7.4, соответственно фикс должен быть совместим с этими версиями.

A: end принимает к себе на вход только переменную, т.к. работает с ней по ссылке. https://www.php.net/manual/ru/function.end.php

Список параметров ¶
array
Массив. Этот массив передаётся по ссылке, потому что он модифицируется данной функцией. Это означает что вы должны передать его как реальную переменную, а не как функцию, возвращающую массив, так как по ссылке можно передавать только фактические переменные.

Нужно результат explode положить в отдельную переменную и уже еë передавать в end


text:
Q: Is re-asking a question with an accepted answer allowed, if that answer isn't the right answer any longer? I asked a question before, and after a very long time and many updates, I solved it and was able to get past it.
However now the problem is back, and the original solution does not help in this case. What would be the best approach to reopen this question? Since it became community wiki, it has not seen action except by me, editing the question as I went on and finally answered the question.
It feels like unaccepting the answer and editing the question again would mean no one will really pay attention to it since it has 5 answers now, and it had 10 edits happen on it.
Is there a way I can ask this same question again? And does this mean that the solution to the question was wrong or just that something else went wrong?

A: Ask a new question, referencing the old one and explaining why those answers won't work in the current situation.

A: Definitely ask a new question, link the old.  A question should be a resource for others when it's complete, one specific, answerable question...and the accepted answer should have been for that question.
Things change, you now have a different question that needs answering...so do exactly that, ask a new question for your new problem, and both will later serve as specific resources with a viable answer.

Look at it from the other possibility: if you did edit the original, you'd have a bunch of out-of-context answers that don't fit the question, and it would be a poor/confusing resource for others finding it later.


text:
Q: ACPI BIOS ERROR (bug), gets stuck My Ubuntu 18.04 is failing to boot and is displaying the following message.
ACPI BIOS ERROR (bug): Failure creating named object ... AE_ALREADY_EXISTS

...
Common problems:
- Boot args (cat /proc/cmdline)
  - Check rootdelay= (did the system wait long enough?)
- Missing modules (cat /proc/modules; ls /dev)
ALERT! UUID=70269fa2-b15e-4014-b59b-9dcede085887 does not exist. Dropping to a shell!

I have tried to add "nomodeset" in the grub but nothing changes. The recovery mode does not work either.
This have happened several times before. I solved it before by changing the driver after changing the grub permanently (adding the "nomodeset"). The problem now is that it gets stuck, and nothing seems to work.
Any ideas on how to solve this problem?

A: Possible solution: I changed the SATA configuration to ACPI in BIOS and it worked.


text:
Q: Build a App that accepts language pack I'm quite lost here and I need guidance.
I need to build a web app that will support language packs... the idea is to start with a default language such as English, and then the client will be able to download a language pack and install it and then choose between the default language and any other installed language. Are there any patterns on the matter? Maybe a open source software I could study (and take as an example)? Or maybe some literature on it?
Edit1: The idea here is that the user will deploy the web app on premises (or cloud IaaS) and install as many language packs as are available, and the app would check the browser language and check if there's a compatible language pack to translate to... .Net already does that using localized resources files, that require recompilation...

A: The example from the unix world is gettext, but I bet you're looking for something a little more modern.
At the bottom of it, you have to structure your string-consuming code to use members to read what strings to handle/print/etc, eg, this.mainForm.Title = StringLib.MainFormTitle.
StringLib would be just a big static class with a ton of get/set properties.
Then, create separate assemblies for each language you wish to support, name them something like langpack.en-US.dll, langpack.it-IT.dll, etc. Each would contain two classes - one class that you would instantiate to get metadata about the language pack (culture, version, etc) and another class, that when so invoked, filles in your StringLib class's static properties.
At run-time, look for all langpack files, then use reflection to load them. Use reflection to figure out the name of the lang pack, present those in a list for the user to select from. The user selects a langpack, at which point you invoke the initializer class in the lang pack. The initializer makes a ton of calls to init the StringLib class's properties, and off you go.
In MainApp.csproj:
public class StringLib {
    public static string MainFormTitle { get; set; }
    ...
}

In langpack.en-US.csproj:
public class LangPackDescriptor : ILangPackDescriptor {
    public readonly string LangPackName = "American English";
    public readonly string CultureString = "en-US";
    ...
}

public class EnUsLangPackInit : ILangPackInit {
    public void Init() {
        StringLib.MainFormTitle = "My Application Name"
        ...
    }
}

In langpack.it-IT.csproj
public class LangPackDescriptor : ILangPackDescriptor {
    public static string LangPackName = "Italian";
    public string string CultureString = "it-IT";
    ...
}

public class ItItLangPackInit : ILangPackInit{
    public void Init() {
        StringLib.MainFormTitle = "Il Nome Del Mio Applicazione"
        ...
    }
}

Using reflection to initalize, given a filename:
public void LoadLang(string filename) {
   Assembly langpackAssembly;
   ILangPackDescriptor descriptor;
   ILangPackInit initializer;

   langpackAssembly = Assembly.LoadFrom(filename);

   Type[] langpackTypes = langpackAssembly.GetExportedTypes();

   foreach( Type foundType in langpackTypes ) {
        if ( foundType.GetInterfaces().Contains<Type>( typeof(ILangPackDescriptor) ) ) {
            descriptor = Activator.CreateInstance(foundType);
        }

        if ( foundType.GetInterfaces().Contains<Type>( typeof(ILangPackInit) ) ) {
            initializer = Activator.CreateInstance(foundType);
        }
   }

   // If the passed-in file was the langpack.en-US.dll file, then this
   // calls langpack.en-US.dll's EnUsLangPackInit.Init() method.
   initializer.Init();
}


text:
Q: Why does 8250 UART driver not wake up TTY if more than 256 characters are pending? What is the motivation of this if-condition in void serial8250_tx_chars(struct uart_8250_port *up)?
if (uart_circ_chars_pending(xmit) < WAKEUP_CHARS)
    uart_write_wakeup(port);

It has been there ever since Linux 1.1.13 (May 1994) and repeats in most UART drivers.
Background: customized Linux 3.4.91, embedded system on ARMv7, UART port 0 is configured for 38400 baud, 16 byte FIFO for i/o. None of this can be changed in our setup.
When printf-ing very heavily on the console via UART, the internal 4kB-buffer (UART_XMIT_SIZE) fills up and then stalls the user-space process until the buffer is emptied (which takes one second at 38400 baud!). Then this behavior repeats. This is because function n_tty_write() goes to sleep when the buffer is full, and is not woken up for a long time because of the questionable condition above.
I would find it more natural and efficient if this check was simply removed. Then the printfs would fill up the buffer as quickly as they can, and then continue at the speed at which the buffer is being emptied, rather than the burst-processing I am observing.
It works fine in my environment but surely I am missing or misunderstanding something. There must be a reason for the current implementation. Are there any side effects if I remove that condition?
As a side-question: are there configuration options to tune this behavior, e.g. to have printf always return immediately and discard the output if the buffer is full?

A: It's an efficiency measure.  The CPU runs so much faster than the serial port that if the kernel let the userspace process run every time there was a little bit of room in the buffer, it would end up making a trip to userspace and back for every single byte of data.  That's very wasteful of CPU time:
$ time dd if=/dev/zero of=/dev/null bs=1 count=10000000
10000000+0 records in
10000000+0 records out
10000000 bytes (10 MB, 9.5 MiB) copied, 5.95145 s, 1.7 MB/s

real    0m5.954s
user    0m1.960s
sys     0m3.992s

$ time dd if=/dev/zero of=/dev/null bs=1000 count=10000
10000+0 records in
10000+0 records out
10000000 bytes (10 MB, 9.5 MiB) copied, 0.011041 s, 906 MB/s

real    0m0.014s
user    0m0.000s
sys     0m0.012s

The above test isn't even reading and writing a real device: the whole time difference is how often the system is bouncing between userspace and kernelspace.
If userspace doesn't want to be held up, it can use non-blocking I/O, or it can check use a select() call to see if there's room to write to the device... and if there's not, it can dump the remainder into a buffer of its own and continue processing.  Admittedly, that does complicate things, since now you have a buffer that you have to flush... but if you're using stdio, that's generally true anyway.


text:
Q: Exception with bulk insert with remote sql server I am calling a rest full service which in turn performs bulk insert in sql server database. Every thing works fine when rest server and the database server are on same machine, but in case of remote database sever following exception is encoutered.
System.InvalidOperationException: The transaction associated with the current
connection has completed but has not been disposed.
The transaction must be disposed before the connection can be used to
execute SQL statements.

I am using following transactions.
TransactionOptions tOptions = new TransactionOptions();
tOptions.IsolationLevel = IsolationLevel.ReadCommitted;
//This transaction is required here as it checks for all db operations.
using (var transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew, tOptions))
{
    //DB operations....
    transactionScope.Complete();
}

A: Configuring the windows MSDTC service on my IIS server did the trick.
The following link shows how to configure MSDTC.
http://www.deepakkapoor.net/turn-on-msdtc-windows-7/


text:
Q: Unit tests for Spring JsonView I started working with Spring MVC recently so I may be missing something obvious.
I am using the Spring MVC JsonView view and I would like to unit test the json that's being returned by the controller to make sure that all data is serialized correctly.
Is there any way to do this? If I test my model in the controller, this is before serialization so that doesn't really help me for this particular case.
Thank you

A: Test whether the controller returns the correct data. The serialization mechanism is part of spring/jackson, and has been already tested there.


text:
Q: reading multiple tabs from excel in different dataframes I am trying to read multiple tabs in spreadsheet to different dataframes and once all tabs with data are over the program should stop.
For first part I am looking to do something like
xls = pd.ExcelFile('Unique.xlsx')
for i in range(1,n): # n should be number of tabs with data
 try:
    df_Sector(i)=xls.parse('Sheet'+i) # df_Sector(i) has to be dataframe
 except:
    pass

I want the program to stop once all tabs with data are read

A: This will read all sheets and make a dictionary of dataframes:
xl = pd.read_excel('Unique.xlsx', sheet_name=None)

To get specific sheets, you could do:
xl_dict = {}
sheetname_list = ['blah1', 'blah2', 'blah3']
for sheet in sheetname_list:
    xl_dict[sheet] = pd.read_excel('Unique.xlsx', sheet_name=sheet)

or:
xl = pd.read_excel('Unique.xlsx', sheet_name=sheetname_list)

A: USE sheet_name=None TO PARSE ALL SHEET!
Approach answered by this answer is faster compared to make ExcelFile first.
Benchmark:
%%timeit
dfs = pd.read_excel(path, sheet_name=None)
# 279 ms ± 20.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit
xl = pd.ExcelFile(path)
dfs = {sh:xl.parse(sh) for sh in xl.sheet_names}
# 335 ms ± 40.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

A: Demo:
file name
In [94]: fn = r'D:\temp\.data\test.xlsx'

creating pandas.io.excel.ExcelFile object
In [95]: xl = pd.ExcelFile(fn)

it has sheet_names attribute
In [96]: xl.sheet_names
Out[96]: ['Sheet1', 'aaa']

we can use it for looping through sheets
In [98]: for sh in xl.sheet_names:
    ...:     df = xl.parse(sh)
    ...:     print('Processing: [{}] ...'.format(sh))
    ...:     print(df.head())
    ...:
Processing: [Sheet1] ...
   col1  col2  col3
0    11    12    13
1    21    22    23
2    31    32    33
Processing: [aaa] ...
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

a bit more elegant way is to generate a dictionary of DataFrames:
In [100]: dfs = {sh:xl.parse(sh) for sh in xl.sheet_names}

In [101]: dfs.keys()
Out[101]: dict_keys(['Sheet1', 'aaa'])

In [102]: dfs['Sheet1']
Out[102]:
   col1  col2  col3
0    11    12    13
1    21    22    23
2    31    32    33

In [103]: dfs['aaa']
Out[103]:
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9


text:
Q: JavaScript only targets first element on page I have the following script which I am trying to target any link with a class of .button to add a  tag around the text element. For example:
Read More

Becomes
Read More

My script:
// insert span into anchor
"use strict";

var anchor = document.querySelector(".button");
var html = anchor.innerHTML;

anchor.innerHTML = "" + html + "";

This works, but only on the first instance of the page?

A: You should loop through all the elements using the ALL selector querySelectorAll() like :
var anchors = document.querySelectorAll(".button");

for( var i=0;i<anchors.length;i++){
     anchors[i].innerHTML = "" + anchors[i].innerHTML + "";
}

var anchors = document.querySelectorAll(".button");

for (var i = 0; i < anchors.length; i++) {
  anchors[i].innerHTML = "" + anchors[i].innerHTML + "";
}

console.log(document.body.innerHTML);
<button class='button'>Read More</button>

<button class='button'>Read More</button>

<button class='button'>Read More</button>

A: querySelector() returns only the first matched element. To get all the elements from the page you have to use querySelectorAll(). Then loop through all the element for the change to make:

"use strict";

var anchor = document.querySelectorAll(".button");
anchor.forEach(function(a){
  a.innerHTML = "" + a.textContent + "";
});
span{
  color: green;
}
Home

About Us

Read More


text:
Q: failure occurred in gateway sendAndReceive using int-sftp:outbound-gateway I was able to login into SFTP location using a Bitvise SFTP access client tool with just userid and pswd.
So, I am trying to use int-sftp:outbound-gateway  and access an SFTP location by using the userid and pswd but not with any key file and getting the below error.  My question is : Can we access the SFTP location only with ID, Pswd thru an application?
WARNING: failure occurred in gateway sendAndReceive
Throwable occurred: org.springframework.integration.MessageHandlingException: error occurred in message handler [org.springframework.integration.sftp.gateway.SftpOutboundGateway#0]
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:79)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:115)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:102)
    at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:178)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:149)
    at org.springframework.integration.core.MessagingTemplate.doSend(MessagingTemplate.java:330)
    at org.springframework.integration.core.MessagingTemplate.doSendAndReceive(MessagingTemplate.java:361)
    at org.springframework.integration.core.MessagingTemplate.sendAndReceive(MessagingTemplate.java:274)
    at org.springframework.integration.core.MessagingTemplate.convertSendAndReceive(MessagingTemplate.java:315)
    at org.springframework.integration.gateway.MessagingGatewaySupport.doSendAndReceive(MessagingGatewaySupport.java:225)
    at org.springframework.integration.gateway.MessagingGatewaySupport.sendAndReceive(MessagingGatewaySupport.java:204)
    at org.springframework.integration.gateway.GatewayProxyFactoryBean.invokeGatewayMethod(GatewayProxyFactoryBean.java:323)
    at org.springframework.integration.gateway.GatewayProxyFactoryBean.doInvoke(GatewayProxyFactoryBean.java:286)
    at org.springframework.integration.gateway.GatewayProxyFactoryBean.invoke(GatewayProxyFactoryBean.java:277)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at $Proxy10.lsGetAndRmFiles(Unknown Source)
    at com.farmers.csi.batchutil.service.CopyOfSchedulerServiceImplDup.main(CopyOfSchedulerServiceImplDup.java:93)
Caused by: java.lang.IllegalStateException: failed to create SFTP Session
    at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:321)
    at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:293)


text:
Q: I can hear myself through my headphones I bought a wireless headset yesterday, and I tested it on Windows, it worked alright. Then I went to Linux, connected the headset, and noticed I could hear myself. I've tried looking at alsamixer to see what could be disabled, but nothing seems to change, and in pavucontrol it all seems to be alright too.
What could be going wrong?

A: Some headsets (especially Turtle Beach) have the mic hard-wired to the headset speakers as a feature so that you know when your mic is hot/on. I've experienced the level feedback of this changing (becoming louder/softer) when connecting to different devices.
It's been noted that this is called sidetone.


text:
Q: Imageview element disappers on selecting the link I have a XML file with a imageview as follows. It also has a TextView anmed "linksend".
<ImageView
    android:id="@+id/imgview1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    />

I have a Java file as as follows
ImageView imageView=(ImageView)rootView.findViewById(R.id.imgview1);
URL url;
url = new URL(someurlforimage);
Bitmap bmp;
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);

TextView tv=(TextView)rootView.findViewById(R.id.linksend);
tv.append(Html.fromHtml("" +"Press link"+""));
tv.setMovementMethod(LinkMovementMethod.getInstance());

The image disappears from the imageview when the html link is pressed. Though the html page opens in a separate browser, the app's image becomes empty.


text:
Q: kubernetes CRISocket information upload fails with node not found I am using the following kubeadmin config with external etcd setup for HA kubernetes setup following https://kubernetes.io/docs/setup/independent/high-availability/#external-etcd-nodes in bare metal server with centos7.
etcd version - v3.2.26
kind: ClusterConfiguration
kubernetesVersion: v1.13.1
apiServer:
  certSANs:
  - "k8-master01.loc.prov.domain.tld"
controlPlaneEndpoint: "k8-master01.loc.prov.domain.tld:8080"
etcd:
    external:
        endpoints:
        - https://k8-master01.loc.prov.domain.tld:2379
        - https://k8-master02.loc.prov.domain.tld:2379
        - https://k8-master03.loc.prov.domain.tld:2379
        caFile: /etc/kubernetes/pki/etcd/ca.crt
        certFile: /etc/kubernetes/pki/apiserver-etcd-client.crt
        keyFile: /etc/kubernetes/pki/apiserver-etcd-client.key

However init keeps failing at following step:

I0204 15:04:24.985393  142883 uploadconfig.go:133] [upload-config] Preserving the CRISocket information for the control-plane node
[patchnode] Uploading the CRI Socket information "/var/run/dockershim.sock" to the Node API object "k8-master01.loc.prov.domain.tld" as an annotation
I0204 15:04:25.485719  142883 round_trippers.go:419] curl -k -v -XGET  -H "User-Agent: kubeadm/v1.13.1 (linux/amd64) kubernetes/eec55b9" -H "Accept: application/json, */*" 'https://k8-master01.loc.prov.domain.tld:8080/api/v1/nodes/k8-master01.loc.prov.domain.tld'
I0204 15:04:25.488810  142883 round_trippers.go:438] GET https://k8-master01.loc.prov.domain.tld:8080/api/v1/nodes/k8-master01.loc.prov.domain.tld 404 Not Found in 3 milliseconds

It keeps retrying and then eventually times out.

error execution phase upload-config/kubelet: Error writing Crisocket information for the control-plane node: timed out waiting for the condition

( Hostname has been fuzzed in above log )
Any suggestions as to how we can proceed?

A: As Anshu Prateek mentioned in the comments:

We resolved the issue. The SSL termination for haproxy was messed up and it was causing failures in certain cases only.


text:
Q: Parker-like loop of order 2187? The Parker loop has order $2^{13}$, and reducing it modulo its 'center' yields -- not just a $12$-dimensional $\mathbb{Z} /(2)$-vector space, but one which can be naturally identified with the subspace of $(\mathbb{Z} /(2))^{24}$ which is the extended $24$-bit Golay code.
Analogous to the extended $24$-bit Golay code is the $12$-coordinate extended ternary Golay code, which is a $6$-dimensional subspace of $(\mathbb{Z} /(3))^{12}$. Is there likewise a known analogue of the Parker loop which has order $3^{7}$ and which may be likewise identified with the extended ternary Golay code once it quotiented by its center? (And, if no such thing is known, is it because it has been proven not to exist?)

A: Parker's loop can be viewed as a special case of Griess's construction of code loops for doubly even binary codes ("Code loops", J. Algebra 100 (1986), 224-234, http://deepblue.lib.umich.edu/bitstream/2027.42/26195/1/0000274.pdf).  Over $F_p$ with $p$ odd, things are more subtle, but there are some constructions.
For example, see "Local subgroups of the Monster and odd code loops" by Thomas Richardson (Trans. AMS 247 (1995), 1453-1531, http://www.ams.org/journals/tran/1995-347-05/S0002-9947-1995-1266532-4/S0002-9947-1995-1266532-4.pdf).  His construction gives a loop of order $3^7$ corresponding to the ternary Golay code.
The analogy may not be perfect: for example, the loop Richardson constructs has a slightly bigger center than one might guess.  However, these odd code loops seem to be useful for some of the same sort of things as Parker's loop is.  I don't know whether there is an even closer analogue (it's not clear to me which properties are really essential).

A: To follow up on Henry Cohn's answer, see also:
A. Drapal and P. Vojtechovsky,
Code loops in both parities,
Journal of Algebraic Combinatorics 31 (2010), no. 4, 585-611.