问:
Cannot access Angular scope variable from pug/HTML (yeoman angular-fullstack)
I cannot access from PUG to a variable in the controller. Please, may anybody help me?

I´m trying to access the AwesomeThings array with $ctrl.awesomeThings,
  with JavaController.awesomeThings, with this.awesomeThings, with java.awesomeThings, and none
  of them seem to work. The ng-repeat never creates nor an option. It seems
  that the array is not being recognized.

Could you please help me guys? I´m sure i´m missing something that I do not know of the new versions of angular-fullstack + Typescript.

Thanks a lot.

The PUG file

```<code>.container
  p
    | Documentación Java
  hr
  ul.nav.nav-tabs.nav-stacked.col-md-4.col-lg-4.col-sm-6
    li(ng-repeat='thing in awesomeThings') //THIS IS WHAT DOES NOT WORK
      a(ng-href='{{thing.URL}}', uib-tooltip='{{thing.nombre}}', target="_blank") {{thing.nombre}}
</code>```

The Controller

```<code>'use strict';

export default class JavaController {

  awesomeThings = [{nombre:"La tecnología Java", URL: "http://www.ciberaula.com/articulo/tecnologia_java"},
      {nombre:"La Programación orientada a Objetos (VIDEO)", URL: "https://www.youtube.com/watch?v=8UgQNQML_b8"},
      {nombre:"Herencia y relaciones entre objetos", URL: "https://www.arquitecturajava.com/herencia-y-el-principio-de-substitucion-de-liskov/"},
      {nombre:"Herencia en Java", URL: "https://jarroba.com/herencia-en-la-programacion-orientada-a-objetos-ejemplo-en-java/"},
      {nombre:"Java, overrides y encapsulación", URL: "https://www.arquitecturajava.com/java-override-y-encapsulacion/"},
      {nombre:"Artuitectura de componentes y JEE (PDF)", URL: "http://ocw.uc3m.es/ingenieria-telematica/software-de-comunicaciones/transparencias/3_cmpnts-JavaEE.pdf"},
      {nombre:"Clases y medotodos", URL: "https://www.aprenderaprogramar.com/index.php?option=com_content&view=article&id=426:ique-es-una-clase-java-concepto-atributos-propiedades-o-campos-constructor-y-metodos-cu00623b&catid=68&Itemid=188"},
      {nombre:"Glosario de conceptos", URL: "https://www.java.com/es/download/faq/helpful_concepts.xml"},
      {nombre:"Arquitecturas MVC/REST", URL: "https://www.youtube.com/watch?v=qyt2Ct0hWqU"},
      {nombre:"POJO, DTO, JavaBeans", URL: "https://www.youtube.com/watch?v=Iy7je1tJ20Y"},
      {nombre:"CURSO JAVA DESDE CERO (lista de videos)", URL: "https://www.youtube.com/playlist?list=PLU8oAlHdN5BktAXdEVCLUYzvDyqRQJ2lk"},
      {nombre:"MAVEN, Qué es", URL: "http://www.javiergarzas.com/2014/06/maven-en-10-min.html"},
      {nombre:"Qué es JUnit", URL: "https://mikiorbe.wordpress.com/2009/10/23/junit-herramienta-indispensable-para-el-desarrollo-java"},
      {nombre:"Qué es JavaDocs", URL: "http://java-white-box.blogspot.com.es/2012/08/javadoc-que-es-el-javadoc-como-utilizar.html"},
      {nombre:"Arquitectura Java - Básico (VIDEO)", URL: "http://java-white-box.blogspot.com.es/2012/08/javadoc-que-es-el-javadoc-como-utilizar.html"},
      {nombre:"Arquitectura Java - La máquina virtual Java", URL: "https://cursos.arquitecturajava.com/courses/programacion-orientada-a-objeto-en-java/lectures/2857884http://cursos.arquitecturajava.com/courses/programacion-orientada-a-objeto-en-java/lectures/2857884"},
      {nombre:"Arquitectura Java - Clases y objetos", URL: "https://cursos.arquitecturajava.com/courses/programacion-orientada-a-objeto-en-java/lectures/2863618"}
      ];

  /*@ngInject*/
  constructor() {

      console.log(this.awesomeThings);
  }

}
</code>```

The Index.ts for my controller

```<code>'use strict';
const angular = require('angular');
import routes from './java.routes';
import JavaController from './java.controller';

export default angular.module('homeCalidadApp.java', [
      'homeCalidadApp.auth',
      'ui.router'
    ])
  .config(routes)
  .controller('JavaController', JavaController)
  .name;
</code>```

答:
After some research, I finally found what was the trouble and the solution:

The controller must be identified by controllerAs method. Then, after
  identifying the controllerAs name, you will be able to access to it.

If you use, for example,  controllerAs("pp"), the value in the pug file will be {{pp.value}}

Here is the link with the info. Check @jasonals comment on 12 Oct
  2013

The PUG file:

```<code>.container
  p
    | Documentación Java
  hr
  ul.nav.nav-tabs.nav-stacked.col-md-4.col-lg-4.col-sm-6
    li(ng-repeat='thing in ctrl.awesomeThings') //CHECK HERE. The right value is CTRL.awesomeThings
      a( ng-href='{{thing.URL}}', uib-tooltip='{{thing.nombre}}', target="_blank") {{thing.nombre}}
</code>```

The route

```<code>export default function routes($stateProvider) {
  'ngInject';
  $stateProvider
  .state('java', {
      url: '/java',
      template: require('./java.pug'),
      controller: 'JavaController as ctrl'
    });
};
</code>```

The Controller

```<code>export default class JavaController {
    $http;
  awesomeThings = [{nombre:"La tecnología Java", URL: "http://www.ciberaula.com/articulo/tecnologia_java"},
      {nombre:"La Programación orientada a Objetos (VIDEO)", URL: "https://www.youtube.com/watch?v=8UgQNQML_b8"},
      {nombre:"Herencia y relaciones entre objetos", URL: "https://www.arquitecturajava.com/herencia-y-el-principio-de-substitucion-de-liskov/"},
      {nombre:"Herencia en Java", URL: "https://jarroba.com/herencia-en-la-programacion-orientada-a-objetos-ejemplo-en-java/"},
      {nombre:"Java, overrides y encapsulación", URL: "https://www.arquitecturajava.com/java-override-y-encapsulacion/"},
      {nombre:"Artuitectura de componentes y JEE (PDF)", URL: "http://ocw.uc3m.es/ingenieria-telematica/software-de-comunicaciones/transparencias/3_cmpnts-JavaEE.pdf"},
      {nombre:"Clases y medotodos", URL: "https://www.aprenderaprogramar.com/index.php?option=com_content&view=article&id=426:ique-es-una-clase-java-concepto-atributos-propiedades-o-campos-constructor-y-metodos-cu00623b&catid=68&Itemid=188"},
      {nombre:"Glosario de conceptos", URL: "https://www.java.com/es/download/faq/helpful_concepts.xml"},
      {nombre:"Arquitecturas MVC/REST", URL: "https://www.youtube.com/watch?v=qyt2Ct0hWqU"},
      {nombre:"POJO, DTO, JavaBeans", URL: "https://www.youtube.com/watch?v=Iy7je1tJ20Y"},
      {nombre:"CURSO JAVA DESDE CERO (lista de videos)", URL: "https://www.youtube.com/playlist?list=PLU8oAlHdN5BktAXdEVCLUYzvDyqRQJ2lk"},
      {nombre:"MAVEN, Qué es", URL: "http://www.javiergarzas.com/2014/06/maven-en-10-min.html"},
      {nombre:"Qué es JUnit", URL: "https://mikiorbe.wordpress.com/2009/10/23/junit-herramienta-indispensable-para-el-desarrollo-java"},
      {nombre:"Qué es JavaDocs", URL: "http://java-white-box.blogspot.com.es/2012/08/javadoc-que-es-el-javadoc-como-utilizar.html"},
      {nombre:"Arquitectura Java - Básico (VIDEO)", URL: "http://java-white-box.blogspot.com.es/2012/08/javadoc-que-es-el-javadoc-como-utilizar.html"},
      {nombre:"Arquitectura Java - La máquina virtual Java", URL: "https://cursos.arquitecturajava.com/courses/programacion-orientada-a-objeto-en-java/lectures/2857884http://cursos.arquitecturajava.com/courses/programacion-orientada-a-objeto-en-java/lectures/2857884"},
      {nombre:"Arquitectura Java - Clases y objetos", URL: "https://cursos.arquitecturajava.com/courses/programacion-orientada-a-objeto-en-java/lectures/2863618"}
      ];
    /*@ngInject*/
    constructor($http, $scope, socket) {
      this.$http = $http;
      //this.socket = socket;
      $scope.awesomeThings = this.awesomeThings;
    }
}
</code>```

Body:
I cannot access from PUG to a variable in the controller. Please, may anybody help me?

I´m trying to access the AwesomeThings array with $ctrl.awesomeThings,
  with JavaController.awesomeThings, with this.awesomeThings, with java.awesomeThings, and none
  of them seem to work. The ng-repeat never creates nor an option. It seems
  that the array is not being recognized.

Could you please help me guys? I´m sure i´m missing something that I do not know of the new versions of angular-fullstack + Typescript.

Thanks a lot.

The PUG file

.container
  p
    | Documentación Java
  hr
  ul.nav.nav-tabs.nav-stacked.col-md-4.col-lg-4.col-sm-6
    li(ng-repeat='thing in awesomeThings') //THIS IS WHAT DOES NOT WORK
      a(ng-href='{{thing.URL}}', uib-tooltip='{{thing.nombre}}', target="_blank") {{thing.nombre}}

The Controller

'use strict';

export default class JavaController {

  awesomeThings = [{nombre:"La tecnología Java", URL: "http://www.ciberaula.com/articulo/tecnologia_java"},
      {nombre:"La Programación orientada a Objetos (VIDEO)", URL: "https://www.youtube.com/watch?v=8UgQNQML_b8"},
      {nombre:"Herencia y relaciones entre objetos", URL: "https://www.arquitecturajava.com/herencia-y-el-principio-de-substitucion-de-liskov/"},
      {nombre:"Herencia en Java", URL: "https://jarroba.com/herencia-en-la-programacion-orientada-a-objetos-ejemplo-en-java/"},
      {nombre:"Java, overrides y encapsulación", URL: "https://www.arquitecturajava.com/java-override-y-encapsulacion/"},
      {nombre:"Artuitectura de componentes y JEE (PDF)", URL: "http://ocw.uc3m.es/ingenieria-telematica/software-de-comunicaciones/transparencias/3_cmpnts-JavaEE.pdf"},
      {nombre:"Clases y medotodos", URL: "https://www.aprenderaprogramar.com/index.php?option=com_content&view=article&id=426:ique-es-una-clase-java-concepto-atributos-propiedades-o-campos-constructor-y-metodos-cu00623b&catid=68&Itemid=188"},
      {nombre:"Glosario de conceptos", URL: "https://www.java.com/es/download/faq/helpful_concepts.xml"},
      {nombre:"Arquitecturas MVC/REST", URL: "https://www.youtube.com/watch?v=qyt2Ct0hWqU"},
      {nombre:"POJO, DTO, JavaBeans", URL: "https://www.youtube.com/watch?v=Iy7je1tJ20Y"},
      {nombre:"CURSO JAVA DESDE CERO (lista de videos)", URL: "https://www.youtube.com/playlist?list=PLU8oAlHdN5BktAXdEVCLUYzvDyqRQJ2lk"},
      {nombre:"MAVEN, Qué es", URL: "http://www.javiergarzas.com/2014/06/maven-en-10-min.html"},
      {nombre:"Qué es JUnit", URL: "https://mikiorbe.wordpress.com/2009/10/23/junit-herramienta-indispensable-para-el-desarrollo-java"},
      {nombre:"Qué es JavaDocs", URL: "http://java-white-box.blogspot.com.es/2012/08/javadoc-que-es-el-javadoc-como-utilizar.html"},
      {nombre:"Arquitectura Java - Básico (VIDEO)", URL: "http://java-white-box.blogspot.com.es/2012/08/javadoc-que-es-el-javadoc-como-utilizar.html"},
      {nombre:"Arquitectura Java - La máquina virtual Java", URL: "https://cursos.arquitecturajava.com/courses/programacion-orientada-a-objeto-en-java/lectures/2857884http://cursos.arquitecturajava.com/courses/programacion-orientada-a-objeto-en-java/lectures/2857884"},
      {nombre:"Arquitectura Java - Clases y objetos", URL: "https://cursos.arquitecturajava.com/courses/programacion-orientada-a-objeto-en-java/lectures/2863618"}
      ];

  /*@ngInject*/
  constructor() {

      console.log(this.awesomeThings);
  }

}

The Index.ts for my controller

'use strict';
const angular = require('angular');
import routes from './java.routes';
import JavaController from './java.controller';

export default angular.module('homeCalidadApp.java', [
      'homeCalidadApp.auth',
      'ui.router'
    ])
  .config(routes)
  .controller('JavaController', JavaController)
  .name;

Body:
After some research, I finally found what was the trouble and the solution:

The controller must be identified by controllerAs method. Then, after
  identifying the controllerAs name, you will be able to access to it.

If you use, for example,  controllerAs("pp"), the value in the pug file will be {{pp.value}}

Here is the link with the info. Check @jasonals comment on 12 Oct
  2013

The PUG file:

.container
  p
    | Documentaci&oacute;n Java
  hr
  ul.nav.nav-tabs.nav-stacked.col-md-4.col-lg-4.col-sm-6
    li(ng-repeat='thing in ctrl.awesomeThings') //CHECK HERE. The right value is CTRL.awesomeThings
      a( ng-href='{{thing.URL}}', uib-tooltip='{{thing.nombre}}', target="_blank") {{thing.nombre}}

The route

export default function routes($stateProvider) {
  'ngInject';
  $stateProvider
  .state('java', {
      url: '/java',
      template: require('./java.pug'),
      controller: 'JavaController as ctrl'
    });
};

The Controller

export default class JavaController {
    $http;
  awesomeThings = [{nombre:"La tecnología Java", URL: "http://www.ciberaula.com/articulo/tecnologia_java"},
      {nombre:"La Programación orientada a Objetos (VIDEO)", URL: "https://www.youtube.com/watch?v=8UgQNQML_b8"},
      {nombre:"Herencia y relaciones entre objetos", URL: "https://www.arquitecturajava.com/herencia-y-el-principio-de-substitucion-de-liskov/"},
      {nombre:"Herencia en Java", URL: "https://jarroba.com/herencia-en-la-programacion-orientada-a-objetos-ejemplo-en-java/"},
      {nombre:"Java, overrides y encapsulación", URL: "https://www.arquitecturajava.com/java-override-y-encapsulacion/"},
      {nombre:"Artuitectura de componentes y JEE (PDF)", URL: "http://ocw.uc3m.es/ingenieria-telematica/software-de-comunicaciones/transparencias/3_cmpnts-JavaEE.pdf"},
      {nombre:"Clases y medotodos", URL: "https://www.aprenderaprogramar.com/index.php?option=com_content&view=article&id=426:ique-es-una-clase-java-concepto-atributos-propiedades-o-campos-constructor-y-metodos-cu00623b&catid=68&Itemid=188"},
      {nombre:"Glosario de conceptos", URL: "https://www.java.com/es/download/faq/helpful_concepts.xml"},
      {nombre:"Arquitecturas MVC/REST", URL: "https://www.youtube.com/watch?v=qyt2Ct0hWqU"},
      {nombre:"POJO, DTO, JavaBeans", URL: "https://www.youtube.com/watch?v=Iy7je1tJ20Y"},
      {nombre:"CURSO JAVA DESDE CERO (lista de videos)", URL: "https://www.youtube.com/playlist?list=PLU8oAlHdN5BktAXdEVCLUYzvDyqRQJ2lk"},
      {nombre:"MAVEN, Qué es", URL: "http://www.javiergarzas.com/2014/06/maven-en-10-min.html"},
      {nombre:"Qué es JUnit", URL: "https://mikiorbe.wordpress.com/2009/10/23/junit-herramienta-indispensable-para-el-desarrollo-java"},
      {nombre:"Qué es JavaDocs", URL: "http://java-white-box.blogspot.com.es/2012/08/javadoc-que-es-el-javadoc-como-utilizar.html"},
      {nombre:"Arquitectura Java - Básico (VIDEO)", URL: "http://java-white-box.blogspot.com.es/2012/08/javadoc-que-es-el-javadoc-como-utilizar.html"},
      {nombre:"Arquitectura Java - La máquina virtual Java", URL: "https://cursos.arquitecturajava.com/courses/programacion-orientada-a-objeto-en-java/lectures/2857884http://cursos.arquitecturajava.com/courses/programacion-orientada-a-objeto-en-java/lectures/2857884"},
      {nombre:"Arquitectura Java - Clases y objetos", URL: "https://cursos.arquitecturajava.com/courses/programacion-orientada-a-objeto-en-java/lectures/2863618"}
      ];
    /*@ngInject*/
    constructor($http, $scope, socket) {
      this.$http = $http;
      //this.socket = socket;
      $scope.awesomeThings = this.awesomeThings;
    }
}


来源: stackexchange

问:
Load and subscribe on extension
I'm starting to create a simple chrome extension and one of the features I need is a notification system, so I'm using onesignal, in my script. I wish the user when installing the chrome extension to subscribe automaticlly, but it is not loading the object of onesignal which I can't figure out why. I'm saying this because no subscriptions is showing up after I install it.

My code:
manifest.json

```<code>{
  "name": "My title",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "some description",
  "background": {
    "scripts": [
      "background.js","OneSignal.js"
    ],
    "persistent": false
  },
  "browser_action": {
    "default_title": "my extension"
  },
  "permissions": [
    "https://*/*",
    "http://*/*",
    "tabs",
    "gcm",
    "notifications",
    "storage",
    "identity"
  ]
}
</code>```

background.js:

```<code>OneSignal.init({appId: "dasdasd-b228-437d-bb8f-43asdasdb3", googleProjectNumber: "99999999"});
</code>```

Am I missing something?

答:
The problem is in the scripts order:

Solution:

```<code>...
background": {
    "scripts": [
      "OneSignal.js","background.js"
    ],
..
</code>```

ContentLicense: CC BY-SA 3.0

Title: Load and subscribe on extension

Body:
I'm starting to create a simple chrome extension and one of the features I need is a notification system, so I'm using onesignal, in my script. I wish the user when installing the chrome extension to subscribe automaticlly, but it is not loading the object of onesignal which I can't figure out why. I'm saying this because no subscriptions is showing up after I install it.

My code:
manifest.json

{
  "name": "My title",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "some description",
  "background": {
    "scripts": [
      "background.js","OneSignal.js"
    ],
    "persistent": false
  },
  "browser_action": {
    "default_title": "my extension"
  },
  "permissions": [
    "https://*/*",
    "http://*/*",
    "tabs",
    "gcm",
    "notifications",
    "storage",
    "identity"
  ]
}

background.js:

OneSignal.init({appId: "dasdasd-b228-437d-bb8f-43asdasdb3", googleProjectNumber: "99999999"});

Am I missing something?

Body:
The problem is in the scripts order:

Solution:

...
background": {
    "scripts": [
      "OneSignal.js","background.js"
    ],
..


问:
HTML5 Speech Synthesis
Simply put, it is very simple and contains minimum amount of conding (only two lines)

but I am still not hearing anything.   But Google TTS works perfectly on my laptop.

I only see "one two" alert when I run the page below.

```<code><!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head>

<body>

<script>
    var utterance = new SpeechSynthesisUtterance('Hello baby');
    window.speechSynthesis.speak(utterance);
    alert("one two");
</script>

</body>
</html>
</code>```

And I use Google Chrome Ver 36.  How do I view the errors in my JavaScript?   Thanks a lot Stack Overflow!

答:
The above answer works nicely, but if you want to pick another voice use this:</p>

```<code>function saySomething(whatToSay){
  const synth = window.speechSynthesis;
  // enter your voice here, because voices list loads asynchronously.. check the console.log below.
  getVoice("Google US English", synth)
    .then(voice => {
      var utterThis = new SpeechSynthesisUtterance(whatToSay);
      utterThis.voice = voice;
      synth.speak(utterThis);
    })
    .catch(error => console.log("error: ", error));
}

function getVoice(voiceName, synth){
  return new Promise((resolve, reject) =>{
    synth.onvoiceschanged = function(){
      const voices = synth.getVoices();

      console.log("see all available languages and voices on your system: ", voices);

      for(let i = 0; i < voices.length ; i++) {
          if(voices[i].name == voiceName) {
            resolve(voices[i]);
          }
        }
    }
    synth.getVoices();
  });
}

saySomething("Mu ha ha! Works now.");
</code>```

Title: HTML5 Speech Synthesis

Body:
Simply put, it is very simple and contains minimum amount of conding (only two lines)

but I am still not hearing anything.   But Google TTS works perfectly on my laptop.

I only see "one two" alert when I run the page below.

<!DOCTYPE html>   <meta charset="utf-8">

And I use Google Chrome Ver 36.  How do I view the errors in my JavaScript?   Thanks a lot Stack Overflow!

Body:
The above answer works nicely, but if you want to pick another voice use this:

function saySomething(whatToSay){
  const synth = window.speechSynthesis;
  // enter your voice here, because voices list loads asynchronously.. check the console.log below.
  getVoice("Google US English", synth)
    .then(voice => {
      var utterThis = new SpeechSynthesisUtterance(whatToSay);
      utterThis.voice = voice;
      synth.speak(utterThis);
    })
    .catch(error => console.log("error: ", error));
}

function getVoice(voiceName, synth){
  return new Promise((resolve, reject) =>{
    synth.onvoiceschanged = function(){
      const voices = synth.getVoices();

      console.log("see all available languages and voices on your system: ", voices);

      for(let i = 0; i < voices.length ; i++) {
          if(voices[i].name == voiceName) {
            resolve(voices[i]);
          }
        }
    }
    synth.getVoices();
  });
}

saySomething("Mu ha ha! Works now.");


问:
Simulate Control-Alt-Delete key sequence in Vista and XP
Can I simulate in C#/C++ code Control+Alt+Delete sequence in Vista?
When UAC enabled/disabled?
How it is done in XP?

Can you provide a code sample that works in Vista?

答:
You have to call next code from service process only</p>

```<code>HDESK desktop = OpenDesktopW(L"Winlogon", 0, TRUE,
    DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | DESKTOP_ENUMERATE |
    DESKTOP_HOOKCONTROL | DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
    DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);
int result = SetThreadDesktop(desktop);
if (result)
{
    HMODULE sasdll = LoadLibraryA("sas.dll");
    if (sasdll)
    {
        typedef void(__stdcall * SendSAS_t)(BOOL);
        SendSAS_t sendSAS = (SendSAS_t)GetProcAddress(sasdll, "SendSAS");
        if (sendSAS)
            sendSAS(FALSE);
    }
}
CloseDesktop(desktop);
</code>```

OwnerDisplayName: Yuval

LastEditorDisplayName: Yuval

Body:
You have to call next code from service process only

HDESK desktop = OpenDesktopW(L"Winlogon", 0, TRUE,
    DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | DESKTOP_ENUMERATE |
    DESKTOP_HOOKCONTROL | DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
    DESKTOP_SWITCHDESKTOP | GENERIC_WRITE);
int result = SetThreadDesktop(desktop);
if (result)
{
    HMODULE sasdll = LoadLibraryA("sas.dll");
    if (sasdll)
    {
        typedef void(__stdcall * SendSAS_t)(BOOL);
        SendSAS_t sendSAS = (SendSAS_t)GetProcAddress(sasdll, "SendSAS");
        if (sendSAS)
            sendSAS(FALSE);
    }
}
CloseDesktop(desktop);


问:
Generic way to exit a .NET application
I understand that there are a few ways to exit an application, such as Application.Exit(), Application.ExitThread(), Environment.Exit(), etc.

I have an external "commons" library, and I'm trying to create a generic FailIf method that logs the failure to the logs, does this and that and this and that, then finally exits the application... here's a short version of it.

```<code>    public static void FailIf(Boolean fail, String message, Int32 exitCode = 1)
    {
        if (String.IsNullOrEmpty(message))
            throw new ArgumentNullException("message");

        if (fail)
        {
            //Do whatever I need to do

            //Currently Environment.Exit(exitCode)
            Environment.Exit(exitCode);
        }
    }
</code>```

I have read that using Environment.Exit isn't the best way to handle things when it comes to WinForm apps, and also when working with WPF apps and Silverlight there are different ways to exit... My question is really:

What do I put to exit gracefully to cover all application types?

答: If it's just an abort, use Environment.Exit(). If it's something very critical (that can't handle any sort of cleanup), use Environment.FailFast().

ContentLicense: CC BY-SA 2.5

Title: Generic way to exit a .NET application

Body:
I understand that there are a few ways to exit an application, such as Application.Exit(), Application.ExitThread(), Environment.Exit(), etc.

I have an external "commons" library, and I'm trying to create a generic FailIf method that logs the failure to the logs, does this and that and this and that, then finally exits the application... here's a short version of it.

    public static void FailIf(Boolean fail, String message, Int32 exitCode = 1)
    {
        if (String.IsNullOrEmpty(message))
            throw new ArgumentNullException("message");

        if (fail)
        {
            //Do whatever I need to do

            //Currently Environment.Exit(exitCode)
            Environment.Exit(exitCode);
        }
    }

I have read that using Environment.Exit isn't the best way to handle things when it comes to WinForm apps, and also when working with WPF apps and Silverlight there are different ways to exit... My question is really:

What do I put to exit gracefully to cover all application types?


问:
pip not working, citing /private/var path failure
In many years of python I have not seen this. When I try to pip install, it complains about /private/var. Is this a permissions issue?

location-tools is the name of my python package that I'm trying to install. I am in a virtual environment but I get the exact same error outside of it.

```<code>    pip install .                                                                                 1   master
Processing /Users/tommy/Development/python-location-tools
Building wheels for collected packages: location-tools
  Running setup.py bdist_wheel for location-tools ... error
  Complete output from command /usr/local/opt/python/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-ROZvTR-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/tmpm2DqL7pip-wheel- --python-tag cp27:
  Requirement already satisfied: gmplot==1.2.0 in /usr/local/lib/python2.7/site-packages (from -r requirements.txt (line 1))
  Requirement already satisfied: requests in /usr/local/lib/python2.7/site-packages (from gmplot==1.2.0->-r requirements.txt (line 1))
  Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
  Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
  Requirement already satisfied: urllib3<1.23,>=1.21.1 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
  Requirement already satisfied: idna<2.6,>=2.5 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib
  creating build/lib/location_tools
  copying location_tools/__init__.py -> build/lib/location_tools
  copying location_tools/plotting.py -> build/lib/location_tools
  running build_scripts
  creating build/scripts-2.7
  error: file '/private/var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-ROZvTR-build/bin/ll_plot' does not exist

  ----------------------------------------
  Failed building wheel for location-tools
  Running setup.py clean for location-tools
Failed to build location-tools
Installing collected packages: location-tools
  Running setup.py install for location-tools ... error
    Complete output from command /usr/local/opt/python/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-ROZvTR-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-bggTuL-record/install-record.txt --single-version-externally-managed --compile:
    Requirement already satisfied: gmplot==1.2.0 in /usr/local/lib/python2.7/site-packages (from -r requirements.txt (line 1))
    Requirement already satisfied: requests in /usr/local/lib/python2.7/site-packages (from gmplot==1.2.0->-r requirements.txt (line 1))
    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
    Requirement already satisfied: urllib3<1.23,>=1.21.1 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
    Requirement already satisfied: idna<2.6,>=2.5 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
    running install
    running build
    running build_py
    creating build
    creating build/lib
    creating build/lib/location_tools
    copying location_tools/__init__.py -> build/lib/location_tools
    copying location_tools/plotting.py -> build/lib/location_tools
    running build_scripts
    creating build/scripts-2.7
    error: file '/private/var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-ROZvTR-build/bin/ll_plot' does not exist

    ----------------------------------------
Command "/usr/local/opt/python/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-ROZvTR-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-bggTuL-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-ROZvT
</code>```

答:
As mentioned in the comments this is something wrong in your setup.py. Based on the error messages it seems that the setup.py script is trying to access a ll_plot executable. Since it is saying that it doesn't exist it is likely that you have an entry point script (via setuptools) or are trying to access the binary executable relative to the setup.py or other build script.

You'll want to check the shebang on any scripts you have to make sure they aren't trying to use a non-existent environment. Of course if this is a public package (or not too) you'll want to make sure to document the build prerequisites and how the environment needs to be configured to build the package properly.

Body:
In many years of python I have not seen this. When I try to pip install, it complains about /private/var. Is this a permissions issue?

location-tools is the name of my python package that I'm trying to install. I am in a virtual environment but I get the exact same error outside of it.

    pip install .                                                                                 1   master
Processing /Users/tommy/Development/python-location-tools
Building wheels for collected packages: location-tools
  Running setup.py bdist_wheel for location-tools ... error
  Complete output from command /usr/local/opt/python/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-ROZvTR-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/tmpm2DqL7pip-wheel- --python-tag cp27:
  Requirement already satisfied: gmplot==1.2.0 in /usr/local/lib/python2.7/site-packages (from -r requirements.txt (line 1))
  Requirement already satisfied: requests in /usr/local/lib/python2.7/site-packages (from gmplot==1.2.0->-r requirements.txt (line 1))
  Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
  Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
  Requirement already satisfied: urllib3<1.23,>=1.21.1 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
  Requirement already satisfied: idna<2.6,>=2.5 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib
  creating build/lib/location_tools
  copying location_tools/__init__.py -> build/lib/location_tools
  copying location_tools/plotting.py -> build/lib/location_tools
  running build_scripts
  creating build/scripts-2.7
  error: file '/private/var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-ROZvTR-build/bin/ll_plot' does not exist

  ----------------------------------------
  Failed building wheel for location-tools
  Running setup.py clean for location-tools
Failed to build location-tools
Installing collected packages: location-tools
  Running setup.py install for location-tools ... error
    Complete output from command /usr/local/opt/python/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-ROZvTR-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-bggTuL-record/install-record.txt --single-version-externally-managed --compile:
    Requirement already satisfied: gmplot==1.2.0 in /usr/local/lib/python2.7/site-packages (from -r requirements.txt (line 1))
    Requirement already satisfied: requests in /usr/local/lib/python2.7/site-packages (from gmplot==1.2.0->-r requirements.txt (line 1))
    Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
    Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
    Requirement already satisfied: urllib3<1.23,>=1.21.1 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
    Requirement already satisfied: idna<2.6,>=2.5 in /usr/local/lib/python2.7/site-packages (from requests->gmplot==1.2.0->-r requirements.txt (line 1))
    running install
    running build
    running build_py
    creating build
    creating build/lib
    creating build/lib/location_tools
    copying location_tools/__init__.py -> build/lib/location_tools
    copying location_tools/plotting.py -> build/lib/location_tools
    running build_scripts
    creating build/scripts-2.7
    error: file '/private/var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-ROZvTR-build/bin/ll_plot' does not exist

    ----------------------------------------
Command "/usr/local/opt/python/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-ROZvTR-build/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-bggTuL-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/v9/c461bkzn6r3ctmvg91df94c80000gn/T/pip-ROZvT


问:
Make header responsive for different screen resolutions
I am trying to make header responsive. Currently header is fixed and when  you view it from different screen resoultions it is not lookin good.

#tie-wrapper #theme-header {
    background-image: url(http://example.com/header-image.jpg);
    background-repeat: no-repeat;
}```

I wish to have same image on different resolutions. It should decrease with website. Also logo is centered so the image should be.

I really don't know how to add this image for different resolutions.

Thanks

答:
You can use different images at different screen widths using css:

```<code>@media only screen and (max-width: 1023px) {
    #tie-wrapper #theme-header {
        background: url('http://example.com/header-image_FULLWIDTH.jpg') center center/cover no-repeat;
        min-height: 500px;
        width: 100%;
    }
}
@media only screen and (max-width: 767px) {
    #tie-wrapper #theme-header {
        background: url('http://example.com/header-image_LARGE.jpg') center center/cover no-repeat;
        min-height: 400px;
    }
}
@media only screen and (max-width: 480px) {
    #tie-wrapper #theme-header {
        background: url('http://example.com/header-image_MEDIUM.jpg') center center/cover no-repeat;
        min-height: 300px;
    }
}
</code>```

I will normally add this code into my template file and using wp_get_attachement(), load up different sizes of images. Or you can hard code it in your styles.css. Either way.

Body:
I am trying to make header responsive. Currently header is fixed and when  you view it from different screen resoultions it is not lookin good.

#tie-wrapper #theme-header {
    background-image: url(http://example.com/header-image.jpg);
    background-repeat: no-repeat;
}

I wish to have same image on different resolutions. It should decrease with website. Also logo is centered so the image should be.

I really don't know how to add this image for different resolutions.

Thanks

Body:
You can use different images at different screen widths using css:

@media only screen and (max-width: 1023px) {
    #tie-wrapper #theme-header {
        background: url('http://example.com/header-image_FULLWIDTH.jpg') center center/cover no-repeat;
        min-height: 500px;
        width: 100%;
    }
}
@media only screen and (max-width: 767px) {
    #tie-wrapper #theme-header {
        background: url('http://example.com/header-image_LARGE.jpg') center center/cover no-repeat;
        min-height: 400px;
    }
}
@media only screen and (max-width: 480px) {
    #tie-wrapper #theme-header {
        background: url('http://example.com/header-image_MEDIUM.jpg') center center/cover no-repeat;
        min-height: 300px;
    }
}

I will normally add this code into my template file and using wp_get_attachement(), load up different sizes of images. Or you can hard code it in your styles.css. Either way.


问:
Is gcroot necessary inside a native C++ function?
I'm new to c++/cli programming and today I came across gcroot in one of my project and confused with its usage.
I found gcroot is the wrapper of GChandle, who notifies garbage-collector that the managed object is being referenced so the object doesn't get removed.

So it makes sense to use gcroot to declare properties in native class to hold reference to managed object. But I found gcroot is also used everywhere in the project like below:

```<code>int NativeFunction()
{
    gcroot<ManagedType^> xx = gcnew ManagedType();
    return xx->FunctionCalled();
}
</code>```

is this kind of implementation a good practice? is it necessary to use gcroot here?

what if I declare xx without gcroot, like:

```<code>ManagedType^ xx = gcnew ManagedType();
</code>```

does it create any problem?

答:
There are multiple levels of wrongness here.  Starting with the dead-wrong, you are right, using gcroot<> is entirely unnecessary and actively harmful.  It is a wrapper for GCHandle, you'll call GCHandle::Alloc(), GCHandle::ToIntPtr(), GCHandle::FromIntPtr() and GCHandle::Free() at runtime.  For no benefit whatsoever, the GC can already find the ManagedType object reference without any help.  A primary duty of the just-in-time compiler.  Your substitute is fine.

Then there is the what-the-heck wrongness, what kind of magic is being performed by the parameterless ManagedType constructor?  You'll have to take a look, there are decent odds that the author of this code just didn't realize that the static keyword should have been useful.  So he could have simply written ManagedType::FunctionCalled() and avoid allocating an object completely.  Relying too much on the gcroot<> crutch would certainly have prevented him from seeing that.

Then there is the nasty problem of calling this "native code".  It is not, it has to be compiled with /clr or #pragma managed in effect.  Which produces MSIL that has to be just-in-time compiled at runtime.  Just like managed code.  But without the benefits of managed code, it is just as unverifiable as native code.  And none of the benefits of native code, you won't get the extra optimizer love.  This tends to get extra bad when the entire library is getting compiled with /clr in effect.  Unfortunately the designers did too good of a job to make that easy to notice, you'd only observe the loss of performance.

Proper way is to do this the way native code always does this.  With a function pointer.  You get the one you need with Marshal::GetFunctionPointerForDelegate().  It is harder to write correctly however, and probably not something you should consider on working code unless you need to solve a perf problem.

Body:
I'm new to c++/cli programming and today I came across gcroot in one of my project and confused with its usage.
I found gcroot is the wrapper of GChandle, who notifies garbage-collector that the managed object is being referenced so the object doesn't get removed.

So it makes sense to use gcroot to declare properties in native class to hold reference to managed object. But I found gcroot is also used everywhere in the project like below:

int NativeFunction()
{
    gcroot<ManagedType^> xx = gcnew ManagedType();
    return xx->FunctionCalled();
}

is this kind of implementation a good practice? is it necessary to use gcroot here?

what if I declare xx without gcroot, like:

ManagedType^ xx = gcnew ManagedType();

does it create any problem?


问:
How to return a value from a method with a generic return type and where clause
I can make a function return a value with a generic return type but I can't make it return a value when I am using a where clause as well.

This is the code I am using:

```<code>func genericFunction<T: Collection>(collectionOne: T, collectionTwo: T) where T.Iterator.Element == (NSNumber) -> [Int] {

}
</code>```

It compiles ok. But if I try and return this:

```<code>let array = [1]

return array
</code>```

I get this error: 'unexpected non-void return type in void function' but as you can see the from the method declaration there is a return type so I have probably used the wrong syntax to declare the method.

What syntax should I use to return a value from the method?

Thanks in advance.

答:
```<code>func genericFunction<T: Collection>(collectionOne: T, collectionTwo: T)
     where T.Iterator.Element == (NSNumber) -> [Int]
</code>```

defines a function returning Void, with the constraint

```<code>T.Iterator.Element == (NSNumber) -> [Int]
</code>```

i.e. the element type is restricted to be a (NSNumber) -> [Int] closure.

What you probably want is

```<code>func genericFunction<T: Collection>(collectionOne: T, collectionTwo: T) -> [Int]
    where T.Iterator.Element == (NSNumber)
</code>```

which is a function returning [Int], with the element type
restricted to NSNumber.

In other words, the where-clause comes after the return type.

Body:
I can make a function return a value with a generic return type but I can't make it return a value when I am using a where clause as well.

This is the code I am using:

func genericFunction<T: Collection>(collectionOne: T, collectionTwo: T) where T.Iterator.Element == (NSNumber) -> [Int] {

}

It compiles ok. But if I try and return this:

let array = [1]

return array

I get this error: 'unexpected non-void return type in void function' but as you can see the from the method declaration there is a return type so I have probably used the wrong syntax to declare the method.

What syntax should I use to return a value from the method?

Thanks in advance.

Body:
func genericFunction<T: Collection>(collectionOne: T, collectionTwo: T)
     where T.Iterator.Element == (NSNumber) -> [Int]

defines a function returning Void, with the constraint

T.Iterator.Element == (NSNumber) -> [Int]

i.e. the element type is restricted to be a (NSNumber) -> [Int] closure.

What you probably want is

func genericFunction<T: Collection>(collectionOne: T, collectionTwo: T) -> [Int]
    where T.Iterator.Element == (NSNumber)

which is a function returning [Int], with the element type
restricted to NSNumber.

In other words, the where-clause comes after the return type.


问:
Do not receive certain PHP error messages
I am running Apache/PHP locally, and do receive errors in many cases, like uninitialized variables - but I have noticed a few cases where I do not receive error messages and am wondering if this is normal OR if I am missing out on anything,

```<code><?php

ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);

$1a = "Hello world!";
echo $1a;

?>
</code>```

Also producing no error:

```<code><?php

ini_set('display_errors', 'On');
error_reporting(E_ALL);

function a()
{
 $b = 5;
 echo $b;
}}

a();

?>
</code>```

Does this script product PHP errors as it should for you? If so, I am wondering why I receive none. This is not an error I am likely to make, but there have been other times where I receive a blank page like above, where I would like some sort of feedback.

答: Your calls to ini_set never get executed, because the error happens in the parsing phase (i.e. before anything gets executed). You need to set those configuration values earlier in .htaccess, httpd.conf or php.ini.

Body:
I am running Apache/PHP locally, and do receive errors in many cases, like uninitialized variables - but I have noticed a few cases where I do not receive error messages and am wondering if this is normal OR if I am missing out on anything,

<?php

ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);

$1a = "Hello world!";
echo $1a;

?>

Also producing no error:

<?php

ini_set('display_errors', 'On');
error_reporting(E_ALL);

function a()
{
 $b = 5;
 echo $b;
}}

a();

?>

Does this script product PHP errors as it should for you? If so, I am wondering why I receive none. This is not an error I am likely to make, but there have been other times where I receive a blank page like above, where I would like some sort of feedback.


问:
Expire my link after X hour nodejs

I am sending this email to invite people for registration.That's my route

router.post('/invite-supervisor', (req,res) => {
    const email = req.body.invite_email;
    const secretToken = randomstring.generate();
  //  console.log('Email :',email);

    //Composing email
    const html = `Hi there

    To get registered please click on the following link and paste your secret token for registration.

    Token : ${secretToken}

    http://localhost:3000/signup/${secretToken}

    Have a good day!`;

    //p

    mailer.sendEmail('admin@teamfly.com',email,'Please signup through this link',html);
    req.flash('success','An invitation email sent to '+email);
    res.redirect('/');

});
```

Now I want to disable my link after few hours.How can I do it.

答:
If it is not easy on your side to create and manage database for tokens and their expiration time, you can use JWT tokens and include the expiration time inside token itself: https://jwt.io

Especially with the Node.js you have already well-developed library for it: https://www.npmjs.com/package/jsonwebtoken

When you create your JWT token, you can set up "expiresIn" option to i.e. 6h and it automatically creates the "exp" field (so you dont have to count it)

Then when you verify token, it will automatically checks if it is still valid

Title: Expire my link after X hour nodejs

Body:
I am sending this email to invite people for registration.That's my route

router.post('/invite-supervisor', (req,res) => {
    const email = req.body.invite_email;
    const secretToken = randomstring.generate();
  //  console.log('Email :',email);

    //Composing email
    const html = `Hi there

    To get registered please click on the following link and paste your secret token for registration.

    Token : ${secretToken}

    http://localhost:3000/signup/${secretToken}

    Have a good day!`;

    //p

    mailer.sendEmail('admin@teamfly.com',email,'Please signup through this link',html);
    req.flash('success','An invitation email sent to '+email);
    res.redirect('/');

});

Now I want to disable my link after few hours.How can I do it.


问:
ADAL Authentication issue: sign in page presented in loop on android 7.0
We are using microsoft.identitymodel.clients.activedirectory library for authentication in our xamarin.Android app. Authentication is not working on android 7.0 devices. We are not able to enter password as the sign in page is presented in a loop.

The expectation is once we provide the username (somename@microsoft.com) it should redirect to a screen where it ask for password. In our case it never redirect to this screen.

We are using microsoft.identitymodel.clients.activedirectory 3.16.1

If we try to debug the code the AcquireTokenAsync() method never return the result.

Edit: Here is the Code:

```<code> public async Task<string> Authenticate(Android.App.Activity activity, bool prompt)
        {
            AuthenticationResult AResult;
            AuthenticationContext context = new AuthenticationContext(AdalIssuerAuthority);
            PlatformParameters prametrs = new PlatformParameters(activity);
            try
            {

                if (prompt)
                {
                    AResult = await context.AcquireTokenAsync(AdalResourceId, AdalClientId, _returnUri, prametrs);
                }
                else
                {
                    AResult = await context.AcquireTokenSilentAsync(AdalResourceId, AdalClientId);
                }

                if (string.IsNullOrEmpty(AResult.AccessToken))
                {
                    AResult = await context.AcquireTokenAsync(AdalResourceId, AdalClientId, _returnUri, prametrs);
                }

                if (AResult.AccessToken != null)
                {
                    Constants.szUserName = AResult.UserInfo.GivenName + " " + AResult.UserInfo.FamilyName;
                    Constants.Token = Constants.ADALAccessToken;
                    Constants.szUserAlias = Constants.szUserAlias;
                }

                return AResult.AccessToken;
            }
            catch (Exception ex)
            {
                //logging excepton here
            }
        }
</code>```

Code from Login Activity:

```<code> protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        try
        {
            base.OnActivityResult(requestCode, resultCode, data);
            AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
        }
        catch (Exception ex)
        {
            //log exception
        }
    }
</code>```

答:
I too got the same issue.

The step to override the OnActivityResult() was missed

Please add the below to MainActivity.cs ( Android project)

```<code>protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
    AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
}
</code>```

Body:
We are using microsoft.identitymodel.clients.activedirectory library for authentication in our xamarin.Android app. Authentication is not working on android 7.0 devices. We are not able to enter password as the sign in page is presented in a loop.

The expectation is once we provide the username (somename@microsoft.com) it should redirect to a screen where it ask for password. In our case it never redirect to this screen.

We are using microsoft.identitymodel.clients.activedirectory 3.16.1

If we try to debug the code the AcquireTokenAsync() method never return the result.

Edit: Here is the Code:

 public async Task<string> Authenticate(Android.App.Activity activity, bool prompt)
        {
            AuthenticationResult AResult;
            AuthenticationContext context = new AuthenticationContext(AdalIssuerAuthority);
            PlatformParameters prametrs = new PlatformParameters(activity);
            try
            {

                if (prompt)
                {
                    AResult = await context.AcquireTokenAsync(AdalResourceId, AdalClientId, _returnUri, prametrs);
                }
                else
                {
                    AResult = await context.AcquireTokenSilentAsync(AdalResourceId, AdalClientId);
                }

                if (string.IsNullOrEmpty(AResult.AccessToken))
                {
                    AResult = await context.AcquireTokenAsync(AdalResourceId, AdalClientId, _returnUri, prametrs);
                }

                if (AResult.AccessToken != null)
                {
                    Constants.szUserName = AResult.UserInfo.GivenName + " " + AResult.UserInfo.FamilyName;
                    Constants.Token = Constants.ADALAccessToken;
                    Constants.szUserAlias = Constants.szUserAlias;
                }

                return AResult.AccessToken;
            }
            catch (Exception ex)
            {
                //logging excepton here
            }
        }

Code from Login Activity:

 protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        try
        {
            base.OnActivityResult(requestCode, resultCode, data);
            AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
        }
        catch (Exception ex)
        {
            //log exception
        }
    }

Body:
I too got the same issue.

The step to override the OnActivityResult() was missed

Please add the below to MainActivity.cs ( Android project)

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
    AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
}


问:
Formal Languages : Grammar, construct a grammar which produces a particular pattern
I have to construction an L(G) which creates the following pattern:

"The word starts always with a 'b', if an a is in the word, that is immediately followed by 'b'"

So we cannot have two 'a' consequently

```<code>For ex the pattern can be:  'b', 'bb', 'bab', 'bbbbbbab', 'bababab'
</code>```

I construct the Finite State Machine, but I am not able to find a general L(G) which produces this kind of grammar, this is what I got so far:

```<code>L(G) = { b^n  a^m b^k | n>1, a => 0, b > 1 }
</code>```

Does anybody has an idea how to proceed with this problem, if yes please tell me what can I do?

答:
The language is this:

All strings of a's and b's which start with at least one b and which have at least one b after any a.

Whenever you're trying to understand a language, I recommend thinking about the shortest strings in the language and how longer strings are built up. The shortest string in the language described above is b. If we have a string in the language, how can we get longer strings? Well, we can always add more b's to get a string in the language. If we add an a, we must add at least one b. This suggests a regular expression of the form:

```<code>  bb* means one b, then any number of additional b's
  ^       this Kleene star lets us add any number of a's, or none at all
  |       ^
  |       |
bb* (abb*)*
|-| |-----|
 |     |
 |     V
 V     after any a, we must have at least one b
 the string must start with at least one b
</code>```

To get a grammar, we can use our observations of the shortest string and steps for deriving longer ones to write a recursive definition:

b is in L (the shortest string is the base case)

if x is in L, xb is in L (we can always add a b)

if x is in L, xab is in L (we can add an a if we follow it with a b)

nothing else is in L (boilerplate for recursive definitions)

To go from a recursive definition to a grammar, add a production to derive the base case from the start symbol:

```<code>S -> b
</code>```

S, by definition, derives a string in our language. In particular, from the other two productive rules above, we know that we can add one b or both an a and a b to the end of anything S derives, so we add productions

```<code>S -> Sb
S -> Sab
</code>```

Putting it all together, we get:

```<code>S -> b
S -> Sb
S -> Sab
</code>```

Another, maybe better, way to get a grammar is to find an automaton that gives you your language, and then use a construction to get the grammar. We might recognize this language is regular and write down a DFA for it:

```<code>      _               _
     / \             / \
  b |  |        a,b |  |
     \ V             \ V
----->q0----->q1----->q2
       ^  a   |   a
       |      |
       \______/
          b
</code>```

Here, q0 is the initial and only accepting state, q1 is the state where you have seen an a but not the required b, and q2 is a dead state reached after seeing two as in a row. To write down the grammar, you write down the transitions as follows:

```<code>(q0) -> b(q0)
(q0) -> a(q1)
(q1) -> b(q0)
(q1) -> a(q2)
(q2) -> b(q2)
(q2) -> a(q2)
</code>```

Finally, add empty/epsilon/lambda productions for every nonterminal representing an accepting state:

```<code>(q0) -> e
</code>```

Put it together and you have a grammar:

```<code>(q0) -> b(q0)
(q0) -> a(q1)
(q1) -> b(q0)
(q1) -> a(q2)
(q2) -> b(q2)
(q2) -> a(q2)
(q0) -> e
</code>```

You can remove empty/epsilon/lambda transitions from this and empty states to put it into Chomsky normal form (or whatever, close to it, I forget the order terminals and nonterminals need to be in):

```<code>(q0) -> a(q1)
(q0) -> b(q0) | b
(q1) -> b(q0) | b
</code>```

This is the same as our grammar before, except it adds an extra nonterminal whose only responsibility is putting the required b after an a, whereas the other grammar does it in one production.

Body:
I have to construction an L(G) which creates the following pattern:

"The word starts always with a 'b', if an a is in the word, that is immediately followed by 'b'"

So we cannot have two 'a' consequently

For ex the pattern can be:  'b', 'bb', 'bab', 'bbbbbbab', 'bababab'

I construct the Finite State Machine, but I am not able to find a general L(G) which produces this kind of grammar, this is what I got so far:

L(G) = { b^n  a^m b^k | n>1, a => 0, b > 1 }

Does anybody has an idea how to proceed with this problem, if yes please tell me what can I do?

Body:
The language is this:

All strings of a's and b's which start with at least one b and which have at least one b after any a.

Whenever you're trying to understand a language, I recommend thinking about the shortest strings in the language and how longer strings are built up. The shortest string in the language described above is b. If we have a string in the language, how can we get longer strings? Well, we can always add more b's to get a string in the language. If we add an a, we must add at least one b. This suggests a regular expression of the form:

  bb* means one b, then any number of additional b's
  ^       this Kleene star lets us add any number of a's, or none at all
  |       ^
  |       |
bb* (abb*)*
|-| |-----|
 |     |
 |     V
 V     after any a, we must have at least one b
 the string must start with at least one b

To get a grammar, we can use our observations of the shortest string and steps for deriving longer ones to write a recursive definition:

b is in L (the shortest string is the base case)

if x is in L, xb is in L (we can always add a b)

if x is in L, xab is in L (we can add an a if we follow it with a b)

nothing else is in L (boilerplate for recursive definitions)

To go from a recursive definition to a grammar, add a production to derive the base case from the start symbol:

S -> b

S, by definition, derives a string in our language. In particular, from the other two productive rules above, we know that we can add one b or both an a and a b to the end of anything S derives, so we add productions

S -> Sb
S -> Sab

Putting it all together, we get:

S -> b
S -> Sb
S -> Sab

Another, maybe better, way to get a grammar is to find an automaton that gives you your language, and then use a construction to get the grammar. We might recognize this language is regular and write down a DFA for it:

      _               _
     / \             / \
  b |  |        a,b |  |
     \ V             \ V
----->q0----->q1----->q2
       ^  a   |   a
       |      |
       \______/
          b

Here, q0 is the initial and only accepting state, q1 is the state where you have seen an a but not the required b, and q2 is a dead state reached after seeing two as in a row. To write down the grammar, you write down the transitions as follows:

(q0) -> b(q0)
(q0) -> a(q1)
(q1) -> b(q0)
(q1) -> a(q2)
(q2) -> b(q2)
(q2) -> a(q2)

Finally, add empty/epsilon/lambda productions for every nonterminal representing an accepting state:

(q0) -> e

Put it together and you have a grammar:

(q0) -> b(q0)
(q0) -> a(q1)
(q1) -> b(q0)
(q1) -> a(q2)
(q2) -> b(q2)
(q2) -> a(q2)
(q0) -> e

You can remove empty/epsilon/lambda transitions from this and empty states to put it into Chomsky normal form (or whatever, close to it, I forget the order terminals and nonterminals need to be in):

(q0) -> a(q1)
(q0) -> b(q0) | b
(q1) -> b(q0) | b

This is the same as our grammar before, except it adds an extra nonterminal whose only responsibility is putting the required b after an a, whereas the other grammar does it in one production.


问:
PHP MySQLi query returns NULL
I am trying to get my PHP code to connect to my database hosted on the same server, but no matter what I do, it always ends up returning an empty set.

```<code>$servername = "localhost";
                $username = "user";
                $password = "pass";
                $dbnom = "name";

                $conn = new mysqli($servername, $username, $password, $dbnom);

                mysqli_set_charset($conn, "utf8");

                if(!$conn) {
                    die("La connexion a échoué : " . mysqli_connect_error());
                }

                $championsSQL = "SELECT pa_championId FROM participants";
                $resultSQL = mysqli_query($conn, $championsSQL);

                if(mysqli_num_rows($resultSQL) > 0) {
                    while($row = mysqli_fetch_assoc($resultSQL)) {
                        echo "Nom des champions : " . $row["pa_championId"] . "<br>";
                    }
                }
                else {
                    echo "Aucun résultat";
                }
                var_dump($resultSQL);
                mysqli_close($conn);
</code>```

The MySQL request "SELECT pa_championId FROM participants" works when I enter it manually into the mysql command line on the server.
The var_dump at the end always returns NULL.
The PHP is from the "Select Data With MySQLi section of this website : https://www.w3schools.com/php/php_mysql_select.asp

I know this question has been posted many times before, but none of the answers I found fit my exact situation.

Logs : https://pastebin.com/M2GCQe4D

答:
My best guess is that the connection failed but your $conn wasn't empty so it never enteres this condition:

```<code>if(!$conn) {
     die("La connexion a échoué : " . mysqli_connect_error());
}
</code>```

You should try using this to see if it returned any errors

```<code>if ($conn->connect_error) {
    die("La connexion a échoué : " . $conn->connect_error);
}
</code>```

Title: PHP MySQLi query returns NULL

Body:
I am trying to get my PHP code to connect to my database hosted on the same server, but no matter what I do, it always ends up returning an empty set.

$servername = "localhost";
                $username = "user";
                $password = "pass";
                $dbnom = "name";

                $conn = new mysqli($servername, $username, $password, $dbnom);

                mysqli_set_charset($conn, "utf8");

                if(!$conn) {
                    die("La connexion a échoué : " . mysqli_connect_error());
                }

                $championsSQL = "SELECT pa_championId FROM participants";
                $resultSQL = mysqli_query($conn, $championsSQL);

                if(mysqli_num_rows($resultSQL) > 0) {
                    while($row = mysqli_fetch_assoc($resultSQL)) {
                        echo "Nom des champions : " . $row["pa_championId"] . "
";
                    }
                }
                else {
                    echo "Aucun résultat";
                }
                var_dump($resultSQL);
                mysqli_close($conn);

The MySQL request "SELECT pa_championId FROM participants" works when I enter it manually into the mysql command line on the server.
The var_dump at the end always returns NULL.
The PHP is from the "Select Data With MySQLi section of this website : https://www.w3schools.com/php/php_mysql_select.asp

I know this question has been posted many times before, but none of the answers I found fit my exact situation.

Logs : https://pastebin.com/M2GCQe4D

Body:
My best guess is that the connection failed but your $conn wasn't empty so it never enteres this condition:

if(!$conn) {
     die("La connexion a échoué : " . mysqli_connect_error());
}

You should try using this to see if it returned any errors

if ($conn->connect_error) {
    die("La connexion a échoué : " . $conn->connect_error);
}


问:
Does POSIX standard specify what calling convention functions like read() should follow?
I know that POSIX defines a set of functions that should be present in the compliant system. These include read(), write(), printf(), and many other that we know as "libc" functions.

But does POSIX enforce a calling convention for them, or it is up to OS implementors to choose?

答:
But does POSIX enforce a calling convention for them [...]?

No. POSIX aims to be portable. Calling conventions are heavily dependent on the architecture as they specify the way how stack and registers are used when calling subroutines. If POSIX made enforcements on certain calling conventions, it wouldn't be universally applicable any longer, or, alternatively, it would have to define calling conventions for each possible architecture, which is impossible.


问:
Firestore get all docs and subcollections of root collection
Say I have this kind of structure

```<code>    A (collection): {
       a (doc): {
           name:'Tim',
           B (collection):{
               b (doc): {
                      color:'blue'
               }
             }
          }
    }
</code>```

where A and B are collections while a and b are documents.

Is there a way to get everything contained in a root document with one query?

If I query like this

```<code>db.collection("A").doc("a").get()
</code>```

I just gets name:'Tim' field. What I want is to also get all B's documents.

I basically wish my query returns

```<code>         {
           user:'Tim',
           B (collection):{
               b (doc): {
                      color:'blue'
               }
             }
          }
</code>```

Is it possibly or do I really need to make multiple queries one for each collection :/ ?

Say I have a really deep nested tree of collections representing the user profile, my costs will raise like hell since each time I load a user profile I have a multiplier of read requests 1 x N where N is the depth of my tree :/.

答:
Adding to Matt R answer, if you're using babel or you can use async/await,  you can get the same result with less code(no catch/then):

```<code>// Get reference to all of the documents
console.log("Retrieving list of documents in collection");
let documents = await collectionRef.get();
documents.forEach(async doc => {
    console.log("Parent Document ID: ", doc.id);
    let subCollectionDocs = await collectionRef.doc(doc.id).collection("subCollection").get()
    subCollectionDocs.forEach(subCollectionDoc => {
        subCollectionDoc.forEach(doc => {
            console.log("Sub Document ID: ", doc.id);
        })
    });
});
</code>```

Body:
Say I have this kind of structure

    A (collection): {
       a (doc): {
           name:'Tim',
           B (collection):{
               b (doc): {
                      color:'blue'
               }
             }
          }
    }

where A and B are collections while a and b are documents.

Is there a way to get everything contained in a root document with one query?

If I query like this

db.collection("A").doc("a").get()

I just gets name:'Tim' field. What I want is to also get all B's documents.

I basically wish my query returns

         {
           user:'Tim',
           B (collection):{
               b (doc): {
                      color:'blue'
               }
             }
          }

Is it possibly or do I really need to make multiple queries one for each collection :/ ?

Say I have a really deep nested tree of collections representing the user profile, my costs will raise like hell since each time I load a user profile I have a multiplier of read requests 1 x N where N is the depth of my tree :/.

Body:
Adding to Matt R answer, if you're using babel or you can use async/await,  you can get the same result with less code(no catch/then):

// Get reference to all of the documents
console.log("Retrieving list of documents in collection");
let documents = await collectionRef.get();
documents.forEach(async doc => {
    console.log("Parent Document ID: ", doc.id);
    let subCollectionDocs = await collectionRef.doc(doc.id).collection("subCollection").get()
    subCollectionDocs.forEach(subCollectionDoc => {
        subCollectionDoc.forEach(doc => {
            console.log("Sub Document ID: ", doc.id);
        })
    });
});

ContentLicense: CC BY-SA 4.0


问:
Access Admin Panel in SonataAdminBundle without SonataUserBundle
I work in a Symfony Project with SonataAdminBundle, and I have 3 types of user : ROLE_SUPER_ADMIN ROLE_CORRESPONDANT and ROLE_CLIENT

ROLE_SUPER_ADMIN and ROLE_CORRESPONDANT have permission to access to Admin Panel,

and in Admin Panel I have a Menu like this :

Dashbord

Products

Stocks

Operations

Users

Correspondants

Clients

But I like to show only this item for ROLE_CORRESPONDANT:

Dashboard

Operations

Users

Clients

I now that it is easy with SonataUserBundle, but my problem that I should not use it, I should use only FOSUserBundle,

```<code>sonata_admin:

    dashboard:
        groups:
            Accueil:
                icon: '<i class="fa fa-home"></i>'

                items:
                    - app.admin.produit
                    // I would like to define roles her for each item
</code>```

Someone please can help me with idea if it is feasible?
Thanks for all

答:
app/config/config.yml

```<code>sonata_admin:
    dashboard:
        groups:
            news:
                label:                ~
                label_catalogue:      ~
                items:
                    - sonata.news.admin.post
                    - route:        blog_home
                      label:        Blog
                      roles:        [ ROLE_FOO, ROLE_BAR ]
                    - route:        blog_article
                      route_params: { articleId: 3 }
                      label:        Article
                roles: [ ROLE_ADMIN, ROLE_SONATA_ADMIN]
</code>```

link

Body:
I work in a Symfony Project with SonataAdminBundle, and I have 3 types of user : ROLE_SUPER_ADMIN ROLE_CORRESPONDANT and ROLE_CLIENT

ROLE_SUPER_ADMIN and ROLE_CORRESPONDANT have permission to access to Admin Panel,

and in Admin Panel I have a Menu like this :

Dashbord

Products

Stocks

Operations

Users

Correspondants

Clients

But I like to show only this item for ROLE_CORRESPONDANT:

Dashboard

Operations

Users

Clients

I now that it is easy with SonataUserBundle, but my problem that I should not use it, I should use only FOSUserBundle,

sonata_admin:

    dashboard:
        groups:
            Accueil:
                icon: ''

                items:
                    - app.admin.produit
                    // I would like to define roles her for each item

Someone please can help me with idea if it is feasible?
Thanks for all

Body:
app/config/config.yml

sonata_admin:
    dashboard:
        groups:
            news:
                label:                ~
                label_catalogue:      ~
                items:
                    - sonata.news.admin.post
                    - route:        blog_home
                      label:        Blog
                      roles:        [ ROLE_FOO, ROLE_BAR ]
                    - route:        blog_article
                      route_params: { articleId: 3 }
                      label:        Article
                roles: [ ROLE_ADMIN, ROLE_SONATA_ADMIN]

link


问:
My custom django-admin command won't call celery task
I am trying to write a custom django-admin command that executes a celery task, however the task doesn't execute and django just hangs when I try.

```<code>from django.core.management.base import BaseCommand
from myapp.tasks import my_celery_task

class Command(BaseCommand):
    def handle(self, *args, **options):
        print "starting task"
        my_celery_task.delay()
        print "task has been sent"
</code>```

The output I receive when calling the command is:

```<code>starting task
</code>```

I never reach the "task has been sent" line. It just hangs. I'm not sure why the task isn't running. Celery tasks are called perfectly when called by a view.

答: The issue was actually with RabbitMQ on Mac after upgrading to High Sierra.</p>

Body:
I am trying to write a custom django-admin command that executes a celery task, however the task doesn't execute and django just hangs when I try.

from django.core.management.base import BaseCommand
from myapp.tasks import my_celery_task

class Command(BaseCommand):
    def handle(self, *args, **options):
        print "starting task"
        my_celery_task.delay()
        print "task has been sent"

The output I receive when calling the command is:

starting task

I never reach the "task has been sent" line. It just hangs. I'm not sure why the task isn't running. Celery tasks are called perfectly when called by a view.


问:
Renumbering divs with Dojo
I found a thread on S.O. similar to what I need here. jQuery removing an element and renumbering remaining elements

The above uses jQuery which we don't use so I'm not sure how to translate this idea of div renumbering to Dojo.

I inherited a massive web project that makes extensive use of Dojo 1.5. I totally dig what I understand of it so far but I have a question.

We have a page with numbered divs that I am successfully able to remove and delete the divs from. What I am needing though are divs in sequential order. Here's an example of what I need to re-div

```<code><div id="filter_9_values_2_div">
<div id="filter_9_values_1_div">
<div id="filter_9_values_4_div">
</code>```

Ideally in my javascript routine where I delete a div, I'd like to rename these in order so they look like this....

```<code><div id="filter_9_values_1_div">
<div id="filter_9_values_2_div">
<div id="filter_9_values_3_div">
</code>```

Does anyone have any idea how I would pull this off? I know how to successfully add a new div and make it unique but the idea of rewriting the divs is a complete mystery to me. As always many thanks in advance for the help. Janie.

答:
```<code>dojo.query('div').forEach(function(el, index){
   dojo.attr(el, "id", "filter_9_values_" + (index + 1) + "_div");
});
</code>```

You might want to use something more specific as a query rather then using just "div" and if you needed more generic ID rather then having the "filter_9_values_..._div" you'd have to use regexp or split to build the string you want but this should give you the basic idea how to iterate over a collection of DOM elements and perform any action on them you could imagine.

Title: Renumbering divs with Dojo

Body:
I found a thread on S.O. similar to what I need here. jQuery removing an element and renumbering remaining elements

The above uses jQuery which we don't use so I'm not sure how to translate this idea of div renumbering to Dojo.

I inherited a massive web project that makes extensive use of Dojo 1.5. I totally dig what I understand of it so far but I have a question.

We have a page with numbered divs that I am successfully able to remove and delete the divs from. What I am needing though are divs in sequential order. Here's an example of what I need to re-div

Ideally in my javascript routine where I delete a div, I'd like to rename these in order so they look like this....

Does anyone have any idea how I would pull this off? I know how to successfully add a new div and make it unique but the idea of rewriting the divs is a complete mystery to me. As always many thanks in advance for the help. Janie.

Body:
dojo.query('div').forEach(function(el, index){
   dojo.attr(el, "id", "filter_9_values_" + (index + 1) + "_div");
});

You might want to use something more specific as a query rather then using just "div" and if you needed more generic ID rather then having the "filter_9_values_..._div" you'd have to use regexp or split to build the string you want but this should give you the basic idea how to iterate over a collection of DOM elements and perform any action on them you could imagine.


问:
How to add 2 products to sql at the same time
I have 2 tables:

Table order: IDorder, productId, quantity, price

Table orderdetails: ID, ShipName, ShipMobile, ShipAddress, ShipEmail, DateOrder.

My OrderDetailsDao (As Model):

```<code>raovatmuabanthucungEntities re = null;
public OrderDetailsDao()
{
    re = new raovatmuabanthucungEntities();
}
public long Insert(orderdetails detail)
{
    re.orderdetails.Add(order);
    re.SaveChanges();
    return order.ID;
}
</code>```

My OrderDao:

raovatmuabanthucungEntities re = null;
        public OrderDao()
        {
            re = new raovatmuabanthucungEntities();
        }
        public bool Insert(order order)
        {
            try
            {
                re.order.Add(order);
                re.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }```
</div>
</div>
</p>

<ul>
<li>My Controller: </li>
</ul>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> public ActionResult Payment(string shipName, string mobile, string address, string email)
        {
            var detail = new orderdetail();
            detail.NgayDatHang = DateTime.Now;
            detail.ShipAddress = address;
            detail.ShipMobile = mobile;
            detail.ShipName = shipName;
            detail.ShipEmail = email;
            try
            {
                var id = new OrderDetailsDao().Insert(detail);
                var cart = (List<CartItem>)Session[CartSession];
                var orderDao = new OrderDao();
                decimal total = 0;
                foreach (var item in cart)
                {
                    var order = new order();
                    order.ProductId= item.Product.ProductId;
                    order.IDOrder = id;
                    order.Price = item.Product.Price;
                    order.quantity = item.quantity;
                    orderDao.Insert(order);
                }
            }
            catch (Exception ex)
            {
                //ghi log
                return Redirect("/loi-thanh-toan");
            }
            return Redirect("/hoan-thanh");
        }</code>```

I have tried to debug but foreach loop work normaly and return 2 products when i click button PAY. But in my sql server table only 1 record inserted. And var cart = (List<CartItem>)Session[CartSession]; is my session to save products added to cart. Sorry for disturbing you but i don't know how to fix this. Please tell me if i miss something, i will update my question ... Thank for all.

答:
Actually in the line mentioned below :

```<code>order.IDOrder = id;
</code>```

you are trying to insert duplicates into a primary Key field (as communicated by you in messages), so the first time it succeeds to insert value and the second time it fails to do so as duplicate primary keys are not allowed.

Also, re.SaveChanges(); is adding an over-head to your database write operation. It is better if you create an IEnumerable or List of "order" and pass it to Insert() to save all at once.

Change this:

```<code>    try
    {
        var id = new OrderDetailsDao().Insert(detail);
        var cart = (List<CartItem>)Session[CartSession];
        var orderDao = new OrderDao();
        decimal total = 0;
        foreach (var item in cart)
        {
            var order = new order();
            order.ProductId= item.Product.ProductId;
            order.IDOrder = id;
            order.Price = item.Product.Price;
            order.quantity = item.quantity;
            orderDao.Insert(order);
        }
    }
</code>```

to:

```<code>    try
    {
        var id = new OrderDetailsDao().Insert(detail);
        var cart = (List<CartItem>)Session[CartSession];
        var orderDao = new OrderDao();
        decimal total = 0;
        List<order> orders = new List<order>();
        foreach (var item in cart)
        {
            var order = new order();
            order.ProductId= item.Product.ProductId;
            order.IDOrder = id;
            order.Price = item.Product.Price;
            order.quantity = item.quantity;
            orders.Add(order);
        }
        orderDao.Insert(orders);
    }
</code>```

Also, change this:

```<code>  public bool Insert(order order)
  {
    try
    {
        re.order.Add(order);
        re.SaveChanges();
        return true;
    }
    catch
    {
        return false;
    }
}
</code>```

to:

```<code>public bool Insert(List<order> orders)
{
    foreach(var order in orders)
    {
         re.order.Add(order);
    }
    try
    {
        re.SaveChanges();
        return true;
    }
    catch
    {
        return false;
    }
}
</code>```

Body:
I have 2 tables:

Table order: IDorder, productId, quantity, price

Table orderdetails: ID, ShipName, ShipMobile, ShipAddress, ShipEmail, DateOrder.

My OrderDetailsDao (As Model):

raovatmuabanthucungEntities re = null;
public OrderDetailsDao()
{
    re = new raovatmuabanthucungEntities();
}
public long Insert(orderdetails detail)
{
    re.orderdetails.Add(order);
    re.SaveChanges();
    return order.ID;
}

My OrderDao:

raovatmuabanthucungEntities re = null;
        public OrderDao()
        {
            re = new raovatmuabanthucungEntities();
        }
        public bool Insert(order order)
        {
            try
            {
                re.order.Add(order);
                re.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

My Controller:

 public ActionResult Payment(string shipName, string mobile, string address, string email)
        {
            var detail = new orderdetail();
            detail.NgayDatHang = DateTime.Now;
            detail.ShipAddress = address;
            detail.ShipMobile = mobile;
            detail.ShipName = shipName;
            detail.ShipEmail = email;
            try
            {
                var id = new OrderDetailsDao().Insert(detail);
                var cart = (List<CartItem>)Session[CartSession];
                var orderDao = new OrderDao();
                decimal total = 0;
                foreach (var item in cart)
                {
                    var order = new order();
                    order.ProductId= item.Product.ProductId;
                    order.IDOrder = id;
                    order.Price = item.Product.Price;
                    order.quantity = item.quantity;
                    orderDao.Insert(order);
                }
            }
            catch (Exception ex)
            {
                //ghi log
                return Redirect("/loi-thanh-toan");
            }
            return Redirect("/hoan-thanh");
        }

I have tried to debug but foreach loop work normaly and return 2 products when i click button PAY. But in my sql server table only 1 record inserted. And var cart = (List<CartItem>)Session[CartSession]; is my session to save products added to cart. Sorry for disturbing you but i don't know how to fix this. Please tell me if i miss something, i will update my question ... Thank for all.

Body:
Actually in the line mentioned below :

order.IDOrder = id;

you are trying to insert duplicates into a primary Key field (as communicated by you in messages), so the first time it succeeds to insert value and the second time it fails to do so as duplicate primary keys are not allowed.

Also, re.SaveChanges(); is adding an over-head to your database write operation. It is better if you create an IEnumerable or List of "order" and pass it to Insert() to save all at once.

Change this:

    try
    {
        var id = new OrderDetailsDao().Insert(detail);
        var cart = (List<CartItem>)Session[CartSession];
        var orderDao = new OrderDao();
        decimal total = 0;
        foreach (var item in cart)
        {
            var order = new order();
            order.ProductId= item.Product.ProductId;
            order.IDOrder = id;
            order.Price = item.Product.Price;
            order.quantity = item.quantity;
            orderDao.Insert(order);
        }
    }

to:

    try
    {
        var id = new OrderDetailsDao().Insert(detail);
        var cart = (List<CartItem>)Session[CartSession];
        var orderDao = new OrderDao();
        decimal total = 0;
        List<order> orders = new List<order>();
        foreach (var item in cart)
        {
            var order = new order();
            order.ProductId= item.Product.ProductId;
            order.IDOrder = id;
            order.Price = item.Product.Price;
            order.quantity = item.quantity;
            orders.Add(order);
        }
        orderDao.Insert(orders);
    }

Also, change this:

  public bool Insert(order order)
  {
    try
    {
        re.order.Add(order);
        re.SaveChanges();
        return true;
    }
    catch
    {
        return false;
    }
}

to:

public bool Insert(List<order> orders)
{
    foreach(var order in orders)
    {
         re.order.Add(order);
    }
    try
    {
        re.SaveChanges();
        return true;
    }
    catch
    {
        return false;
    }
}


问:
Import classes from external typescript library which uses namespaces
I have an existing Angular 2 Project and now I have to use an external TypeScript Library which uses Namespaces. I somehow need to import some classes from the External library so I can use them.

externalLibrary.ts:

```<code>namespace com.foo.bar {

  export class A {
    doSomething() {
    }
  }
}
</code>```

And in My Angular2 Component I want to to do:

```<code>myA: A = new A();
myA.doSomething();
</code>```

So far, i have tried:

1)

```<code>import {A} from '../dir/externalLibrary';
</code>```

which results in a compilation error because it says: 'externalLibrary.ts is not a module'.

2)

```<code>/// <reference path='../dir/externalLibrary.ts'>
...
myA: com.foo.bar.A = new com.foo.bar.A();
</code>```

which results in a run-time error saying: 'ReferenceError: com is not defined'

My Question is: How can I use the class A in my Project?
I am thankful for any help.

EDIT 1:

Just for clarification: The external library is a Java Library which is then transpiled into TypeScript. It consists of ~80.000 lines of code, therefore I can not change too much, because it would take too much time. This is also the reason why I have to stick to namespaces because the Typescipt transpiler creates them out of the existing java package structure.

@Aaron: Thanks for the answer but my upcoming problem with the 'export namespace' approach is as follows:
If i put 'export' before a namespace other Classes can not be found any longer:

b.ts:

```<code>export namespace com.foo.bar
{
    export interface B {

    }
}
</code>```

a.ts

```<code>export namespace com.foo.bar {

    export class A implements B
    {

    }
}
</code>```

In file a.ts the compiler says: 'cannot find name B'.
I also tried to somehow import B but I failed. Is there any posibillity to import B or am I completely on the wrong way?

答:
which results in a compilation error because it says: 'externalLibrary.ts is not a module'.

This compile error appears to be the truth. Looking at your definition it isn't exporting a module, it's just declaring a global namespace. You can use an import alias (TS feature, not ES6) to clean up your usage a bit:

```<code>import A = com.foo.bar.A;
new A();
</code>```

```<code>/// <reference path='../dir/externalLibrary.ts'>`
myA: com.foo.bar.A = new com.foo.bar.A();
</code>```

which results in a run-time error saying: 'ReferenceError: com is not defined'

This means you need to actually include the compiled externalLibrary.js in your running code. That could be as simple as a

Body:
I have an existing Angular 2 Project and now I have to use an external TypeScript Library which uses Namespaces. I somehow need to import some classes from the External library so I can use them.

externalLibrary.ts:

namespace com.foo.bar {

  export class A {
    doSomething() {
    }
  }
}

And in My Angular2 Component I want to to do:

myA: A = new A();
myA.doSomething();

So far, i have tried:

1)

import {A} from '../dir/externalLibrary';

which results in a compilation error because it says: 'externalLibrary.ts is not a module'.

2)

/// <reference path='../dir/externalLibrary.ts'>
...
myA: com.foo.bar.A = new com.foo.bar.A();

which results in a run-time error saying: 'ReferenceError: com is not defined'

My Question is: How can I use the class A in my Project?
I am thankful for any help.

EDIT 1:

Just for clarification: The external library is a Java Library which is then transpiled into TypeScript. It consists of ~80.000 lines of code, therefore I can not change too much, because it would take too much time. This is also the reason why I have to stick to namespaces because the Typescipt transpiler creates them out of the existing java package structure.

@Aaron: Thanks for the answer but my upcoming problem with the 'export namespace' approach is as follows:
If i put 'export' before a namespace other Classes can not be found any longer:

b.ts:

export namespace com.foo.bar
{
    export interface B {

    }
}

a.ts

export namespace com.foo.bar {

    export class A implements B
    {

    }
}

In file a.ts the compiler says: 'cannot find name B'.
I also tried to somehow import B but I failed. Is there any posibillity to import B or am I completely on the wrong way?

Body:
which results in a compilation error because it says: 'externalLibrary.ts is not a module'.

This compile error appears to be the truth. Looking at your definition it isn't exporting a module, it's just declaring a global namespace. You can use an import alias (TS feature, not ES6) to clean up your usage a bit:

import A = com.foo.bar.A;
new A();

/// <reference path='../dir/externalLibrary.ts'>`
myA: com.foo.bar.A = new com.foo.bar.A();

which results in a run-time error saying: 'ReferenceError: com is not defined'

This means you need to actually include the compiled externalLibrary.js in your running code. That could be as simple as a <script> tag, or if you're using a bundler you might be able to import the file as a side-effect: import "./dir/externalLibrary";

If you control the external library (not clear to me if you do) then you can export the namespace:

export namespace com.foo.bar { ... }

Which turns it into a module (that exports a namespace), and you can import the top level namespace:

import { com } from "../dir/externalLibrary";
const a: com.foo.bar.A = new com.foo.bar.A();

You can't import A directly, but you can still use an import alias:

import { com } from "../dir/externalLibrary";
import A = com.foo.bar.A;
const a: A = new A();

But at this point I would say the namespace is pointless. Just export the class from your module:

export class A { ... }

Now you can import it directly and use it:

import { A } from "../dir/externalLibrary";
const a = new A();
a.doSomething();

Edit

Once you turn a file into a module (by adding a top-level export) then only exported members are visible outside the file, and they must be explicitly imported by other files to be used.

You've updated your question with this example that you previously had:

// a.ts
namespace com.foo.bar {
    export class A implements B { }
}
// b.ts
namespace com.foo.bar {
   export class B { }
}

In this case what it was doing is merging namespaces com.foo.bar in global scope. However, once you make these files modules (by adding export namespace) then they are no longer in global scope and are unaware of each other unless they explicitly import each other, so A implements B in the above doesn't know what B is anymore.

You need to import B. But with modules, you can't merge an imported name with a local declared name, so my previous example importing {com} won't work (nor does it make sense when you think of module files as isolated scopes, which is what they are):

// a.ts
import { com } from "./b"; // import "com"
export namespace com.foo.bar { } // declare "com" -- Error: name conflict

You could import the other file using a * as wildcard (basically an ES6 namespace import) to avoid this collision:

// a.ts
import * as b from "./b";
import B = b.com.foo.bar.B; // alias now starts with `b.`
export namespace com.foo.bar {
    export class A implements B { }
}

I'm just going to say right now that the format this code is generated in is outdated and causing friction with ES6 modules. Using namespaces in an ES6 module is considered mostly anachronistic -- before ES6 module files existed, which themselves define scopes, namespaces (in ES5 just global objects/function closures) were a way to define scope. With ES6 modules what you really want is for your file structure to be enough, so com/foo/bar/a.ts is itself the scope, and when you export class A from that file, you are not conflicting with anything, even if A is exported by another file, that other file is a different scope. Consumer files will import by the file path import { A } from "./com/bar/a" (or whatever the relative path is), and if necessary to avoid name conflicts with other A imports it can be handled by that importing file using as.

That said, I understand refactoring your code generation to export idiomatic ES6 modules without namespaces might not be feasible. I would say you have two options:

Go back to generating code using global namespaces (no export namespace) and resolve your build issue so those files are actually included in the build. You haven't mentioned your method here (only that you got a runtime ReferenceError, indicating the file is not being included in your setup), but if you're able to use ES6 import/export I assume you're using a module bundler like Webpack or Rollup. Module bundlers are designed to bundle modules so including some global code can be surprisingly non-trivial. Remember that just because TypeScript can compile it, doesn't mean your bundler knows how to bundle it.

Modify the code generation to export the namespaces, and import in all files using * as wildcards, as in my last example.