问:
why is mySQL missing a column?
This statement is not populating the image_path column. I have copied and pasted column names from phpMyAdmin to ensure accuracy.</p>

```<code>INSERT INTO (theme_name, theme_path, image_path)
VALUES ('',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/themes/Original/',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/thumbnails/original.png')
</code>```

答: If you omitted the table name on purpopse, check that the datatypes are correct for the columns. Check lengths of target columns are long enough to hold what you are inserting.</p>

Title: why is mySQL missing a column?

Body:
This statement is not populating the image_path column. I have copied and pasted column names from phpMyAdmin to ensure accuracy.

INSERT INTO (theme_name, theme_path, image_path)
VALUES ('',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/themes/Original/',
        '/Applications/MAMP/htdocs/waggleb/wp-content/plugins/app-switcher/thumbnails/original.png')


来源: stackexchange

问:
Connect to Flask websocket from python code
I'm interested in creating bidirectional exchange between Flask server and client. Seems that websockets are very convinient for achieving my goal. But i stucked on implementation. I've created simple Flask app with Flask-SocketIO like described in docs:

```<code>from flask_socketio import SocketIO
from flask import Flask

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@socketio.on('message')
def handle_message(message):
    print('received message: ' + message)

if __name__ == '__main__':
    socketio.run(app)
</code>```

Client uses websocket-client package and looks as follows:

```<code>from websocket import create_connection

ws = create_connection("ws://localhost:5000")
ws.send("hello world")
</code>```

In this configuration it doesn't work.

Also i tried to use Flask-Sockets on the server side:

```<code>from flask import Flask
from flask_sockets import Sockets

app = Flask(__name__)
sockets = Sockets(app)

@sockets.route('/')
def echo_socket(ws):
    while not ws.closed:
        message = ws.receive()
        print(message)

if __name__ == '__main__':
    app.run()
</code>```

It also doesn't work. I found several posts in some places (for example there and there) with "working" examples but actually they all don't work.

So is it possible to do what i need? If yes, how to do that? If no, what is alternatives?

答: flask sokets.io actually are not a websockets, they are SocketsIO. If one wants to integrate real WebSocket in his flask application he could use this project.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm interested in creating bidirectional exchange between Flask server and client. Seems that websockets are very convinient for achieving my goal. But i stucked on implementation. I've created simple Flask app with Flask-SocketIO like described in docs:

from flask_socketio import SocketIO
from flask import Flask

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@socketio.on('message')
def handle_message(message):
    print('received message: ' + message)

if __name__ == '__main__':
    socketio.run(app)

Client uses websocket-client package and looks as follows:

from websocket import create_connection

ws = create_connection("ws://localhost:5000")
ws.send("hello world")

In this configuration it doesn't work.

Also i tried to use Flask-Sockets on the server side:

from flask import Flask
from flask_sockets import Sockets

app = Flask(__name__)
sockets = Sockets(app)

@sockets.route('/')
def echo_socket(ws):
    while not ws.closed:
        message = ws.receive()
        print(message)

if __name__ == '__main__':
    app.run()

It also doesn't work. I found several posts in some places (for example there and there) with "working" examples but actually they all don't work.

So is it possible to do what i need? If yes, how to do that? If no, what is alternatives?


问:
How to get past the error : The multi-part identifier "p.ra" could not be bound in SQL
I am using following SQL code to extract data from S

```<code>select
   round(p.ra,6) as ra, round(p.dec,6) as dec,
   p.run,
   round(p.extinction_r,3) as rExtSFD,
   round(p.modelMag_u,3) as uRaw,
   round(p.modelMag_g,3) as gRaw,
   round(p.modelMag_r,3) as rRaw,
   round(p.modelMag_i,3) as iRaw,
   round(p.modelMag_z,3) as zRaw,
   round(p.modelMagErr_u,3) as uErr,
   round(p.modelMagErr_g,3) as gErr,
   round(p.modelMagErr_r,3) as rErr,
   round(p.modelMagErr_i,3) as iErr,
   round(p.modelMagErr_z,3) as zErr,
   round(p.psfMag_u,3) as uRawPSF,
   round(p.psfMag_g,3) as gRawPSF,
   round(p.psfMag_r,3) as rRawPSF,
   round(p.psfMag_i,3) as iRawPSF,
   round(p.psfMag_z,3) as zRawPSF,
   round(p.psfMagErr_u,3) as upsfErr,
   round(p.psfMagErr_g,3) as gpsfErr,
   round(p.psfMagErr_r,3) as rpsfErr,
   round(p.psfMagErr_i,3) as ipsfErr,
   round(p.psfMagErr_z,3) as zpsfErr, p.type,
   (case when (p.flags & '16') = 0 then 1 else 0 end) as ISOLATED

from
   photoObjAll
into
   mydb.SDSSimagingSample
where
   p.ra > 0.0 and p.ra < 10.0
   and p.dec > -1 and p.dec < 1
   and (p.type = 3 OR p.type = 6)
   and (p.flags & '4295229440') = 0
   and p.mode = 1
   and p.modelMag_r < 22.5
</code>```

I am getting the following error:

```<code>The multi-part identifier "p.ra" could not be bound. The multi-part
identifier "p.ra" could not be bound. The multi-part identifier "p.dec"
could . . . . . . . . . .
not be bound.
</code>```

I am new to SQL and do not know how to get past this. The info regarding SDSS data access can be found here: http://skyserver.sdss.org/CasJobs/Guide.aspx

答:
You are missing an alias from your table. You never told the engine what you are referring to as "p".

Correct syntax would be:

```<code>SELECT
 p.*
INTO whatever
FROM
    table as p
WHERE p.condition
</code>```

Body:
I am using following SQL code to extract data from S

select
   round(p.ra,6) as ra, round(p.dec,6) as dec,
   p.run,
   round(p.extinction_r,3) as rExtSFD,
   round(p.modelMag_u,3) as uRaw,
   round(p.modelMag_g,3) as gRaw,
   round(p.modelMag_r,3) as rRaw,
   round(p.modelMag_i,3) as iRaw,
   round(p.modelMag_z,3) as zRaw,
   round(p.modelMagErr_u,3) as uErr,
   round(p.modelMagErr_g,3) as gErr,
   round(p.modelMagErr_r,3) as rErr,
   round(p.modelMagErr_i,3) as iErr,
   round(p.modelMagErr_z,3) as zErr,
   round(p.psfMag_u,3) as uRawPSF,
   round(p.psfMag_g,3) as gRawPSF,
   round(p.psfMag_r,3) as rRawPSF,
   round(p.psfMag_i,3) as iRawPSF,
   round(p.psfMag_z,3) as zRawPSF,
   round(p.psfMagErr_u,3) as upsfErr,
   round(p.psfMagErr_g,3) as gpsfErr,
   round(p.psfMagErr_r,3) as rpsfErr,
   round(p.psfMagErr_i,3) as ipsfErr,
   round(p.psfMagErr_z,3) as zpsfErr, p.type,
   (case when (p.flags & '16') = 0 then 1 else 0 end) as ISOLATED

from
   photoObjAll
into
   mydb.SDSSimagingSample
where
   p.ra > 0.0 and p.ra < 10.0
   and p.dec > -1 and p.dec < 1
   and (p.type = 3 OR p.type = 6)
   and (p.flags & '4295229440') = 0
   and p.mode = 1
   and p.modelMag_r < 22.5

I am getting the following error:

The multi-part identifier "p.ra" could not be bound. The multi-part
identifier "p.ra" could not be bound. The multi-part identifier "p.dec"
could . . . . . . . . . .
not be bound.

I am new to SQL and do not know how to get past this. The info regarding SDSS data access can be found here: http://skyserver.sdss.org/CasJobs/Guide.aspx

Body:
You are missing an alias from your table. You never told the engine what you are referring to as "p".

Correct syntax would be:

SELECT
 p.*
INTO whatever
FROM
    table as p
WHERE p.condition


问:
Why can I combine a bitwise operator with a math operator, like &+, in Java?
I was writing some code earlier today, and forgot I was writing Java instead of Swift and accidentally typed &+. Surprisingly, I didn't get any errors, and the code compiled and ran fine.

I played around a little bit, and found that &+, &-, |+, |-, ^+, and ^- all compile and run without errors. It looks like they all act like the first bitwise operator when acting on numbers:

```<code>1 &+ 2 == 1 & 2
3 |+ 4 == 3 | 4
7 ^+ 9 == 7 ^ 9
</code>```

On the other hand, it seems like any other combination of a bitwise operator and a math operator, like +&, &/, and ^*, all give compile-time errors.

Why do &+, &-, |+, |-, ^+, and ^- compile and run without errors? Do they have some purpose that I'm not seeing, or is it just some compilation oddity?

答:
The + stands for the Unary Plus Operator + resulting in a positive number.

The - means the Unary Minus Operator - resulting in a negative number.

1 &+ 2 is 1 & +2

3 |- 4 is 3 | -4

7 ^+ 9 is 7 ^ +9

Notice that * and / operators cannot be used in the same way (1 &/ 2).

Body:
I was writing some code earlier today, and forgot I was writing Java instead of Swift and accidentally typed &+. Surprisingly, I didn't get any errors, and the code compiled and ran fine.

I played around a little bit, and found that &+, &-, |+, |-, ^+, and ^- all compile and run without errors. It looks like they all act like the first bitwise operator when acting on numbers:

1 &+ 2 == 1 & 2
3 |+ 4 == 3 | 4
7 ^+ 9 == 7 ^ 9

On the other hand, it seems like any other combination of a bitwise operator and a math operator, like +&, &/, and ^*, all give compile-time errors.

Why do &+, &-, |+, |-, ^+, and ^- compile and run without errors? Do they have some purpose that I'm not seeing, or is it just some compilation oddity?


问:
Are official centos-atomic or centos-minimal docker images available?
I've seen that Red Hat have their own registry to make available RHEL atomic and minimal docker images.

Are there equivalent CentOS images publically available? I wasn't able to find any on Docker Hub or the Project Atomic downloads.

答:
With Red Hat Universal Base Image being made available I'd assume that is now their solution to my question since it can be used without a RHEL subscription.

However, it does seem that you need a RHEL subscription to install additional packages onto the base images.


问:
Angular - button click event take priority over row click event
Having a table with rows, I can click on a row to access the details of one row via a seperate page. This is done via the [routerlink].

```<code> <tr *ngFor="let setting of applicatieData.settings" [routerLink]="['/settings-edit', setting.id]">
    <td class="col-3">{{ setting.shortName | slice:0:10 }}</td>
    <td class="col-4">{{ setting.value }}</td>
    <th class="col-3"><button class="btn btn-info" type="button" (click)="toggleValue(setting.id)">Toggle</button></th>
    <td class="col-2" (contextmenu)="onrightClick($event, setting.id)"><i class="icon-ellipsis-vert"></i></td>
</tr>
</code>```

I would like the 'Toggle' button click event to take priority over previously mentioned row click event. How can I do that?

The right click with the 'context menu' works fine.

答:
you can try this

  1
  2
  3
  4

```

Body:
Having a table with rows, I can click on a row to access the details of one row via a seperate page. This is done via the [routerlink].

    {{ setting.shortName | slice:0:10 }}
    {{ setting.value }}
    <button class="btn btn-info" type="button" (click)="toggleValue(setting.id)">Toggle</button>

I would like the 'Toggle' button click event to take priority over previously mentioned row click event. How can I do that?

The right click with the 'context menu' works fine.

Body:
you can try this

<tr>
  <td class="col-3" (click)="clickFila()">1</td>
  <td class="col-4" (click)="clickFila()">2</td>
  <th class="col-3" (click)="clickFila()">3</th>
  <td class="col-2"(click)="clickColumna()">4</td>
</tr>


问:
ReactJS vs NodeJS - Why do I need to create both?
I understand that React is frontend, and NodeJS is the backend that allows Javascript code to function outside of a browser. What I don't understand (and this is after following tutorials online on setting up a React project and a NodeJS project) is why I have to create an instance of each.

For example, in my React project, I managed to create a website. But because I needed a backend, I decided to use NodeJS. But I'm doing NodeJS tutorials, and I can create a website using NodeJS too. I'm confused because right now, it's appearing to be that React and NodeJS do the SAME THING.

I have never worked with NodeJS before so I am a bit confused. I was under the impression that I would just use NodeJS to host the backend, but after seeing that I'm literally having to create an entire website with NodeJS, I don't understand how I'm supposed to use React and NodeJS together.

How do the two, React and NodeJS, integrate together to create a fully-functioning web app? I have yet to see something online that clearly breaks down how the two interact.

答:
The point is that react and any other SPA library is working on a client-side (browser).

React fetch and consume the data from the server API.

You don't need to use Node.js for building API. You can use various frameworks based on the technology you prefer.

If you are not familiar with the Back End, you can use https://www.npmjs.com/package/http-server to have a fake API service and can build the Front End part with it.


问:
Whats wrong with my 2nd call to ReadINIStr?
I am a newbiew to NSIS. Trying to build a little sample that help to understand the techniques that I'd like to use in the production-installer that's build eventually...

I'd like to build a silent-installer that gets its parameter from an .INI-File with multiple section. Want to specific the section the command-line of the installer.

So, I have this NSIS-TEST.INI-File:

```<code>[PROD]
PATHONE=c:\Folder\Foo
AppName=My little stupid app
</code>```

The idea is to have command-line like this:

```<code>FooSetup config=prod
</code>```

The actual setup NSIS-TEST.NSI is:

```<code>; Script generated by the HM NIS Edit Script Wizard.
var /global REGAPPKEY
var /global PRODUCT_DIR_REGKEY
; HM NIS Edit Wizard helper defines
!define REG_APPKEY ""
!define config "PROD"
!define PATHONE ""
!define PRODUCT_NAME "foo"
!define PRODUCT_VERSION "1.0"
!define PRODUCT_PUBLISHER "foo"
!define PRODUCT_WEB_SITE "http://www.example.com"
!define PRODUCT_UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}"
!define PRODUCT_UNINST_ROOT_KEY "HKLM"

Name "${PRODUCT_NAME} ${PRODUCT_VERSION}"

OutFile "FooSetup.exe"
InstallDir "c:\foo-goo"
Icon "${NSISDIR}\Contrib\Graphics\Icons\modern-install.ico"
UninstallIcon "${NSISDIR}\Contrib\Graphics\Icons\modern-uninstall.ico"
;SilentInstall silent
;SilentUninstall silent
;InstallDirRegKey HKLM "${PRODUCT_DIR_REGKEY}" ""

Section -aHauptgruppe SEC01

ReadINIStr $REGAPPKEY $INSTDIR\nsis-test.ini  ${config} "AppName"

ReadINIStr $PATHONE $INSTDIR\nsis-test.ini ${config} "PATHONE"

;MessageBox MB_ICONINFORMATION|MB_OK "config=${config}"

  ;SetOutPath "$INSTDIR"
  ;SetOverwrite ifnewer
;  File "..\..\..\pfad\zur\datei\AppMainExe.exe"
 ; CreateDirectory "$SMPROGRAMS\foo"
 ; CreateShortCut "$SMPROGRAMS\foo\foo.lnk" "$INSTDIR\AppMainExe.exe"
 ; CreateShortCut "$DESKTOP\foo.lnk" "$INSTDIR\AppMainExe.exe"
 ; File "..\..\..\path\to\file\Example.file"
SectionEnd

Section -AdditionalIcons
  WriteIniStr "$INSTDIR\${PRODUCT_NAME}.url" "InternetShortcut" "URL" "${PRODUCT_WEB_SITE}"
  CreateShortCut "$SMPROGRAMS\foo\Website.lnk" "$INSTDIR\${PRODUCT_NAME}.url"
  CreateShortCut "$SMPROGRAMS\foo\Uninstall.lnk" "$INSTDIR\uninst.exe"
SectionEnd

Section -Post
  WriteUninstaller "$INSTDIR\uninst.exe"
  ;WriteRegStr HKLM "${PRODUCT_DIR_REGKEY}" "" "$INSTDIR\AppMainExe.exe"
  ;WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayName" "$(^Name)"
  ;WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "UninstallString" "$INSTDIR\uninst.exe"
  ;WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayIcon" "$INSTDIR\AppMainExe.exe"
  ;WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayVersion" "${PRODUCT_VERSION}"
  ;WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "URLInfoAbout" "${PRODUCT_WEB_SITE}"
  ;WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "Publisher" "${PRODUCT_PUBLISHER}"
SectionEnd

Function un.onUninstSuccess
  MessageBox MB_ICONINFORMATION|MB_OK "$(^Name) wurde erfolgreich deinstalliert."
FunctionEnd

Function un.onInit
  MessageBox MB_ICONQUESTION|MB_YESNO|MB_DEFBUTTON2 "M�chten Sie $(^Name) und alle seinen Komponenten deinstallieren?" IDYES +2
  Abort
FunctionEnd

Section Uninstall
  Delete "$INSTDIR\${PRODUCT_NAME}.url"
  Delete "$INSTDIR\uninst.exe"
  Delete "$INSTDIR\Example.file"
  Delete "$INSTDIR\AppMainExe.exe"

  Delete "$SMPROGRAMS\foo\Uninstall.lnk"
  Delete "$SMPROGRAMS\foo\Website.lnk"
  Delete "$DESKTOP\foo.lnk"
  Delete "$SMPROGRAMS\foo\foo.lnk"

  RMDir "$SMPROGRAMS\foo"
  RMDir "$INSTDIR"

  DeleteRegKey ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}"
  ;DeleteRegKey HKLM "${PRODUCT_DIR_REGKEY}"
  SetAutoClose true
SectionEnd

FooSetup config=prod
</code>```

If I compile this, the last lines of the output are:

```<code>Section: "-aHauptgruppe" ->(SEC01)
ReadINIStr $REGAPPKEY [PROD]:AppName from $INSTDIR\nsis-test.ini

Usage: ReadINIStr $(user_var: output) ini_file section entry_name
Error in script "c:\blabla\setup2019\nsis-test.nsi" on line 29 -- aborting creation process
</code>```

So it has processed the first of my ReadINIStr-Instructions and barfed on the second one. I have looked at this code for hours, have injected line-feed etc., but I can't see what's so different about the 2nd instruction...

答:
$PATHONE is not a variable. You're missing:

```<code>Var PATHONE
</code>```

Note you do have:

```<code>!define PATHONE ""
</code>```

So be careful not getting the two confused.

Body:
I am a newbiew to NSIS. Trying to build a little sample that help to understand the techniques that I'd like to use in the production-installer that's build eventually...

I'd like to build a silent-installer that gets its parameter from an .INI-File with multiple section. Want to specific the section the command-line of the installer.

So, I have this NSIS-TEST.INI-File:

[PROD]
PATHONE=c:\Folder\Foo
AppName=My little stupid app

The idea is to have command-line like this:

FooSetup config=prod

The actual setup NSIS-TEST.NSI is:

; Script generated by the HM NIS Edit Script Wizard.
var /global REGAPPKEY
var /global PRODUCT_DIR_REGKEY
; HM NIS Edit Wizard helper defines
!define REG_APPKEY ""
!define config "PROD"
!define PATHONE ""
!define PRODUCT_NAME "foo"
!define PRODUCT_VERSION "1.0"
!define PRODUCT_PUBLISHER "foo"
!define PRODUCT_WEB_SITE "http://www.example.com"
!define PRODUCT_UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}"
!define PRODUCT_UNINST_ROOT_KEY "HKLM"

Name "${PRODUCT_NAME} ${PRODUCT_VERSION}"

OutFile "FooSetup.exe"
InstallDir "c:\foo-goo"
Icon "${NSISDIR}\Contrib\Graphics\Icons\modern-install.ico"
UninstallIcon "${NSISDIR}\Contrib\Graphics\Icons\modern-uninstall.ico"
;SilentInstall silent
;SilentUninstall silent
;InstallDirRegKey HKLM "${PRODUCT_DIR_REGKEY}" ""

Section -aHauptgruppe SEC01

ReadINIStr $REGAPPKEY $INSTDIR\nsis-test.ini  ${config} "AppName"

ReadINIStr $PATHONE $INSTDIR\nsis-test.ini ${config} "PATHONE"

;MessageBox MB_ICONINFORMATION|MB_OK "config=${config}"

  ;SetOutPath "$INSTDIR"
  ;SetOverwrite ifnewer
;  File "..\..\..\pfad\zur\datei\AppMainExe.exe"
 ; CreateDirectory "$SMPROGRAMS\foo"
 ; CreateShortCut "$SMPROGRAMS\foo\foo.lnk" "$INSTDIR\AppMainExe.exe"
 ; CreateShortCut "$DESKTOP\foo.lnk" "$INSTDIR\AppMainExe.exe"
 ; File "..\..\..\path\to\file\Example.file"
SectionEnd

Section -AdditionalIcons
  WriteIniStr "$INSTDIR\${PRODUCT_NAME}.url" "InternetShortcut" "URL" "${PRODUCT_WEB_SITE}"
  CreateShortCut "$SMPROGRAMS\foo\Website.lnk" "$INSTDIR\${PRODUCT_NAME}.url"
  CreateShortCut "$SMPROGRAMS\foo\Uninstall.lnk" "$INSTDIR\uninst.exe"
SectionEnd

Section -Post
  WriteUninstaller "$INSTDIR\uninst.exe"
  ;WriteRegStr HKLM "${PRODUCT_DIR_REGKEY}" "" "$INSTDIR\AppMainExe.exe"
  ;WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayName" "$(^Name)"
  ;WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "UninstallString" "$INSTDIR\uninst.exe"
  ;WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayIcon" "$INSTDIR\AppMainExe.exe"
  ;WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayVersion" "${PRODUCT_VERSION}"
  ;WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "URLInfoAbout" "${PRODUCT_WEB_SITE}"
  ;WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "Publisher" "${PRODUCT_PUBLISHER}"
SectionEnd

Function un.onUninstSuccess
  MessageBox MB_ICONINFORMATION|MB_OK "$(^Name) wurde erfolgreich deinstalliert."
FunctionEnd

Function un.onInit
  MessageBox MB_ICONQUESTION|MB_YESNO|MB_DEFBUTTON2 "M�chten Sie $(^Name) und alle seinen Komponenten deinstallieren?" IDYES +2
  Abort
FunctionEnd

Section Uninstall
  Delete "$INSTDIR\${PRODUCT_NAME}.url"
  Delete "$INSTDIR\uninst.exe"
  Delete "$INSTDIR\Example.file"
  Delete "$INSTDIR\AppMainExe.exe"

  Delete "$SMPROGRAMS\foo\Uninstall.lnk"
  Delete "$SMPROGRAMS\foo\Website.lnk"
  Delete "$DESKTOP\foo.lnk"
  Delete "$SMPROGRAMS\foo\foo.lnk"

  RMDir "$SMPROGRAMS\foo"
  RMDir "$INSTDIR"

  DeleteRegKey ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}"
  ;DeleteRegKey HKLM "${PRODUCT_DIR_REGKEY}"
  SetAutoClose true
SectionEnd

FooSetup config=prod

If I compile this, the last lines of the output are:

Section: "-aHauptgruppe" ->(SEC01)
ReadINIStr $REGAPPKEY [PROD]:AppName from $INSTDIR\nsis-test.ini

Usage: ReadINIStr $(user_var: output) ini_file section entry_name
Error in script "c:\blabla\setup2019\nsis-test.nsi" on line 29 -- aborting creation process

So it has processed the first of my ReadINIStr-Instructions and barfed on the second one. I have looked at this code for hours, have injected line-feed etc., but I can't see what's so different about the 2nd instruction...

Body:
$PATHONE is not a variable. You're missing:

Var PATHONE

Note you do have:

!define PATHONE ""

So be careful not getting the two confused.


问:
Filter based on Sql Value
This is my data source. My data has model number and company name, different companies can have the same model numbers as well as other models.

I want to add filter in tableau something like this

sql (select Model Number from Table where company = 'Sony')

The data on tableau will be

```<code>Model Number     Company1 (sony)  Company2(Dell)  company3(Lenovo ) etc
</code>```

How can I achieve this

答:
If what you wanted was only to see Sony products, as Siva mentioned, you can just drag it to the filters shelf and select the value.  However, it sounds like you want to analyze data by both company and model number.  To get that:

Drag Model Number to the Rows shelf at the top

Drag Company to the Columns shelf at the top

Double-click your measure, such as Number of Records, to have Tableau add it to the visualization.

You can use the "show me" feature in the top right to pick different visualizations.  The training videos on the tableau website are a good way to get up and running quickly to solve other issues.

Title: Filter based on Sql Value

Body:
This is my data source. My data has model number and company name, different companies can have the same model numbers as well as other models.

I want to add filter in tableau something like this

sql (select Model Number from Table where company = 'Sony')

The data on tableau will be

Model Number     Company1 (sony)  Company2(Dell)  company3(Lenovo ) etc

How can I achieve this


问:
Form elements not clickable html css
The button and text fields on my login page are unresponsive / I am unable to click or interact with them. It worked fine yesterday and is linked to a PHP database. I have no idea what code I changed but it was possibly CSS that has stopped it working. Any advice would be great as I am lost. </p>

<p>I have tried editing CSS but to avail. </p>

```<code><!DOCTYPE HTML>
<html lang="en">
<head>
  <title>Maoine in Eirinn (MIE) Wild Atlantic Gaeltacht Properties</title>
  <meta charset="utf-8">
 <link rel="stylesheet" href="css/styles.css">
 </head>
<body>
<div id="container">
<?php include("includes/header.html");?>
<?php include("includes/nav.html");?>
<div id="content">
<?php
if (empty($_SESSION))
session_start();
if (isset($_SESSION['errors'])) {
echo "<div class='form-errors'>";
foreach($_SESSION['errors'] as $error)
{
 echo "<p>";
 echo $error;
 echo "</p>";
}
echo "</div>";
}
unset($_SESSION['errors']);
?>
<div id="login">
<h3> Login </h3>
<form action="login_action.php" method="POST">
<p>
Username: <input type="text" name="adminname" required="required">
</p><p>
Password: <input type="password" name="password" required="required">
</p><p>
<input type="submit" value="Login">
</p>
</form>
</div>
</div>
<?php include("includes/footer.html");?>
</div>
</body>
</html>

body{background-color: #EEEEEE; }

#container{margin: auto;
    width: 100%;
    background-color: #EEEEEE;
    border: 10px solid #EEEEEE;
    }

#header{
    background-color: #449966;
    height: 110px;
    margin-top: 38px;
    }

#nav{background-color: #000000;
    clear: left;
      }
#moira{
  float:right;
  padding-right: 50px;
  position: relative;
  margin-left: 50px;
}
#martin{
  float:right;
  padding-right: 50px;
  position: relative;
  margin-left: 50px;
}
#openinghours{`
  width: 30%;
  float:left;
  margin-left: 100px;}
#contactus{width: 50%;
  float:left;
  margin-bottom: 200px;}
#content{background-color: #EEEEEE;
    padding: 50px;
    min-height: 500px;
    text-align: center;
    }

#content a {background-color: #449966; color: white; text-decoration:none; padding:5px;}
#content a:hover {background-color: #878787; color: white;}

#footer{background-color: #449966;
    height: 50px;
    padding: 10px;
    display: flex;
    margin-top: 200px;
    bottom: 0;
    width: 100%;
    position: fixed;
}
#comments {width: 70%; float: left;}
.container{
    position: relative;
    border-radius: 8px;
    width: 90%;
    height: 500px;
    overflow: hidden;
}
#login{z-index: 100;}
#logo {float:left;}
#copyright {float:left;}
#footer ul{    text-align: center;
     width: 50%;
     margin: auto;}
#footer a{ color:#449966; }
#socialMedia{float:right; width: 150px; display: flex;}
#sitename{text-align: center;
       width: 100%;}
#languageimage img{
  border: 1px solid #ddd;
  border-radius: 50%;
  float:right;
  display: flex;
  vertical-align: top;}
table td {padding: 10px;}
table {width: 100%}

table tr:nth-child(1) {
    background-color: #449966;
    }
table tr {
    background-color:#FFFFFF;
    }
#displayproperties{width: 75%;}
#addtestimonial{width: 25%; margin-left: 50px; float: right;}
#addtestimonial table {border: 0px;}
#addtestimonial table tr td {padding: 0px; border: 0px;}
#addtestimonial table tr {background-color: #c6e1e0; border: 0px;}

.show {display:block;}

#commentform {
           font-family: Arial;
                 width: auto;
         }
label { float:left;
    width: 50px;
    clear: left;
    text-align: left;
    padding-right: 15px;
    margin-top: 10px;
    }
input, textarea {margin-top: 10px; }
#mysubmit { margin-left:65px;
        padding-bottom: 10px;
          }

body {margin:0;font-family:Arial}

.topnav {
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.active {
  background-color: #449966;
  color: white;
}

.topnav .icon {
  display: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  font-size: 17px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.dropdown-content {
  display: none;
  position: fixed;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}
#youtubewaw{margin-bottom: 200px;}

.topnav a:hover, .dropdown:hover .dropbtn {
  background-color: #449966;
  color: white;
}

.dropdown-content a:hover {
  background-color: #449966;
  color: black;
}

.dropdown:hover .dropdown-content {
  display: block;
}
@media only screen and (max-width: 1200px) {
    #openinghours{float:none;}
    #addtestimonial{float:none;}

@media only screen and (max-width: 768px) {
    body{font-size:90%;}
    #displayproducts td:nth-child(1){display:none;}
    #commentform{width: auto; font-size: 80%;}
    #mysubmit{margin-left: 0;}
    #openinghours{float:none;}
    td:nth-of-type(4){display:none;}
    #content{ padding: 0px;}}

@media screen and (max-width: 768px) {
    #sitename{display:none;}
  .topnav a:not(:first-child), .dropdown .dropbtn {
    display: none;
  }
  .topnav a.icon {
    float: right;
    display: block;
  }

}

@media screen and (max-width: 768px) {
    #sitename{display:none;}
  .topnav.responsive {position: relative;}
  .topnav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }
  .topnav.responsive .dropdown {float: none;}
  .topnav.responsive .dropdown-content {position: relative;}
  .topnav.responsive .dropdown .dropbtn {
    display: block;
    width: 100%;
    text-align: left;
  }
}
</code>```

答:
I noticed you have an accidental  ` character.

```<code>#openinghours{`
  width: 30%;
  float:left;
  margin-left: 100px;}
</code>```

Also you've got some id called #mysubmit but your submit input doesn't use that ID.

Title: Form elements not clickable html css

Body:
The button and text fields on my login page are unresponsive / I am unable to click or interact with them. It worked fine yesterday and is linked to a PHP database. I have no idea what code I changed but it was possibly CSS that has stopped it working. Any advice would be great as I am lost.

I have tried editing CSS but to avail.

<!DOCTYPE HTML>

  <title>Maoine in Eirinn (MIE) Wild Atlantic Gaeltacht Properties</title>
  <meta charset="utf-8">
 <link rel="stylesheet" href="css/styles.css">

<?php include("includes/header.html");?>
<?php include("includes/nav.html");?>

<?php
if (empty($_SESSION))
session_start();
if (isset($_SESSION['errors'])) {
echo "
";
foreach($_SESSION['errors'] as $error)
{
 echo "
";
 echo $error;
 echo "
";
}
echo "
";
}
unset($_SESSION['errors']);
?>

 Login

<form action="login_action.php" method="POST">

Username: <input type="text" name="adminname" required="required">

Password: <input type="password" name="password" required="required">

<input type="submit" value="Login">

</form>

<?php include("includes/footer.html");?>

body{background-color: #EEEEEE; }

#container{margin: auto;
    width: 100%;
    background-color: #EEEEEE;
    border: 10px solid #EEEEEE;
    }

#header{
    background-color: #449966;
    height: 110px;
    margin-top: 38px;
    }

#nav{background-color: #000000;
    clear: left;
      }
#moira{
  float:right;
  padding-right: 50px;
  position: relative;
  margin-left: 50px;
}
#martin{
  float:right;
  padding-right: 50px;
  position: relative;
  margin-left: 50px;
}
#openinghours{`
  width: 30%;
  float:left;
  margin-left: 100px;}
#contactus{width: 50%;
  float:left;
  margin-bottom: 200px;}
#content{background-color: #EEEEEE;
    padding: 50px;
    min-height: 500px;
    text-align: center;
    }

#content a {background-color: #449966; color: white; text-decoration:none; padding:5px;}
#content a:hover {background-color: #878787; color: white;}

#footer{background-color: #449966;
    height: 50px;
    padding: 10px;
    display: flex;
    margin-top: 200px;
    bottom: 0;
    width: 100%;
    position: fixed;
}
#comments {width: 70%; float: left;}
.container{
    position: relative;
    border-radius: 8px;
    width: 90%;
    height: 500px;
    overflow: hidden;
}
#login{z-index: 100;}
#logo {float:left;}
#copyright {float:left;}
#footer ul{    text-align: center;
     width: 50%;
     margin: auto;}
#footer a{ color:#449966; }
#socialMedia{float:right; width: 150px; display: flex;}
#sitename{text-align: center;
       width: 100%;}
#languageimage img{
  border: 1px solid #ddd;
  border-radius: 50%;
  float:right;
  display: flex;
  vertical-align: top;}
table td {padding: 10px;}
table {width: 100%}

table tr:nth-child(1) {
    background-color: #449966;
    }
table tr {
    background-color:#FFFFFF;
    }
#displayproperties{width: 75%;}
#addtestimonial{width: 25%; margin-left: 50px; float: right;}
#addtestimonial table {border: 0px;}
#addtestimonial table tr td {padding: 0px; border: 0px;}
#addtestimonial table tr {background-color: #c6e1e0; border: 0px;}

.show {display:block;}

#commentform {
           font-family: Arial;
                 width: auto;
         }
label { float:left;
    width: 50px;
    clear: left;
    text-align: left;
    padding-right: 15px;
    margin-top: 10px;
    }
input, textarea {margin-top: 10px; }
#mysubmit { margin-left:65px;
        padding-bottom: 10px;
          }

body {margin:0;font-family:Arial}

.topnav {
  overflow: hidden;
  background-color: #333;
  position: fixed;
  top: 0;
  width: 100%;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.active {
  background-color: #449966;
  color: white;
}

.topnav .icon {
  display: none;
}

.dropdown {
  float: left;
  overflow: hidden;
}

.dropdown .dropbtn {
  font-size: 17px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit;
  margin: 0;
}

.dropdown-content {
  display: none;
  position: fixed;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}
#youtubewaw{margin-bottom: 200px;}

.topnav a:hover, .dropdown:hover .dropbtn {
  background-color: #449966;
  color: white;
}

.dropdown-content a:hover {
  background-color: #449966;
  color: black;
}

.dropdown:hover .dropdown-content {
  display: block;
}
@media only screen and (max-width: 1200px) {
    #openinghours{float:none;}
    #addtestimonial{float:none;}

@media only screen and (max-width: 768px) {
    body{font-size:90%;}
    #displayproducts td:nth-child(1){display:none;}
    #commentform{width: auto; font-size: 80%;}
    #mysubmit{margin-left: 0;}
    #openinghours{float:none;}
    td:nth-of-type(4){display:none;}
    #content{ padding: 0px;}}

@media screen and (max-width: 768px) {
    #sitename{display:none;}
  .topnav a:not(:first-child), .dropdown .dropbtn {
    display: none;
  }
  .topnav a.icon {
    float: right;
    display: block;
  }

}

@media screen and (max-width: 768px) {
    #sitename{display:none;}
  .topnav.responsive {position: relative;}
  .topnav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }
  .topnav.responsive .dropdown {float: none;}
  .topnav.responsive .dropdown-content {position: relative;}
  .topnav.responsive .dropdown .dropbtn {
    display: block;
    width: 100%;
    text-align: left;
  }
}

Body:
I noticed you have an accidental  ` character.

#openinghours{`
  width: 30%;
  float:left;
  margin-left: 100px;}

Also you've got some id called #mysubmit but your submit input doesn't use that ID.


问:
How change a iframe content?

Possible Duplicate:

  How to change style of iframe content cross-domain?

Hi everybody.

Is it possible to change an iframe content if it comes from another site?
e.g.

```<code><html>
<head></head>
 <body>
  <iframe src="http://www.google.com"></iframe>
 </body>
</html>
</code>```

Thanks.

答:
No;

But you can get around this, sort of, if you pipe the content through your own domain.

So if you have a script at mydomain/fakegoogle that does something along the lines of

```<code>echo file_get_contents("google.com").
</code>```

Then on your iframe, point the source at mydomain/fakegoogle.  Not the most efficient, but it works if all you need is the content from that cross domain request.

ContentLicense: CC BY-SA 3.0

Title: How change a iframe content?

Body:
Possible Duplicate:

  How to change style of iframe content cross-domain?

Hi everybody.

Is it possible to change an iframe content if it comes from another site?
e.g.

Thanks.

Body:
No;

But you can get around this, sort of, if you pipe the content through your own domain.

So if you have a script at mydomain/fakegoogle that does something along the lines of

echo file_get_contents("google.com").

Then on your iframe, point the source at mydomain/fakegoogle.  Not the most efficient, but it works if all you need is the content from that cross domain request.


问:
How to add vertical menu items in MS-Word ribbon using manifest.xml file in Word Add-in
I want to add menus buttons in vertical alignment in MS Word ribbon using manifest.xml. When i add button control they are aligned side by side horizontally, i want them to be align vertically instead, as the last column in provided image.

here is my manifest.xml

```<code><ExtensionPoint xsi:type="PrimaryCommandSurface">
    <CustomTab id="wizdom.tab.name">
        <Group id="wizdom.Group1">
          <Label resid="wizdom.groupLabel" />
          <Icon>
            <bt:Image size="16" resid="wizdom.icon_32x32" />
            <bt:Image size="32" resid="wizdom.icon_32x32" />
            <bt:Image size="80" resid="wizdom.icon_32x32" />
          </Icon>

          <Control xsi:type="Button" id="wizdom.TaskpaneButton">
            <Label resid="wizdom.TaskpaneButton.Label" />
            <Supertip>
              <Title resid="wizdom.TaskpaneButton.Label" />
              <Description resid="wizdom.TaskpaneButton.Tooltip" />
            </Supertip>
            <Icon>
              <bt:Image size="16" resid="wizdom.icon_32x32" />
              <bt:Image size="32" resid="wizdom.icon_32x32" />
              <bt:Image size="80" resid="wizdom.icon_32x32" />
            </Icon>

            <Action xsi:type="ShowTaskpane">
              <TaskpaneId>ButtonId1</TaskpaneId>
              <SourceLocation resid="wizdom.Taskpane.Url" />
            </Action>
          </Control>
        </Group>
    </CustomTab>
</ExtensionPoint>
</code>```

答: I'm afraid that there is no way to customize the layout of a button group with Office Add-ins. To ensure a consistent experience, Office keeps control of the layout. If you shrink the Office window enough, you'll see the buttons shrink and their alignment change. For example, the following show the Script Lab add-in when Office is full screen and when it is resized much smaller.

Body:
I want to add menus buttons in vertical alignment in MS Word ribbon using manifest.xml. When i add button control they are aligned side by side horizontally, i want them to be align vertically instead, as the last column in provided image.

here is my manifest.xml

<ExtensionPoint xsi:type="PrimaryCommandSurface">
    <CustomTab id="wizdom.tab.name">
        <Group id="wizdom.Group1">

          <Icon>
            <bt:Image size="16" resid="wizdom.icon_32x32" />
            <bt:Image size="32" resid="wizdom.icon_32x32" />
            <bt:Image size="80" resid="wizdom.icon_32x32" />
          </Icon>

          <Control xsi:type="Button" id="wizdom.TaskpaneButton">

            <Supertip>
              <Title resid="wizdom.TaskpaneButton.Label" />
              <Description resid="wizdom.TaskpaneButton.Tooltip" />
            </Supertip>
            <Icon>
              <bt:Image size="16" resid="wizdom.icon_32x32" />
              <bt:Image size="32" resid="wizdom.icon_32x32" />
              <bt:Image size="80" resid="wizdom.icon_32x32" />
            </Icon>

            <Action xsi:type="ShowTaskpane">
              <TaskpaneId>ButtonId1</TaskpaneId>
              <SourceLocation resid="wizdom.Taskpane.Url" />
            </Action>
          </Control>
        </Group>
    </CustomTab>
</ExtensionPoint>


答:
You are using the "p." alias on several of the columns in your select statement but your table is not aliased with "p".

You need to change it to

```<code>from
photoObjAll as p
</code>```

Title: How to get past the error : The multi-part identifier "p.ra" could not be bound in SQL

Body:
You are using the "p." alias on several of the columns in your select statement but your table is not aliased with "p".

You need to change it to

from
photoObjAll as p


问:
using Spring JPA how to read multiple reference data from DB views
I would like to fetch read only data from multiple DB views,   using Spring JPA

That data is just reference data  Data like colors, printer types, countries, etc

The reference data is always aligned [key, value]

I have multiple DB views for example:

```<code>v_color:   R,RED, # B,BLUE    # G, GREEN     etc
v_country: US,USA # FR,France # TB, Free Tibet   etc
v_printer: EP, Epson # HP, HP # KY, Kyocera
</code>```

I would like to have the same ReferenceData @Entity class for them

```<code>@Entity
@Table(name="V_REF_DATA" , schema="APP")
public class ReferenceData {

    @Id
    @Column(name = "ID")
    private Long id; //The rownum!

    @Column(name="LABEL")
    String label;

    @Column(name="VALUE")
    String value;
</code>```

with a single repository like so:

```<code>public interface ReferenceDataRepository extends JpaRepository<ReferenceData ,String> {

    @Query(value = "SELECT ID,LABEL,VALUE  FROM v_color nativeQuery = true)
    List<ReferenceData> getColorValues();

    @Query(value = "SELECT ID,LABEL,VALUE  FROM v_country", nativeQuery = true)
    List<ReferenceData> getCountryCodesValues();

    // same for all others
}
</code>```

Is it possible/recommended?

答:
You can try something like this </p>

```<code>TypedQuery< ReferenceData> query =
em.createNamedQuery(SELECT ID,LABEL,VALUE  FROM v_color);
List<ReferenceData> results = query.getResultList();
</code>```

Body:
I would like to fetch read only data from multiple DB views,   using Spring JPA

That data is just reference data  Data like colors, printer types, countries, etc

The reference data is always aligned [key, value]

I have multiple DB views for example:

v_color:   R,RED, # B,BLUE    # G, GREEN     etc
v_country: US,USA # FR,France # TB, Free Tibet   etc
v_printer: EP, Epson # HP, HP # KY, Kyocera

I would like to have the same ReferenceData @Entity class for them

@Entity
@Table(name="V_REF_DATA" , schema="APP")
public class ReferenceData {

    @Id
    @Column(name = "ID")
    private Long id; //The rownum!

    @Column(name="LABEL")
    String label;

    @Column(name="VALUE")
    String value;

with a single repository like so:

public interface ReferenceDataRepository extends JpaRepository<ReferenceData ,String> {

    @Query(value = "SELECT ID,LABEL,VALUE  FROM v_color nativeQuery = true)
    List<ReferenceData> getColorValues();

    @Query(value = "SELECT ID,LABEL,VALUE  FROM v_country", nativeQuery = true)
    List<ReferenceData> getCountryCodesValues();

    // same for all others
}

Is it possible/recommended?

Body:
You can try something like this

TypedQuery< ReferenceData> query =
em.createNamedQuery(SELECT ID,LABEL,VALUE  FROM v_color);
List<ReferenceData> results = query.getResultList();


问:
Understanding a shuffling function
I found on this thread the following function to shuffle any kind of data types:

```<code>#define NELEMS(x)  (sizeof(x) / sizeof(x[0]))

/* arrange the N elements of ARRAY in random order.
 * Only effective if N is much smaller than RAND_MAX;
 * if this may not be the case, use a better random
 * number generator. */
static void shuffle(void *array, size_t n, size_t size) {
    char tmp[size];
    char *arr = array;
    size_t stride = size * sizeof(char);

    if (n > 1) {
        size_t i;
        for (i = 0; i < n - 1; ++i) {
            size_t rnd = (size_t) rand();
            size_t j = i + rnd / (RAND_MAX / (n - i) + 1);

            memcpy(tmp, arr + j * stride, size);
            memcpy(arr + j * stride, arr + i * stride, size);
            memcpy(arr + i * stride, tmp, size);
        }
    }
}
</code>```

I have been testing and it seems to work fine but I'm having a hard time understanding how and why it works.

How and why doesn't it swap an element of the array directly on array

How come it is possible to assign array to a char*: char *arr = array;

The offset i * stride or j * stride in memcpy functions is bigger than the total size of the array (sizeof(array)). How come the pointer arithmetic works here?

答:
For better understanding I will shuffle the answering order:

2 - array is a pointer of type void. In C, pointers may be assigned to and from pointers of type void*. Any pointer to an object may be converted to type void* without loss of information. If the result is converted back to the original pointer type, the original pointer is recovered.

1 - It does not work the same for single elements, you do not have a generic type that can be assigned to any type. So the code is switching the content of pointed memory.

3 - n is the number of elements in array, while size is the size of a single element in the array. stride = size * sizeof(char); means stride is equal to size, as sizeof(char) equals 1. The size of the array sizeof(array) equals n * size - the number of elements in the array multiplied with the size of an element. Since both i and j are less than n, i * stride and j * stride
will never be greater than the memory used by the array. I wonder though why the use of this stride, as far as I know sizeof(char) is always 1.

Title: Understanding a shuffling function

Body:
I found on this thread the following function to shuffle any kind of data types:

#define NELEMS(x)  (sizeof(x) / sizeof(x[0]))

/* arrange the N elements of ARRAY in random order.
 * Only effective if N is much smaller than RAND_MAX;
 * if this may not be the case, use a better random
 * number generator. */
static void shuffle(void *array, size_t n, size_t size) {
    char tmp[size];
    char *arr = array;
    size_t stride = size * sizeof(char);

    if (n > 1) {
        size_t i;
        for (i = 0; i < n - 1; ++i) {
            size_t rnd = (size_t) rand();
            size_t j = i + rnd / (RAND_MAX / (n - i) + 1);

            memcpy(tmp, arr + j * stride, size);
            memcpy(arr + j * stride, arr + i * stride, size);
            memcpy(arr + i * stride, tmp, size);
        }
    }
}

I have been testing and it seems to work fine but I'm having a hard time understanding how and why it works.

How and why doesn't it swap an element of the array directly on array

How come it is possible to assign array to a char*: char *arr = array;

The offset i * stride or j * stride in memcpy functions is bigger than the total size of the array (sizeof(array)). How come the pointer arithmetic works here?


问:
What's the RIGHT Way to do Multi-Threading in Azure
I've got an Azure app that needs 3 distinctly unique tasks to run as long-running processes.  I could easily spin up 3 Worker Roles, but that would cost 3x more than I need to spend given how simple the tasks are.  I'd like to run each task in its own thread since each task is very different in the amount of time they take to complete, and how frequently the need to run.

Given that scenario, or even a general multi-threading Azure scenario, what's the best way you know of to have each task run independently?

A few considerations I'd like to propose are:

Keep the CPU utilization low (not always possible with EventWaitHandles..?).

Uses the most current framework utilities (i.e. TPL or PLINQ).

Graceful shutdown and restart in case of an unrecoverable exception.

Thanks for the suggestions, links, or code samples.

EDIT

Here's what I've settled on - Given the code is bound for the Azure cloud, a self-healing option seems the most appropriate.  This approach aims to take a collection of threads and delegate their work to a diversity of "units of work."

Here's how it's glued together.  First, a simple class to wrap a diversity of workers.

```<code>public class ThreadWorker
{
    internal void RunInternal()
    {
        try
        {
            Run();
        }
        catch (SystemException)
        {
            throw;
        }
        catch (Exception)
        {
        }
    }

    public virtual void Run()
    {
    }

    public virtual void OnStop()
    {
    }
}
</code>```

Next, the code to keep a series of threads alive indefinitely.  This involves a list of threads, a list of "workers" (one per thread), and an infinite loop that checks the status of each thread on a given interval.

Note that an exception that terminates a thread won't tear down the other threads.  If an unhandled exception is encountered, the thread will be restarted the next time the event wait handle responds.

```<code>private readonly List<Thread> _threads = new List<Thread>();
private readonly List<ThreadWorker> _workers = new List<ThreadWorker>();
private EventWaitHandle EventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

public override void Run()
{
    foreach (var worker in _workers)
    {
        _threads.Add(new Thread(worker.RunInternal));
    }

    foreach (var thread in _threads)
    {
         thread.Start();
    }

    while (!EventWaitHandle.WaitOne(500))
    {
         // Restart any threads that have stopped running
         for (var i = 0; i < _threads.Count; i++)
         {
               if (_threads[i].IsAlive)
               {
                   continue;
               }

                _threads[i] = new Thread(_workers[i].RunInternal);
                _threads[i].Start();
          }

          EventWaitHandle.WaitOne(2000);
    }
}
</code>```

Simple enough - the main thread (in this case an Azure worker role's Run method) blocks for half a second between checks to the active list of threads.  Terminated threads are re-started and the host thread then blocks for 2 seconds before checking the worker threads' health again.

Adding workers is as simple as adding a list of classes that inherit from the ThreadWorker base class

```<code>_workers.Add(new SomeWorker());
_workers.Add(new AnotherWorker());
</code>```

And, finally, the concrete workers:

```<code>public class SomeWorker: ThreadWorker
{
    public override void Run()
    {
        while (true)
        {
            // Do your long running work here.

            Thread.Sleep(2000); // Take a breather - not necessary.
        }
    }
}

public class AnotherWorker: ThreadWorker
{
    public override void Run()
    {
        while (true)
        {
            // Do your long running work here.
        }
    }
}
</code>```

答:
I will start a Thread for each one of those long life tasks.

Actually that is what I do in one of my Roles: Run multiple WorkerRoles per instance

I load the types and call the Run method in a separate thread.

Body:
I've got an Azure app that needs 3 distinctly unique tasks to run as long-running processes.  I could easily spin up 3 Worker Roles, but that would cost 3x more than I need to spend given how simple the tasks are.  I'd like to run each task in its own thread since each task is very different in the amount of time they take to complete, and how frequently the need to run.

Given that scenario, or even a general multi-threading Azure scenario, what's the best way you know of to have each task run independently?

A few considerations I'd like to propose are:

Keep the CPU utilization low (not always possible with EventWaitHandles..?).

Uses the most current framework utilities (i.e. TPL or PLINQ).

Graceful shutdown and restart in case of an unrecoverable exception.

Thanks for the suggestions, links, or code samples.

EDIT

Here's what I've settled on - Given the code is bound for the Azure cloud, a self-healing option seems the most appropriate.  This approach aims to take a collection of threads and delegate their work to a diversity of "units of work."

Here's how it's glued together.  First, a simple class to wrap a diversity of workers.

public class ThreadWorker
{
    internal void RunInternal()
    {
        try
        {
            Run();
        }
        catch (SystemException)
        {
            throw;
        }
        catch (Exception)
        {
        }
    }

    public virtual void Run()
    {
    }

    public virtual void OnStop()
    {
    }
}

Next, the code to keep a series of threads alive indefinitely.  This involves a list of threads, a list of "workers" (one per thread), and an infinite loop that checks the status of each thread on a given interval.

Note that an exception that terminates a thread won't tear down the other threads.  If an unhandled exception is encountered, the thread will be restarted the next time the event wait handle responds.

private readonly List<Thread> _threads = new List<Thread>();
private readonly List<ThreadWorker> _workers = new List<ThreadWorker>();
private EventWaitHandle EventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);

public override void Run()
{
    foreach (var worker in _workers)
    {
        _threads.Add(new Thread(worker.RunInternal));
    }

    foreach (var thread in _threads)
    {
         thread.Start();
    }

    while (!EventWaitHandle.WaitOne(500))
    {
         // Restart any threads that have stopped running
         for (var i = 0; i < _threads.Count; i++)
         {
               if (_threads[i].IsAlive)
               {
                   continue;
               }

                _threads[i] = new Thread(_workers[i].RunInternal);
                _threads[i].Start();
          }

          EventWaitHandle.WaitOne(2000);
    }
}

Simple enough - the main thread (in this case an Azure worker role's Run method) blocks for half a second between checks to the active list of threads.  Terminated threads are re-started and the host thread then blocks for 2 seconds before checking the worker threads' health again.

Adding workers is as simple as adding a list of classes that inherit from the ThreadWorker base class

_workers.Add(new SomeWorker());
_workers.Add(new AnotherWorker());

And, finally, the concrete workers:

public class SomeWorker: ThreadWorker
{
    public override void Run()
    {
        while (true)
        {
            // Do your long running work here.

            Thread.Sleep(2000); // Take a breather - not necessary.
        }
    }
}

public class AnotherWorker: ThreadWorker
{
    public override void Run()
    {
        while (true)
        {
            // Do your long running work here.
        }
    }
}


问:
How to install Azure Az - Cannot convert value "2.0.0-preview" to type "System.Version"
I get the following Exception when I try to install Azure Az with PowerShell:

PowerShell 5.1 and .NET is installed. All AzureRM, Azure and Azure Az Modules which where previously installed are now uninstalled.

I tried different versions, with clobber and without, with force and without and I also executed the commands in an admin powershell.
For example:

Install-Module -Name Az -AllowClobber

Install-Module -Name Az -RequiredVersion 2.0.0

I had Azure Az already installed on this computer but had to uninstall it. I uninstalled it with this script by Microsoft.

答: Please upgrade PowerShellGet to latest version by following https://learn.microsoft.com/en-us/powershell/gallery/installing-psget. PowerShellGet with Version 1.0.0.1 could not recognize preview version string. </p>


问:
Accessing Class Members of an Argument within a Member Function
I'm writing up some code as part of a little project I'm working on, and something stood out to me as I was testing my code. I'm working with a class function shown below:

```<code>class Matrix{
    public:
        //Constructors
        Matrix();                   //EMPTY Matrix
        Matrix(int, int);           //Matrix WITH ROW AND COL
        Matrix(const Matrix &);     //Copy a matrix to this one
        ~Matrix();                  //Destructor

        //Matrix operations involving the matrix in question
        Matrix madd(Matrix const &m) const; // Matrix addition

    private:
        double **array; //vector<vector<double>> array;
        int nrows;
        int ncols;
        int ncell;
};
</code>```

Below, paying attention to the madd function, I've written it out in another file shown below:

```<code>Matrix Matrix::madd(Matrix const &m) const{
    assert(nrows==m.nrows && ncols==m.ncols);

    Matrix result(nrows,ncols);
    int i,j;

    for (i=0 ; i<nrows ; i++)
        for (j=0 ; j<ncols ; j++)
            result.array[i][j] = array[i][j] + m.array[i][j];

    return result;
}
</code>```

I suppose you can guess that it does matrix addition. To be honest, I found some code online, and I'm just trying to modify it for my own use, so this function wasn't completely written by me. I managed to compile this, and after a small test, it worked correctly, but what I'm confused by is how in the function I was able to call m.ncols and m.nrows. Looking at the class definition, the members are private, so how am I allowed to access them? Even though the argument m is passed as a const, since the nrows and ncols parameters are protected, shouldn't I NOT be able to access them (from the argument)? I'm confused as to why this is allowed.

答:
From access specifiers at cppreference.com

A private member of a class can only be accessed by the members and friends of that class, regardless of whether the members are on the same or different instances:

```<code>class S {
private:
    int n; // S::n is private
public:
    S() : n(10) {} // this->n is accessible in S::S
    S(const S& other) : n(other.n) {} // other.n is accessible in S::S
};
</code>```

Body:
I'm writing up some code as part of a little project I'm working on, and something stood out to me as I was testing my code. I'm working with a class function shown below:

class Matrix{
    public:
        //Constructors
        Matrix();                   //EMPTY Matrix
        Matrix(int, int);           //Matrix WITH ROW AND COL
        Matrix(const Matrix &);     //Copy a matrix to this one
        ~Matrix();                  //Destructor

        //Matrix operations involving the matrix in question
        Matrix madd(Matrix const &m) const; // Matrix addition

    private:
        double **array; //vector<vector<double>> array;
        int nrows;
        int ncols;
        int ncell;
};

Below, paying attention to the madd function, I've written it out in another file shown below:

Matrix Matrix::madd(Matrix const &m) const{
    assert(nrows==m.nrows && ncols==m.ncols);

    Matrix result(nrows,ncols);
    int i,j;

    for (i=0 ; i<nrows ; i++)
        for (j=0 ; j<ncols ; j++)
            result.array[i][j] = array[i][j] + m.array[i][j];

    return result;
}

I suppose you can guess that it does matrix addition. To be honest, I found some code online, and I'm just trying to modify it for my own use, so this function wasn't completely written by me. I managed to compile this, and after a small test, it worked correctly, but what I'm confused by is how in the function I was able to call m.ncols and m.nrows. Looking at the class definition, the members are private, so how am I allowed to access them? Even though the argument m is passed as a const, since the nrows and ncols parameters are protected, shouldn't I NOT be able to access them (from the argument)? I'm confused as to why this is allowed.

Body:
From access specifiers at cppreference.com

A private member of a class can only be accessed by the members and friends of that class, regardless of whether the members are on the same or different instances:

class S {
private:
    int n; // S::n is private
public:
    S() : n(10) {} // this->n is accessible in S::S
    S(const S& other) : n(other.n) {} // other.n is accessible in S::S
};


问:
Variable '$_data' cannot be non input type in GraphQL mutation with Prisma
I am using Prisma with GraphQL and get errors when I run the mutatioin.
I deployed prisma succussfully and binded it with local graphQL.

-- datamodel.graphql - prisma setting

```<code>type Link {
  id: ID! @unique
  description: String!
  url: String!
  postedBy: User
}

type User {
  id: ID! @unique
  name: String!
  email: String! @unique
  password: String!
  links: [Link!]!
}
</code>```

-- schema.graphql - local setting

```<code># import Link from "./generated/prisma.graphql"
type Query {
  info: String!
  feed: [Link!]!
}

type Mutation {
  post(url: String!, description: String!): Link!
  signup(email: String!, password: String!, name: String!): AuthPayload
  login(email: String!, password: String!): AuthPayload
}

type AuthPayload {
  token: String
  user: User
}

type User {
  id: ID!
  name: String!
  email: String!
  links: [Link!]!
}
</code>```

Resolver for signup mutation is

```<code>async function signup(parent, args, context, info) {
  // 1
  const password = await bcrypt.hash(args.password, 10)
  // 2
  const user = await context.db.mutation.createUser({
    data: { ...args, password },
  }, `{ id }`)

  // 3
  const token = jwt.sign({ userId: user.id }, APP_SECRET)

  // 4
  return {
    token,
    user,
  }
}
</code>```

And this is .graphqlconfig.yml content

```<code>projects:
  app:
    schemaPath: src/schema.graphql
    extensions:
      endpoints:
        default: http://localhost:4000
  database:
    schemaPath: src/generated/prisma.graphql
    extensions:
      prisma: database/prisma.yml
</code>```

GraphQL query I run is .

```<code>mutation {
  signup(
    name: "Alice"
    email: "alice@graph.cool"
    password: "graphql"
  ) {
    token
    user {
      id
    }
  }
}
</code>```

And the response I got when I run this is

```<code>{
  "data": {
    "signup": null
  },
  "errors": [
    {
      "message": "Variable '$_data' cannot be non input type 'UserCreateInput!'. (line 1, column 19):\nmutation ($_data: UserCreateInput!) {\n                  ^",
      "locations": [],
      "path": [
        "createUser"
      ]
    }
  ]
}
</code>```

I can'find the reason of this.

Thank you.

答:
Try use prisma deploy --force

This worked for me.

Body:
I am using Prisma with GraphQL and get errors when I run the mutatioin.
I deployed prisma succussfully and binded it with local graphQL.

-- datamodel.graphql - prisma setting

type Link {
  id: ID! @unique
  description: String!
  url: String!
  postedBy: User
}

type User {
  id: ID! @unique
  name: String!
  email: String! @unique
  password: String!
  links: [Link!]!
}

-- schema.graphql - local setting

# import Link from "./generated/prisma.graphql"
type Query {
  info: String!
  feed: [Link!]!
}

type Mutation {
  post(url: String!, description: String!): Link!
  signup(email: String!, password: String!, name: String!): AuthPayload
  login(email: String!, password: String!): AuthPayload
}

type AuthPayload {
  token: String
  user: User
}

type User {
  id: ID!
  name: String!
  email: String!
  links: [Link!]!
}

Resolver for signup mutation is

async function signup(parent, args, context, info) {
  // 1
  const password = await bcrypt.hash(args.password, 10)
  // 2
  const user = await context.db.mutation.createUser({
    data: { ...args, password },
  }, `{ id }`)

  // 3
  const token = jwt.sign({ userId: user.id }, APP_SECRET)

  // 4
  return {
    token,
    user,
  }
}

And this is .graphqlconfig.yml content

projects:
  app:
    schemaPath: src/schema.graphql
    extensions:
      endpoints:
        default: http://localhost:4000
  database:
    schemaPath: src/generated/prisma.graphql
    extensions:
      prisma: database/prisma.yml

GraphQL query I run is .

mutation {
  signup(
    name: "Alice"
    email: "alice@graph.cool"
    password: "graphql"
  ) {
    token
    user {
      id
    }
  }
}

And the response I got when I run this is

{
  "data": {
    "signup": null
  },
  "errors": [
    {
      "message": "Variable '$_data' cannot be non input type 'UserCreateInput!'. (line 1, column 19):\nmutation ($_data: UserCreateInput!) {\n                  ^",
      "locations": [],
      "path": [
        "createUser"
      ]
    }
  ]
}

I can'find the reason of this.

Thank you.


问:
Why is this CRON task not running a Python Program Raspberry Pi
I have a CRON task scheduled as followed:

```<code>30 18 * * 1-5 python python /home/pi/myscript.py
</code>```

Why is it not executing?

答:
The format of writing cron job is incorrect.

Correct entry for this is as following:

```<code>30 18 * * 1-5 "python /home/pi/myscript.py"
</code>```

If you are using Python 3.x then change accordingly i.e.:

```<code>30 18 * * 1-5 "python3 /home/pi/myscript.py"
</code>```

Body:
I have a CRON task scheduled as followed:

30 18 * * 1-5 python python /home/pi/myscript.py

Why is it not executing?

Body:
The format of writing cron job is incorrect.

Correct entry for this is as following:

30 18 * * 1-5 "python /home/pi/myscript.py"

If you are using Python 3.x then change accordingly i.e.:

30 18 * * 1-5 "python3 /home/pi/myscript.py"


问:
How to remove a translation using CakePHP 3 TranslateBehavior
I am using TranslateBehavior and it mostly works great. However there is a problem of removing translations.
I had this problem where empty strings were returned if they were present in i18n table, which makes sense. I set

```<code>allowEmptyTranslations => false
</code>```

flag and it solved the problem but created another. I am now unable to remove translations. I tried leaving the fields empty or saving a single space. The first technique did not change the fields at all, the other did save, but I couldn't then change the space into anything else. If I try to input a new value, I get a duplicate row error directly from the database, so I assume the actual field was unset beforehand if there was only a space (Translate must have treated it as empty). Therefore it seems that allowEmptyTranslations works for both saving and retrieving.

In short des anybody know a way to remove translations?

答:
I'm note sure what your duplicate row error problem is about, but if you want to actually save empty strings (or nulls), then you'll have to enable allowEmptyTranslations, you could do that on the fly if you want.

Here's a quick and dirty example, where $table would be the table object that has the translate behavior attached, and $entity would be the entity for which you'd want to save translations:

```<code>// ...

$translateBehavior = $table->behaviors()->get('Translate');
$allowEmptyTranslations = $translateBehavior->getConfig('allowEmptyTranslations');
$translateBehavior->setConfig('allowEmptyTranslations', true);

$result = $table->save($entity);
// ...

$translateBehavior->setConfig('allowEmptyTranslations', $allowEmptyTranslations);
</code>```

Alternatively you could also delete translation entries, here $entity would be the entity for which you'd want to remove a translation, let's say it belongs to a table class named ArticlesTable, and you'd want to remove the french translation for the title field:

```<code>$translateBehavior = $table->behaviors()->get('Translate');
$translationTable = $translateBehavior->getTableLocator()->get(
    $translateBehavior->getConfig('translationTable')
);

$translationEntity = $translationTable
    ->find()
    ->where([
        'foreign_key' => $entity->id,
        'model' => 'Articles',
        'field' => 'title',
        'locale' => 'fr_FR',
    ])
    ->firstOrFail();

$result = $translationTable->delete($translationEntity);
</code>```

The examples are untested, but you get the idea.

Body:
I am using TranslateBehavior and it mostly works great. However there is a problem of removing translations.
I had this problem where empty strings were returned if they were present in i18n table, which makes sense. I set

allowEmptyTranslations => false

flag and it solved the problem but created another. I am now unable to remove translations. I tried leaving the fields empty or saving a single space. The first technique did not change the fields at all, the other did save, but I couldn't then change the space into anything else. If I try to input a new value, I get a duplicate row error directly from the database, so I assume the actual field was unset beforehand if there was only a space (Translate must have treated it as empty). Therefore it seems that allowEmptyTranslations works for both saving and retrieving.

In short des anybody know a way to remove translations?

Body:
I'm note sure what your duplicate row error problem is about, but if you want to actually save empty strings (or nulls), then you'll have to enable allowEmptyTranslations, you could do that on the fly if you want.

Here's a quick and dirty example, where $table would be the table object that has the translate behavior attached, and $entity would be the entity for which you'd want to save translations:

// ...

$translateBehavior = $table->behaviors()->get('Translate');
$allowEmptyTranslations = $translateBehavior->getConfig('allowEmptyTranslations');
$translateBehavior->setConfig('allowEmptyTranslations', true);

$result = $table->save($entity);
// ...

$translateBehavior->setConfig('allowEmptyTranslations', $allowEmptyTranslations);

Alternatively you could also delete translation entries, here $entity would be the entity for which you'd want to remove a translation, let's say it belongs to a table class named ArticlesTable, and you'd want to remove the french translation for the title field:

$translateBehavior = $table->behaviors()->get('Translate');
$translationTable = $translateBehavior->getTableLocator()->get(
    $translateBehavior->getConfig('translationTable')
);

$translationEntity = $translationTable
    ->find()
    ->where([
        'foreign_key' => $entity->id,
        'model' => 'Articles',
        'field' => 'title',
        'locale' => 'fr_FR',
    ])
    ->firstOrFail();

$result = $translationTable->delete($translationEntity);

The examples are untested, but you get the idea.


问:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client in Node JS
I am trying to update a data using a specific ID which is not working but gives above error.

When I update, first I search the database for that specific id and then save the data to MongoDB

here is my server.js

```<code>const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

//importing MongoDB model schema
let ToDo = require('./todo.model');

const app = express();
const todoRoutes = express.Router();

const PORT = 4000;

//middlewares
app.use(bodyParser.json());
app.use(cors());
app.use('/todos', todoRoutes);

//connection to the MongoDB database
mongoose.connect('mongodb://127.0.0.1:27017/todos', {useNewUrlParser: true});
const connection = mongoose.connection;
connection.once('open', () =>{
    console.log("Connected to the MongoDB through port: 27017");
 });

app.listen(PORT, () => {
    console.log(`Listening to port: ${PORT}`);
});

//get all data - removed to show only the code snippet I am getting errors

//get data by an ID - removed to show only the code snippet I am getting errors

//add items to database -removed to show only the code snippet I am getting errors

//update items
todoRoutes.route('/update/:id').post((req, res) => {
    let id = req.params.id;
    ToDo.findById(id, (err, todo) => {
        if(err) throw err;
        if(!todo) res.status(400).send("No data found");

        todo.todo_description = req.body.todo_description;
        todo.todo_responsible = req.body.todo_responsible;
        todo.todo_priority = req.body.todo_priority;
        todo.todo_completed = req.body.todo_completed;
        res.end();

        todo.save().then(todo => {
            res.json(200).send("Data Updated! " + todo);
            res.end();
        }).catch(err => {
            res.status(400).send("Error occured! " + err);
        });
    });
});
</code>```

This is the error I am getting...

Can someone please help me?

答:
This error usually means that you send a response more than once.

Notice that you send two responses one after the other res.json() and res.end()

If you want for some reason to just end the response, use res.end(), otherwise use res.status(200).json({ result: ‘Data updated’ + todo })

If you send both, it will complain about trying to modify the response (via res.end()) after sending it (via res.status().json())

Body:
I am trying to update a data using a specific ID which is not working but gives above error.

When I update, first I search the database for that specific id and then save the data to MongoDB

here is my server.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');

//importing MongoDB model schema
let ToDo = require('./todo.model');

const app = express();
const todoRoutes = express.Router();

const PORT = 4000;

//middlewares
app.use(bodyParser.json());
app.use(cors());
app.use('/todos', todoRoutes);

//connection to the MongoDB database
mongoose.connect('mongodb://127.0.0.1:27017/todos', {useNewUrlParser: true});
const connection = mongoose.connection;
connection.once('open', () =>{
    console.log("Connected to the MongoDB through port: 27017");
 });

app.listen(PORT, () => {
    console.log(`Listening to port: ${PORT}`);
});

//get all data - removed to show only the code snippet I am getting errors

//get data by an ID - removed to show only the code snippet I am getting errors

//add items to database -removed to show only the code snippet I am getting errors

//update items
todoRoutes.route('/update/:id').post((req, res) => {
    let id = req.params.id;
    ToDo.findById(id, (err, todo) => {
        if(err) throw err;
        if(!todo) res.status(400).send("No data found");

        todo.todo_description = req.body.todo_description;
        todo.todo_responsible = req.body.todo_responsible;
        todo.todo_priority = req.body.todo_priority;
        todo.todo_completed = req.body.todo_completed;
        res.end();

        todo.save().then(todo => {
            res.json(200).send("Data Updated! " + todo);
            res.end();
        }).catch(err => {
            res.status(400).send("Error occured! " + err);
        });
    });
});

This is the error I am getting...

Can someone please help me?


问:
Design View in Access not bringing up an append query?
I am updating a MS Access away from access. There are some Append Queries that the design view will not come up at all. I read somewhere that if the append is extra old you just need to save the DB as an older version. However, that also fails to do anything.

I am using O365 Access with a 2007-2016 file format DB. It has been upgraded multiple times over the years I would assume it might've started as a 2000 DB.

What can I do to see the design of the append?

答:
If you open the Visual Basic IDE (Alt+F11), and then open the Immediate Window (Ctrl+G), you should then be able to enter the following expression on a new line in the Immediate Window (changing Query1 to the name of your query) and press Enter to view the SQL associated with the query:

```<code>?CurrentDb.QueryDefs("Query1").SQL
</code>```

You could then inspect the tables/queries referenced in the SQL and see if anything is amiss, or copy the SQL to a new query to see if it exhibits the same behaviour.

Body:
If you open the Visual Basic IDE (Alt+F11), and then open the Immediate Window (Ctrl+G), you should then be able to enter the following expression on a new line in the Immediate Window (changing Query1 to the name of your query) and press Enter to view the SQL associated with the query:

?CurrentDb.QueryDefs("Query1").SQL

You could then inspect the tables/queries referenced in the SQL and see if anything is amiss, or copy the SQL to a new query to see if it exhibits the same behaviour.


问:
How to get a file from laravel folder storage for a treatment
I saved an image in storage / app / public and I created a symbolic link to public / storage and the link works well but when I try to get the image with the method Storage :: get ($path) I am being sent a FileNotFoundException. I would like to know how to get my image in my code

```<code> $fichier=Storage::get('storage/avatarDebutFemme.png');
</code>```

Illuminate \ Contracts \ Filesystem \ FileNotFoundException
  storage/avatarDebutFemme.png

Previous exceptions

File not found at path: storage/avatarDebutFemme.png (0)

答: Follow ,laravel site it can be helpfull for your problem File Storage-Laravel</p>

Body:
I saved an image in storage / app / public and I created a symbolic link to public / storage and the link works well but when I try to get the image with the method Storage :: get ($path) I am being sent a FileNotFoundException. I would like to know how to get my image in my code

 $fichier=Storage::get('storage/avatarDebutFemme.png');

Illuminate \ Contracts \ Filesystem \ FileNotFoundException
  storage/avatarDebutFemme.png

Previous exceptions

File not found at path: storage/avatarDebutFemme.png (0)


问:
How to check Firebase query result is 0
How to check Fire base query result is 0

I am developing a login page - if the data is not present then directly register the user.  But based on the data returned from the fire base , if the result is 0 , then insert into the fire base

```<code>if (!txt_phone.equals("")) {
    Query query = auth.orderByChild("phoneNo").equalTo(StringUtils.trim(txt_phone)).limitToFirst(1);
    query.addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User exisitngUser = null;
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        exisitngUser = snapshot.getValue(User.class);
                    }
                    Log.d(TAG, "Exisiting User" + exisitngUser.toString());

                    if (exisitngUser != null && exisitngUser.getPhoneNo() != null && exisitngUser.getPhoneNo().equalsIgnoreCase(txt_phone)) {
                        Log.i(TAG, "onDataChange Method");
                        addFlag[0] = true;
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("phoneNo", txt_phone);
                        intent.putExtra("userName", txt_userName);
                        startActivity(intent);
                        finish();
                    } else if (addFlag[0] = false) {
                        Log.i(TAG, "onDataChange Method else");
                        addFlag[0] = true;
                        addUser = FirebaseDatabase.getInstance().getReference("Messanger");
                        User login = new User("1", txt_userName, txt_password, txt_phone, null, "Active", null);
                        addUser.child("loginUser").push().setValue(login);
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("phoneNo", txt_phone);
                        intent.putExtra("userName", txt_userName);
                        startActivity(intent);
                        finish();
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.w(TAG, "getUser:onCancelled", databaseError.toException());
                }
            });
//This is called before the data is returned, How to I block this until the data is checked
            if (!txt_phone.equals("") && addFlag[0] == false) {
                Log.i(TAG, "Out of onDataChange Method");
                addFlag[0] = true;
                addUser = FirebaseDatabase.getInstance().getReference("Message");
                User user = new User("1", txt_userName, txt_password, txt_phone, null, "Active", null);
                addUser.child("User").push().setValue(user);
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("phoneNo", txt_phone);
                intent.putExtra("userName", txt_userName);
                startActivity(intent);
                finish();
            }
        }
    }
});
</code>```

This is called first [!txt_phone.equals("") && addFlag[0] == false] for a new user, even before the query results is returned. I need it to wait until the result is returned from the firebase, if the firebase returns 0 then this if[!txt_phone.equals("") && addFlag[0] == false] should be executed.

答: If you are referring to the DataSnapshot you can always call the hasChildren() method which will indicate if there were any query results matching your criteria. That method returns a boolean indicating the result.

Title: How to check Firebase query result is 0

Body:
How to check Fire base query result is 0

I am developing a login page - if the data is not present then directly register the user.  But based on the data returned from the fire base , if the result is 0 , then insert into the fire base

if (!txt_phone.equals("")) {
    Query query = auth.orderByChild("phoneNo").equalTo(StringUtils.trim(txt_phone)).limitToFirst(1);
    query.addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User exisitngUser = null;
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        exisitngUser = snapshot.getValue(User.class);
                    }
                    Log.d(TAG, "Exisiting User" + exisitngUser.toString());

                    if (exisitngUser != null && exisitngUser.getPhoneNo() != null && exisitngUser.getPhoneNo().equalsIgnoreCase(txt_phone)) {
                        Log.i(TAG, "onDataChange Method");
                        addFlag[0] = true;
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("phoneNo", txt_phone);
                        intent.putExtra("userName", txt_userName);
                        startActivity(intent);
                        finish();
                    } else if (addFlag[0] = false) {
                        Log.i(TAG, "onDataChange Method else");
                        addFlag[0] = true;
                        addUser = FirebaseDatabase.getInstance().getReference("Messanger");
                        User login = new User("1", txt_userName, txt_password, txt_phone, null, "Active", null);
                        addUser.child("loginUser").push().setValue(login);
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("phoneNo", txt_phone);
                        intent.putExtra("userName", txt_userName);
                        startActivity(intent);
                        finish();
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Log.w(TAG, "getUser:onCancelled", databaseError.toException());
                }
            });
//This is called before the data is returned, How to I block this until the data is checked
            if (!txt_phone.equals("") && addFlag[0] == false) {
                Log.i(TAG, "Out of onDataChange Method");
                addFlag[0] = true;
                addUser = FirebaseDatabase.getInstance().getReference("Message");
                User user = new User("1", txt_userName, txt_password, txt_phone, null, "Active", null);
                addUser.child("User").push().setValue(user);
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("phoneNo", txt_phone);
                intent.putExtra("userName", txt_userName);
                startActivity(intent);
                finish();
            }
        }
    }
});

This is called first [!txt_phone.equals("") && addFlag[0] == false] for a new user, even before the query results is returned. I need it to wait until the result is returned from the firebase, if the firebase returns 0 then this if[!txt_phone.equals("") && addFlag[0] == false] should be executed.


问:
Can not find module “@angular-devkit/build-angular”
Using npm, I followed the getting started directions on the Angular CLI quick start page.

Angular CLI Quickstart

Running ng serve --open after creating and going into my new project "frontend" gave this error:

```<code>Could not find module "@angular-devkit/build-angular" from "C:\\Users\\Brandon\\project-name\\frontend".
Error: Could not find module "@angular-devkit/build-angular" from "C:\\Users\\Brandon\\project-name\\frontend".
 at Object.resolve (C:\Users\Brandon\project-name\node_modules\@angular-devkit\core\node\resolve.js:141:11)
 at Observable.rxjs_1.Observable [as _subscribe] (C:\Users\Brandon\project-name\node_modules\@angular-devkit\architect\src\architect.js:132:40)
</code>```

I have tried suggestions from the other question similar to mine but it did not work. Answer was to run npm install --save-dev @angular-devkit/build-angular.

Similar Question

I have also deleted modules, cleared cache, then did an install which also did not work.

package.json:

```<code>{
 "name": "frontend",
 "version": "0.0.0",
 "scripts": {
   "ng": "ng",
   "start": "ng serve",
   "build": "ng build",
   "test": "ng test",
   "lint": "ng lint",
   "e2e": "ng e2e"
 },
"private": true,
"dependencies": {
  "@angular/animations": "^6.0.2",
  "@angular/common": "^6.0.2",
  "@angular/compiler": "^6.0.2",
  "@angular/core": "^6.0.2",
  "@angular/forms": "^6.0.2",
  "@angular/http": "^6.0.2",
  "@angular/platform-browser": "^6.0.2",
  "@angular/platform-browser-dynamic": "^6.0.2",
  "@angular/router": "^6.0.2",
  "core-js": "^2.5.4",
  "rxjs": "^6.0.0",
  "zone.js": "^0.8.26"
 },
"devDependencies": {
  "@angular/compiler-cli": "^6.0.2",
  "@angular-devkit/build-angular": "~0.6.3",
  "typescript": "~2.7.2",
  "@angular/cli": "^6.0.3",
  "@angular/language-service": "^6.0.2",
  "@types/jasmine": "~2.8.6",
  "@types/jasminewd2": "~2.0.3",
  "@types/node": "~8.9.4",
  "codelyzer": "~4.2.1",
  "jasmine-core": "~2.99.1",
  "jasmine-spec-reporter": "~4.2.1",
  "karma": "~1.7.1",
  "karma-chrome-launcher": "~2.2.0",
  "karma-coverage-istanbul-reporter": "~1.4.2",
  "karma-jasmine": "~1.1.1",
  "karma-jasmine-html-reporter": "^0.2.2",
  "protractor": "~5.3.0",
  "ts-node": "~5.0.1",
  "tslint": "~5.9.1"
 }
}
</code>```

angular.json:

```<code> {
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "frontend": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/frontend",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "frontend:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "frontend:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "frontend:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "frontend-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "frontend:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "frontend"
}
</code>```

答:
If you are using angular version 8 please run the below command to fix this issue.</p>

```<code>ng update @angular/cli @angular/core
</code>```

Body:
Using npm, I followed the getting started directions on the Angular CLI quick start page.

Angular CLI Quickstart

Running ng serve --open after creating and going into my new project "frontend" gave this error:

Could not find module "@angular-devkit/build-angular" from "C:\\Users\\Brandon\\project-name\\frontend".
Error: Could not find module "@angular-devkit/build-angular" from "C:\\Users\\Brandon\\project-name\\frontend".
 at Object.resolve (C:\Users\Brandon\project-name\node_modules\@angular-devkit\core\node\resolve.js:141:11)
 at Observable.rxjs_1.Observable [as _subscribe] (C:\Users\Brandon\project-name\node_modules\@angular-devkit\architect\src\architect.js:132:40)

I have tried suggestions from the other question similar to mine but it did not work. Answer was to run npm install --save-dev @angular-devkit/build-angular.

Similar Question

I have also deleted modules, cleared cache, then did an install which also did not work.

package.json:

{
 "name": "frontend",
 "version": "0.0.0",
 "scripts": {
   "ng": "ng",
   "start": "ng serve",
   "build": "ng build",
   "test": "ng test",
   "lint": "ng lint",
   "e2e": "ng e2e"
 },
"private": true,
"dependencies": {
  "@angular/animations": "^6.0.2",
  "@angular/common": "^6.0.2",
  "@angular/compiler": "^6.0.2",
  "@angular/core": "^6.0.2",
  "@angular/forms": "^6.0.2",
  "@angular/http": "^6.0.2",
  "@angular/platform-browser": "^6.0.2",
  "@angular/platform-browser-dynamic": "^6.0.2",
  "@angular/router": "^6.0.2",
  "core-js": "^2.5.4",
  "rxjs": "^6.0.0",
  "zone.js": "^0.8.26"
 },
"devDependencies": {
  "@angular/compiler-cli": "^6.0.2",
  "@angular-devkit/build-angular": "~0.6.3",
  "typescript": "~2.7.2",
  "@angular/cli": "^6.0.3",
  "@angular/language-service": "^6.0.2",
  "@types/jasmine": "~2.8.6",
  "@types/jasminewd2": "~2.0.3",
  "@types/node": "~8.9.4",
  "codelyzer": "~4.2.1",
  "jasmine-core": "~2.99.1",
  "jasmine-spec-reporter": "~4.2.1",
  "karma": "~1.7.1",
  "karma-chrome-launcher": "~2.2.0",
  "karma-coverage-istanbul-reporter": "~1.4.2",
  "karma-jasmine": "~1.1.1",
  "karma-jasmine-html-reporter": "^0.2.2",
  "protractor": "~5.3.0",
  "ts-node": "~5.0.1",
  "tslint": "~5.9.1"
 }
}

angular.json:

 {
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "frontend": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/frontend",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "frontend:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "frontend:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "frontend:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "frontend-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "frontend:serve"
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "frontend"
}

Body:
If you are using angular version 8 please run the below command to fix this issue.

ng update @angular/cli @angular/core


问:
Default size for database fields
What the size that you use for common database fields, like firstName, lastName, Email, password, etc? I see these common fields in a lot of databases of blogs, forums, e-commerces, etc. But I don't know if there is some reference or default for the size for that common fields. So, I want to know what the method/reference/basis that you to use for selecting size for common fields.</p>

答:
Partly, it depends on your DBMS. Some, like MySQL 5, care about the length of a VARCHAR(n) column as opposed to an unlimited-length TEXT column; others, like PostgreSQL, consider TEXT and VARCHAR(n) as internally identical, with the exception that a length is checked on VARCHAR(n) columns. Writing something like VARCHAR(65536) in PostgreSQL is silly; if you want an unlimited-length column, choose TEXT and be done with it.

Of course, sometimes trying to store too long of a value will break your layout, or allow someone to abuse the system by choosing a long name with no spaces (for example). Usually what I do for username fields like that is just choose an upper length such that anyone who wants a longer username is trying to cause trouble; 64 characters is a nice round value and seems to work well. For real names and addresses (which aren't frequently displayed to users like a username is), you'll want to go with something longer. You want a value large enough that it can accept any valid input, but not so large that someone could stuff a gigabyte-long string in the field just to attack your system. 1024 characters is pretty reasonable: 1k is an small enough amount of text to easily work with, a round number, and larger than any sane address line or name.

Email addresses can, per the associated RFC whose number I am too lazy to look up right now, be no longer than 320 characters. So there's your email field length. Turns out that SMTP limits the length of fields to 256 characters; since email addresses must be bracketed, the longest valid email address is actually 254 characters. (This page goes into more detail.) So there's your email field length.

Passwords should NEVER be stored in plaintext, so your password field should be a byte array or BLOB type exactly long enough to store the output of the hash function you are using (or largest element of the cryptographic group in use, for more advanced schemes like SRP-6a).

OwnerDisplayName: Click Ok

ContentLicense: CC BY-SA 2.5

Title: Default size for database fields

OwnerDisplayName: kquinn