问:
how to change date format in ionic 3
this i my code. i want to change the date format. it showing  Fri Feb 14 2020 00:00:00 GMT+0530 (India Standard Time) this format but i want 14-02-2020. how to get this. please help me guys.

.html file

```<code>  <ion-item>
    <ion-label>From date {{selectedDate}} </ion-label>
  </ion-item>

  <ionic-calendar-date-picker (onSelect)="dateSelected($event)"
  [(ngModel)]="selectedDate" ngDefaultControl displayFormat="DD-MM-YYYY"></ionic-calendar-date-picker>

  <ion-item>
    <ion-label>To date {{selectedDate1}} </ion-label>
  </ion-item>

  <ionic-calendar-date-picker displayFormat="DD/MM/YYYY" (onSelect)="dateSelected1($event)"
  [(ngModel)]="selectedDate1" ngDefaultControl displayFormat="DD-MM-YYYY"></ionic-calendar-date-picker>

</ion-content>
</code>```

.ts file

dateSelected($event)

{

```<code>this.selectedDate=$event;

// moment().format('DD-MM-YYYY')

//  this.dateSelected(moment().format('DD/MM/YYYY'));

 alert($event);
</code>```

}

dateSelected1($event)

{

```<code>this.selectedDate1=$event;

 moment().format('DD-MM-YYYY');

 alert($event);
</code>```

}

答:
You need to do as mentioned below:

```<code>    const formattedDate = moment(this.selectedDate1).format('DD-MM-YYYY');
    console.log(formattedDate);
</code>```

This will print the formatted date as "19-02-2020"

Title: how to change date format in ionic 3

Body:
this i my code. i want to change the date format. it showing  Fri Feb 14 2020 00:00:00 GMT+0530 (India Standard Time) this format but i want 14-02-2020. how to get this. please help me guys.

.html file

  <ion-item>
    <ion-label>From date {{selectedDate}} </ion-label>
  </ion-item>

  <ionic-calendar-date-picker (onSelect)="dateSelected($event)"
  [(ngModel)]="selectedDate" ngDefaultControl displayFormat="DD-MM-YYYY"></ionic-calendar-date-picker>

  <ion-item>
    <ion-label>To date {{selectedDate1}} </ion-label>
  </ion-item>

  <ionic-calendar-date-picker displayFormat="DD/MM/YYYY" (onSelect)="dateSelected1($event)"
  [(ngModel)]="selectedDate1" ngDefaultControl displayFormat="DD-MM-YYYY"></ionic-calendar-date-picker>

</ion-content>

.ts file

dateSelected($event)

{

this.selectedDate=$event;

// moment().format('DD-MM-YYYY')

//  this.dateSelected(moment().format('DD/MM/YYYY'));

 alert($event);

}

dateSelected1($event)

{

this.selectedDate1=$event;

 moment().format('DD-MM-YYYY');

 alert($event);

}

Body:
You need to do as mentioned below:

    const formattedDate = moment(this.selectedDate1).format('DD-MM-YYYY');
    console.log(formattedDate);

This will print the formatted date as "19-02-2020"


来源: stackexchange

问:
How can I give access of var/www/html to another user using AWS?
Stackoverflow community,
I have to add another user in the AWS ec2 user account and also want to give the permission of /var/www/html in FileZilla / WinSCP using AWS ec2 user. I have created the user as well as the AWS user policy but it is giving the access of/in FileZilla / WinSCP. Can anyone let me know how can I solve this issue by permitting /var/www/html to a specific user?

答:
I cannot totally get what are you requiring. But I think this would be a pure Linux permission problem, not an AWS problem.
For changing the permission of a folder in AMZ Linux, you could do it just like that you can assign the permission to a single user or a group in other universal Linux version with chmod command.

Here are some sample snippets for your reference:

```<code>sudo chmod [the_new_user_you_created] 755 -R /var/www/html

sudo chown -R ec2-user:apache /var/www
</code>```

For the best practice, you could find the recommendation for initializing a web server in AWS from this official link:
To set file permissions for the Apache web server

ContentLicense: CC BY-SA 4.0

Body:
I cannot totally get what are you requiring. But I think this would be a pure Linux permission problem, not an AWS problem.
For changing the permission of a folder in AMZ Linux, you could do it just like that you can assign the permission to a single user or a group in other universal Linux version with chmod command.

Here are some sample snippets for your reference:

sudo chmod [the_new_user_you_created] 755 -R /var/www/html

sudo chown -R ec2-user:apache /var/www

For the best practice, you could find the recommendation for initializing a web server in AWS from this official link:
To set file permissions for the Apache web server


问:
Icon disappears from taskbar when changing window
I am trying to create a CRUD application where it has several windows. List customer, register customer, delete customer, edit customer.
For this I am trying to switch from window to another window, the problem is that when I switch the window the icon in the taskbar disappears. I must be doing it wrong. I am used to web applications, this is my first desktop application.

Taskbar icon:

Pseudo code:

I've tried QStackedWidget but setting pages from the index doesn't look good when you have a lot of pages.

I updated my question using QMainWindow, I did not use QWindow because it does not support setLayout, for example.

import sys
import time
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QMainWindow, QDialog, QApplication, QDesktopWidget, QGridLayout, QLabel, QWidget

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = 'Main Window'
        self.top = 100
        self.left = 100
        self.width = 350
        self.height = 200
        self.InitUI()
        self.show()

    def InitUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.width, self.height)

        qtRectangle = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())

        layout = QGridLayout()

        label1 = QLabel('First Screen - Please wait...')
        label1.setFont(QFont("Times", 25, QFont.Bold))
        layout.addWidget(label1, 0, 0, Qt.AlignCenter)

        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        QTimer.singleShot(5000, self.goToSecondScreen)

    def goToSecondScreen(self):
        w = SecondWindow(parent=self)
        w.show()
        self.hide()

class SecondWindow(QMainWindow):
    def __init__(self, parent):
        super().__init__(parent=parent)
        self.title = 'Second Window'
        self.top = 100
        self.left = 100
        self.width = 680
        self.height = 500
        self.InitUI()
        self.show()

    def InitUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.width, self.height)

        qtRectangle = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())

        layout = QGridLayout()

        label1 = QLabel('Second Screen - Please wait...')
        label1.setFont(QFont("Times", 25, QFont.Bold))
        layout.addWidget(label1, 0, 0, Qt.AlignCenter)

        self.setLayout(layout)

        QTimer.singleShot(5000, self.goToThirdWindow)

    def goToThirdWindow(self):
        w = ThirdWindow(parent=self)
        w.show()
        self.hide()

class ThirdWindow(QMainWindow):
    def __init__(self, parent):
        super().__init__(parent=parent)
        self.title = 'Third Window'
        self.top = 100
        self.left = 100
        self.width = 680
        self.height = 500
        self.InitUI()
        self.show()

    def InitUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.width, self.height)

        qtRectangle = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())

        layout = QGridLayout()

        label1 = QLabel('ThirdWindow Screen')
        label1.setFont(QFont("Times", 25, QFont.Bold))
        layout.addWidget(label1, 0, 0, Qt.AlignCenter)

        self.setLayout(layout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MainWindow()
    sys.exit(app.exec_())
```

答: as I've tested your code I saw that the taskbar cannot be found because you are creating QDialog instances, not a window, try creating an instance of a window instead not a QDialog instance</p>


问:
I'm working on react project.And I got errors like
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! enlite_starter@1.3.1 build: cross-env NODE_ENV=production webpack --config internals/webpack/webpack.prod.babel.js --color -p --progress --hide-modules --display-optimization-bailout
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the enlite_starter@1.3.1 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Swetha\AppData\Roaming\npm-cache_logs\2020-02-19T06_52_25_635Z-debug.log

答:
npm ERR! code ELIFECYCLE

Check out my answer to this question. It might help you out.


问:
msfconsole pop-out an error : Bundler faild to load , cannot load such file -- bundler/setup
So l installed parrot OS on my PC hard drive ,
after that l updated hole system and tried to run MSFCONSOLE .
After l execute that command l get this error :

```<code>Bundler failed to load and return this error:

cannot load such file -- bundler/setup

you may need to uninstall or upgrade bundler
</code>```

After this l uninstall bundler and install it again it didn't work .

l tried to upgrade it as well but it said that all packages are up to date .

Also l ran gem install bundler
it successfully installed bundler and 1 gem but after that it pops-out same message after l ran msfconsole

Is it the right way to fix this..?

答:
Open the Terminal and run the following commands:

cd /usr/share/metasploit-framework.

Upgrade your bundler/setup : gem install bundler.

Install bundle: bundle install.

gem update --system.

Restart Metasploit.

Body:
So l installed parrot OS on my PC hard drive ,
after that l updated hole system and tried to run MSFCONSOLE .
After l execute that command l get this error :

Bundler failed to load and return this error:

cannot load such file -- bundler/setup

you may need to uninstall or upgrade bundler

After this l uninstall bundler and install it again it didn't work .

l tried to upgrade it as well but it said that all packages are up to date .

Also l ran gem install bundler
it successfully installed bundler and 1 gem but after that it pops-out same message after l ran msfconsole

Is it the right way to fix this..?


问:
Starlette + asyncio.create_task() doesn't log error if task object is stored in instance variable
Okay, this is very weird, but here goes -

import asyncio

from starlette.applications import Starlette

class MyTasks:
    def __init__(self):
        self.task = None

    async def main(self):
        self.task = asyncio.create_task(self.hello())

    async def hello(self):
        raise ValueError

async def main():
    await MyTasks().main()

app = Starlette(on_startup=[main])
```

<hr>

```$ uvicorn test:app
INFO:     Started server process [26622]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```

<p>Hmm, no <code>ValueError</code> here...</p>

<hr>

<p>Now, remove the assignment to <code>self.task</code> in <code>MyTasks.main()</code>.</p>

<pre class="lang-py prettyprint-override"><code>    async def main(self):
        asyncio.create_task(self.hello())
    ...
</code>```

```<code>$ uvicorn test:app
INFO:     Started server process [29083]
INFO:     Waiting for application startup.
ERROR:    Task exception was never retrieved
future: <Task finished name='Task-3' coro=<MyTasks.hello() done, defined at ./test.py:13> exception=ValueError()>
Traceback (most recent call last):
  File "./test.py", line 14, in hello
    raise ValueError
ValueError
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
</code>```

... And voila.

What's going on here? How does that assignment make or break the exception logging!?

答:
A task is a subclass of future, which means that it has the concept of a result. In case of a task, the result is the value returned by the coroutine it drives. If the coroutine raises an exception, then the exception is encapsulated in the task object. Correctly written code is expected to eventually either await the task or access its result, in order for exceptions not to pass silently.

To help debug code that forgets to access the task, task's destructor logs an error if the task raised an exception but was never awaited. This error cannot be logged before running the destructor because as long as your code holds on to the task object, it might conceivable await it at any point. The point when the destructor runs is the first instance when Python can reliably "prove" that the task is unawaited.

But this last-ditch logging is not something you should rely on, it's provided on a best-effort basis. For example, running the destructor can be postponed due to GC. I expect that assigning the task to an instance whose bound method is being driven by the task makes the task part of a reference cycle. This postpones running the destructor until a full GC, and you don't see the log.

To fix the problem, you should either catch the exceptions in your coroutine and log them yourself instead of allowing them to propagate, or actually await the task at some point in your code.

Body:
Okay, this is very weird, but here goes -

import asyncio

from starlette.applications import Starlette

class MyTasks:
    def __init__(self):
        self.task = None

    async def main(self):
        self.task = asyncio.create_task(self.hello())

    async def hello(self):
        raise ValueError

async def main():
    await MyTasks().main()

app = Starlette(on_startup=[main])

$ uvicorn test:app
INFO:     Started server process [26622]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

Hmm, no ValueError here...

Now, remove the assignment to self.task in MyTasks.main().

    async def main(self):
        asyncio.create_task(self.hello())
    ...

$ uvicorn test:app
INFO:     Started server process [29083]
INFO:     Waiting for application startup.
ERROR:    Task exception was never retrieved
future: <Task finished name='Task-3' coro=<MyTasks.hello() done, defined at ./test.py:13> exception=ValueError()>
Traceback (most recent call last):
  File "./test.py", line 14, in hello
    raise ValueError
ValueError
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

... And voila.

What's going on here? How does that assignment make or break the exception logging!?


问:
What is the right way to get an NSString object from an NSArray, keeping Memory Managment in mind?
What is the right way to get an NSString object from an NSArray,  keeping Memory Managment in mind.

Suppose I have an array

```<code>NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];
</code>```

Now I want to get an object from this NSArray at index 2.

```<code>NSString *nameString = [myNewArray objectAtIndex:2]; // is it the right way? how to deal with "nameString"
                                                     // now regarding memory managment, should I release it ?
</code>```

OR I should first alloc nameString and then assign value to it ?

答:
I think you don't totally get the "pointer" concept yet. Your variable nameString is just a pointer. Not a string.

In the line :

```<code>NSString *nameString = [myNewArray objectAtIndex:2];
</code>```

You just assign the pointer to the actual memory address of the second object of the array. That's all.

If you are about to keep this object alive (even if the array will be deallocted), you better retain that object.

ContentLicense: CC BY-SA 3.0

Body:
What is the right way to get an NSString object from an NSArray,  keeping Memory Managment in mind.

Suppose I have an array

NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];

Now I want to get an object from this NSArray at index 2.

NSString *nameString = [myNewArray objectAtIndex:2]; // is it the right way? how to deal with "nameString"
                                                     // now regarding memory managment, should I release it ?

OR I should first alloc nameString and then assign value to it ?

Body:
I think you don't totally get the "pointer" concept yet. Your variable nameString is just a pointer. Not a string.

In the line :

NSString *nameString = [myNewArray objectAtIndex:2];

You just assign the pointer to the actual memory address of the second object of the array. That's all.

If you are about to keep this object alive (even if the array will be deallocted), you better retain that object.


问:
Some beginner questions about elf files, sections headers and how they work in general when we run an application
I'm learning about the elf file. I read some stuff on it and I'm starting to understand very very little about it however something is puzzeling me. I want to continue learning it and mastering it but first I want to make sure I got the most simple things right. I will state what I know below please correct me where I'm making a mistake.

When you write a C application and you compile it(say with gcc) it gets translated into machine instructions which represent code and data.
The output of invoking the compiler is an elf file.
The elf file contains(among other things) a section header which is basically a series of Elf64_Shdr each for every section your compiled application contains.
So basically a section is just some machine instructions which represent either code or data and some info about it like where it(address of first instruction) is and how long it is(size), whether it is writable or readable(some flags), etc. Is my understanding of sections and section header correct?

When we run the make command and pass it the elf file the linker comes into play and looks at all sections created by the compiler, at their names and attributes and groups them into 'segments' following the rules of a ld script file and creates the executable file which we can run So basically segments are nothing more than sections of same attributes grouped togheter in a common section with a specific name. Is this correct?

Then when we actually run the created executable the loader comes into play and looks at these segments created by the linker and by reading this information which they contain it maps the machine instructions to various memory locations so the process can run. This is what is called(in my understanding) a memory image. Is this correct?

Thank you for reading and helping me clear my doubts thank you.

答:
There are multiple inaccuracies in your description, and it's unclear whether you are imprecise in understanding the processing involved, or in describing them.

When you write a C application and you compile it(say with gcc) it gets translated into machine instructions which represent code and data.

This isn't entirely accurate: there is a difference between "machine instructions" and "machine code".

When you compile a .c file, some compilers will translate it into machine instructions (assembly), and then pass it to assembler to produce machine code (GCC does that). Other compilers have integrated assembler, and effectively skip the assembly generation step (Clang does that).

The output of invoking the compiler is an elf file.

On some but not all systems, the result of compilation is a relocatable ELF file. Other systems produce object files in a different format, such as XCOFF or Mach-O.

The elf file contains(among other things) a section header which is basically a series of Elf64_Shdr each for every section your compiled application contains.

The application is not built yet, so this is inaccurate. Also, Elf64_Shdr only applies to 64-bit ELF platforms; on 32-bit machines it's Elf32_Ehdr.

When we run the make command

The make command has nothing to do with anything. It just invokes compiler and linker (or other tools) as appropriate. You can replace it with a shell script, or just type the commands by hand.

and pass it the elf file

The link step involves one or more (usually more) relocatable ELF object files, archive libraries and dynamic libraries.

the linker comes into play and looks at all sections created by the compiler, at their names and attributes and groups them into 'segments' following the rules of a ld script file

To understand what the linker does you can read this series of blog posts.

Your description trivializes what the linker does. The linker is much more complicated, and performs relocation resolution which you didn't mention, and many other tasks.

and creates the executable file which we can run.

Usually true.

You can ask linker to combine several relocatable object files into a combined object file (with ld -r foo.o bar.o -o combined.o), and in that case the result will not be an executable file.

You can also ask the linker to link a shared library instead of linking an executable.

So basically segments are nothing more than sections of same attributes grouped togheter in a common section with a specific name.

False. There is lot more to linking than grouping sections together.

Then when we actually run the created executable the loader comes into play

The loader only comes into play for dynamically-linked executables. Fully-static executables do not have a loader, and are started directly by the kernel itself.

and looks at these segments created by the linker and by reading this information which they contain it maps the machine instructions to various memory locations so the process can run. This is what is called(in my understanding) a memory image.

Mostly correct. Some parts of the memory image do not come from disk at all (e.g. thread-local storage and contents of combined .bss sections)


问:
Thunderbird Webextensions .messages.getFull() raises Exception 0x80004005 (NS_ERROR_FAILURE)
This is a kind of follow-up of the following question/answer:
https://stackoverflow.com/a/60246205/6342243

The code at the end of this question gets a list of accounts, selects the emailAccountName, gets a MessageList object from the wantedMailFolderType and tries to get a MessagePart object from just one single messageId via browser.messages.getFull( messageId ) which always fails with the following Exception message:

```<code>[Exception...
"Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)
[nsIMsgMessageService.streamMessage]"
nsresult: "0x80004005 (NS_ERROR_FAILURE)"
location: "JS frame :: resource:///modules/gloda/mimemsg.js
                    :: MsgHdrToMimeMessage
                    :: line 238"  data: no]
                       mimemsg.js:238:16
</code>```

This behaviour is the same on linux mint 19.3 (64-Bit) running thunderbird 68.4.1 (64-Bit)
as well as on windows 7 (64-Bit) running thunderbird 68.2.2 (32-Bit).

Here the code which reproduces the error:

```<code>emailAccountName     = "firstname.lastname@email.com";
wantedMailFolderType = "trash";

console.log( tstamp() + " Entered Main Program" );
function tstamp () {
    let d =new Date();
    return "" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();
}

function accountsList_successCallback( arrayOfMailAccount ) {
    console.log( tstamp() + " Entered accountsList_successCallback()" );
    let accountId = false;
    for (let i = 0; i < arrayOfMailAccount.length; i++) {
    if ( arrayOfMailAccount[i].name == emailAccountName ) {
        accountId  = arrayOfMailAccount[i].id;
        break;
        }
    }
    console.log( tstamp() + " Leaving accountsList_successCallback(), returning accountId: " + accountId );
    return accountId;
}
function mailAccount_successCallback( mailAccount ) {
    console.log( tstamp() + " Entered mailAccount_successCallback()" );
    let mailFolder = false;
    for (let i = 0; i < mailAccount.folders.length; i++) {
    if ( mailAccount.folders[i].type == wantedMailFolderType ) {
        mailFolder = mailAccount.folders[i];
        break;
        }
    }
    console.log( tstamp() + " Leaving mailAccount_successCallback(), returning mailFolder: " + mailFolder.type );
    return mailFolder;
}
async function getMessagesList( mailFolder ) {
    console.log( tstamp() + " Entered getMessagesList()" );
    let page = await browser.messages.list( mailFolder );
    let messageHeader = page.messages[ 0 ];
    let messageId     = messageHeader.id;
    console.log( `Trying to .getFull( messageId == ${messageId} ) MessagePart object now...` );
    let messagePart = await browser.messages.getFull( messageId );
    console.log( tstamp() + " Leaving getMessagesList()" );
}

browser.accounts.list()
    .then( accountsList_successCallback)  // after .accounts.list() Promise is fulfilled...
                                          // accountsList_successCallback is called, which
                                          // in this example returns the accountId string...
    .then( accountId => browser.accounts.get( accountId ))
    .then( mailAccount_successCallback)   // after .accounts.get() Promise is fulfilled...
                                          // mailAccount_successCallback is called, which
                                          // returns the wanted MailFolder...
    .then( getMessagesList )              // ... passed to getMessagesList(), which successfully
                                          // awaits a MessageList object...
                                          // but every call to .getFull( messageId ) fails.
    .catch( finalCatch )
;

function finalCatch( error ) {
    console.error( "ERROR passed to finalCatch() : " + error);
}

console.log( tstamp() + " Leaving Main Program" );

</code>```

This was the output of the last run (line-numbers in popup.js xx-ed out, because they do not match with this extract):

```<code>52:40.859 Entered Main Program                                                   popup.js:xx:9
52:40.874 Leaving Main Program                                                   popup.js:xx:9
52:40.964 Entered accountsList_successCallback()                                 popup.js:xx:13
52:40.964 Leaving accountsList_successCallback(), returning accountId: account26 popup.js:xx:13
52:40.988 Entered mailAccount_successCallback()                                  popup.js:xx:13
52:40.989 Leaving mailAccount_successCallback(), returning mailFolder: trash     popup.js:xx:13
52:40.989 Entered getMessagesList()                                              popup.js:xx:13
Trying to .getFull( messageId == 1 ) MessagePart object now...                   popup.js:xx:13
[Exception...
 "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)
 [nsIMsgMessageService.streamMessage]"
  nsresult: "0x80004005 (NS_ERROR_FAILURE)"
  location: "JS frame :: resource:///modules/gloda/mimemsg.js
                      :: MsgHdrToMimeMessage
                      :: line 238"  data: no]
                         mimemsg.js:238:16
ERROR passed to finalCatch() : Error: An unexpected error occurred               popup.js:xx:13
</code>```

Could anyone please try this out on his machine?
How to proceed further?
Should a bug on BugZilla be reportet?

Thanks in advance. richard

答:
The problem is solved!

The exception was raised as long as and only while there was another login to the same IMAP-Account on another PC active.
It seems that as long as there is more than one login or session simultaneously to the same Email-Account, the exception is raised.

Sorry for disturbing.

Thank you very much for your attention. richard

Body:
This is a kind of follow-up of the following question/answer:
https://stackoverflow.com/a/60246205/6342243

The code at the end of this question gets a list of accounts, selects the emailAccountName, gets a MessageList object from the wantedMailFolderType and tries to get a MessagePart object from just one single messageId via browser.messages.getFull( messageId ) which always fails with the following Exception message:

[Exception...
"Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)
[nsIMsgMessageService.streamMessage]"
nsresult: "0x80004005 (NS_ERROR_FAILURE)"
location: "JS frame :: resource:///modules/gloda/mimemsg.js
                    :: MsgHdrToMimeMessage
                    :: line 238"  data: no]
                       mimemsg.js:238:16

This behaviour is the same on linux mint 19.3 (64-Bit) running thunderbird 68.4.1 (64-Bit)
as well as on windows 7 (64-Bit) running thunderbird 68.2.2 (32-Bit).

Here the code which reproduces the error:

emailAccountName     = "firstname.lastname@email.com";
wantedMailFolderType = "trash";

console.log( tstamp() + " Entered Main Program" );
function tstamp () {
    let d =new Date();
    return "" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds();
}

function accountsList_successCallback( arrayOfMailAccount ) {
    console.log( tstamp() + " Entered accountsList_successCallback()" );
    let accountId = false;
    for (let i = 0; i < arrayOfMailAccount.length; i++) {
    if ( arrayOfMailAccount[i].name == emailAccountName ) {
        accountId  = arrayOfMailAccount[i].id;
        break;
        }
    }
    console.log( tstamp() + " Leaving accountsList_successCallback(), returning accountId: " + accountId );
    return accountId;
}
function mailAccount_successCallback( mailAccount ) {
    console.log( tstamp() + " Entered mailAccount_successCallback()" );
    let mailFolder = false;
    for (let i = 0; i < mailAccount.folders.length; i++) {
    if ( mailAccount.folders[i].type == wantedMailFolderType ) {
        mailFolder = mailAccount.folders[i];
        break;
        }
    }
    console.log( tstamp() + " Leaving mailAccount_successCallback(), returning mailFolder: " + mailFolder.type );
    return mailFolder;
}
async function getMessagesList( mailFolder ) {
    console.log( tstamp() + " Entered getMessagesList()" );
    let page = await browser.messages.list( mailFolder );
    let messageHeader = page.messages[ 0 ];
    let messageId     = messageHeader.id;
    console.log( `Trying to .getFull( messageId == ${messageId} ) MessagePart object now...` );
    let messagePart = await browser.messages.getFull( messageId );
    console.log( tstamp() + " Leaving getMessagesList()" );
}

browser.accounts.list()
    .then( accountsList_successCallback)  // after .accounts.list() Promise is fulfilled...
                                          // accountsList_successCallback is called, which
                                          // in this example returns the accountId string...
    .then( accountId => browser.accounts.get( accountId ))
    .then( mailAccount_successCallback)   // after .accounts.get() Promise is fulfilled...
                                          // mailAccount_successCallback is called, which
                                          // returns the wanted MailFolder...
    .then( getMessagesList )              // ... passed to getMessagesList(), which successfully
                                          // awaits a MessageList object...
                                          // but every call to .getFull( messageId ) fails.
    .catch( finalCatch )
;

function finalCatch( error ) {
    console.error( "ERROR passed to finalCatch() : " + error);
}

console.log( tstamp() + " Leaving Main Program" );

This was the output of the last run (line-numbers in popup.js xx-ed out, because they do not match with this extract):

52:40.859 Entered Main Program                                                   popup.js:xx:9
52:40.874 Leaving Main Program                                                   popup.js:xx:9
52:40.964 Entered accountsList_successCallback()                                 popup.js:xx:13
52:40.964 Leaving accountsList_successCallback(), returning accountId: account26 popup.js:xx:13
52:40.988 Entered mailAccount_successCallback()                                  popup.js:xx:13
52:40.989 Leaving mailAccount_successCallback(), returning mailFolder: trash     popup.js:xx:13
52:40.989 Entered getMessagesList()                                              popup.js:xx:13
Trying to .getFull( messageId == 1 ) MessagePart object now...                   popup.js:xx:13
[Exception...
 "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)
 [nsIMsgMessageService.streamMessage]"
  nsresult: "0x80004005 (NS_ERROR_FAILURE)"
  location: "JS frame :: resource:///modules/gloda/mimemsg.js
                      :: MsgHdrToMimeMessage
                      :: line 238"  data: no]
                         mimemsg.js:238:16
ERROR passed to finalCatch() : Error: An unexpected error occurred               popup.js:xx:13

Could anyone please try this out on his machine?
How to proceed further?
Should a bug on BugZilla be reportet?

Thanks in advance. richard


问:
OAuthException using Instagram Display API
Getting an error when calling a POST at this endoint. https://api.instagram.com/oauth/authorize

This is the request body:

```<code>{
    "client_id": "62022....13674",
    "client_secret": "081f5d8d8d0.....cfbe88d8df1bf1",
    "grant_type": "authorization_code",
    "redirect_uri": "https://mystifying-khorana-f72562.netlify.com/",
    "code": "AQA6nvV5uJ1PEblnIy2lEx0e6IMc6rOAmnW0Rx6_nVHwQn1IYUp85hRd2rbB9K-BC0877g5Djhy9QjqqD-ImRFPwz0HJDgNEOwD4w5qltzNGYQyoFQd7ttyS9E1E61JdsFduGLXzTU2b8X8vICd_KaJDXeFL9drc8uickz3yy-UaziuKLbExqcMfeEubRcwVnPQFwyLQUnQgcljgXyvV5eeGADgVZYXvZ7Lb7REtyOXReA"
}
</code>```

This is the error that gets returned:

```<code>{
    "error_type": "OAuthException",
    "code": 400,
    "error_message": "Invalid platform app"
}
</code>```

It may be something simple but I cannot figure out what is wrong. I followed the getting started piece line by line.
https://developers.facebook.com/docs/instagram-basic-display-api/getting-started

答: You are POSTing to the wrong URL. You need to send that request to: https://api.instagram.com/oauth/access_token to exchange the code for an access token.

Body:
Getting an error when calling a POST at this endoint. https://api.instagram.com/oauth/authorize

This is the request body:

{
    "client_id": "62022....13674",
    "client_secret": "081f5d8d8d0.....cfbe88d8df1bf1",
    "grant_type": "authorization_code",
    "redirect_uri": "https://mystifying-khorana-f72562.netlify.com/",
    "code": "AQA6nvV5uJ1PEblnIy2lEx0e6IMc6rOAmnW0Rx6_nVHwQn1IYUp85hRd2rbB9K-BC0877g5Djhy9QjqqD-ImRFPwz0HJDgNEOwD4w5qltzNGYQyoFQd7ttyS9E1E61JdsFduGLXzTU2b8X8vICd_KaJDXeFL9drc8uickz3yy-UaziuKLbExqcMfeEubRcwVnPQFwyLQUnQgcljgXyvV5eeGADgVZYXvZ7Lb7REtyOXReA"
}

This is the error that gets returned:

{
    "error_type": "OAuthException",
    "code": 400,
    "error_message": "Invalid platform app"
}

It may be something simple but I cannot figure out what is wrong. I followed the getting started piece line by line.
https://developers.facebook.com/docs/instagram-basic-display-api/getting-started


问:
Setting an element's focus only if user has tabbed to it
I am trying to make some collapsible accordion containers on my website accessible, but I am running into an issue.

The accordions are controlled by link elements on the page - this way, a keyboard-only user can tab to them and access them. The first issue I ran into was that if a user tabbed to one of the links, the page wouldn't always scroll up to show them which one they had tabbed to. I fixed this issue setting the focus using the following code, which scrolls the link to the top of the viewport:

```<code>$(".accordion .accordion-item .accordion-heading a").focus(
    function()
    {
        $('html:not(:animated), body:not(:animated)').animate({
            scrollTop: $(this).offset().top
        }, 250);
    }
    );
</code>```

The problem I am encountering now is that when a mouse-user clicks on the link, it jumps to the top of the page and does not open the container unless the mouse-user clicks the link again.

Is there a way I can set the focus code above to only fire if the link has been tabbed to? Or, is there a better way of handling the focus issue so that it works for both keyboard-only and mouse users?

Thanks!

答:
Firstly a quick apology, having now seen your accordion is built correctly, links with in-page anchors are actually preferable if the accordion is constructed using javascript on page load and falls back to just a list of in page anchor links and content between them.

I am that used to seeing href="#"> on accordion openers and weird accordion implementations I jumped to conclusions, change it back from <buttons>!

Fixing your problem

Probably not the answer you are looking for but remove the .focus() function entirely.

It produces strange behaviour where if I have one accordion item open and i tab back with Alt + Tab quickly scrolling can be really confusing as it jumps around if you tab quicker than the scroll.

One of the golden rules of accessibility is to only adjusted the scroll position on a page if it is expected (i.e. a return to top button or using in-page anchors).

In the example and on your website once I disabled the 'scroll to top on focus' the site actually behaved as expected.

I understand why you did it as occasionally a link that is focused appears off the page, however this remedies itself when you tab again or by scrolling down (your site is logical so that if I tab and my focus is not visible I know it is off the page.)

This tends to happen (items not scrolling into view) when the item is just out of sight, by a px or two, it is common and ironically now falls into 'expected' behaviour (another rule, follow accepted and expected behaviour when designing components and pages).

If you really want to fix it

In your focus function instead of just scrolling to the top of the page whenever an item is focused, check if it is off the page.

Below is an example function I found (not tested) that you can use to check if the item is in the viewport, if it is then don't do anything, if it isn't then do your scroll function.

```<code>var isInViewport = function (elem) {
    var bounding = elem.getBoundingClientRect();
    return (
        bounding.top >= 0 &&
        bounding.left >= 0 &&
        bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
};
</code>```

So roughly (yet again haven't tested that the correct items are passed in, this is just to give you an idea).

```<code>$(".accordion .accordion-item .accordion-heading a").focus(
    function()
    {
        if(isInViewport(this) === false){
             //item is not in the viewport so scroll it into view
            $('html:not(:animated), body:not(:animated)').animate({
                scrollTop: $(this).offset().top //I would perhaps add a couple of hundred pixels here to make the item appear in a more natural area.
            }, 250); //remove the animation as a further accessibility improvement, animations can be off putting to people with motion or anxiety disorders.
        }
    }
);
</code>```

This fixes your problem as no mouse user will ever be able to click an item that is off the page so they won't ever trigger the scroll event that causes the focus issue.

Body:
I am trying to make some collapsible accordion containers on my website accessible, but I am running into an issue.

The accordions are controlled by link elements on the page - this way, a keyboard-only user can tab to them and access them. The first issue I ran into was that if a user tabbed to one of the links, the page wouldn't always scroll up to show them which one they had tabbed to. I fixed this issue setting the focus using the following code, which scrolls the link to the top of the viewport:

$(".accordion .accordion-item .accordion-heading a").focus(
    function()
    {
        $('html:not(:animated), body:not(:animated)').animate({
            scrollTop: $(this).offset().top
        }, 250);
    }
    );

The problem I am encountering now is that when a mouse-user clicks on the link, it jumps to the top of the page and does not open the container unless the mouse-user clicks the link again.

Is there a way I can set the focus code above to only fire if the link has been tabbed to? Or, is there a better way of handling the focus issue so that it works for both keyboard-only and mouse users?

Thanks!

Body:
Firstly a quick apology, having now seen your accordion is built correctly, links with in-page anchors are actually preferable if the accordion is constructed using javascript on page load and falls back to just a list of in page anchor links and content between them.

I am that used to seeing <a href="#"> on accordion openers and weird accordion implementations I jumped to conclusions, change it back from <buttons>!

Fixing your problem

Probably not the answer you are looking for but remove the .focus() function entirely.

It produces strange behaviour where if I have one accordion item open and i tab back with Alt + Tab quickly scrolling can be really confusing as it jumps around if you tab quicker than the scroll.

One of the golden rules of accessibility is to only adjusted the scroll position on a page if it is expected (i.e. a return to top button or using in-page anchors).

In the example and on your website once I disabled the 'scroll to top on focus' the site actually behaved as expected.

I understand why you did it as occasionally a link that is focused appears off the page, however this remedies itself when you tab again or by scrolling down (your site is logical so that if I tab and my focus is not visible I know it is off the page.)

This tends to happen (items not scrolling into view) when the item is just out of sight, by a px or two, it is common and ironically now falls into 'expected' behaviour (another rule, follow accepted and expected behaviour when designing components and pages).

If you really want to fix it

In your focus function instead of just scrolling to the top of the page whenever an item is focused, check if it is off the page.

Below is an example function I found (not tested) that you can use to check if the item is in the viewport, if it is then don't do anything, if it isn't then do your scroll function.

var isInViewport = function (elem) {
    var bounding = elem.getBoundingClientRect();
    return (
        bounding.top >= 0 &&
        bounding.left >= 0 &&
        bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
};

So roughly (yet again haven't tested that the correct items are passed in, this is just to give you an idea).

$(".accordion .accordion-item .accordion-heading a").focus(
    function()
    {
        if(isInViewport(this) === false){
             //item is not in the viewport so scroll it into view
            $('html:not(:animated), body:not(:animated)').animate({
                scrollTop: $(this).offset().top //I would perhaps add a couple of hundred pixels here to make the item appear in a more natural area.
            }, 250); //remove the animation as a further accessibility improvement, animations can be off putting to people with motion or anxiety disorders.
        }
    }
);

This fixes your problem as no mouse user will ever be able to click an item that is off the page so they won't ever trigger the scroll event that causes the focus issue.


问:
How do I get statistics on Azure Devops usage?
I am currently administering a project on DevOps and wish to verify how many users are using the platform actively.

I want the following information -

```<code>        1. Unique visitors per month
        2. All visits per month
        3. All visits by roles
</code>```

答:
Based on my opinion, all of those what you want could be achieved by audit log.

Beside the api that Daniel mentioned, we offered a direct download button to download those data. Just select the time period and download them with CSV/JSON format:

Here, I suggest you download with CSV because it is convenient to apply data filter in it.

Unique visitors per month

This could be get from the last row: ActorDisplayName.

All visits by roles

This can be achieved by combined with Users list files. In users page, we also offered a button to download user lists as .csv file.

Just combine the data of auditlog.csv and users.csv, then you will get the statistics on visiting by roles.

All visits per month

Not sure what the exactly visit you mentioned. But I think you could get most of you want from auditlog.csv, because we stored the access ip, user agent, and detailed operations.

You may think above is not friendly for viewing. So I recommend analyze those statics with Power BI. It can help create histograms, pie charts or line charts and etc, which are very awesome to analyze the data.

Body:
I am currently administering a project on DevOps and wish to verify how many users are using the platform actively.

I want the following information -

        1. Unique visitors per month
        2. All visits per month
        3. All visits by roles


问:
variable expected when trying to change value of a variable
I'm a student learning java and for this code I'm writing for a homework assignment, cant use ternary operators or any if/switch statments, or add a variable and need to change the value of one of my vairables to one from 0

its a toggle method so needs to change from 0 and 1 when called

```<code>firstSwitchState = firstSwitchState + firstSwitchState % 2 = 0;
</code>```

答:
If you wish to toggle firstSwitchState from 0 to 1 or from 1 to 0, use XOR:

```<code>firstSwitchState = firstSwitchState ^ 1;
</code>```

or

```<code>firstSwitchState ^= 1;
</code>```

If the original value is 1, it will become 0.

If the original value is 0, it will become 1.

Body:
I'm a student learning java and for this code I'm writing for a homework assignment, cant use ternary operators or any if/switch statments, or add a variable and need to change the value of one of my vairables to one from 0

its a toggle method so needs to change from 0 and 1 when called

firstSwitchState = firstSwitchState + firstSwitchState % 2 = 0;

Body:
If you wish to toggle firstSwitchState from 0 to 1 or from 1 to 0, use XOR:

firstSwitchState = firstSwitchState ^ 1;

or

firstSwitchState ^= 1;

If the original value is 1, it will become 0.

If the original value is 0, it will become 1.


问:
Getting error when running npm start for reactjs in ec2
I was trying to deploy my node and react app on AWS ec2, node app working fine, but react app giving error on npm run build

Tried npm start also, but still getting the same error.
Here is the error

Tried set NODE_OPTIONS=--max_old_space_size=8172 to increase the memory, but error remains same

```<code>Security context: 0x0f19d05408a1 <JSObject>
    2: visitQueue [0x581c2dbffa1] [/home/ubuntu/expert-erp/source/node_modules/@babel/traverse/lib/context.js:~96] [pc=0x302cbe090747](this=0x2c145b2a5559 <TraversalContext map = 0x32c1b0aaf1e1>,0x2c145b2a55a1 <JSArray[1]>)
    3: visitMultiple [0x581c2dbbd11] [/home/ubuntu/expert-erp/source/node_modules/@babel/traverse/lib/contex...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

Writing Node.js report to file: report.20191008.111057.11400.0.001.json
Node.js report completed
 1: 0x9d33e0 node::Abort() [node]
 2: 0x9d4596 node::OnFatalError(char const*, char const*) [node]
 3: 0xb32dbe v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node]
 4: 0xb33139 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node]
 5: 0xcde455  [node]
 6: 0xcdeae6 v8::internal::Heap::RecomputeLimits(v8::internal::GarbageCollector) [node]
 7: 0xcea97a v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [node]
 8: 0xceb885 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]
 9: 0xcee298 v8::internal::Heap::AllocateRawWithRetryOrFail(int, v8::internal::AllocationType, v8::internal::AllocationAlignment) [node]
10: 0xcb4bc7 v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType) [node]
11: 0xfeaafb v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [node]
12: 0x136d539  [node]
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! Expert-Board@0.0.1 build: `react-scripts build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the Expert-Board@0.0.1 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/ubuntu/.npm/_logs/2019-10-08T11_10_57_852Z-debug.log
</code>```

答:
The issue was not related to react-scripts space size.

It was EC2 instance size issue, after increasing the memory of instance it was running perfectly.

(Note: I was trying to run it on EC2 free tier, that comes with 8GB of SSD and 0.8GB of RAM, and it was insufficient to run two apps on the same instance. But after changing the instance to 2GB RAM, there were no issues at all.)

Body:
I was trying to deploy my node and react app on AWS ec2, node app working fine, but react app giving error on npm run build

Tried npm start also, but still getting the same error.
Here is the error

Tried set NODE_OPTIONS=--max_old_space_size=8172 to increase the memory, but error remains same

Security context: 0x0f19d05408a1 <JSObject>
    2: visitQueue [0x581c2dbffa1] [/home/ubuntu/expert-erp/source/node_modules/@babel/traverse/lib/context.js:~96] [pc=0x302cbe090747](this=0x2c145b2a5559 <TraversalContext map = 0x32c1b0aaf1e1>,0x2c145b2a55a1 <JSArray[1]>)
    3: visitMultiple [0x581c2dbbd11] [/home/ubuntu/expert-erp/source/node_modules/@babel/traverse/lib/contex...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

Writing Node.js report to file: report.20191008.111057.11400.0.001.json
Node.js report completed
 1: 0x9d33e0 node::Abort() [node]
 2: 0x9d4596 node::OnFatalError(char const*, char const*) [node]
 3: 0xb32dbe v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node]
 4: 0xb33139 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node]
 5: 0xcde455  [node]
 6: 0xcdeae6 v8::internal::Heap::RecomputeLimits(v8::internal::GarbageCollector) [node]
 7: 0xcea97a v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [node]
 8: 0xceb885 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]
 9: 0xcee298 v8::internal::Heap::AllocateRawWithRetryOrFail(int, v8::internal::AllocationType, v8::internal::AllocationAlignment) [node]
10: 0xcb4bc7 v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType) [node]
11: 0xfeaafb v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [node]
12: 0x136d539  [node]
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! Expert-Board@0.0.1 build: `react-scripts build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the Expert-Board@0.0.1 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/ubuntu/.npm/_logs/2019-10-08T11_10_57_852Z-debug.log


问:
Cannot find setter for attribute app:visibleGone
I am trying to implement the MVVM architecture in my android application. I'm using Kotlin for the same.

This is my binding adapter class:

```<code>class BindingAdapter {
    companion object {
        @JvmStatic @BindingAdapter("app:visibleGone") fun showHide(view: View, show: Boolean) {
            view.visibility =
                    if (show)
                        View.VISIBLE
                    else
                        View.GONE
        }
    }
}
</code>```

Here is my XML file:

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
                name="isLoading"
                type="boolean"/>
    </data>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/cardview_light_background"
            android:orientation="vertical">

        <TextView
                android:id="@+id/loading_rates"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center_vertical|center_horizontal"
                android:text="@string/loading_rates"
                android:textAlignment="center"
                app:visibleGone="@{isLoading}"/>

        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/cardview_light_background"
                android:orientation="vertical"
                app:visibleGone="@{!isLoading}">

            <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"
                    android:layout_marginTop="20dp"
                    android:gravity="center_horizontal"
                    android:text="@string/rate_list"
                    android:textAlignment="center"
                    android:textSize="@dimen/rate_text"
                    android:textStyle="bold"/>

            <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rate_list"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    app:layoutManager="LinearLayoutManager"/>

        </LinearLayout>

    </LinearLayout>
</layout>
</code>```

The error message says:

```<code>Found data binding errors.
****/ data binding error ****msg:Cannot find the setter for attribute 'app:visibleGone' with parameter type boolean on android.widget.TextView. file:/home/sparker0i/CurrencyConverter/app/src/main/res/layout/fragment_rate_list.xml loc:23:35 - 23:43 ****\ data binding error ****
</code>```

Line 23 resolves to the loading_rates TextView's line just above the app:visibleGone statement

I'm not able to understand that despite setting the BindingAdapter inside my Kotlin class, why am I not able to compile the code succesfully?

答:
Before you try any complex solution, just verify that you have applied the following plugin in you app.gradle

```<code>apply plugin: 'kotlin-kapt'
</code>```

If that is missing, it will keep giving errors. I found that missing from mine, after 8 hours of tussle and reading other SOF posts.
It worked.

Adding picture for reference:

Body:
I am trying to implement the MVVM architecture in my android application. I'm using Kotlin for the same.

This is my binding adapter class:

class BindingAdapter {
    companion object {
        @JvmStatic @BindingAdapter("app:visibleGone") fun showHide(view: View, show: Boolean) {
            view.visibility =
                    if (show)
                        View.VISIBLE
                    else
                        View.GONE
        }
    }
}

Here is my XML file:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
                name="isLoading"
                type="boolean"/>
    </data>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/cardview_light_background"
            android:orientation="vertical">

        <TextView
                android:id="@+id/loading_rates"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center_vertical|center_horizontal"
                android:text="@string/loading_rates"
                android:textAlignment="center"
                app:visibleGone="@{isLoading}"/>

        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/cardview_light_background"
                android:orientation="vertical"
                app:visibleGone="@{!isLoading}">

            <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"
                    android:layout_marginTop="20dp"
                    android:gravity="center_horizontal"
                    android:text="@string/rate_list"
                    android:textAlignment="center"
                    android:textSize="@dimen/rate_text"
                    android:textStyle="bold"/>

            <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rate_list"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    app:layoutManager="LinearLayoutManager"/>

        </LinearLayout>

    </LinearLayout>
</layout>

The error message says:

Found data binding errors.
****/ data binding error ****msg:Cannot find the setter for attribute 'app:visibleGone' with parameter type boolean on android.widget.TextView. file:/home/sparker0i/CurrencyConverter/app/src/main/res/layout/fragment_rate_list.xml loc:23:35 - 23:43 ****\ data binding error ****

Line 23 resolves to the loading_rates TextView's line just above the app:visibleGone statement

I'm not able to understand that despite setting the BindingAdapter inside my Kotlin class, why am I not able to compile the code succesfully?

Body:
Before you try any complex solution, just verify that you have applied the following plugin in you app.gradle

apply plugin: 'kotlin-kapt'

If that is missing, it will keep giving errors. I found that missing from mine, after 8 hours of tussle and reading other SOF posts.
It worked.

Adding picture for reference:


问:
Fail to add new record on nHibernate many to one mapping
```<code>String or binary data would be truncated.
The statement has been terminated.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: String or binary data would be truncated.
The statement has been terminated.

Source Error:
Line 33:             ITransaction tx = session.BeginTransaction();
Line 34:             session.SaveOrUpdate(productX);
Line 35:             tx.Commit();
Line 36:         }
Line 37:

Source File: ProductService.cs    Line: 35

Stack Trace:
[SqlException (0x80131904): String or binary data would be truncated.
The statement has been terminated.]

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Aquamate.DataObjects.Core" assembly="Aquamate.DataObjects.Core">
    <class name="Product" table="revProduct">
        <id name="Pid" >
            <generator class="guid.comb" />
        </id>
        <many-to-one name="ProductCategory" class="Category" lazy="proxy">
            <column name="Catid" not-null="true" />
        </many-to-one>
        <property name="NameEng" not-null="true" />
        <property name="NameTch" not-null="true" />
        <property name="Status" not-null="true" />
        <property name="Sort" not-null="true" />
    </class>
</hibernate-mapping>
</code>```

答:
What this error usually means is that you are trying to insert a value to a database column where the size of the data is bigger than what is defined for the column.

Check the size defined in the database for all the mapped properties and compare it with the data you are trying to insert.

NHIbernate Profiler can be your best friend here


问:
The response received in AJAX call is shown in another HTML page
I have ajax request call which sends an ID to the server, then the server sends a JSON response. I want to update the innerHTML of the pre tag using the value in that JSON Response.

Form HTML

```<code><form id="AssociateForm" class="form form-inline" style="float:right" action="{% url 'Project:MyView' TR.id %}" method="POST" target="_blank">
    <div class="form-group">
        <input type="text" name="JIRA_ID" style="width:150px" placeholder="ID" class="form-control has-success" id="{{TR.id}}">
        <button name="button" type="submit" id='Submit_{{TR.id}}' class="btn btn-primary">Associate</button>
    </div>
</form>
</code>```

AJAX

```<code><script>
    $("#AssociateForm").submit(function(e) {
        e.preventDefault();

        var form = $(this);
        var url = form.attr('action');

        var local_id = $('input[name=J_ID]').attr('id');

        var formData = {
            'J_ID' : $('input[name=J_ID]').val()
        };
        console.log(formData)

        $.ajax({
            url: url,
            data: formData,
            dataType: 'json',

            success: function (datas) {
                var data = JSON.parse(datas);
                if(datas.status){
                    alert(datas);
                   //$('#Failure_'+local_id).innerHTML = data.category + ' issue: '+data.j_id +' ('+data.j_status+')'
                }
            },
            error: function(jqXHR, textStatus){
                alert("In error")
            }
        })
        .done(function(data){
            alert(data)
        });
    });
</script>
</code>```

for some reason, the above code is not printing the console log as well.

But,

When the response comes, the success section is not triggered. Instead, the complete JSON string is printed on a different page.

JSON Response

{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}

below is from View-Page-source

```<code><html>
   <head></head>
   <body data-gr-c-s-loaded="true">
     <pre style="word-wrap: break-word; white-space: pre-wrap;">

        {"category": "known", "j_id": "AU298", "j_status": "Confirmed"}

     ```

```

答:
This is possibly because you are submitting a form, and after submitting it will open a new tab, as Form is submitted.
To resolve this, you can probably use the below code:</p>

```<code><form action="..." method="POST" target="_blank">
<input type="submit" id="btn-form-submit"/>
</form>
<script>
 $('#btn-submit').click( function(){ $('#btn-form-submit').click(); } );
</script>
</code>```

Body:
I have ajax request call which sends an ID to the server, then the server sends a JSON response. I want to update the innerHTML of the pre tag using the value in that JSON Response.

Form HTML

<form id="AssociateForm" class="form form-inline" style="float:right" action="{% url 'Project:MyView' TR.id %}" method="POST" target="_blank">

        <input type="text" name="JIRA_ID" style="width:150px" placeholder="ID" class="form-control has-success" id="{{TR.id}}">
        <button name="button" type="submit" id='Submit_{{TR.id}}' class="btn btn-primary">Associate</button>

</form>

AJAX

for some reason, the above code is not printing the console log as well.

But,

When the response comes, the success section is not triggered. Instead, the complete JSON string is printed on a different page.

JSON Response

{"category": "known", "j_id": "AU298", "j_status": "Confirmed"}

below is from View-Page-source

        {"category": "known", "j_id": "AU298", "j_status": "Confirmed"}

Body:
This is possibly because you are submitting a form, and after submitting it will open a new tab, as Form is submitted.
To resolve this, you can probably use the below code:

<form action="..." method="POST" target="_blank">
<input type="submit" id="btn-form-submit"/>
</form>
<script>
 $('#btn-submit').click( function(){ $('#btn-form-submit').click(); } );
</script>


问:
How to convert string to File object in javascript ?
I am trying to convert string to File object in javascript but I get an error.

my code:

```<code> var contents = fs.readFileSync('./dmv_file_reader.txt').toString()

 var  readerfile1 = new File([""], contents);
</code>```

(i have to use contents as file and not as string)

and my output is :

```<code>ReferenceError: File is not defined
    at d:\Workspace\DMV\dist\win-ia32-unpacked\resources\app.asar\main.js:67:32
    at process._tickCallback (internal/process/next_tick.js:103:7)
</code>```

any solution some1?

答:
First you have to create blob from Javascript object and that blob object can be passed to File() constructor to create a File Object.Hope this helps.</p>

```<code> var contents = fs.readFileSync('./dmv_file_reader.txt').toString()
 var blob = new Blob([contents], { type: 'text/plain' });
 var file = new File([blob], "foo.txt", {type: "text/plain"});
</code>```

Body:
I am trying to convert string to File object in javascript but I get an error.

my code:

 var contents = fs.readFileSync('./dmv_file_reader.txt').toString()

 var  readerfile1 = new File([""], contents);

(i have to use contents as file and not as string)

and my output is :

ReferenceError: File is not defined
    at d:\Workspace\DMV\dist\win-ia32-unpacked\resources\app.asar\main.js:67:32
    at process._tickCallback (internal/process/next_tick.js:103:7)

any solution some1?

Body:
First you have to create blob from Javascript object and that blob object can be passed to File() constructor to create a File Object.Hope this helps.

 var contents = fs.readFileSync('./dmv_file_reader.txt').toString()
 var blob = new Blob([contents], { type: 'text/plain' });
 var file = new File([blob], "foo.txt", {type: "text/plain"});


问:
Not able to successfully run an Azure Function which contains code to Upload Video to YouTube
I am basically creating an HTTP Trigger Azure function, which has the code to upload a video to YouTube using the YouTube API. The code was pretty much provided by the YouTubeAPI docs: https://developers.google.com/youtube/v3/docs/videos/insert. I re-formatted the code a bit to fit it into the Azure function.

However, when I try to run the function locally on my Visual Studio, I get an 500 error saying:

Executed 'Function1' (Failed, Id=84400f0c-b6e4-4c78-bf55-30c4527a8b5f)
  System.Private.CoreLib: Exception while executing function: Function1.
  System.Private.CoreLib: Could not find file
  'C:\Users\Peter\Desktop\TestDemo\UploadVideo\UploadVideo\bin\Debug\netcoreapp2.1\client_secrets.json'.

I am not sure how to fix this error and to make the function run without any errors. Is there anything that needs to be added/changed in the code (below) to fix this issue?

My goal: my ultimate goal is to trigger this azure function whenever there is a new video added into the Azure Blob Storage.

Code

```<code>using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Upload;
using Google.Apis.YouTube.v3.Data;
using System.Reflection;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Threading;

namespace UploadVideo
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            log.LogInformation("YouTube Data API: Upload Video");
            log.LogInformation("==============================");

            try
            {
                await Run();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    log.LogInformation("Error: " + e.Message);
                }
            }

            return new OkObjectResult($"Video Processed..");

        }

        private static async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = @"C:\Users\Peter\Desktop\audio\test.mp4"; // Replace with path to actual movie file.

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }

        private static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                    break;
            }
        }

        private static void videosInsertRequest_ResponseReceived(Video video)
        {
            Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        }
    }
}
</code>```

答:
Could not find file 'C:\Users\Peter\Desktop\TestDemo\UploadVideo\UploadVideo\bin\Debug\netcoreapp2.1\client_secrets.json'.

Its looking for the "client_secrets.json" it need to be in the same directory with your code.  as you havent told it to look any where else

```<code>using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
        {
</code>```

Note

GoogleWebAuthorizationBroker.AuthorizeAsync is only designed for use with installed applications its going to open the web browser on the server and prompt a user to authenticate the code.

correct me if im wrong but azure functions dont have a ui endpoint where you can prompt a user for authentication.  which would mean that the only thing you could use would be a service account and the YouTube api doesn't support service
accounts.

Body:
I am basically creating an HTTP Trigger Azure function, which has the code to upload a video to YouTube using the YouTube API. The code was pretty much provided by the YouTubeAPI docs: https://developers.google.com/youtube/v3/docs/videos/insert. I re-formatted the code a bit to fit it into the Azure function.

However, when I try to run the function locally on my Visual Studio, I get an 500 error saying:

Executed 'Function1' (Failed, Id=84400f0c-b6e4-4c78-bf55-30c4527a8b5f)
  System.Private.CoreLib: Exception while executing function: Function1.
  System.Private.CoreLib: Could not find file
  'C:\Users\Peter\Desktop\TestDemo\UploadVideo\UploadVideo\bin\Debug\netcoreapp2.1\client_secrets.json'.

I am not sure how to fix this error and to make the function run without any errors. Is there anything that needs to be added/changed in the code (below) to fix this issue?

My goal: my ultimate goal is to trigger this azure function whenever there is a new video added into the Azure Blob Storage.

Code

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Upload;
using Google.Apis.YouTube.v3.Data;
using System.Reflection;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Threading;

namespace UploadVideo
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            log.LogInformation("YouTube Data API: Upload Video");
            log.LogInformation("==============================");

            try
            {
                await Run();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    log.LogInformation("Error: " + e.Message);
                }
            }

            return new OkObjectResult($"Video Processed..");

        }

        private static async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = @"C:\Users\Peter\Desktop\audio\test.mp4"; // Replace with path to actual movie file.

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }

        private static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                    break;
            }
        }

        private static void videosInsertRequest_ResponseReceived(Video video)
        {
            Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        }
    }
}

Body:
Could not find file 'C:\Users\Peter\Desktop\TestDemo\UploadVideo\UploadVideo\bin\Debug\netcoreapp2.1\client_secrets.json'.

Its looking for the "client_secrets.json" it need to be in the same directory with your code.  as you havent told it to look any where else

using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
        {

Note

GoogleWebAuthorizationBroker.AuthorizeAsync is only designed for use with installed applications its going to open the web browser on the server and prompt a user to authenticate the code.

correct me if im wrong but azure functions dont have a ui endpoint where you can prompt a user for authentication.  which would mean that the only thing you could use would be a service account and the YouTube api doesn't support service
accounts.


问:
AWS Instance Connect with a resource tag condition
I am trying to limit ssh access to ec2 instances by using a resource tag condition in my instance connect policy. So basically I have something like that:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Action": "ec2-instance-connect:SendSSHPublicKey",
        "Resource": "arn:aws:ec2:*:*:instance/*",,
        "Condition": {
            "StringEquals": {"ec2:ResourceTag/Squad": "blah"}
        }
      },
      {
        "Effect": "Allow",
        "Action": "ec2:DescribeInstances",
        "Resource": "*"
      }
    ]
}
</code>```

However, that seems it doesn't work. Isn't instance connect able to use the ec2:ResourceTag condition? I have seen it working with a condition like ec2:osuser, so I am wondering if there is a limitation or I'm doing something wrong.

答: I think IAM policy not able to limitation ssh access. I'm not sure but I haven't hear anyone IAM policy for limitation SSH. I think it's must be setup into your EC2 instance.</p>

Body:
I am trying to limit ssh access to ec2 instances by using a resource tag condition in my instance connect policy. So basically I have something like that:

{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Action": "ec2-instance-connect:SendSSHPublicKey",
        "Resource": "arn:aws:ec2:*:*:instance/*",,
        "Condition": {
            "StringEquals": {"ec2:ResourceTag/Squad": "blah"}
        }
      },
      {
        "Effect": "Allow",
        "Action": "ec2:DescribeInstances",
        "Resource": "*"
      }
    ]
}

However, that seems it doesn't work. Isn't instance connect able to use the ec2:ResourceTag condition? I have seen it working with a condition like ec2:osuser, so I am wondering if there is a limitation or I'm doing something wrong.


问:
how to change date format in ionic 3
this i my code. i want to change the date format. it showing  Fri Feb 14 2020 00:00:00 GMT+0530 (India Standard Time) this format but i want 14-02-2020. how to get this. please help me guys.

.html file

```<code>  <ion-item>
    <ion-label>From date {{selectedDate}} </ion-label>
  </ion-item>

  <ionic-calendar-date-picker (onSelect)="dateSelected($event)"
  [(ngModel)]="selectedDate" ngDefaultControl displayFormat="DD-MM-YYYY"></ionic-calendar-date-picker>

  <ion-item>
    <ion-label>To date {{selectedDate1}} </ion-label>
  </ion-item>

  <ionic-calendar-date-picker displayFormat="DD/MM/YYYY" (onSelect)="dateSelected1($event)"
  [(ngModel)]="selectedDate1" ngDefaultControl displayFormat="DD-MM-YYYY"></ionic-calendar-date-picker>

</ion-content>
</code>```

.ts file

dateSelected($event)

{

```<code>this.selectedDate=$event;

// moment().format('DD-MM-YYYY')

//  this.dateSelected(moment().format('DD/MM/YYYY'));

 alert($event);
</code>```

}

dateSelected1($event)

{

```<code>this.selectedDate1=$event;

 moment().format('DD-MM-YYYY');

 alert($event);
</code>```

}

答:
You can try this.

```

Title: how to change date format in ionic 3

Body:
this i my code. i want to change the date format. it showing  Fri Feb 14 2020 00:00:00 GMT+0530 (India Standard Time) this format but i want 14-02-2020. how to get this. please help me guys.

.html file

  <ion-item>
    <ion-label>From date {{selectedDate}} </ion-label>
  </ion-item>

  <ionic-calendar-date-picker (onSelect)="dateSelected($event)"
  [(ngModel)]="selectedDate" ngDefaultControl displayFormat="DD-MM-YYYY"></ionic-calendar-date-picker>

  <ion-item>
    <ion-label>To date {{selectedDate1}} </ion-label>
  </ion-item>

  <ionic-calendar-date-picker displayFormat="DD/MM/YYYY" (onSelect)="dateSelected1($event)"
  [(ngModel)]="selectedDate1" ngDefaultControl displayFormat="DD-MM-YYYY"></ionic-calendar-date-picker>

</ion-content>

.ts file

dateSelected($event)

{

this.selectedDate=$event;

// moment().format('DD-MM-YYYY')

//  this.dateSelected(moment().format('DD/MM/YYYY'));

 alert($event);

}

dateSelected1($event)

{

this.selectedDate1=$event;

 moment().format('DD-MM-YYYY');

 alert($event);

}

Body:
You can try this.

<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>
<script>
    var ds = "Fri Feb 14 2020 00:00:00 GMT+0530 (India Standard Time)";
    var date = moment(new Date(ds.substr(0, 16)));
    console.log(date.format("DD-MM-YYYY"));
</script>


问:
if statement in gridview template filed
I have a gridview. its data source is a datatable that is loaded from the database.
In this gridview, i have a template column. The content of this column is not directly pulled from the database but instead, i use the id of the current item to make a name and look for that name in a directory of images. The template field is:

```<code><asp:TemplateField>
    <itemtemplate>
        <img src='../user/images/<% =itemType %><%# DataBinder.Eval(Container.DataItem, "id") %>.jpg?'
            alt='<%# DataBinder.Eval(Container.DataItem, "Title") %>' />
    </itemtemplate>
</asp:TemplateField>
</code>```

Not all the items have images so I would like to check if this file exists. If it does, I'd like to use the above code to place it, if it doesn't i'd like to leave the field empty.
In the .cs file this is a matter of an if statement with the condition set to File.Exist(). But I could not find the syntax to do it in the .aspx file.
Is this possible and if so how?
Thanks.

答:
you could code this behavior on the RowDataBound event. somethink like the below

Remember to make the image runat="server"

```<code> protected void GridViewProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if(e.Row.RowType = DataControlRowType.DataRow){
    if(!File.Exist(yourFileName){
        //hide the image
        var img=e.Row.FindControl("theImageId");
        img.visible=false;
     }
   }
}
</code>```

I think you should go for the above solution.

anyway Just add the below

```<code><asp:TemplateField>
    <itemtemplate>
        <img src='../user/images/<% =itemType %><%# DataBinder.Eval(Container.DataItem, "id") %>.jpg?'
            alt='<%# DataBinder.Eval(Container.DataItem, "Title") %>'
    <%= File.Exists("yourFileName")? string.Empty : "style='display: none'" %> />
    </itemtemplate>
</asp:TemplateField>
</code>```

Title: if statement in gridview template filed

Body:
I have a gridview. its data source is a datatable that is loaded from the database.
In this gridview, i have a template column. The content of this column is not directly pulled from the database but instead, i use the id of the current item to make a name and look for that name in a directory of images. The template field is:

<asp:TemplateField>
    <itemtemplate>
        <img src='../user/images/<% =itemType %><%# DataBinder.Eval(Container.DataItem, "id") %>.jpg?'
            alt='<%# DataBinder.Eval(Container.DataItem, "Title") %>' />
    </itemtemplate>
</asp:TemplateField>

Not all the items have images so I would like to check if this file exists. If it does, I'd like to use the above code to place it, if it doesn't i'd like to leave the field empty.
In the .cs file this is a matter of an if statement with the condition set to File.Exist(). But I could not find the syntax to do it in the .aspx file.
Is this possible and if so how?
Thanks.

Body:
you could code this behavior on the RowDataBound event. somethink like the below

Remember to make the image runat="server"

 protected void GridViewProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if(e.Row.RowType = DataControlRowType.DataRow){
    if(!File.Exist(yourFileName){
        //hide the image
        var img=e.Row.FindControl("theImageId");
        img.visible=false;
     }
   }
}

I think you should go for the above solution.

anyway Just add the below

<asp:TemplateField>
    <itemtemplate>
        <img src='../user/images/<% =itemType %><%# DataBinder.Eval(Container.DataItem, "id") %>.jpg?'
            alt='<%# DataBinder.Eval(Container.DataItem, "Title") %>'
    <%= File.Exists("yourFileName")? string.Empty : "style='display: none'" %> />
    </itemtemplate>
</asp:TemplateField>


问:
I'm working on react project.And I got errors like
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! enlite_starter@1.3.1 build: cross-env NODE_ENV=production webpack --config internals/webpack/webpack.prod.babel.js --color -p --progress --hide-modules --display-optimization-bailout
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the enlite_starter@1.3.1 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Swetha\AppData\Roaming\npm-cache_logs\2020-02-19T06_52_25_635Z-debug.log

答:
First run

```<code>npm run clean
</code>```

Then delete the node_modules folder and run

```<code>npm install
</code>```

This seems to have solved the problem.

Or if this doesnt work try

Changing access in node_modules directory

```<code>chmod -R a+rwx ./node_modules
</code>```

idk on what system you are

Body:
First run

npm run clean

Then delete the node_modules folder and run

npm install

This seems to have solved the problem.

Or if this doesnt work try

Changing access in node_modules directory

chmod -R a+rwx ./node_modules

idk on what system you are


问:
IllegalStateException Can't change activity type once set
I can see an exception being thrown on multiple devices for which I could not find anything beside tests classes from Google using that exception's string.
Would you have any hint why this could be happening?

```<code>Fatal Exception: java.lang.IllegalStateException: Can't change activity type once set: { mBounds=Rect(0, 0 - 1080, 2076) mAppBounds=Rect(0, 0 - 1080, 2076) mWindowingMode=fullscreen mActivityType=home} activityType=standard
       at android.os.Parcel.createException(Parcel.java:1974)
       at android.os.Parcel.readException(Parcel.java:1934)
       at android.os.Parcel.readException(Parcel.java:1884)
       at android.app.IActivityManager$Stub$Proxy.startActivity(IActivityManager.java:3604)
       at android.app.Instrumentation.execStartActivity(Instrumentation.java:1669)
       at android.app.Activity.startActivityForResult(Activity.java:4688)
       at android.support.v4.app.FragmentActivity.startActivityForResult(SourceFile:767)
       at android.app.Activity.startActivityForResult(Activity.java:4646)
       at android.support.v4.app.FragmentActivity.startActivityForResult(SourceFile:754)
       at android.app.Activity.startActivity(Activity.java:5007)
       at android.app.Activity.startActivity(Activity.java:4975)
       at com.myapp.MyActivity.showAndroidHomeScreen(SourceFile:208)
       at com.myapp.MyActivity.onBackPressed(SourceFile:548)
       at android.app.Activity.onKeyUp(Activity.java:3168)
       at android.view.KeyEvent.dispatch(KeyEvent.java:3374)
       at android.app.Activity.dispatchKeyEvent(Activity.java:3451)
       at android.support.v4.app.SupportActivity.superDispatchKeyEvent(SourceFile:108)
       at android.support.v4.view.KeyEventDispatcher.dispatchKeyEvent(SourceFile:84)
       at android.support.v4.app.SupportActivity.dispatchKeyEvent(SourceFile:126)
       at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(SourceFile:535)
       at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(SourceFile:59)
       at android.support.v7.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(SourceFile:2533)
       at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:564)
       at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:6012)
       at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5867)
       at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5320)
       at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:5373)
       at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:5339)
       at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:5498)
       at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:5347)
       at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5555)
       at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5320)
       at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:5373)
       at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:5339)
       at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:5347)
       at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5320)
       at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:5373)
       at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:5339)
       at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:5531)
       at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:5700)
       at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:3407)
       at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:2854)
       at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:2845)
       at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:3384)
       at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
       at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
       at android.os.MessageQueue.next(MessageQueue.java:326)
       at android.os.Looper.loop(Looper.java:181)
       at android.app.ActivityThread.main(ActivityThread.java:6981)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

Caused by android.os.RemoteException: Remote stack trace:
    at android.app.WindowConfiguration.setActivityType(WindowConfiguration.java:366)
    at android.app.WindowConfiguration.setTo(WindowConfiguration.java:390)
    at android.content.res.Configuration.setTo(Configuration.java:1136)
    at com.android.server.wm.ConfigurationContainer.onConfigurationChanged(ConfigurationContainer.java:124)
    at com.android.server.wm.ConfigurationContainer.onParentChanged(ConfigurationContainer.java:523)
</code>```

This is the code causing the issue:

```<code> private void showAndroidHomeScreen() {
        final Intent mainScreen = new Intent(Intent.ACTION_MAIN);
        mainScreen.addCategory(Intent.CATEGORY_HOME);
        mainScreen.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        PackageManager pm = getPackageManager();
        if (pm.queryIntentActivities(mainScreen, 0).size() > 0) {
            startActivity(mainScreen);
        }
    }
</code>```

答:
It's launcher problem. Just check with different launcher
Root cause it is happening because launcher is using launchMode="singleInstance" for it's Launcher Activity. if it's your launcher then use android:launchMode="singleTask".
also try with removing

mainScreen.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)

Hope it helps.

UPDATE
updated android:launchMode="singleTask" for activity that you need yo set up for default, it will fixed your issues.
no need to use FLAG_ACTIVITY_NO_HISTORY.

Body:
I can see an exception being thrown on multiple devices for which I could not find anything beside tests classes from Google using that exception's string.
Would you have any hint why this could be happening?

Fatal Exception: java.lang.IllegalStateException: Can't change activity type once set: { mBounds=Rect(0, 0 - 1080, 2076) mAppBounds=Rect(0, 0 - 1080, 2076) mWindowingMode=fullscreen mActivityType=home} activityType=standard
       at android.os.Parcel.createException(Parcel.java:1974)
       at android.os.Parcel.readException(Parcel.java:1934)
       at android.os.Parcel.readException(Parcel.java:1884)
       at android.app.IActivityManager$Stub$Proxy.startActivity(IActivityManager.java:3604)
       at android.app.Instrumentation.execStartActivity(Instrumentation.java:1669)
       at android.app.Activity.startActivityForResult(Activity.java:4688)
       at android.support.v4.app.FragmentActivity.startActivityForResult(SourceFile:767)
       at android.app.Activity.startActivityForResult(Activity.java:4646)
       at android.support.v4.app.FragmentActivity.startActivityForResult(SourceFile:754)
       at android.app.Activity.startActivity(Activity.java:5007)
       at android.app.Activity.startActivity(Activity.java:4975)
       at com.myapp.MyActivity.showAndroidHomeScreen(SourceFile:208)
       at com.myapp.MyActivity.onBackPressed(SourceFile:548)
       at android.app.Activity.onKeyUp(Activity.java:3168)
       at android.view.KeyEvent.dispatch(KeyEvent.java:3374)
       at android.app.Activity.dispatchKeyEvent(Activity.java:3451)
       at android.support.v4.app.SupportActivity.superDispatchKeyEvent(SourceFile:108)
       at android.support.v4.view.KeyEventDispatcher.dispatchKeyEvent(SourceFile:84)
       at android.support.v4.app.SupportActivity.dispatchKeyEvent(SourceFile:126)
       at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(SourceFile:535)
       at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(SourceFile:59)
       at android.support.v7.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(SourceFile:2533)
       at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:564)
       at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:6012)
       at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5867)
       at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5320)
       at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:5373)
       at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:5339)
       at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:5498)
       at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:5347)
       at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:5555)
       at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5320)
       at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:5373)
       at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:5339)
       at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:5347)
       at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:5320)
       at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:5373)
       at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:5339)
       at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:5531)
       at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:5700)
       at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:3407)
       at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:2854)
       at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:2845)
       at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:3384)
       at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
       at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
       at android.os.MessageQueue.next(MessageQueue.java:326)
       at android.os.Looper.loop(Looper.java:181)
       at android.app.ActivityThread.main(ActivityThread.java:6981)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

Caused by android.os.RemoteException: Remote stack trace:
    at android.app.WindowConfiguration.setActivityType(WindowConfiguration.java:366)
    at android.app.WindowConfiguration.setTo(WindowConfiguration.java:390)
    at android.content.res.Configuration.setTo(Configuration.java:1136)
    at com.android.server.wm.ConfigurationContainer.onConfigurationChanged(ConfigurationContainer.java:124)
    at com.android.server.wm.ConfigurationContainer.onParentChanged(ConfigurationContainer.java:523)

This is the code causing the issue:

 private void showAndroidHomeScreen() {
        final Intent mainScreen = new Intent(Intent.ACTION_MAIN);
        mainScreen.addCategory(Intent.CATEGORY_HOME);
        mainScreen.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        PackageManager pm = getPackageManager();
        if (pm.queryIntentActivities(mainScreen, 0).size() > 0) {
            startActivity(mainScreen);
        }
    }