text:
Q: Escribir en un archivo txt Lo que quiero es agregar "una linea texto" cada vez que se ejecute el código.
Sin embargo lo que consigo es reemplazar todo el contenido del txt. Dejo aquí mi código.
const fs = require("fs");
let ruta = './log.txt'
let texto = "Esto es una prueba \n\t";
fs.open(ruta, 'w+', (err, fd) => {
    if (err) {
        console.log(err);
    }
    else {
        fs.appendFile(ruta, texto, function (err) {
            if (err) throw err;
            fs.close(log, function (err) {
                if (err) throw err;
                console.log('It\'s saved!');
            });
        });
    }
});

A: Si miras la documentación de fs.open(), verás que entre los flags que hay disponibles están:

'w+' - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
'a' - Open file for appending. The file is created if it does not exist.

Traducción:
'w+': Abre en modo lectura y escritura. Crea el fichero si no existe y si existe lo trunca (borra todo su contenido).
'a': Abre el fichero para añadir. Si no existe el fichero, se crea.
Por tanto tu problema es que estás borrando el contenido del fichero cada vez que lo abres, debes cambiar el flag por 'a' (aprovecho para arreglar un par de fallos que tienes el código, mira mis comentarios:
const fs = require("fs");
let ruta = './log.txt'
let texto = "Esto es una prueba \n\t";
fs.open(ruta, 'a', (err, fd) => {
    if (err) {
        console.log(err);
    }
    else {
        //si tienes ya el fd (file descriptor), usémoslo
        fs.appendFile(fd, texto, function (err) {
            if (err) throw err;
            //de nuevo, usemos el fd para cerrar el fichero abierto
            fs.close(fd, function (err) {
                if (err) throw err;
                console.log('It\'s saved!');
            });
        });
    }
});

De todos modos, si sólo quieres escribir, no necesitas abrir el fichero antes, si a appendFile le pasas la ruta como string abre y cierra el fichero automáticamente, simplificando el código:
const fs = require("fs");
let ruta = './log.txt'
let texto = "Esto es una prueba \n\t";
fs.appendFile(ruta, texto, function (err) {
  if (err) throw err;
});


text:
Q: Android Bluetooth Turn OFF While Connecting Apparently Android 5.0 and higher have messed up the use of Bluetooth LE and I need to create a workaround for it.
What I have noticed is that the time to Connect to a discovered device is LONG.
However if the Bluetooth Service is turned OFF and then ON, it generally will Connect faster.
The app I am working on needs to run on Android 4.3 and higher.
Typically I just launch the   BluetoothGatt.connect()  and all is good.
But with the Android 5.0+ the Connect() launches, but stays there a LONG TIME before finalizing the action.
With that in mind I put in a  Handler().postDelayed() routine with a 10 second timeout to look to 'see' if the Connection has successfully completed.
If the Connection has not finalized I want to programatically Turn OFF the phone's Bluetooth service entirely and then Turn it ON again.
However when I attempt to execute BluetoothAdapter.disable()  the app crashes.
I can only guess that is because the BluetoothGatt.connect() activity is still attempting to complete in the background (via the BluetoothLEService).
I can manually turn OFF the phone's Bluetooth Service regardless of its 'condition' and it works.
So how can I programatically shut OFF the phone's Bluetooth service while a Connect() attempt is still attempting to execute - basically a TURN OFF NOW
Your suggestions/advice would be greatly appreciated.
Thanks

A: Well with a lot of trial & error I found a sequence that appears to work.
Within  my Handler().postDelayed()  I now have the following code
new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
      if (!mConnected && !paymentDone && myOSVersionNum >= 5.0) {
          mBluetoothLeService.initialize();
          mBluetoothLeService.disconnect();
          BluetoothAdapter myBTadapter = BluetoothAdapter.getDefaultAdapter();
          myBTadapter.disable();
          while (myBTadapter.isEnabled()){
            // Wait Here Until DISABLED
          }
          // Now Turn Back ON & Re-Connect
          myBTadapter.enable();
          mBluetoothLeService.connect(mDeviceAddress);
       }
      }
    }, 6000);   // 6 Seconds  (6,000 Milliseconds)

I am sure that others will find problems with the approach I ended up with and, hopefully, critique it towards a better method.
In spite of that, I don't know if this will be of any assistance to anyone else, but it seems as though I had to:
1. Terminate the Service action ( initialize() & disconnect() )
2. Define a new BT Adapter (the existing, original definition wouldn't work)
3. Utilize the new BT Adapter to begin again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to add items properly to the state (empty array) in reactjs? im trying to add items to the empty array selectedProducts, but every item i add becomes nested inside the other, my goal is to have one array with all the items selected spread inside.
im new to react so examples would be greatly appreciated :)
my state:
state = {
    products: products,
    selectedProducts: [],
    totalPrice: 0
  };

the method:
handleQuantityChange = item => {
    const {selectedProducts} = this.state
    const carsSelected = Object.assign([{...selectedProducts}],item)
    this.setState(
      {selectedProducts:carsSelected}
    );

the result (every 0 represent a nested array that shows one item(car)):
[{…}, id: 2, name: "Bugatti", price: 3200000, description: "Extremely Fast", total: 0, …]
0:
0:
0:
__proto__: Object
count: 0
description: "High Performance"
id: 4
img:
name: "BMW"
price: 120000
total: 0
__proto__: Object
count: 0
description: "Kinda Fast"
id: 3
img:
name: "Maserati"
price: 800000
total: 0
__proto__: Object
count: 0
description: "Extremely Fast"
id: 2
img:
name: "Bugatti"
price: 3200000
total: 0
length: 1

A: You can simply do this,
this.setState({
   selectedProducts: [...this.state.selectedProducts , item]
});

A: handleQuantityChange = item => {
    const {selectedProducts} = this.state
    const carsSelected = [...selectedProducts,item]
    this.setState(
      {selectedProducts:carsSelected}
    );

A: you don't need to use object.assign and spread operator together.
for array you can use like this
this.setState({
   selectedProducts: [...this.state.selectedProducts , item]
});

for object you can use like this
this.setState({
   selectedProducts: {...this.state.selectedProducts , item: '123'}
});


text:
Q: Spotify Web-Control Desktop Player I wish I could control the current song, pause / play, fast forward or rewind music, all through a social network that I'm developing. To study in depth the spotify, I saw that he already has something like a Webservice that does exactly what I need, but only accepts requests from domain "embed.spotify.com", I believe as a form of protection for handling this information without user authorization,
Question:
Is there is any role in spotify API that allows these functions with user's authorization?


text:
Q: ImageminPlugin with CustomWeback in Angular doesn't work in production // webpack.config.js
const ImageminPlugin = require('imagemin-webpack-plugin').default

module.exports = {
  plugins: [
    new ImageminPlugin({
      pngquant: {
        quality: '50' // unreasonably low value to see it works
      }
    })
  ]
}

// angular.json
"architect": {
  "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./webpack.config.js"
      },
    }
  },
  "serve": {
    "builder": "@angular-builders/custom-webpack:dev-server",
    "options": {
      "customWebpackConfig": {
        "path": "./webpack.config.js"
      },
    }
  }
}

This works fine in development but when I run the application in production:
"start:prod": "angular-http-server --path dist/event-io -p $PORT",
"build:prod": "ng build --prod --stats-json",

the image has its original size even though the plugin is actually loaded.
Is there a problem with order?


text:
Q: How to know which button postbacks the page? I have a problem. When I press "return" key in the text box ASP.NETpage page must do some AJAX operation.It does Ajax operation but it also reloads or postbacks the page.
And now I want to ask:
How can I know which button is clicked?
Thank your for your attention!!!

A: Try this:
   /// <summary>
/// Retrieves the control that caused the postback.
/// </summary>
/// <param name="page"></param>
/// <returns></returns>
private Control GetControlThatCausedPostBack()
{
    //initialize a control and set it to null
    Control ctrl = null;

    //get the event target name and find the control
    string ctrlName = Page.Request.Params.Get("__EVENTTARGET");
    if (!String.IsNullOrEmpty(ctrlName))
        ctrl = Page.FindControl(ctrlName);

    //return the control to the calling method
    return ctrl;
}

A: When a button has a name property, that gets passed back with the form data. Ensure each button has a unique name.


text:
Q: Check if a MySQL query has boolean values and display ✓ or ✖ I am new to mySQL and I am fetching several data from a DB and throwing it over a table like this:
// Create connection
$connection = new mysqli( $servername, $username, $password, $dbname );

//test if connection failed
if ( mysqli_connect_errno() ) {
  die( "Error: "
    . mysqli_connect_error()
    . " (" . mysqli_connect_errno()
    . ")" );
}

//get results from database
$result = mysqli_query( $connection, "SELECT * FROM SentEmails" );
$all_property = array(); //declare an array for saving property

//showing property
echo '

'; //initialize table tag
while ( $property = mysqli_fetch_field( $result ) ) {
  echo '' . $property->name . '/td>'; //get field name for header
  array_push( $all_property, $property->name ); //save those to array
}
echo '
'; //end tr tag

//showing all data
while ( $row = mysqli_fetch_array( $result ) ) {
  echo "
";
  foreach ( $all_property as $item ) {
    echo '' . $row[ $item ] . '	'; //get items using property value
  }
  echo '
';
}
echo "
";

However some of the columns are boolean. I would like to display a "✓" or a "✖" in the appropriate column, instead of "1" or "0". Is this possible, without breaking down the SELECT or mounting the table over several steps? Perhaps a javascript function after the table is ready? Thank you.


text:
Q: travis ci build failure on java9 I have upgraded my project to jdk-9 env. But when I pushed the branch, I met a building problem that travis-ci didn't find the package "Javax.json" as following:
My configuration:
{
    "language": "java",
    "install": "mvn install -DskipTests=true -Dmaven.javadoc.skip=true",
    "jdk": "oraclejdk9",
    "group": "stable",
    "dist": "trusty",
    "os": "linux"
}

Error information(partly):
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/travis/build/ArvinSiChuan/TwentySeventeenAutumn/src/main/java/com/arvinsichuan/helloidea/HelloIdea.java:[7,18] package javax.json does not exist
[ERROR] /home/travis/build/ArvinSiChuan/TwentySeventeenAutumn/src/main/java/com/arvinsichuan/mongojdbc/MongoJDBC.java:[14,18] package javax.json does not exist
[ERROR] /home/travis/build/ArvinSiChuan/TwentySeventeenAutumn/src/main/java/com/arvinsichuan/mongojdbc/MongoJDBC.java:[15,18] package javax.json does not exist
[ERROR] /home/travis/build/ArvinSiChuan/TwentySeventeenAutumn/src/main/java/com/arvinsichuan/mongojdbc/MongoJDBC.java:[48,9] cannot find symbol
  symbol:   class JsonObjectBuilder
  location: class com.arvinsichuan.mongojdbc.MongoJDBC
[ERROR] /home/travis/build/ArvinSiChuan/TwentySeventeenAutumn/src/main/java/com/arvinsichuan/mongojdbc/MongoJDBC.java:[48,41] cannot find symbol
  symbol:   variable Json
  location: class com.arvinsichuan.mongojdbc.MongoJDBC
[INFO] 5 errors
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.799 s
[INFO] Finished at: 2017-09-22T05:49:56Z
[INFO] Final Memory: 23M/512M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-
    plugin:3.1:compile (default-compile) on project JEETwentySeventeenAutumn:
    Compilation failure: Compilation failure:
[ERROR] /home/travis/build/ArvinSiChuan/TwentySeventeenAutumn/src/main/java/com/arvinsichuan/helloidea/HelloIdea.java:[7,18] package javax.json does not exist
[ERROR] /home/travis/build/ArvinSiChuan/TwentySeventeenAutumn/src/main/java/com/arvinsichuan/mongojdbc/MongoJDBC.java:[14,18] package javax.json does not exist
[ERROR] /home/travis/build/ArvinSiChuan/TwentySeventeenAutumn/src/main/java/com/arvinsichuan/mongojdbc/MongoJDBC.java:[15,18] package javax.json does not exist
[ERROR] /home/travis/build/ArvinSiChuan/TwentySeventeenAutumn/src/main/java/com/arvinsichuan/mongojdbc/MongoJDBC.java:[48,9] cannot find symbol
[ERROR]   symbol:   class JsonObjectBuilder
[ERROR]   location: class com.arvinsichuan.mongojdbc.MongoJDBC
[ERROR] /home/travis/build/ArvinSiChuan/TwentySeventeenAutumn/src/main/java/com/arvinsichuan/mongojdbc/MongoJDBC.java:[48,41] cannot find symbol
[ERROR]   symbol:   variable Json
[ERROR]   location: class com.arvinsichuan.mongojdbc.MongoJDBC
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1]
http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
The command "mvn install -DskipTests=true -Dmaven.javadoc.skip=true" failed
and exited with 1 during .
Your build has been stopped.

A: Add the dependency:
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>


text:
Q: UITest cannot find element when contained in Modal View Controller I have an application that has the following structure:

*

*A root UIViewController (A).

*Inside it is a UINavigationController (B) that pushes and pops different UIViewControllers (C).

*Sometimes, the UIViewControllers (C) inside the UINavigationController (B) will present Modal UIViewControllers (D).

When trying to record a UITest elements inside A, B and C are detected. But any elements inside the Modal UIViewControllers D are not found. I just get stuck until I get an error that looks like this:
Timeout waiting for fulfillment of promise for 'remote query'.
All elements have accessibility identifiers.
Any ideas?


text:
Q: Do threads waiting on CountDownLatch execute in fifo order? Say i have a count down latch like with count=1
Suppose i have two threads(T1, T2) waiting on latch.
Say T1 came first and called latch.await() and later came T2
When latch is count down is there is guarantee that T1 will be executed first and later T2

A: No, there is no such guarantee, CountDownLatch dose not have a fair policy.
However, ReentrantLock and Condition have fair policy:

Waiting threads are signalled in FIFO order.
The ordering of lock reacquisition for threads returning from waiting
  methods is the same as for threads initially acquiring the lock, which
  is in the default case not specified, but for fair locks favors those
  threads that have been waiting the longest.

So if you want the waiting threads wake up in fifo order, you can combine CountDownLatch and Condition:
Create a ReentrantLock:
 ReentrantLock lock = new ReentrantLock(true);
 Condition condition = lock.newCondition();

Let T1 and T2 wait on this condition:
lock.lock();
try {
    while (...) {
        condition.await();
    }
} finally {
    lock.unlock();
}
doSomething();

Create a new thread T3 wait on CountDownLatch and signal T1 & T2:
countDownLatch.await();
lock.lock();
try {
    condition.signalAll();
} finally {
    lock.unlock();
}

A: This might vary according to how the underlying operating system manages threads, but in my experience (on Windows) the order in which a thread acquires a lock (semaphore or mutex) is never guaranteed. If one thread has a higher priority then logically that ought to make a difference, but that is outside of my experience so I can't say whether it does in practice.


text:
Q: Asp.net Dropdown list's FindByValue issue related to page formatting I have three dropdown lists:
//three dropdown lists as follow:
ddlStartupPage.Items.FindByValue(Session["StartUpPage"].ToString()).Selected = true;
ddlValue1.Items.FindByValue(Session["v1"].ToString()).Selected = true;
ddlValue2.Items.FindByValue(Session["v2"].ToString()).Selected = true;

I am using findByValue method of dropdownlists. The first line is running ok. But when I uncomment the last two lines, it's causing page formatting issues.
I am using master page and update panel in my asp.net page.

A: Try this Code
ddlproj.SelectedIndex = ddlproj.Items.IndexOf(ddlproj.Items.FindByText(dtproj.
Rows[0]["project"].ToString()));


text:
Q: How can I highlight entities and code keywords in HTML input boxes? Let's say I have an HTML input box. I want an input box that highlights code keywords, like this one: http://runnable.com/new/JavaScript , or http://jsfiddle.net/ or something like that. How can I do it? CSS, JS, etc can be used in solutions.

A: Option 1) Spend ages writing your own solution
Option 2) Make use of one of the results found when searching "javascript syntax highlighter" in Google...


text:
Q: ¿Cómo heredo un datalist en in input? Tengo un formulario de altas, el cual quiero agregar más filas para agregar multiples altas, pero al momento de clonar mis campos de texto, no se crean los nuevos.
<input type="button" class="form-control" onClick="addRow('tablaArticulos')" value="Agregar otro artículo" style="height: 40px; font-size:20px" /> <INPUT type="button" value="Borrar fila(s)" class="form-control" style="height: 40px; font-size:20px" onClick="deleteRow('tablaArticulos')" />

            Selección
            Nombre
            Nombre del proveedor
            Descripci&oacuten
            Num. de parte
            Cantidad
            Categoria
            Ubicaci&oacuten
            Responsable

            <INPUT onclick="toggle(this)" type="checkboox" name="chkbox[]" title="Seleccionar todos"/>
            <input type="text" class="form-control" id="nombre[1]" name="nombre[1]" size="25" maxlength="150" required/>

               <?php
                  echo'<input type="text" name="marca[1]" class="form-control" list="empresas_todas">';
                  echo "<datalist id='empresas_todas'>";
                  include ('conexion.php');
                  $result = mysql_query ("SELECT * FROM proveedores order by nombre_proveedor asc"); //consulta de la tabla
                  while ($row = mysql_fetch_array ($result)){
                     echo "<option value='".$row['nombre_proveedor']."'>".$row['nombre_proveedor']."</option>";
                  }
                    echo "</datalist></input>";
               ?>

           <input class="form-control" id="descripcion[1]" type="text" name="descripcion[1]" size="25" maxlength="570" required/>
           <input type="text" class="form-control" id="no_parte[1]" name="no_parte[1]" size="20" maxlength="170" style="text-transform:uppercase;" onkeyup="javascript:this.value=this.value.toUpperCase();" />

                        <input id="cantidad[1]" NAME="cantidad[1]" class="form-control" type="number" pattern="\d*"/ min="1" value="1">

                        <SELECT id="categoria[1]" name="categoria[1]" class="form-control" style="width: 117px">
                            <?php
                                include ('conexion.php');
                                $result = mysql_query ("SELECT * FROM categorias order by categoria asc"); //consulta de la tabla
                                while ($row = mysql_fetch_array ($result)){
                                    echo "<option value='".$row['categoria']."'>".$row['categoria']."</option>";
                                }
                            ?>
                        </SELECT>

                    <input class="form-control" type="text" id="ubicacion[1]" name="ubicacion[1]" size="25" maxlength="150" required/>
                    <SELECT class="form-control" id="responsable[1]" NAME="responsable[1]" style="width: 117px">
                        <?
                            include ('conexion.php');
                            $result = mysql_query ("SELECT * FROM responsables order by nombre asc"); //consulta de la tabla
                            while ($row = mysql_fetch_array ($result)){
                                echo "<option value='".$row['nombre']."'>".$row['nombre']."</option>";
                            }
                        ?>
                    </SELECT>

             <input type="submit" class="form-control" style="height: 40px; font-size:20px" value="Guardar"/>

Se me ocurrió crear los elementos de nuevo pero tampoco se mostraban en la nueva fila :s
Gracias!

A: El problema es que estás asignando el atributo list con la notación de punto (t3.list) y debes hacerlo con setAttribute():
t3.setAttribute("list", "empresas_todas");

Una vez solucionado eso, el dropdown ya se rellana correctamente (puedes verlo en este JSFiddle).


text:
Q: ArcGIS RuntimeError: Not signed into Portal I'm running ArcGIS Pro Python IDLE and getting an error that says: RuntimeError: Not signed into Portal.
I looked at my ArcGIS administrator to make sure my license was not expired and it isn't. This is a concurrent use license for ArcGIS Desktop through my university. I've never had this problem before.
#import modules
import arcpy
import os

#set working directory
folderpath = os.getcwd()

#set the arcpy envs
arcpy.env.workspace = folderpath
arcpy.env.overwriteOutput = True

fc = "Round2_5.shp"

#Create a list of fields using the ListFields function
fields = arcpy.ListFields(feature_class)

#Iterate through the list of fields
for field in fields:

arcpy.SpatialAutocorrelation_stats(fc, field, "REPORT","INVERSE_DISTANCE",
                                   "EUCLIDEAN_DISTANCE", "NONE")

 #The full error message:
 Traceback (most recent call last):
  File "\\Mac\Home\Desktop\Global Health Job\GIS\2_5_Spatial_Auto.py",
line 8, in <module>
    import arcpy
  File "C:\ArcGIS\Pro\Resources\ArcPy\arcpy\__init__.py", line 72, in
<module>
    from arcpy.geoprocessing import gp
  File "C:\ArcGIS\Pro\Resources\ArcPy\arcpy\geoprocessing\__init__.py",
 line 14, in <module>
    from ._base import *
  File "C:\ArcGIS\Pro\Resources\ArcPy\arcpy\geoprocessing\_base.py", line
 14, in <module>
    import arcgisscripting
 RuntimeError: Not signed into Portal.

A: Your script is using the ArcGIS Pro Python Interpreter. This interpreter needs to be logged on Portal or ArcGIS Online if a named user license is configured.
I realized you use ArcMap libraries in your script.
In that case, try to execute your Python Script using the ArcMap Interpreter located in C:\Python27


text:
Q: Iterators built with different continuation tokens are producing the same results in Google Apps I am programming a Google Apps script within a spreadsheet. My use case includes iterating over a large set of folders that are children of a given one. The problem is that the processing takes longer than the maximum that Google allows (6 minutes), so I had to program my script to be able to resume later. I am creating a trigger to resume the task, but that is not part of my problem (at least, not the more important one at this moment).
My code looks like this (reduced to the minimum to illustrate my problem):
function launchProcess() {
    var scriptProperties = PropertiesService.getScriptProperties();
    scriptProperties.setProperty(SOURCE_PARENT_FOLDER_KEY, SOURCE_PARENT_FOLDER_ID);
    scriptProperties.deleteProperty(CONTINUATION_TOKEN_KEY);
    continueProcess();
}

function continueProcess() {
    try {
        var startTime = (new Date()).getTime();
        var scriptProperties = PropertiesService.getScriptProperties();
        var srcParentFolderId = scriptProperties.getProperty(SOURCE_PARENT_FOLDER_KEY);
        var continuationToken = scriptProperties.getProperty(CONTINUATION_TOKEN_KEY);
        var iterator = continuationToken == null ? DriveApp.getFolderById(srcParentFolderId).getFolders() : DriveApp.continueFolderIterator(continuationToken);

        var timeLimitIsNear = false;
        var currTime;
        while (iterator.hasNext() && !timeLimitIsNear) {
            var folder = iterator.next();

            processFolder_(folder);

            currTime = (new Date()).getTime();
            timeLimitIsNear = (currTime - startTime >= MAX_RUNNING_TIME);
        }

        if (!iterator.hasNext()) {
            scriptProperties.deleteProperty(CONTINUATION_TOKEN_KEY);
        } else {
            var contToken = iterator.getContinuationToken();
            scriptProperties.setProperty(CONTINUATION_TOKEN_KEY, contToken);
        }

    } catch (e) {
        //sends a mail with the error
    }
}

When launchProcess is invoked, it only prepares the program for the other method, continueProcess, that iterates over the set of folders. The iterator is obtained by using the continuation token, when it is present (it will not be there in the first invocation). When the time limit is near, continueProcess obtains the continuation token, saves it in a property and waits for the next invocation.
The problem I have is that the iterator is always returning the same set of folders although it has been built from different tokens (I have printed them, so I know they are different).
Any idea about what am I doing wrong?
Thank you in advance.

A: It appears that your loop was not built correctly. (edit : actually, probably also another issue about how we break the while loop, see my thoughts about that in comments)
Note also that there is no special reason to use a try/catch in this context since I see no reason that the hasNext() method would return an error (but if you think so you can always add it)
here is an example that works, I added the trigger creation / delete lines to implement my test.
EDIT : code updated with logs and counter
var SOURCE_PARENT_FOLDER_ID = '0B3qSFd3iikE3MS0yMzU4YjQ4NC04NjQxLTQyYmEtYTExNC1lMWVhNTZiMjlhMmI'
var MAX_RUNNING_TIME = 5*35*6;

function launchProcessFolder() {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('SOURCE_PARENT_FOLDER_KEY', SOURCE_PARENT_FOLDER_ID);
  scriptProperties.setProperty('counter', 0);
  scriptProperties.deleteProperty('CONTINUATION_TOKEN_KEY');
  ScriptApp.newTrigger('continueProcess').timeBased().everyMinutes(10).create();
  continueProcessFolder();
}

function continueProcessFolder() {
  var startTime = (new Date()).getTime();
  var scriptProperties = PropertiesService.getScriptProperties();
  var srcParentFolderId = scriptProperties.getProperty('SOURCE_PARENT_FOLDER_KEY');
  var continuationToken = scriptProperties.getProperty('CONTINUATION_TOKEN_KEY');
  var iterator = continuationToken == null ? DriveApp.getFolderById(srcParentFolderId).getFolders() : DriveApp.continueFolderIterator(continuationToken);
  var timeLimitIsNear = false;
  var currTime;
  var counter = Number(scriptProperties.getProperty('counter'));
  while (iterator.hasNext() && !timeLimitIsNear) {
    var folder = iterator.next();
    counter++;
    Logger.log(counter+'  -  '+folder.getName());

    currTime = (new Date()).getTime();
    timeLimitIsNear = (currTime - startTime >= MAX_RUNNING_TIME);

    if (!iterator.hasNext()) {
      scriptProperties.deleteProperty('CONTINUATION_TOKEN_KEY');
      ScriptApp.deleteTrigger(ScriptApp.getProjectTriggers()[0]);
      Logger.log('******************no more folders**************');
      break;
    }
  }
  if(timeLimitIsNear){
    var contToken = iterator.getContinuationToken();
    scriptProperties.setProperty('CONTINUATION_TOKEN_KEY', contToken);
    scriptProperties.setProperty('counter', counter);
    Logger.log('write to scriptProperties');
  }
}

EDIT 2 :
(see also last comment)
Here is a test with the script modified to get files in a folder. From my different tests it appears that the operation is very fast and that I needed to set a quite short timeout limit to make it happen before reaching the end of the list.
I added a couple of Logger.log() and a counter to see exactly what was happening and to know for sure what was interrupting the while loop.
With the current values I can see that it works as expected, the first (and second) break happens with time limitation and the logger confirms that the token is written. On a third run I can see that all files have been dumped.
var SOURCE_PARENT_FOLDER_ID = '0B3qSFd3iikE3MS0yMzU4YjQ4NC04NjQxLTQyYmEtYTExNC1lMWVhNTZiMjlhMmI'
var MAX_RUNNING_TIME = 5*35*6;

function launchProcess() {
  var scriptProperties = PropertiesService.getScriptProperties();
  scriptProperties.setProperty('SOURCE_PARENT_FOLDER_KEY', SOURCE_PARENT_FOLDER_ID);
  scriptProperties.setProperty('counter', 0);
  scriptProperties.deleteProperty('CONTINUATION_TOKEN_KEY');
  ScriptApp.newTrigger('continueProcess').timeBased().everyMinutes(10).create();
  continueProcess();
}

function continueProcess() {
  var startTime = (new Date()).getTime();
  var scriptProperties = PropertiesService.getScriptProperties();
  var srcParentFolderId = scriptProperties.getProperty('SOURCE_PARENT_FOLDER_KEY');
  var continuationToken = scriptProperties.getProperty('CONTINUATION_TOKEN_KEY');
  var iterator = continuationToken == null ? DriveApp.getFolderById(srcParentFolderId).getFiles() : DriveApp.continueFileIterator(continuationToken);
  var timeLimitIsNear = false;
  var currTime;
  var counter = Number(scriptProperties.getProperty('counter'));
  while (iterator.hasNext() && !timeLimitIsNear) {
    var file = iterator.next();
    counter++;
    Logger.log(counter+'  -  '+file.getName());

    currTime = (new Date()).getTime();
    timeLimitIsNear = (currTime - startTime >= MAX_RUNNING_TIME);

    if (!iterator.hasNext()) {
      scriptProperties.deleteProperty('CONTINUATION_TOKEN_KEY');
      ScriptApp.deleteTrigger(ScriptApp.getProjectTriggers()[0]);
      Logger.log('******************no more files**************');
      break;
    }
  }
  if(timeLimitIsNear){
    var contToken = iterator.getContinuationToken();
    scriptProperties.setProperty('CONTINUATION_TOKEN_KEY', contToken);
    scriptProperties.setProperty('counter', counter);
    Logger.log('write to scriptProperties');
  }
}

A: As of January 1, 2016 this is still a problem. The bug report lists a solution using the Advanced Drive API, which is documented here, under "Listing folders".
If you don't want to use Advanced services, an alternative solution would be to use the Folder Iterator to make an array of File Ids.
It appears to me that the Folder Iterator misbehaves only when created using DriveApp.continueFolderIterator(). When using this method, only 100 Folders are included in the returned Folder Iterator.
Using DriveApp.getFolders() and only getting Folder Ids, I am able to iterate through 694 folders in 2.734 seconds, according the Execution transcript.
function allFolderIds() {
  var folders = DriveApp.getFolders(),
      ids = [];
  while (folders.hasNext()) {
    var id = folders.next().getId();
    ids.push(id);
  }
  Logger.log('Total folders: %s', ids.length);
  return ids;
}

I used the returned array to work my way through all the folders, using a trigger. The Id array is too big to save in the cache, so I created a temp file and used the cache to save the temp file Id.

A: This is caused by a bug in GAS:
https://code.google.com/p/google-apps-script-issues/issues/detail?id=4116

A: It appears you're only storing a single continuation token. If you want to recursively iterate over a set of folders and allow the script to pause at any point (e.g. to avoid the timeout) and resume later, you'll need to store a bunch more continuation tokens (e.g. in an array of objects).
I've outlined a template that you can use here to get it working properly. This worked with thousands of nested files over the course of 30+ runs perfectly.


text:
Q: What does "SP18" mean on the name of the certification? When I took two exams in June I noticed they had "SP18" on the name, as in:

Exam: Salesforce Certified Platform Developer I (SP18)

What does this SP18 mean? Summer Platform 18? Summer Preview 18?

A: The release version is abbreviated on certifications as below:

Winter - WI
Spring - SP
Summer - SU


text:
Q: Firebase auth with signInWithPopup not working on mobile device I have a problem with the firebase.auth().signInWithPopup() function it works perfectly in the browser but on a real mobile device its not working at all. The popup opens for a quick second but then quickly closes. I think the problem might be with the OAuth redirect domains settings, because a device dosen't have a domain name. Does any of you have a solution for this ?

A: Currently Firebase v3 dosen't support firebase.auth().signInWithPopup() and firebase.auth().signInWithRedirect() on mobile devices until then the solution is to use firebase.auth().signInWithCredential().


text:
Q: how to laravel encrypt on jquery I'm appending a form when I click on a buttom, so I want to encrypt in the form the id of the row to edit.
So I have tried like this:
var txt1 = "
";
var text = txt1.concat(data[0].nombre,"		<button type='button' id='",data[0].id,"' class='btn btn-info edit' data-toggle='tooltip' data-placement='top' title='Editar'></button>	<button type='button' class='btn btn-danger' data-toggle='tooltip' data-placement='top' title='Borrar'></button>

<td  colspan='5' style='padding:0;' class='info-",lastid, "' data-course= ",<?php echo Crypt::encrypt(",data[0].id, "))); ?>>
");
$(".publics").append(text);

But it encrypt ",data[0].id," textually, not the value stored on data[0].id.
How can I encrypt the value?

A: It looks like you don't fully understand how javascript and PHP play together.
PHP runs on your webserver. It takes an incoming request sent from a browser on the client machine. Hands it over to PHP/Laravel. Laravel the handles routing etc. and runs the code in the template file. i.e. executes Crypt::encrypt(",data[0].id, "). At this point the string ",data[0].id, " is already encrypted i.e. all scrambled up.
Then PHP send a response back to the client machine, where the browser executes the javascript. Which means the browser does not get chance to encrypt the string. It can't even execute PHP code.
Your only option would be to use a javascript library to encrypt the id. You can not use PHP code, if the id changes dynamically.


text:
Q: ImageView adds white space around my image I have an ImageView that when I look at in the XML preview layout on Eclipse looks fine, but when I launch the app on my hardware device a big whitespace comes to surround it. This is what the actual image is, without the whitespace that is being added. Here is my XML file  too. How do I get rid of this whitespace?

A: Since your image shouldn't be too large, try this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/linkMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="cat"
        android:src="@drawable/ashsc" />

</LinearLayout>

This way, the image won't attempt to scale and won't create bounds outside the ImageView's image.


text:
Q: How to position DIV within Wordpress I'm trying to have 3 x 340px wide boxes (used for holding social media feeds) next to each other. I've got the first 2 lined up perfectly but the 3rd is not lining up.
I'm using a custom html field in wordpress. Code is below:

Conscious Youth C.I.C

Tweets by TwitterDev

Image here shows what it's doing:

A: Hi you can do this easily by using bootstrap grid. check the jsfiddle output  :: https://jsfiddle.net/ruokr7rp/1/

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css">

Conscious Youth C.I.C

      Tweets by TwitterDev

check this :: https://jsfiddle.net/ruokr7rp/


text:
Q: Qual é a diferença entre os tipos de binding no Angular? No Angular (não AngularJS) existem algumas formas de fazer o binding de propriedades do Component para a View.

Existe uma maneira correta de realizar os bindings? Em que situações cada um dos itens citados deveria ser utilizado e por quê?

A: Não existe uma maneira correta de realizar Data Binding, cada situação pode ser usada da forma como quiser e/ou conseguir aplicar. São 4 formas:

*

*Interpolação: {{ valor }}

*

*associa informação do componente para o template (HTML)

*Property Binding: [propriedade]="valor"

*

*associa informação do componente para o template (HTML)

*Event Binding: (evento)="handler"

*

*associa informação do template (HTML) para o componente

*Two-Way Data Binding: [(ngModel)]="propriedade"

*

*associa informação entre ambos, ou seja, mantém ambos atualizados (componente e template (HTML).

Fonte: https://www.youtube.com/watch?v=rlVxG2lG1Tk&list=PLGxZ4Rq3BOBoSRcKWEdQACbUCNWLczg2G&index=10


text:
Q: making an array controller the target of a button I am working through a chapter of COCOA PROGRAMMING FOR MAC OS X (3RD EDITION) on NSArrayController and it tells me to:
Control-Drag to make the array controller become the target of the Add New Employee button. Set the action to add:
However when I drag over the array controller it does not highlight so I get no target options.
How do I do this correctly in the new XCode

full size image
document.h:
//
//  Document.h
//  RaiseMan
//
//  Created by user on 11/12/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import <Cocoa/Cocoa.h>

@interface Document : NSDocument
{
    NSMutableArray *employees;
}

@end

document.m:
//
//  Document.m
//  RaiseMan
//
//  Created by user on 11/12/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Document.h"

@implementation Document

- (id)init
{
    self = [super init];
    if (self) {
        employees = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)dealloc
{
    [self setEmployees:nil];
    [super dealloc];
}

-(void)setEmployees:(NSMutableArray *)a
{
    //this is an unusual setter method we are goign to ad a lot of smarts in the next chapter
    if (a == employees)
        return;
    [a retain];
    [employees release];
    employees = a;
}

- (NSString *)windowNibName
{
    // Override returning the nib file name of the document
    // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
    return @"Document";
}

- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
    [super windowControllerDidLoadNib:aController];
    // Add any code here that needs to be executed once the windowController has loaded the document's window.
}

- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
    /*
     Insert code here to write your document to data of the specified type. If outError != NULL, ensure that you create and set an appropriate error when returning nil.
    You can also choose to override -fileWrapperOfType:error:, -writeToURL:ofType:error:, or -writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
    */
    NSException *exception = [NSException exceptionWithName:@"UnimplementedMethod" reason:[NSString stringWithFormat:@"%@ is unimplemented", NSStringFromSelector(_cmd)] userInfo:nil];
    @throw exception;
    return nil;
}

- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
    /*
    Insert code here to read your document from the given data of the specified type. If outError != NULL, ensure that you create and set an appropriate error when returning NO.
    You can also choose to override -readFromFileWrapper:ofType:error: or -readFromURL:ofType:error: instead.
    If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded.
    */
    NSException *exception = [NSException exceptionWithName:@"UnimplementedMethod" reason:[NSString stringWithFormat:@"%@ is unimplemented", NSStringFromSelector(_cmd)] userInfo:nil];
    @throw exception;
    return YES;
}

+ (BOOL)autosavesInPlace
{
    return YES;
}

    - (void)setEmployees:(NSMutableArray *)a;

    @end

person.h:
//
//  Person.h
//  RaiseMan
//
//  Created by user on 11/12/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    NSString *personName;
    float expectedRaise;
}

@property (readwrite, copy) NSString *personName;
@property (readwrite) float expectedRaise;

@end

person.m:
//
//  Person.m
//  RaiseMan
//
//  Created by user on 11/12/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Person.h"

@implementation Person

- (id) init
{
    self = [super init];
    expectedRaise = 5.0;
    personName = @"New Person";
    return self;
}

- (void)dealloc
{
    [personName release];
    [super dealloc];
}

@synthesize personName;
@synthesize expectedRaise;

@end

A: Dude.. you are doing it wrong in IB. This is wrong -

These entries should be made in attribute inspector for array controller -

Once you correct it, you will be able to set target correctly :)


text:
Q: Inner product of functions as integration I am trying to teach my self some linear algebra in preparation for a module in machine learning. I am using Gilbert Strang's text Introduction to Linear Algebra and am having some difficulties.
My specific question is: How is the last equation below an example of integration by parts? It seems to be missing $x(t)y(t)$ to me and I don't know where that has gone.
The book gives the following equations leading up to it:
$$x^Ty = (x,y) = \int_{-\infty}^\infty x(t)y(t)~dt$$
From what I can tell, the above is saying that the inner product of the vectors $x$ and $y$ is equivalent or at least approximate to taking the integral of those two vectors as functions. Does the $(x,y)$ just mean inner product? I don't really understand what a vector of a function even is though.
$$(Ax)^Ty = x^T(A^Ty)$$
This associative rule for matrix-vector multiplication was given as a more rigorous view of what the transpose of $A$ actually is. It then partnered it with this:
$$\int_{-\infty}^\infty\frac{dx}{dt}y(t)~dt = \int_{-\infty}^\infty x(t)\left(-\frac{dy}{dt}\right)~dt$$
I can see how the two equations relate to eachother and that this suggests that $A^T$ is anti-symmetric. Gil mentions integration by parts here which I can definitely recognise but it doesn't seem complete, there should be an extra $x(t)y(t)$ surely?

A: It seems that you are somewhat confused about the use of "vectors" terminology.
In the context as mentioned, vectors are quite abstract things. In fact, they
are a generalization of the well known "geometric entities endowed with magnitude
and direction". See the Wikipedia page about
Vector spaces ,
especially the section about Function spaces .
So there is not a "vector of a function": the functions themselves are
abstract vectors. And yes, an inner product - abstract again - for functions
can be defined by the integral as mentioned. What must been shown, however, is
that the thus defined integral preserves some essential properties of the common "geometric" inner product. See the Wikipedia page about Inner product spaces .
The main part of your question ( i.e. why $\left[x(t)y(t)\right]_{-\infty}^{+\infty} = 0$ ) has been answered by 'user161825' .
Hope this helps.


text:
Q: Loop Convergence - Verilog Synthesis I am trying to successively subtract a particular number to get the last digit of the number (without division). For example when q=54, we get q=4 after the loop. Same goes for q=205, output is q=5.
  if(q>10)
    while(q>10)
    begin
    q=q-10;
    end

The iteration should converge logically. However, I am getting an error:
"[Synth 8-3380] loop condition does not converge after 2000 iterations"
I checked the post - Use of For loop in always block. It says that the number of iterations in a loop must be fixed.
Then I tried to implement this loop with fixed iterations as well like below (just for checking if this atleast synthesizes):
if(q>10)
    while(loopco<9)
    begin
    q=q-10;
    loopco=loopco-1;
    end

But the above does not work too. Getting the same error "[Synth 8-3380] loop condition does not converge after 2000 iterations". Logically, it should be 10 iterations as I had declared the value of loopco=8.
Any suggestions on how to implement the above functionality in verilog will be helpful.

A: That code can not be synthesized. For synthesis the loop has to have a compile time known number of iterations. Thus it has to know how many subtractions to make. In this case it can't.
Never forget that for synthesis you are converting a language to hardware. In this case the tool needs to generate the code for N subtractions but the value of N is not known.
You are already stating that you are trying to avoid division. That suggest to me you know the generic division operator can not be synthesized. Trying to work around that using repeated subtract will not work. You should have been suspicious: If it was the easy it would have been done by now.
You could build it yourself if you know the upper limit of q (which you do from the number of bits):
wire [5:0] q;
reg  [3:0] rem;
always @( * )
   if (q<6'd10)
      rem = q;
   else if (q<6'd20)
      rem = q - 6'd10;
   else if (q<6'd30)
      rem = q - 6'd20;
   etc.
   else
      rem = q - 6'd60;

Just noticed this link which pops up next to your question which shows it has been asked in the past:
How to NOT use while() loops in verilog (for synthesis)?


text:
Q: My regular expression is not working Node.js? I have a regular expression which extracts some text to an array. The code works fine in the frontEnd but it doesn't work in the node.js server.
Whenever I run the code in the backend I get this error message:
TypeError: Cannot read property '1' of null
   at C:\Users\PureTech\master\app\server\routes.js:26:11
   at Layer.handle [as handle_request] (C:\Users\PureTech\node_modules\express\lib\router\layer.js:95:5)
   at next (C:\Users\PureTech\node_modules\express\lib\router\route.js:131:13)
   at Route.dispatch (C:\Users\PureTech\node_modules\express\lib\router\route.js:112:3)
   at Layer.handle [as handle_request] (C:\Users\PureTech\node_modules\express\lib\router\layer.js:95:5)
   at C:\Users\PureTech\node_modules\express\lib\router\index.js:277:22
   at Function.process_params (C:\Users\PureTech\node_modules\express\lib\router\index.js:330:12)
   at next (C:\Users\PureTech\node_modules\express\lib\router\index.js:271:10)
   at C:\Users\PureTech\node_modules\express-session\index.js:433:7
   at C:\Users\PureTech\node_modules\connect-mongo\lib\connect-mongo.js:305:11

This is the code I'm talking about. It is a  regular expression that extracts specific numbers in the "text" variable to an array.
var text = '[Extracted] id: 194805284, Waxaad $55 ka heshay  MAXAMED  CABDILAAHI JAAMAC SAALAX (252906152669) Tar: 15/04/19 08:44:40, Haraagaagu waa $1,042.7[Extracted] id: 193537533, Waxaad $3 ka heshay  ABDULKADIR  ABDIDAHIR FARAH (907794804) Tar: 14/04/19 10:15:32, Haraagaagu waa $59.17';
var reso = text.replace("$", "");
var textArray = reso.split('[Extracted]');

var regularExpression = new RegExp(/id:\s+([0-9]+).+Waxaad\s+([0-9]+).+[^\(]+\(([0-9]+)\)\s+Tar:\s+([0-9\/\s:]+)/i);
var output = [];
var item;
for(var i = 1; i < textArray.length;  i++){
    item = textArray[i].match(regularExpression);
    output.push({
        id: item[1].trim(),
        amount: item[2].trim(),
        time: item[3].trim(),
        number: item[4].trim()
    });
}

console.log(output);

I want this script to work on the backend(node.js) as it works on the frontEnd.

A: You have to define:
var regularExpression = new RegExp("id:\s+([0-9]+).+Waxaad\s+([0-9]+).+[^\(]+\(([0-9]+)\)\s+Tar:\s+([0-9\/\s:]+)", "i");

Or
var regularExpression = /id:\s+([0-9]+).+Waxaad\s+([0-9]+).+[^\(]+\(([0-9]+)\)\s+Tar:\s+([0-9\/\s:]+)/i;

A: I figured out the problem.

*

*I removed all the '$' signs by using this script var reso = text.split('$').join("");

*I removed the new RegExp.

And then it worked fine.


text:
Q: Why are tag names case insensitive? I think tag names should be case sensitive since for certain names, such as JavaScript and not javascript adds additional value. That is, the Camel notation nomenclature.

A: Case insensitivity makes it easier on the tagging system. When you see "javascript" as a tag, you can probably immediately tell it's referring to JavaScript. The difference is, between you who is experienced with the language and someone who is new to programming, only you will know the correct capitalization.
By not requiring capitalization, we don't add an extra level of difficulty in knowing how to describe the problem you're having. We already face quite a few misspellings in tags. We cut this down significantly so that we don't have Javascript, JavaScript, and javascript all intending to mean the same concept.

A: Update: I have now settled down with all lowercase tag names.
Camel case is too 'heavy' for tag names; especially if many are put together.
Following is my old view that has since changed:

I suggest that tag names should remain case-insensitive but should be displayed with proper casing i.e. camel case.
Thus javascript and JavaScript should be the same to the tagging system but should be displayed with proper camel case.
At minimum: I suggest- there be a user specific option to choose how it's displayed per user according to his preference.


text:
Q: What the best way to use services with Symfony2 I got a huge Symfony project. I created many service and subservices to epurate the Controller and Services code.
In my code i instantiate these services with:
$this->get('MyServiceName')->myMethod($foo);

One of my coworker use the new keyword to instantiate the class:
    $myservice = new Service();

    $refid = $myservice->mymethod($foo);

So i wondering, is it a best practice? Should i rewrite that code ? What are the impact of this kind of code on the maintenability and the performance of the application?

A: I always use the first way (ie. using the service container) because with Symfony's dependency injection you don't need to worry about dependecies and/or parameters; I've never used the second way (ie. instantiating a service "by hand" with the new keyword) and I'm pretty sure that it is the worst way.
By the way, you should check out the official "best practices" guide and these blog posts by Fabien Potencier.

A: If the service is defined in the Ioc container, then by all means use it from there, because it will be constructed by the container. It takes the responsibility of instantiating new classes away from the developer. If the explicit dependencies change, you will only need to change them in container, not hunt them in the whole project code. This also in most cases has the performance benefit, because some classes need to be instantiated only once. In any way, talk to your co-worker, why he does it like this.


text:
Q: Can't debug VB5 project I am suppose to make changes to one of the very old software that my co. sales. Its a VB5 project.
Just to be clear I CANT change language and must ABSOLUTLY use VB5.... (If I could change to C# I would be the happiest man on earth right now.)
Here is the problem.
I installed Microsoft Visual Basic IDE and loaded the .VBP file in.
I read the code to know what part does what but I would like to see it on screen step by step (Debug mode with breakpoints).
So, I punch in some breakpoints and hit "play" (debug button) but I got this error
Execution error '-2147024894 (80070002)': Automation Error

But curiously the soft work fine when I use the .exe I think it might be a problem with the debugger.
From here I have three options:
1-End program

It end the program
2-Debug

It send me to a line of code but I dont know what is the error.
Here is the code it point me on:
Private Sub Form_Load()
Dim strLangue As String

bBusy = False

Set gImgBackground = Me.imgBackground

Set gBackGround1 = LoadPicture(App.Path & "\images\bg1.gif")
Set gBackGround2 = LoadPicture(App.Path & "\images\bg2.gif")
Me.BackColor = &HC0E0E0
gIniPath = App.Path & "\posi1000.ini"

basMain.gLangFile = App.Path & "\" & inireadvalue(gIniPath, "general", "langfile", "")
If InStr(UCase(basMain.gLangFile), "FR") <> 0 Then
  strLangue = "FR"
ElseIf InStr(UCase(basMain.gLangFile), "EN") <> 0 Then
  strLangue = "EN"
Else
  strLangue = "FR"
End If

strComType = UCase(inireadvalue(gIniPath, "general", "ComType", "MOELLER"))
If strComType = "MOELLER" Then

'    Dim tJRT_COM As JRT_COM.TEST_MOELLER
'    Set tJRT_COM = New JRT_COM.TEST_MOELLER
'    Set tJRT_COM = New JRT_SUCOMA.JRT_SUCOMA

'    Call tJRT_COM.openComDevice("COM1:19200", 0)
'    Set Module1.MyJRT_COM = tJRT_COM

''    Dim t As String

''    Set tJRT_COM = JRT_COM.New(True)
'        Set MyJRT_COM = CreateObject("JRT_SUCOMA.JRT_SUCOMA")
'MyJRT_COM = Ctype(
'    Set MyJRT_COM = New JRT_SUCOMA.JRT_SUCOMA
''    Dim tJRT_COM As New JRT_SUCOMA.JRT_SUCOMA
'

''    Set tJRT_COM = Nothing
'
''    If Module1.MyJRT_COM.setComDevice(gComDevice, strLangue) = 0 Then
''        Module1.MyJRT_COM.
''    End If
'
ElseIf strComType = "OMRON" Then
'    Set MyJRT_COM = New JRT_COM.JRT_OMRON
'    Set MyJRT_COM = CreateObject("JRT_COM.TEST_OMRON")
'    Set MyJRT_COM = MyJRT_COM_MOELLER
''  Else
''    Set MyJRT_COM = New JRT_COM.JRT_MOELLER
''    Set MyJRT_COM = CreateObject("JRT_COM.TEST_MOELLER")
End If

gOfflineMode = inireadvalue(gIniPath, "General", "OfflineMode", "0")

gComDevice = inireadvalue(gIniPath, "General", "ComDevice", "Com1:19200")
If inireadvalue(gIniPath, "General", "ShowSelectComDevice", "0") = "1" Then
  If strComType = "MOELLER" Then
    bBusy = True
    If Module1.MyJRT_COM_MOELLER.SetComDevice(gComDevice, strLangue) = 0 Then
      Call iniwritevalue(gIniPath, "General", "ComDevice", gComDevice)
    End If
    bBusy = False
ElseIf strComType = "OMRON" Then
    bBusy = True
**********It point here**************************************************************
->    If Module1.MyJRT_COM_OMRON.SetComDevice(gComDevice, strLangue) = 0 Then
      Call iniwritevalue(gIniPath, "General", "ComDevice", gComDevice)
    End If
     bBusy = False
    End If
  End If
End Sub

Just so you know I haven't write that code I am only doing some mod work.
Third option:
3-Help

It gives me another error
Cannot find the windows help.

What do I do??? Does anyone had that problem before ???

A: Got it! I had two dependencies "hard coded" in the vb project that would try to load two .dll on the wrong path even if I would browse Microsoft VB IDE to the right file. I had to place those file in the path specified by Microsoft VB5. And problem solve.


text:
Q: React and Date() and useState() used together not working The following code prints the time with the text "am" or "pm" behind the time string.  So the time string overlaps the am or pm string and can be seen behind it on the  z index.  In other words, if the format is [hh:mm:ss a] where a = am/pm, the a is show behind the hh:mm:ss and centered as well.  How can I fix this? I am using codesandbox here is the link below
https://codesandbox.io/s/usestate-hook-practice-forked-t1zkyl?file=/src/components/App.jsx
function App() {

  const now = new Date().toLocaleTimeString();

  const [time, setTime] = useState(now);

  return (

{time}

      <button>Get Time</button>

  );
}

A: Please restart the server. Because this is working just fine.

Check in this link : https://playcode.io/1048731

A: Turns out this was a styling issue. The font size for the body was to small to accommodate the font size for the heading. I just doubled the body font size in styles.css and it works now. Thank you innocent and Mahmoud Y3c so much! Always looking of people to network with and to collaborate with. Just getting started learing NodeJS, React, mongoDB so much appreciated!


text:
Q: Pimcore custom classes I wrote custom classes and want to use them in pimcore application.
I took them to /website/lib/Custom directory on server. Afterwards, I wrote recursive script includer for each Class located in the directory and included that script in /index.php file.
It is absolutely not pimcore standard but it works.
In pimcore/config/startup.php exists snippet:
$autoloaderClassMapFiles = [
    PIMCORE_CONFIGURATION_DIRECTORY . "/autoload-classmap.php",
    PIMCORE_CUSTOM_CONFIGURATION_DIRECTORY . "/autoload-classmap.php",
    PIMCORE_PATH . "/config/autoload-classmap.php",
];
$test = PIMCORE_ASSET_DIRECTORY;
foreach ($autoloaderClassMapFiles as $autoloaderClassMapFile) {
    if (file_exists($autoloaderClassMapFile)) {
        $classMapAutoLoader = new \Pimcore\Loader\ClassMapAutoloader([$autoloaderClassMapFile]);
        $classMapAutoLoader->register();
        break;
    }
}

I guess that this provides inclusion of all those classes put into returning array from autoload-classmap.php.
Having in mind that /pimcore/config/autoload-classmap.php exists, the mentioned loop would break at first iteration so classes that I would put into custom autoload-classmap are not going to be included in project.
My question is can I change files from /pimcore directory and expect that everything would be fine after system update?

A: No, you should not overwrite anything in the pimcore directory, since the files in there get overwritten by the update mechanism.
You can do what you want by using the /website/config/startup.php which will not get overwritten:
https://www.pimcore.org/wiki/display/PIMCORE4/Hook+into+the+startup-process
But instead of loading all your classes as you did, take advantage of the autoloader by adding this to the /website/config/startup.php:
// The first line is not absolutely necessary, since the $autoloader variable already gets
// set in the /pimcore/config/startup.php, but it is a more future-proof option
$autoloader = \Zend_Loader_Autoloader::getInstance();
$autoloader->registerNamespace('Custom');

If you are properly using namespaces and naming your files correctly that's all you need to do.


text:
Q: What is a trait in Azure ML matchbox recommender? Azure Machine Learning has an item called Train Matchbox Recommender. It can be configured with a Number of traits. Unfortunately, the documentation does not describe what such a trait is.
What are traits? Is this related to latent variables?

A: This page may have better descriptions on it.
Basically, traits are the features the algorithm will learn about each user related to each item. For example, in the restaurant ratings recommender traits could include a user's birth year, if they're a student or working professional, martial status, etc.
Hope that helps!

A: In my opinion yes, this is related to latent variables and defines the dimensions of the compressed trait matrix. The columns of this matrix - the latent trait vectors - can be interpreted as stereotypes of users. Hence, the number of traits corresponds with the number of stereotype users in the recommendation model.
You can find more explanation in the corresponding research paper "Matchbox: Large Scale Bayesian Recommendations":

Users and items are represented by feature vectors which are mapped into a low-dimensional 'trait-space' in which similarity is measured in terms of inner products (source).

In classical Collaborative Filtering this latent representation is often computed using Singular Value Decomposition (SVD) through least-squares method and selecting only the first/largest k dimensions of this matrix. This reduces the dimensionality of the user-item-rating matrix. In this Hacker Noon article by Steeve Huang you can find a more detailed explanation.
Update 1: added interpretation of latent vectors


text:
Q: Very Simple Question on Fortran - UNIX Compiling Apologies if this is too naive or obvious but after a fair bit of searching around, I'm not 100% sure that I understand the fortran/unix interface.  My uncertainty is regarding the nature of .src, .f, then .o, and .out files that you run into when compiling fortran programs into a unix executable.  It's tough to google file extensions like this.  But if you could tell me if I've got this straight, I'd really appreciate it!
.src is the source file which contains the meaty fortran code
.f is the 'host-language specific include file' that tells your fortran compiler a little bit about the source code.  It's sometimes interactive.
--- After you've obtained .o or .out files, can throw away the .src and .f files, yeah?
.o is the binary object file that results from compiling but not linking the fortran .f and .src files.  It contains the same meat but now converted into machine-specific instructions?
.out is the linked object file(s) which is executable and remains dependent on the .o file(s) and is machine-specific.  The .out file extension is not really needed and is often omitted?
I think that covers it.  Thanks for any corrects or further descriptions.
Kyle

A: Nothing about these file extensions is set in stone; as you said, they can even be omitted, or you can make up your own. However, it makes life far easier if you use the conventional ones.
I've never seen the .src extension. The directory where the source files are located is often referred to as ./src; maybe you've seen this.
Usually, the source code (plain text) is in a file with extension .f or .f90. The first one indicates fixed source form ("old style"), and the second one free source form ("modern"). Some compilers interpret uppercase file extensions (.F and .F90) as an indication that the source has to be run through the preprocessor first. Instead of letting the compiler use the extensions for these interpretations, all this can also be explicitly stated/overruled by passing flags to the compiler.
Compilation of the source code produces object code (the machine-specific instructions you mention), contained in an object file, usually with .o as extension (sometimes .obj, or other).
After creating the object files, you could indeed throw away your source code files, but you don't want to do that. You want to fix any bugs you most likely made, and also keep them for future alterations to your program.
The object code has to be linked to produce the final executable. If you have more than one object file, they are tied together, with inclusion of any system/external library code you referred to. On Unix, if you don't specify a name for the executable, the default name it gets is usually a.out. Again, you can overrule this by passing an argument to the compiler.

A: No, the Fortran code is usually in .f or .f90 files. In more detail, Fortran source code usually has the extension .f if it uses the fixed source form (the standard source form of Fortran 77 and earlier versions) or .f90 it uses free source form (present from Fortran 90 on).

A:
After you've obtained .o or .out files, can throw away the .src and .f files, yeah?

No.  As an addendum to the answers describing the various suffix conventions, I advise that you don't delete the Fortran source files (the .src or .f files in your description).  You'll need these files if you ever want to modify the program, or if you need to investigate and fix errors you notice from running the executable file (a.out).


text:
Q: Azure Data Factory get data from foreach value I've a lookup activity with gets value from a container within a blob.  I've a foreach activity which is connected to the lookup activity

and under settings it has the value:
@activity('LookupMessageType').output.value

I've another copy activity which runs within this foreach activity.  It copies data from cosmos DB to Azure Data Lake.

This is the query in the source dataset:
select c.Tag, data.assetTag, data.timestamp, data.jsonVersion, data.messageType, data.speed from c join data in c.data
where (data.speed>  item().speed_Value) AND
(data.timestamp >= '@{formatDateTime(addhours(pipeline().TriggerTime, -1), 'yyyy-MM-ddTHH:mm:ssZ' )}'
AND data.timestamp < '@{formatDateTime(pipeline().TriggerTime, 'yyyy-MM-ddTHH:mm:ssZ' )}')

I get an error as I run this pipeline:
{
    "errorCode": "2200",
    "message": "Failure happened on 'Source' side. ErrorCode=UserErrorDocumentDBReadError,'Type=Microsoft.DataTransfer.Common.Shared.HybridDeliveryException,Message=DocumentDb operation failed: Message: {\"errors\":[{\"severity\":\"Error\",\"location\":{\"start\":231,\"end\":235},\"code\":\"SC2005\",\"message\":\"'item' is not a recognized built-in function name.\"}]}\r\nActivityId: *redacted*, documentdb-dotnet-sdk/1.21.1 Host/64-bit MicrosoftWindowsNT/6.2.9200.0.,Source=Microsoft.DataTransfer.ClientLibrary.DocumentDb,''Type=Microsoft.Azure.Documents.BadRequestException,Message=Message: {\"errors\":[{\"severity\":\"Error\",\"location\":{\"start\":231,\"end\":235},\"code\":\"SC2005\",\"message\":\"'item' is not a recognized built-in function name.\"}]}\r\nActivityId: redacted, documentdb-dotnet-sdk/1.21.1 Host/64-bit MicrosoftWindowsNT/6.2.9200.0,Source=Microsoft.Azure.Documents.Client,''Type=System.Runtime.InteropServices.COMException,Message=Exception from HRESULT: 0x800A0B00,Source=,'",
    "failureType": "UserError",
    "target": "Copy Data1"
}

It is saying item is not a built in function name.  I want to use value from the foreach activity to query the source.
Furthermore, here is my dynamic filepath content
@concat('test_', item().speed, '.csv')

I get the desired dynamic file structure with this expression, if I am using static values in the query like:   data.speed> 500

A: So, I figured out what was wrong with the query:
instead of
where (data.speed>  item().speed_Value)
I had to use
where (data.speed> @{item().speed_value})


text:
Q: Падает браузер на selenium из-за неудачного рукопожатия Пытаюсь просто открыть сайт через selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')

driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=options)
driver.get("ссылка")

Установил опции для игнорирования рукопожатия, но сайт всё равно закрывается сразу же после загрузки
[0910/191017.768:ERROR:gl_context_egl.cc(358)] eglCreateContext failed with error EGL_SUCCESS
[9240:5476:0910/191024.312:ERROR:ssl_client_socket_impl.cc(983)] handshake failed; returned -1, SSL error code 1, net_error -101
[9240:5476:0910/191024.446:ERROR:ssl_client_socket_impl.cc(983)] handshake failed; returned -1, SSL error code 1, net_error -101

В чём проблема?


text:
Q: Windows Explorer crash on right-click since last Update Yesterday I installed the pending updates from a week ago or so.
Since then Windows Explorer crashes when right-clicking any item. (The only item where it didn't crash on was on Computer.)
The event log shows:
Faulting application name: Explorer.EXE, version: 6.1.7601.17567, time stamp: 0x4d672ee4
Faulting module name: KERNELBASE.dll, version: 6.1.7601.24441, time stamp: 0x5cb935a7
Exception code: 0xc06d007e
Fault offset: 0x000000000000bdfd
Faulting process id: 0xff8
Faulting application start time: 0x01d51fa5574ad043
Faulting application path: C:\windows\Explorer.EXE
Faulting module path: C:\windows\system32\KERNELBASE.dll
Report Id: dc15feee-8b99-11e9-9549-a41731b5c9d4

Any suggestions on what I can do?

A: I have the same problem while right clicking in the Quick Access area (wanted to remove a folder from there) No idea which update or what caused this issue - any tips for possible solutions?
Faulting application name: explorer.exe, version: 10.0.19041.1202, time stamp: 0xdba1e981
Faulting module name: SHELL32.dll, version: 10.0.19041.1202, time stamp: 0x5a3e4787
Exception code: 0xc0000005
Fault offset: 0x000000000009305c
Faulting process id: 0x1e28
Faulting application start time: 0x01d7b161c6207c86
Faulting application path: C:\WINDOWS\explorer.exe
Faulting module path: C:\WINDOWS\System32\SHELL32.dll
Report Id: becb6c70-7a3d-4d3c-bdb9-bbdb9ce7b63d
Faulting package full name:
Faulting package-relative application ID:

I performed a check in cmd:

C:\WINDOWS\system32>sfc /scannow
Beginning system scan.  This process will take some time.
Beginning verification phase of system scan. Verification 100%
complete.
Windows Resource Protection did not find any integrity violations.

Where can I go from here?


text:
Q: Updating System variables in SSIS package Similar to this post
I have an SSIS Package with a Script Task that creates an Excel file on disk and populates it with data from a SQL Stored Procedure (using Microsoft.Office.Interop.Excel). This works great when testing and when running the deployed package manually through the SSIS Catalog, but when I schedule the task to run automatically through SQL Server Agent, the Package fails in the Script Task step. I have the Job running as a Proxy account that is the same as the account I'm logged into the server with when testing (and the same as the account that works when manually running the packages).
My understanding is that even though the job is running using a Proxy, any desktop interaction occurs within the Profile context of the SQL Server Agent login. Since that profile isn't actively logged in, the interaction fails. Digging in more, there is a bool System Variable in the package called "InteractiveMode" that is set to "False". I have a feeling that if I could switch that to True, everything would be hunky dorey. Trouble is, that variable is only accessible to my Script Task as "ReadOnly"...
Is there any way to set the System:InteractiveMode Variable in an SSIS package manually or programatically at runtime? Please help! I'm having to run these scheduled jobs manually for now, which is a big pain.
Thanks.

A: I had this problem a few months ago and it turned out that the execution options needed to be set to use 32 bit runtime. If you're using SQL Server 2008 R2, you can open your job and double click on the step. It's under the Execution Options tab.

If you continue to have errors, you may want to consider changing the package so that it uses a file system task to create/rename the excel document and then a Data Flow Task to move the data from your stored procedure to your excel document. Depending on your data, you may need to add a Data Conversion step in between. Here's a good article on the topic: http://www.mssqltips.com/sqlservertip/3046/sql-server-integration-services-data-type-conversion-testing/
Edit:
I haven't used SQL Server 2012 yet, but according to MSDN, it looks like the option is under the Configuration tab. Here's their article: http://msdn.microsoft.com/en-us/library/gg471507(v=sql.110).aspx


text:
Q: how do i create a group and sort list compatible with angularjs and bootstrap? Hi i have data like this. (basic example)

*

*fruit, apple, $1

*fruit, orange, $1

*fruit, banana, $1

*vegetable, sprouts, $2

*vegetable, carrots, $1

*Drink, water, $1

*Drink, milk, $2

I would like to have a list that will group by fruit/vegetables/drinks (maybe with an accordion)
Then can be sorted by the sub category (apple for example) (the group sorting order stays as is, the sub items can be sorted a>z  z>a).
the price needs to be click-able so the user can change the values, so the container needs to be rich html elements. (dropdowns etc)
Filtering is also a bonus.
i will be using angularJS for the databinding. and bootstrap is also used.
*for your reference the data is coming from a SharePoint list, and i'm trying to mimic the grouping sorting of list behaviour, but using angular for single page app.
here is an example

Can anyone recommend something that fits this?

A: I worked it out. I used AngularUI accordion, then Lodash to group and sort.


text:
Q: Python EasyGUI- Integerbox Bound Limits I am using EasyGUI as part of a small program I am writing. In it, I am using the IntegerBox "function".
Part of the parameters of this function is the lowerbound and the upperbound (the limits of the value entered). If the value is under the lowerbound or if it exceeds the upperbound, the program raises an error.
Only for this program, I want to remove the lowerbound/upperbound--- so it is possible to put any number in.
My code is:
import easygui as eg
numMin=eg.integerbox(msg="What is the minimum value of the numbers?"
                   , title="Random Number Generator"
                   , default=0
                   , lowerbound=
                   , upperbound=
                   , image=None
                   , root=None
                   )

I don't have anything entered yet, because I don't know what to put. Any input would be greatly appreciated. Thanks!

A: When all else fails, trying reading the documentation (that is, if there is any ;-).
With EasyGui there is, although it's a separate download, the easygui-docs-0.97.zip file, shown on this webpage. Here's what it says in the API section for the integerbox() function:

So, to answer your question, no, there doesn't appear to be a way to disable the bounds-checking the module's integerbox() does.
Update: Here's a new function you can add to the module that doesn't do bounds-checking at all nor does it accept bounds arguments (so it's not strictly call-compatible with the stock version). If you put it in, be sure to also add its name, 'integerbox2', to the definition of the __all__ list near the top of the module's script file.
If you would like to minimize changes to the easygui module's script itself in case there's a future update, you instead could put the new function in a separate .py file and then add an import integerbox2 near the top of easygui.py (plus another line to add it to __all__).
Here's the additional function:
#-------------------------------------------------------------------
# integerbox2 - like integerbox(), but without bounds checking.
#-------------------------------------------------------------------
def integerbox2(msg=""
               , title=" "
               , default=""
               , image=None
               , root=None):
    """
    Show a box in which a user can enter an integer.

    In addition to arguments for msg and title, this function accepts
    an integer argument for "default".

    The default argument may be None.

    When the user enters some text, the text is checked to verify that it
    can be converted to an integer, **no bounds checking is done**.

    If it can be, the integer (not the text) is returned.

    If it cannot, then an error msg is displayed, and the integerbox is
    redisplayed.

    If the user cancels the operation, None is returned.

    :param str msg: the msg to be displayed
    :param str title: the window title
    :param str default: The default value to return
    :param str image: Filename of image to display
    :param tk_widget root: Top-level Tk widget
    :return: the integer value entered by the user

    """
    if not msg:
        msg = "Enter an integer value"

    # Validate the arguments and convert to integers
    exception_string = ('integerbox "{0}" must be an integer.  '
                        'It is >{1}< of type {2}')
    if default:
        try:
            default=int(default)
        except ValueError:
            raise ValueError(exception_string.format('default', default,
                                                     type(default)))

    while 1:
        reply = enterbox(msg, title, str(default), image=image, root=root)
        if reply is None:
            return None
        try:
            reply = int(reply)
        except:
            msgbox('The value that you entered:\n\t"{}"\n'
                   'is not an integer.'.format(reply), "Error")
            continue
        # reply has passed validation check, it is an integer.
        return reply


text:
Q: Scala: Compare types I want to define a function that could compare two class types. I have defined two different classes:
abstract class Task
case class DefinedTask(id: Long) extends Task
case class EmptyTask() extends Task

Then I have a function that returns an object of type Task, that could be either DefinedTask or EmptyTask.
Now, what I'd like to do is to have a function that identifies if this object is a DefinedTask or just an EmptyTask. The problem would be simple, I'd use pattern matching. But I want to generalize it because multiple classes go with this Defined/Empty pattern.
What I'd tried so far is:
def makeReturned[T: Manifest, U: Manifest](obj: T)(u: U)(f: T => Value) =
   if(manifest[U] equals manifest[T]) f(obj) else
     throw new IllegalArgumentException()
}
//call to it
makeReturned(task)(DefinedTask)(makeTask)

U is always DefinedTask, T could be either DefinedTask or EmptyTask, but it is returned as Task.
manifest[U].erasure.toString //"class DefinedTask$"
manifest[T].erasure.toString //"class Task"

Which is right from the compiler's stand point but it's not for me. So, my question is how could I compare them in a way that would give me what I want?

A: It looks like you want run-time, not compile-time checking.  So I think you mean
def makeReturned[U <: Task, T <: Task](obj: T)(u: U)(f: T => Value) = {
  if (obj.getClass.isInstance(u.getClass)) f(obj)
  else throw new IllegalArgumentException
}

or something like that.  Look at the methods on java.lang.Class and pick the one that does what you want.

A: *

*There are some mistakes in your code:

*

*You should make the abstract class Task sealed for exhaustive pattern matching

*Empty case classes are deprecated. The compiler should have warned you about it. case object EmptyTask extends Task would be the correct alternative

*Both case classes and case objects extend the trait Product. You can check the product on being empty with either of the following ways:

*

*task.productArity == 0

*task.productIterator.isEmpty

*I think you'd be much better off reapproaching your problem. Why not just use the standard Option and have the instances of a simple case class Task(id: Int) wrapped in it? This could be the general approach for all the other similar entities of yours.


text:
Q: angular 2 service not calling a php file i'm learning angular 2 and i make a test to connect to a database, but i get an error that: SyntaxError: unexpected token < in JSON at position 0.
so i have my xampp working on port 80 or 443.
the url of my test ( i'm using angular cli ) is: localhost:4200
this is my attempt. i have a service with this method:
  getUsers(){
return this._http.get('getusers.php')
  .map(res => res.json());
 }

the getusers.php file is located at the public folder.
this is it's content. very basic just to get some results and send them back as json:
 // set up the connection variables
    $db_name  = 'mydb';
    $hostname = 'localhost';
    $username = 'myusername';
    $password = 'mypass';

    // connect to the database
    $dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);

    $sql = 'SELECT * FROM users';

    $stmt = $dbh->prepare( $sql );

    $stmt->execute();

    $result = $stmt->fetchAll( PDO::FETCH_ASSOC );

    $json = json_encode( $result );

    echo $json;

so i add that in the component i import the service, initialize it in the constructor and subscribe:
  constructor(private _usersService: UsersService) {}

  ngOnInit() {
     this._usersService.getUsers()
       .subscribe(
         data => this.getUsers = JSON.stringify(data),
         error => alert(error),
         () => console.log("Finihed")
      );
  }

what am i missing here. i do tons of ajax call but first time with angular. maybe it's the ports? or something else i am missing?
best regards

A: so since the situation is a cross domain with the two ports. in your call use the full url with the port:
http://localhost:80/yourproject/public/getContacts.php
and in your server side add CORS headers BEFORE outputting:
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With');
header('Content-Type: application/json');

echo json_encode($result);

since i'm just testing i use the *, but this is not recommended. usuall allow a specific url.

A: You need to subscribe to the the ajax call to work ;
Who ever is calling the   getUsers method should subscribe to it :
 getUsers(){
     return this._http.get('getusers.php')
     .map(res => res.json());
 }

Let's say you're calling get method here :
 myOtherFunction(){
     this.getUsers.subscribe((response)=>{
           console.log('response',response);

     })

}


text:
Q: Why does WWW::Mechanize and login-data break when I switch from a query string to a hash? The following script works fine:
#!/usr/bin/env perl
use strict; use warnings;
use Data::Dumper;
use WWW::Mechanize;

my $loginData = "userName=username&password=password&deeplinkForward=%2Fselfcare%2Frestricted%2FprepareCoCo.do&x=84&y=7";
my $loginUrl = "https://www.login.login/login.do";
my $mech = WWW::Mechanize->new( show_progress => 1 );

my $req = $mech->post( $loginUrl, 'Content' => $loginData  );

my $content = $req->content();
print Dumper $content;

But when I replace the line
my $req = $mech->post( $loginUrl, 'Content' => $loginData  );

with
my %hash = (
    'username' => 'username',
    'password' => 'password',
    'deeplinkForward' => '%2Fselfcare%2Frestricted%2FprepareCoCo.do',
    'x' => '84',
    'y' => '7'
);

my $req = $mech->post( $loginUrl, 'Content' => \%hash );

it doesn't work any more ( the script works, but the login doesn't ). Is there something worng?

A: You have to unescape deeplinkForward:
'deeplinkForward' => '/selfcare/restricted/prepareCoCo.do',

Otherwise, WWW::Mechanize thinks you want to send literal % signs, and helpfully escapes them for you.
To see what's going wrong, try adding this code right before the $mech->post line:
use HTTP::Request::Common 'POST';
print POST( $loginUrl, 'Content' => $loginData )->as_string;
print POST( $loginUrl, 'Content' => \%hash )->as_string;

They should be the same, except for the order of the fields.
It's conceivable that the server requires the fields to be listed in that order (it shouldn't, but...).  In that case, you can use an array instead of a hash (hashes don't preserve ordering).  Just replace %hash with @fields everywhere it appears.
print POST( $loginUrl, 'Content' => \@fields )->as_string;

A: i don't have mechanize in place, but you can try this and see how it goes
my $req = $mech->post( $loginUrl, \%hash);


text:
Q: How to declare nested function for Jasmin byte code? I am writing a compiler and I need to convert Mini Pascal (a simple version of Pascal) to Jasmin byte code.

*

*But how do I declare the nested function in the Jasmin language?

*Because function tt(I): I can only pass in one Integer (which is rr) how do I transfer the variable d from function ss to function tt?
C++ (translated from Mini Pascal by myself):
#include <iostream>

using namespace std;

int a, b;

int ss(int rr)
{
  int d;

  int tt(int rr)
  {
    int e;
    e = rr * 3;
    return rr + d - e + b;
  }

  d = rr - 4;
  return tt(rr);
}

int main()
{
  b = -5;
  a = ss(3);
  cout << a;

  return 0;
}

Mini Pascal:
PROGRAM test_nested_function(input, output, error);
VAR a, b : INTEGER;

  FUNCTION ss(rr :INTEGER) : INTEGER;
  VAR d : INTEGER;

    FUNCTION tt(rr : INTEGER) : INTEGER;
    VAR e : INTEGER;
    BEGIN
      e := rr * 3;
      tt := rr + d - e + b;
    END;

  BEGIN
    d := rr - 4;
    ss := tt(rr)
  END;

BEGIN
  b := -5;
  a := ss(3);
  writelnI(a)
END.

A: When you're translating from a language that has closures to one that doesn't, you have to retain a reference to the outer function somehow. There are, broadly speaking, two ways to do that: nested closures and flat closures. The important thing to note is that, in both of these cases, your closure is not an ordinary top level function. It's some structure that happens to be callable.
Nested Closures
In a nested closure, your nested function simply maintains a reference to the enclosing scope as a pointer to some abstract data structure. So, tt maintains a reference to ss (in the abstract) and then can access the d variable via ss.d. Java pseudo-code for the same:
public class SsStructure {
  private int rr;
  private int d;

  public SsStructure(int rr) {
    this.rr = rr;
    this.d = 0;
  }

}

public class TtStructure {
  private SsStructure closure;

  public TtStructure(SsStructure closure) {
    this.closure = closure;
  }

  public int call(int rr) {
    ...
  }

}

public class Main {
  public static int ss(int rr) {
    SsStructure ss = new SsStructure(rr);
    TtStructure tt = new TtStructure(ss);
    ss.d = ss.rr - 4;
    return tt.call(ss.rr - 4);
  }
}

In this model, your ss function gets a closure frame in your program. All of its local variables (or at least, those needed by the closures) get put into that structure rather than being declared as actual local variables. Then that closure structure gets passed to any nested function that needs it.
If you have functions nested multiple layers deep, then a closure maintains a reference to the immediately enclosing scope. If it needs to access variables that exist multiple layers up the closure stack, it will do so through indirect references, since each closure frame retains a reference to its own enclosing scope.
Flat Closures
With flat closures, your nested function receives copies of the actual concrete variables from the enclosing scope. Your tt is still a structure, but rather than storing a reference to some other ss structure, it gets the actual int it needs.
public class TtStructure {
  private int d;

  public TtStructure(int d) {
    this.d = d;
  }

  public int call(int rr) {
    ...
  }

}

public class Main {
  public static int ss(int rr) {
    int d = rr - 4;
    TtStructure tt = new TtStructure(d);
    return tt.call(rr - 4);
  }
}

This is a more space-efficient approach. Rather than storing a bunch of pointers everywhere, you store only the actual data, and the data you need. Further, if you have nested closures, you automatically flatten them when you create these specialized structures, so there's less indirection.
However, care must be taken if you have mutable closures. If you have a final variable, then there's no problem. In fact, this is exactly why the Java language forbids non-final variables from being closed over.
If you want to allow mutable variables in closures, you'll need to explicitly add in a layer of indirection. This can be a simple class that stores one instance variable, and then you can use that variable in both the enclosing scope and the closure.
public class Cell<T> {
  public T impl;
  public Cell(T impl) {
    this.impl = impl;
  }
}

You need to wrap any local variable in a Cell<T> if it is (a) used in a closure, and (b) reassigned to at any point. Variables that are final (hence never reassigned) need not be wrapped, and those that are only used locally (never in a closure) need not be wrapped.


text:
Q: how to trigger a button in html on pressing the Enter key I have a UI with a button, i want the button to take the click on pressing the Enter key?

A: if(event.which || event.keyCode) {
  if ((event.which == 13) || (event.keyCode == 13)) {
    document.getElementById('buttonID').click();
    return false;
  }
}
else {
  return true;
}


text:
Q: How is this if statement working with comma? there is a if statement
if ((sliding || "Window" == type) &&
    nbCasement % 2 != 1 || sliding || "Garage" == type || f({
    name: "hinge"
}),
    nbCasement > 0 && !sliding && f({
    name: "side"

}),
    d && apiProperty)

with && || and ,
I thought it's same with this code:
f({
    name: "hinge"
});
f({
    name: "side"
});
if ((sliding || "Window" == type) &&
    nbCasement % 2 != 1 || sliding || "Garage" == type ||
    nbCasement > 0 && !sliding &&
    d && apiProperty)

but the result is different what I thought.
How is this statement working?
which condition make f({name:xxx}) run?
the f defind is
  var e = []
          , f = function(a) {
            d && d.blackList && d.blackList[a.name] || e.push(a)
        };

A: The comma operator just evaluates everything, before returning the last value. Your snippet is equivalent to
(sliding || "Window" == type) && nbCasement % 2 != 1 || sliding || "Garage" == type || f({
    name: "hinge"
});
nbCasement > 0 && !sliding && f({
    name: "side"
});
if (d && apiProperty)

which can be cleaned up and prettified to
if (!sliding) {
    if (("Window" != type || nbCasement % 2 == 1) && "Garage" != type)
        f({
            name: "hinge"
        });
    if (nbCasement > 0)
        f({
            name: "side"
        });
}
if (d && apiProperty)


text:
Q: Converting a System.Func<> to a FastFunc<> in F# When interacting with F# libraries from IronPython it seems that Python function object are not automatically converted to the standard F# FastFunc function object when passed to a F# interface accepting a function as one of the parameters.
On the other hand, the Python function objects are nicely converted to System.Func<> if the interface is one of these.
That is, this is not easily callable from python:
let myFunc (f: float->float) =
   f(3.5)

while the following works perfectly:
let myFunc2 (f: System.Func<float, float>) =
    f.Invoke(3.5)

So my question is, if I want to be able to easily feed my F#-functions Python function objects, is there some way that I can convert a System.Func<> object to a FastFunc object (to be able to have a thin interface to IronPython/C# etc but be able to use the supplied function as a regular F# function deeper in the lib)?
Thanks,
Rickard
ps
I haven't enough rep to create a new tag, maybe someone could create a FastFunc tag and tag this question with it if you find it appropriate

A: Here:
    In order to convert from the Func delegate to the FastFunc, we use the
 FuncConvertExtensions class in the FSharp.PowerPack.Linq.dll assembly.

From this site: http://codebetter.com/blogs/matthew.podwysocki/archive/2008/10/15/functional-c-implementing-async-computations-in-c.aspx


text:
Q: Change text color of a dropdown menu in bootstrap-vue I'm creating a website and using boostrap-vue to add a navbar to the top of the screen. The right side of the navbar will contain a dropdown menu titled "Lang". I would like the "Lang" text to be black. The text is currently white, and I cannot find a way to change it.
I've tried the following css code which changes the color of my navbar items, but the "Lang" remains the same white/gray color.
.dropdown {
color: #000!important;
}

.navbar-dark .navbar-nav .nav-link {
    color: #000!important;
}

This is the code for my navbar:

        Planet Pluto
        About Us
        Support
        Credits

          EN
          ES
          RU
          FA

    <BNav/>

I can control the background-color via the .dropdown class, but not the color. The Lang text needs to be color code #000.
The devtools show that the text color is being controlled via the .navbar-dark .navbar-nav .nav-link classes. Adding color:#000!important from the google chrome dev tools produces the desired result. Adding this to the source code will change the color for all navbar items except for my dropdown.
How can I change the text color of my Lang dropdown menu to black?

A: You can use deep selector
::v-deep .nav-link {
   color: #000!important;
}

more restriction on dropdown only
::v-deep .dropdown .nav-link {
   color: #000!important;
}

A: Try varient property
EN


text:
Q: HTML - What kind of layout tags should I use to do a layout I'm doing a layout for an account page.  And I'm thinking my code looks horrible because I am trying to avoid using tables.  Here is a screen shot of what I want to get:

Right now, I'm using something like this (see jsfiddle): http://jsfiddle.net/uaUtq/7/
Here it is for quick review:

        First name

<input type="text" />

        Email

john@gmail.com (Default)

            <input type="text"/>

            <input type="checkbox" />Tickbox

It feels ugly and complicated. What way would you advise to do it?
Thanks

A: There's nothing wrong with using an unordered list for what you're doing. Other options you could think about are just using a form, then just wrapping your label-input pairings in divs for layout purposes:
<form>

    First Name
    <input type="text" id="firstName" />

    Email
    <input type="text" id="email" />

// etc.
</form>

A: Don't mess with too many tags.
Just use
...
 and leave the styling part to CSS
(that's its original purpose anyway : to separate "content" from "design")...

A: i think you should use div instead of li
like this

First Name

<input type="text"/>

Email

<input type="text"/>

and write CSS class for label and control to proper alignment i.e. margin, padding, float, etc.

A: You should use a table. A table is the only way to make the columns aligned so that the first column occupies just the width it needs (the width of the longest label). Any other approach forces you to make a guess on the width, and the results will inevitably vary, and the code will not be robust (the width needs to be adjusted whenever the length of the longest label changes).
(This is a repeating question, and you'll find many versions of it at StackOverflow, with varying answers. The issue is very simple once you stop listening to ideological arguments that are not backed up with facts.)


text:
Q: SQL 2005 XML Special/Escaped Characters from System.Xml.XmlDocument.OuterXml I have some XML that has creating using an XmlDocument object in C#.
I am then inserting the xml data into an XML column in SQL 2005 using the XmlDocument.OuterXml method to get the raw xml.
The problem I have is that the xml contains some special characters. Namely:  This is because the xml is built up from user input from various sources.
When I am performing the insert I get a SQL error message saying XML parsing: illegal xml character.
CREATE TABLE #MyTable (MyColumn XML)
INSERT INTO #MyTable VALUES ('<Element></Element>')

Msg 9420, Level 16, State 1, Line 2
XML parsing: line 1, character 15, illegal xml character
Can someone point me in a direction as to how I can solve this?
It will be extremely hard for me to change anything on the XmlDocument object or original xml itself, however, I can change the mechanism I use to get at the RAW XML. I can also change my database settings if required.

A: If you've got an XmlDocument with invalid characters in, you basically haven't got valid XML. There's no way of representing anything below U+0020 other than tab, carriage return and linefeed in XML. I'm not entirely sure why, but it's invalid XML according to the specification.
You could store the raw text of the invalid XML in the database, but I assume there's some reason why you wanted it to be an XML column in the first place :)
Do you actually want to preserve this invalid XML? Do you know where it comes from and whether it's required? I'd personally try to cleanse the data wherever possible.
(Btw, the first Stack Overflow data dump had a very similar problem, so it's not just you :)

A: This is possible INSERT INTO #MyTable VALUES ('')
I add spaces now for clarity
INSERT INTO #MyTable VALUES (' < E l e m e n t > & a m p ; # x 1 F ; < / E l e m e n t > ')


text:
Q: addEventListener getting ignored I have a loop that adds elements to a dropdown.
The elements get added, and I want to add an event that happens when the user clicks on one of the elements.
So I am adding an event listener like this.
for (var i = 0; cities.length > i; i++) {
        if (cities[i].toLowerCase().indexOf(value.toLowerCase()) !== -1 && citiesList <= 10) {
            citiesList ++;
            dropdown.classList.add('show');
            dropdown.innerHTML += '' + cities[i] + '';
            var item = document.getElementById('dropdown_item-' + i);
            item.addEventListener("click", function(){ console.log("test") });
            console.log(item);
        }
    }

But when I click on the elements the event does not fire even though console.log logs the item correctly and when I add the listener manually through the console it works. I tried using a timeout function but to no prevail.

A: When you += with the innerHTML of a container, the container's contents get completely re-parsed from their HTML markup alone. Anything else (such as event listeners not in the HTML markup) will be lost. Use insertAdjacentHTML instead:

The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It does not reparse the element it is being used on, and thus it does not corrupt the existing elements inside that element. This avoids the extra step of serialization, making it much faster than direct innerHTML manipulation.

dropdown.insertAdjacentHTML('beforeend', '' + cities[i] + '');

That said, it looks like you may be giving the element an ID just so that you can select it and subsequently attach a listener to it. Dynamic IDs are a pretty bad idea - if the reason for the ID, it would be better to create the element using createElement instead:
const a = document.createElement('a');
a.className = "dropdown-item";
a.textContent = cities[i];
a.addEventListener("click", function() {
  console.log("test")
});
dropdown.appendChild(a);

Keep in mind that i will equal to cities.length after the end of the loop, given your current code. If you reference i inside the listener callback, if you want it to reference the i used for that particular iteration, you need a block-scoped i instead: change
for (var i = 0; cities.length > i; i++) {

to
for (let i = 0; cities.length > i; i++) {

(or, even better, use Array.prototype.forEach or something like that instead of manually messing with indicies)