text:
Q: Executing a function in a loop in javascript asynchronously- where to place defer.resolve? I come from java/python background and new to javascript. I need to create a product list with the description of its children as well included in a jsonarray.
parent_list:
[{ children: [ 100714813, 100712694 ],
  sp: '89.10',
  weight: '1 ltr',
  pack_type: 'Carton',
  brand: 'Real',
  p_desc: 'Fruit Power Juice - Orange' }]

Now for every parent I need to again iteratively fetch the children details by connecting to the database and finally have the result consolidated in a single jsonarray. But when I execute the below code, the control doesn't wait for fetching the children data( which makes sense as its being called asynchronously!), the result I get is a jsonarray that contains data only for the parents that have no children.
exports.productDetailsQuery = function(options) {

    var AEROSPIKE_NAMESPACE = '';
    var AEROSPIKE_SET = 'products';
    var PD_KEY_VERSION_NUMBER = '1';

    var defer = sails.Q.defer();

    var results = options.results;
    var parent_list = [];
    var finalData = [];

    var productKeys = results.map(
        function(x){
            return {
                ns: AEROSPIKE_NAMESPACE,
                set: AEROSPIKE_SET,
                key: "pd.v" + PD_KEY_VERSION_NUMBER + '.' + 'c' + options.city_id + '.' + x.sku.toString()
            }
        }
    );

    var status = require('aerospike').status;
    var breakException = {};

    // Read the batch of products.
    sails.aerospike.batchGet(productKeys, function (err, results) {
        if (err.code === status.AEROSPIKE_OK) {
            for (var i = 0; i < results.length; i++) {
                switch (results[i].status) {
                    case status.AEROSPIKE_OK:
                        parent_list.push(results[i].record);
                        break;
                    case status.AEROSPIKE_ERR_RECORD_NOT_FOUND:
                        console.log("NOT_FOUND - ", results[i].keys);
                        break;
                    default:
                        console.log("ERR - %d - ", results[i].status, results[i].keys);
                }
            }
            parent_list.forEach(function(parent){
                var children = parent['children'];
                console.log(children)
                if(children){
                    var childKeys = children.map(function(child){
                        return {
                            ns: AEROSPIKE_NAMESPACE,
                            set: AEROSPIKE_SET,
                            key: "pd.v" + PD_KEY_VERSION_NUMBER + '.' + 'c' + options.city_id + '.' + child.toString()
                        }
                    });
                    sails.aerospike.batchGet(childKeys, function(err, childData){
                        if(err.code === status.AEROSPIKE_OK){
                            console.log('this called')
                            var entry = {};
                            entry['primary_prod'] = parent;
                            entry['variants'] = childData;
                            finalData.push(entry);
                        }
                    });
                }
                else{
                    var entry = {};
                    entry['primary_prod'] = parent;
                    finalData.push(entry);
                }
            });
            defer.resolve(finalData);
        } else {
            defer.reject(err);
        }
    });

    return defer.promise;
}

I need finalData to be like:
[{"primary_prod":{ children: [ 100714813, 100712694 ],
  sp: '89.10',
  weight: '1 ltr',
  pack_type: 'Carton',
  brand: 'Real',
  p_desc: 'Fruit Power Juice - Orange' },
"variants":[{child_data},{child_data}]}, ...........]

Would really appreciate any help as to how to make it work.Is there a specific pattern to handle such cases?
Thanks!

A: What you have written is along the right lines but only the outer batchGet() is promisified. Because there's no attempt to promisify the inner batchGet(), it doesn't contribute to the finally returned promise.
Your overall pattern might be something like this ...
exports.productDetailsQuery = function(options) {
    return sails.aerospike.batchGetAsync(...).then(results) {
        var promises = results.filter(function(res) {
            // Filter out any results that are not `AEROSPIKE_OK`
            ...
        }).map(function(parent) {
            // Map the filtered results to an array of promises
            return sails.aerospike.batchGetAsync(...).then(function(childData) {
                ...
            });
        });
        // Aggregate the array of promises into a single promise that will resolve when all the individual promises resolve, or will reject if any one of the individual promises rejects.
        return sails.Q.all(promises);
    });
}

... where batchGetAsync() is a promisified version of batchGet().
The fully fleshed-out the code will be longer but can be kept reasonably concise, and readable, by first defining a couple of utility functions. You might end up with something like this  :
// utility function for making a "key" object
function makeKey(obj) {
    return {
        ns: '', //AEROSPIKE_NAMESPACE
        set: 'products', //AEROSPIKE_SET
        key: 'pd.v1.c' + options.city_id + '.' + obj.toString()
    }
}

// promisified version of batchGet()
function batchGetAsync(obj) {
    var defer = sails.Q.defer();
    batchGet(obj, function(err, results) {
        if(err.code === status.AEROSPIKE_OK) {
            defer.resolve(results);
        } else {
            defer.reject(err);
        }
    });
    return defer.promise;
}

var status = require('aerospike').status;

// Main routine
exports.productDetailsQuery = function(options) {
    return batchGetAsync(options.results.map(makeKey)).then(results) {
        var promises = results.filter(function(res) {
            if (res.status === status.AEROSPIKE_OK) {
                return true;
            } else if(status.AEROSPIKE_ERR_RECORD_NOT_FOUND) {
                console.log("NOT_FOUND - ", res.keys);
            } else {
                console.log("ERR - %d - ", res.status, res.keys);
            }
            return false;
        }).map(function(parent) {
            var entry = { 'primary_prod': parent },
                children = parent['children'];
            if(children) {
                return batchGetAsync(children.map(makeKey)).then(function(childData) {
                    entry.variants = childData;
                    return entry;
                });
            } else {
                return entry;
            }
        });
        return sails.Q.all(promises);
    });
}

A: With the new ES6 plus async stuff and babel its simpler.  You can npm i -g babel npm i babel-runtime then compile and run the following with babel test.js --optional runtime --stage 2 | node:
import {inspect} from 'util';

let testData = [
  { id: 0, childIds: [1,2]},
  { id: 1, childIds:[] },
  { id: 2, childIds:[] }
];

function dbGet(ids) {
  return new Promise( r=> {
    r(ids.map((id) => { return testData[id];}));
  });
}

async function getChildren(par) {
  let children = await dbGet(par.childIds);
  par.children = children;
}

async function getAll(parentIds) {
  let parents = await dbGet(parentIds);
  for (let p of parents) {
    await getChildren(p);
  }
  return parents;
}

async function test() {
  var results = await getAll([0]);
  console.log(inspect(results,{depth:3}));
}

test().then(f=>{}).catch( e=> {console.log('e',e)});


text:
Q: How to start master/detail in Activity When I will start my master/detail activity(FolderListActivity) from another activity
startActivity(new Intent(getApplicationContext, FolderListActivity.class)))
or
startActivity(new Intent(getApplicationContext, FolderDetailActivity.class)))

it shows only one side in full screen. It works in separately project.
How to properly show  my master/detail. As shown below:

Details
AndroidManifies.xml:
<activity
    ...
</activity>
<activity
    ...
</activity>
  <activity
    android:name="com.mypck.FolderListActivity"
    android:label="@string/app_name" >
</activity>
<activity
    android:name="com.mypck.FolderDetailActivity"
    android:label="@string/title_folder_detail"
    android:parentActivityName=".FolderListActivity" >
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".FolderListActivity" />
</activity>

I've seen this question, but there is no useful answer for me.
Thanks in advance.

A: I did fix it. There was my error, when I moved to my current project I forgot values-large. It has a specific item for large devices.
refs.xml
<resources>

    <item name="activity_folder_list" type="layout">@layout/activity_folder_twopane</item>

</resources>

Regards. B&B

redpajama_set_name: RedPajamaStackExchange


text:
Q: Udp connection port 25000 returns no data I want to receive data from uk.tcpvpn.com on port 25000 udp
I have tried this code but no way i did not receive data
import socket, struct, time, math
from math import pi
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(struct.pack("dddddd",0,0,0,0,0,0), ("uk.tcpvpn.com", 25000))
data, addr = sock.recvfrom(1024)
sock.close()
print(data)

But when i tried with dns servers like 8.8.8.8 port 53 i get data
Is there a solution ?


text:
Q: How do I return back specific data from a csv? I've written code based on the exercise question but it's not returning the correct the number. It feels as if I did everything right.
 static double Q3(String stockFilename, String date) {

    // Given a filename with stock data in the format "date,price,volume" and a date, return the total value of all
    // shares of the stock that were traded that day. The total value is price times (multiplication) volume.

    String line = "";
    String dataArray[];
    double price = 0.0;
    double volume = 0.0;
    try {
        BufferedReader br = new BufferedReader(new FileReader(stockFilename));

        while ((line = br.readLine()) != null) {
            dataArray = line.split(",");

            if(dataArray[0].equals(date)) //Finds the date of that day
                price = Double.parseDouble(dataArray[1]); //Grabs price
                volume = Double.parseDouble(dataArray[2]); //Grabs volume
        }

        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return price*volume;
}

Here is the output:
Incorrect on input: [data/FB_2016.csv, 2016-02-12]
Expected output : 3.6903954403536E9
Your output     : 3.8674439998248E9

As you can see it's returning back a very similar number.

A: You have a several mistakes in your code.
1) You need totalAmount instead of single price and volume.
2) In your if() are missed {} (volume = Double.parseDouble(dataArray[2]); is always executed)
As result, you return [last price in given day] * [last volume in file]. I think, it's a bit different than you expect.
3) So, your code should be something like this:
double totalAmount = 0.0;

...

if(dataArray[0].equals(date)) {
  totalAmount += Double.parseDouble(dataArray[1]) * Double.parseDouble(dataArray[2]);
}

...

return totalAmount;

In this case totalAmount is sum of price * volume for all records for given day.


text:
Q: SWT Table: Cannot retrieve data from table created with TableEditor I'ma having an issue retrieving data from the table that I've created. It displays a check box, string (taken from all_mapping_objects which is added first) and drop down combo with values 0.0 to 1.0. How do I retrieve the all the values once they have been edited in the table, i.e. check box boolean, string value and combo value.
Tried some variations of TableItem[] items = table.getItems() but I only get back empty values.
final Table table = new Table(sectionsInfo, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
              table.setLinesVisible(true);
               InfogridData = new GridData();
                InfogridData.horizontalSpan = 4;
                InfogridData.horizontalAlignment = GridData.BEGINNING;
                InfogridData.horizontalAlignment = GridData.FILL;
                InfogridData.grabExcessHorizontalSpace = true;
                InfogridData.verticalAlignment = GridData.BEGINNING;
                InfogridData.verticalAlignment = GridData.FILL;
                InfogridData.grabExcessVerticalSpace= true;

                TableColumn column = new TableColumn(table, SWT.NONE);
                column.setWidth(500);

                TableColumn column2 = new TableColumn(table, SWT.NONE);
               column2.setWidth(50);

               table.setLayoutData(InfogridData);

              for (int i = 0; i < all_mapping_objects.size(); i++) {
                new TableItem(table, SWT.NONE);
              }
              TableItem[] items = table.getItems();

              for (int i = 0; i < items.length; i++) {
                TableEditor editor = new TableEditor(table); //defines editor which controls objects put in

                CCombo combo = new CCombo(table, SWT.NONE | SWT.READ_ONLY);
                editor.grabHorizontal = true;

                  for (float me = 0; me <= 10; me++) {
                    combo.add("" + me/10);
                  }

                combo.setText("1.0");

                editor.setEditor(combo, items[i], 1); // sets the column
                editor = new TableEditor(table);

                Button button = new Button(table, SWT.CHECK);

                button.setText(all_mapping_objects.get(i).getTextf()); // mapping objects written to the table

                button.pack();
                editor.minimumWidth = button.getSize().x;
                editor.horizontalAlignment = SWT.LEFT;
                editor.setEditor(button, items[i], 0); // sets the column

              }

A: You should use SelectionListener on Button ( SWT.CHECK) and similarly for CCombo. I suggest you to start using TableViewer instead working with SWT Table.


text:
Q: What is the preferred method for creating a wxWidget application: using a GUI tool or procedurally in code? I use wxWidgets to create test tools at work.  I have always created the GUI by creating the widgets in code.  I haven't tried any of the tools available that help to do this.  How do other users of wxWidgets typically create their interface?  If you use a tool, which tool do you use?  If you use a tool, what advantages and disadvantages do you think there are for using that tool?

A: I've used wxFormBuilder for two reasons:

*

*It's cross-platform and I needed something that would work on Linux.

*I'm new to wxWidgets and I didn't want to spend lots of time futzing about with building the GUI.

I think it works quite well, and being familiar with similar GUI building tools (Borland C++ Builder, Jigloo for Java, Delphi) I found it easy to use.
If you stick with the paradigm of using wxFormBuilder to generate base classes, and then you make a class that inherits to layer your application specific logic on top, absolutely not hand-editing the C++ code wxFormBuilder generates, then it works well and you can easily update and modify your GUIs in wxFormBuilder again (and again...).
Advantages:

*

*Can generate your base GUIs quite quickly, in a visual manner, without having to constantly look up the documentation.

*Don't have to do as many code/compile/run cycles just to make sure your GUI is looking like what you expected.

*The base class/derived class paradigm can make a reasonably clean separation of your GUI and business logic code.

Potential Disadvantages

*

*Disclaimer: I've only used wxWidgets to create very simple, straight-forward GUIs, so haven't really pushed the tool to any limits.

*Potentially the base class/derived class paradigm could sometimes get in your way if you are doing something too sophisticated with your GUI (OTOH that could indicate that you may need to re-think your approach.)

*I had a situation where I needed a menu item when compiled for one operating system, but not when compiled for another.  There is no logic in wxFormBuilder to support this. I ended up taking the short-cut of always creating the menu item and then having my derived class make it invisible if it was the wrong OS (not ideal.)

That's about it, I think.

A: What I find is that I often build the first cut at a GUI using a tool, and when it seems to be converging on the "final" form, I start to recode/refactor by hand.
Some of this depends on the tools, though, too.  I'm not a big wxWidget fan.

A: You know, it depends.
E.g. if I need some standard behaviour, I usually use DialogBlocks for GUI because it is the fastest way.
If I need custom behaviour (e.g. my current project is cross-platform media manager whose GUI supports skins) then I do all GUI-relates things in code.
As for custom controls:

*

*If a control does some project-specific thing, then I create it in DialogBlocks using the same project file (with other forms and dialogs used in this project)

*If my control should be reusable (general-purpose control) then I create a separate project for it and create a keleton in DialogBlocks - add empty event handlers and class variables if possible, then write logic manually in Visual Studio.

That's it :)

A: You might want to look into using XRC/XRS files.
Though I must admit I haven't bothered to do so myself. Just generating static GUI code using wxFormBuilder (which has XRC support, btw) has been enough for all my (small-scale) GUI designs.


text:
Q: Why linux shows "File descriptor 4 (????) leaked on ..." and how to remove it? I'm a new guy here.
I get many messages like
"
File descriptor 4 (socket:[78134]) leaked on lvm invocation. Parent PID 15230: sh
File descriptor 7 (socket:[77180]) leaked on lvm invocation. Parent PID 15230: sh
File descriptor 8 (socket:[78138]) leaked on lvm invocation. Parent PID 15230: sh
File descriptor 12 (/dev/sdb) leaked on lvm invocation. Parent PID 15230: sh
File descriptor 13 (/dev/sdc) leaked on lvm invocation. Parent PID 15230: sh
File descriptor 14 (/dev/sdd) leaked on lvm invocation. Parent PID 15230: sh
File descriptor 15 (/dev/sde) leaked on lvm invocation. Parent PID 15230: sh

"
Who knows why system reports that and how to remove?
Thanks!


text:
Q: Is fury a negative status effect? The status effect "fury" seems to recharge my limit breaks at about double the normal speed. But I also saw that there are Items which will cure this effect.  Is fury a bad status effect?  Does it cause me to take more damage?

A: It reduces your Attack %, which represents your accuracy.
If you use magic, don't cure, or if your Attack % is high enough with it don't cure, otherwise cure.
EDIT:
Did some research, and it reduced magic and physical attack accuracy by 30%, so always heal, unless you need to build up your limit break, you can cause this status by using a Hyper.
Clarification: Fury builds up your limit meter faster by increasing the amount it raises by per 1 point of damage, it may also increase damage, however this is contested.
Forum discussing it

A: Wow many wrong answers here, the mechanics are simple.
Fury will decrease hit % by 30%.  Later in the game fury will not be noticeble as will nearly always hit even with it on the reason for this is you can have hit% well over 100% meaning a 30% reduction will be way above 70% and in many cases still over 100%, early game its very noticeable.  Fury the positive effect is it doubles the charging rate of the limit guage which is very useful, you do not deal or take extra damage with fury.
sadness the opposite effect will decrease damage you take by 30% as a positive effect, but it will also halve the rate the limit gauge increases.  the halving is not due to the damage reduction its due to been halved in real terms, so when factoring in the less damage taken the reduction is effectively about 65%.
Both effects have their usefulness, and I consider neither a negative effect, I use them both strategically during the course of the game.


text:
Q: How to tell if tilelayer is fully visible In my app I'm switching tilelayer opacities to create animation. The problem is, the tilelayer doesn't have visible (or something similar) event, which should trigger, once all tiles are visible on page. So now often happens that the preloaded layer's tiles are not fully visible and when I hide the layer bellow, the animation "blinks".
Note: tileLayers are retrieved and appended to map, so I'm changing only opacity
What I wan't to achive:
preloadedLayer.setOpacity(1);
// wait till preloadedLayer is fully visible
visibleLayer.setOpacity(0);

Any idea, how to tell if tiles are fully loaded?
Edit
load event doesn't trigger when tileLayer is already appended to map and
 just the layer's opacity is changed.


text:
Q: Spatial adjustment using control points in QGIS I want to spatial adjust a bunch of points using control points. I have two layers. One is the layer I want to move with the control points in it, and another is the layer with target points pairing with the control points. My QGIS version is 3.22.4. I have already tried vector bender, but it moved the points to a strange location. Is there any way to spatial adjust points with QGIS?
The first image is the points I want to move. green points are the control points. The second image is the target points paring with the control points with the same number.

A: I created a QGIS Graphical Model to perform order 1 polynomial transformations to vector layers.
Order 1 polynomial is an affine (linear) transformation.
The advantage of this model over Vector Bender plugin, is that the transformation will allways be order 1 polynomial, regardless of the number of control points chosen. A minimum of three pairs of points are required, and a least-squared algorithm is used for more than three.
For this model to work, you must create a lines layer called 'gcps', with the same CRS of the points layer to be adjusted.
Draw one line for each control point, in the direction of the transformation. Then, run the 'Order 1 transformer by GCPs' process. INPUT parameter is the layer to be adjusted.

To get the model in your toolbox, save the following text in a 'order_1.model3' file and import it with the Add Model to Toolbox option.
<!DOCTYPE model>
<Option type="Map">
  <Option type="Map" name="children">
    <Option type="Map" name="gdal:convertformat_1">
      <Option type="bool" name="active" value="true"/>
      <Option name="alg_config"/>
      <Option type="QString" name="alg_id" value="gdal:convertformat"/>
      <Option type="QString" name="color" value=""/>
      <Option type="Map" name="comment">
        <Option type="QString" name="color" value=""/>
        <Option type="QString" name="component_description" value="Performs the order 1 polynomial transformation using start and end points of geometries stored in a called 'lines' layer."/>
        <Option type="double" name="component_height" value="60"/>
        <Option type="double" name="component_pos_x" value="440"/>
        <Option type="double" name="component_pos_y" value="150"/>
        <Option type="double" name="component_width" value="100"/>
        <Option type="bool" name="outputs_collapsed" value="true"/>
        <Option type="bool" name="parameters_collapsed" value="true"/>
      </Option>
      <Option type="QString" name="component_description" value="Transform"/>
      <Option type="double" name="component_height" value="30"/>
      <Option type="double" name="component_pos_x" value="300"/>
      <Option type="double" name="component_pos_y" value="165"/>
      <Option type="double" name="component_width" value="180"/>
      <Option name="dependencies"/>
      <Option type="QString" name="id" value="gdal:convertformat_1"/>
      <Option type="Map" name="outputs">
        <Option type="Map" name="Transformed">
          <Option type="QString" name="child_id" value="gdal:convertformat_1"/>
          <Option type="QString" name="color" value=""/>
          <Option type="Map" name="comment">
            <Option type="QString" name="color" value=""/>
            <Option type="QString" name="component_description" value=""/>
            <Option type="double" name="component_height" value="60"/>
            <Option type="double" name="component_pos_x" value="0"/>
            <Option type="double" name="component_pos_y" value="0"/>
            <Option type="double" name="component_width" value="100"/>
            <Option type="bool" name="outputs_collapsed" value="true"/>
            <Option type="bool" name="parameters_collapsed" value="true"/>
          </Option>
          <Option type="QString" name="component_description" value="Transformed"/>
          <Option type="double" name="component_height" value="30"/>
          <Option type="double" name="component_pos_x" value="490"/>
          <Option type="double" name="component_pos_y" value="255"/>
          <Option type="double" name="component_width" value="200"/>
          <Option type="invalid" name="default_value"/>
          <Option type="bool" name="mandatory" value="false"/>
          <Option type="QString" name="name" value="Transformed"/>
          <Option type="QString" name="output_name" value="OUTPUT"/>
          <Option type="bool" name="outputs_collapsed" value="true"/>
          <Option type="bool" name="parameters_collapsed" value="true"/>
        </Option>
      </Option>
      <Option type="bool" name="outputs_collapsed" value="true"/>
      <Option type="bool" name="parameters_collapsed" value="true"/>
      <Option type="Map" name="params">
        <Option type="List" name="INPUT">
          <Option type="Map">
            <Option type="QString" name="parameter_name" value="INPUT"/>
            <Option type="int" name="source" value="0"/>
          </Option>
        </Option>
        <Option type="List" name="OPTIONS">
          <Option type="Map">
            <Option type="QString" name="expression" value="'-order 1 ' ||
aggregate(
  layer:= 'gcps',
  aggregate:= 'concatenate',
  expression:=
    '-gcp ' ||
	x( start_point( $geometry)) ||
	' ' ||
	y( start_point( $geometry)) ||
	' ' ||
	x( end_point( $geometry)) ||
	' ' ||
	y( end_point( $geometry)),
  concatenator:= ' ')"/>
            <Option type="int" name="source" value="3"/>
          </Option>
        </Option>
      </Option>
    </Option>
  </Option>
  <Option type="Map" name="designerParameterValues">
    <Option type="QString" name="INPUT" value="desde_ab5b642a_617c_43e3_b534_07d0f9784913"/>
    <Option type="QString" name="LINES" value="lineas_9451fedc_4089_4e76_849c_12e9da74e703"/>
    <Option type="bool" name="VERBOSE_LOG" value="true"/>
    <Option type="QgsProcessingOutputLayerDefinition" name="gdal:convertformat_1:output">
      <Option type="Map">
        <Option type="Map" name="create_options">
          <Option type="QString" name="fileEncoding" value="System"/>
        </Option>
        <Option type="Map" name="sink">
          <Option type="bool" name="active" value="true"/>
          <Option type="int" name="type" value="1"/>
          <Option type="QString" name="val" value="TEMPORARY_OUTPUT"/>
        </Option>
      </Option>
    </Option>
  </Option>
  <Option name="groupBoxes"/>
  <Option type="Map" name="help">
    <Option type="QString" name="ALG_CREATOR" value="Gabriel De Luca"/>
    <Option type="QString" name="ALG_DESC" value="Performs the order 1 polynomial transformation using start and end points of line geometries stored in a (must be called 'gcps') layer."/>
    <Option type="QString" name="ALG_HELP_CREATOR" value=""/>
    <Option type="QString" name="ALG_VERSION" value="1"/>
    <Option type="QString" name="INPUT" value="Vector layer to be transformed."/>
    <Option type="QString" name="SHORT_DESCRIPTION" value=""/>
    <Option type="QString" name="gdal:convertformat_1:Transformed" value=""/>
  </Option>
  <Option name="modelVariables"/>
  <Option type="QString" name="model_group" value=""/>
  <Option type="QString" name="model_name" value="Order 1 transformer by GCPs"/>
  <Option type="Map" name="parameterDefinitions">
    <Option type="Map" name="INPUT">
      <Option type="List" name="data_types">
        <Option type="int" value="-1"/>
      </Option>
      <Option type="invalid" name="default"/>
      <Option type="invalid" name="defaultGui"/>
      <Option type="QString" name="description" value="INPUT"/>
      <Option type="int" name="flags" value="0"/>
      <Option type="QString" name="help" value=""/>
      <Option name="metadata"/>
      <Option type="QString" name="name" value="INPUT"/>
      <Option type="QString" name="parameter_type" value="vector"/>
    </Option>
    <Option type="Map" name="gdal:convertformat_1:Transformed">
      <Option type="bool" name="create_by_default" value="true"/>
      <Option type="int" name="data_type" value="-1"/>
      <Option type="invalid" name="default"/>
      <Option type="invalid" name="defaultGui"/>
      <Option type="QString" name="description" value="Transformed"/>
      <Option type="int" name="flags" value="0"/>
      <Option type="QString" name="help" value=""/>
      <Option name="metadata"/>
      <Option type="QString" name="name" value="gdal:convertformat_1:Transformed"/>
      <Option type="QString" name="parameter_type" value="vectorDestination"/>
      <Option type="bool" name="supports_non_file_outputs" value="false"/>
    </Option>
  </Option>
  <Option name="parameterOrder"/>
  <Option type="Map" name="parameters">
    <Option type="Map" name="INPUT">
      <Option type="QString" name="color" value=""/>
      <Option type="Map" name="comment">
        <Option type="QString" name="color" value=""/>
        <Option type="QString" name="component_description" value="Vector layer to be transformed."/>
        <Option type="double" name="component_height" value="60"/>
        <Option type="double" name="component_pos_x" value="75"/>
        <Option type="double" name="component_pos_y" value="60"/>
        <Option type="double" name="component_width" value="90"/>
        <Option type="bool" name="outputs_collapsed" value="true"/>
        <Option type="bool" name="parameters_collapsed" value="true"/>
      </Option>
      <Option type="QString" name="component_description" value="INPUT"/>
      <Option type="double" name="component_height" value="30"/>
      <Option type="double" name="component_pos_x" value="210"/>
      <Option type="double" name="component_pos_y" value="75"/>
      <Option type="double" name="component_width" value="180"/>
      <Option type="QString" name="name" value="INPUT"/>
      <Option type="bool" name="outputs_collapsed" value="true"/>
      <Option type="bool" name="parameters_collapsed" value="true"/>
    </Option>
  </Option>
</Option>

Under the hood, it runs an ogr2ogr command.


text:
Q: How to realize a multi-page wizard with client-side controller "rules" in JSF2 or GWT2? In (JSF2 + jQuery) or in GWT:
What would be the best way to realize a multi-page form wizard with explicitly specified form controller "rules" running on the client-side?
The goal is:

*

*form with 3 pages, each containing 'prev'/'next' buttons and finally 1 'submit' button.

*all form items have unique ids for addressing/accessing them.

*for client-side form control there are 2 kind of control "rules" specified in a central place and stored somehow:

*

*active behaviour of 1 item (modifying 1+ other items):
WHEN form item x is checked/changed/text=="MyText"
THEN show/hide/modifyTextOf item y and item z.

*passive behaviour of 1 item (waiting for 1+ events):
WHEN ((itemA.propX is 'blah') AND (itemB.text()=="Yeah!") OR
      (itemC is checked) AND (itemD.value() >= 10))
THEN
    self.setVisible(true); /self.hide(true);   //and
    itemF.setText("It's Magic!");
    ...
END-THEN

The action triggering resp. event listening is intented to be on a per-page basis -- one later enhancement could be to also run "cross-page modifications/listenings", e.g.
itemA on page 1 triggers some action on itemC on page 3.
How would you define, persist (XML,JSON?) this logic and finally run it within
a client-side form controller?

A: PrimeFaces has a ready-to-use component for this, the p:wizard.
With regard to control rules, make use of the rendered attribute.


text:
Q: Python3 pull emails past a certain date using MAPI I am trying to create a script that pulls emails from a certain folder after a certain date. I have a text document, dateLastRan.txt in which the date the last time this script was ran is stored. The data in there will be akin to 2018-09-18.
I grab the date from the document and I grab the date of the messages. I was hoping to only output emails that were past the dateLastRan, but my comparison is complaining. And yeah, I am new to python. Thanks for any advice!
  if(msgDate>dateLastRan):
TypeError: unorderable types: datetime.date() > str()

I respect the error, but how to get around it? Relevant code below:
    import win32com.client
    import datetime
    import re

    badUrl = []

    outlook = win32com.client.Dispatch("Outlook.Application")
    namespace = outlook.GetNamespace("MAPI")
    your_folder = namespace.Folders.Item(1)

    folder = 'ANY' #change this entry to match a folder found within Inbox

    inbox = your_folder.Folders['Inbox'].Folders[folder]

    dateLastRan = '1991-01-01' #used to initialize datelastran
    todaysDate = (datetime.date.today())    #used to determine where to pick back up
    startDate = '1991-01-01'#used to initialize startDate

   #Grab Last Date Ran from file
    try:
        with open('lastDateRan.txt', 'r') as infile:
            for date in infile:
                dateLastRan = date
    except Exception as err:
        print ("lastDateRan.txt not found", '\n')

    print("Date Last Ran = ", dateLastRan, '\n')

    all_messages = inbox.Items

    print("Pulling URLs from folder:",folder,'\n')

    for message in all_messages:
            msgDate = message.senton.date() #get date of message
            print("msg date: ", msgDate)
            print("datelastran: ",dateLastRan)
            if(msgDate>dateLastRan): #<<<<<Comparison here
                print("woot")
                #do stuff

A: Date types and string types cannot be compared.  dateLastRan = '1991-01-01' is a String types. So you need to convert to datetime Type.
Please refer to this code :
begin = datetime.date(2018, 9, 17)  #year, month, day
end = datetime.date(2018, 9, 18)
if(begin > end):
  print("False")
else:
  print("True")

A: So what I ended up doing was todaysDate.replace('-','') to remove the dashes and int(todaysDate) to cast the number. For the date I grabbed from file I had to use dateLastRan = re.sub('-', '', dateLastRan) because .replace was not useable and then followed that with int(dateLastRan). I could then compare properly and only touch emails after the date of the lastDate.
This doesn't take into account time of day, but it's working for now.


text:
Q: "Unknown compiler version" - Boost thinks VS2005 compiler is VS2015 So, I need to build projects in Visual Studio 2005 and Visual Studio 2015 on the same machine (64-but, win10). When switching back to a project built in 2005, Boost thinks I'm still using the 2017 compiler and throws all sorts of errors. Mainly this one: Unknown compiler version
My question: Does Visual Studio 2015 set something on my machine that boost would be looking at to determine the compiler version, or does boost store something? For the life of me, I can't figure out where boost is looking for this information.
I believe this is where boost is checking:
#if (_MSC_VER > 1600)
#  if defined(BOOST_ASSERT_CONFIG)
#     error "Unknown compiler version - please run the configure tests and     report the results"
#  else
#     pragma message("Unknown compiler version - please run the configure     tests and report the results")
#  endif
#endif

Where is _MSC_VER set?

A: To build the Boost.Build system for your version of Visual Studio, run the bootstrap.bat file in the corresponding Visual Studio command prompt.
Boost.Build likes to default to higher versions of Visual Studio when it is compiling. When Boost.Build realizes that you
have more than one version of Visual Studio installed, it will create environment variables like:
VS140COMNTOOLS --> Visual Studio 2015
VS80COMNTOOLS --> Visual Studio 2005
You can switch from the VC++ 14.0 compiler to the VC++ 8 compiler by:

*

*Changing the name of the VC140COMNTOOLS environment variable - you can put an 'x' in front of it or add _DISABLED to
it.

*Navigating to C:\Users{your user name}\AppData\Temp and deleting the auto-generated scripts
"b2_msvc-8.0_{..blahblah..}.cmd" (there should be 2 - one for 32-bit builds and one for 64-bit builds). Although the name
seems to be correct, don't be fooled - this file is not generated often and defaults to the newest version of Visual
Studio on your machine.

Once you have done both these steps, your compiler will regenerate the compilation scripts properly and should work.


text:
Q: Print regex matches in java So I have an IP address as a string.
I have this regex (\d{1-3})\.(\d{1-3})\.(\d{1-3})\.(\d{1-3})
How do I print the matching groups?
Thanks!

A: If you use Pattern and Matcher to do your regex, then you can ask the Matcher for each group using the group(int group) method
So:
Pattern p = Pattern.compile("(\\d{1-3}).(\\d{1-3}).(\\d{1-3}).(\\d{1-3})");
Matcher m = p.matcher("127.0.0.1");
if (m.matches()) {
  System.out.print(m.group(1));
  // m.group(0) is the entire matched item, not the first group.
  // etc...
}

A: import java.util.regex.*;
try {
    Pattern regex = Pattern.compile("(\\d\\{1-3\\})\\.(\\d\\{1-3\\})\\.(\\d\\{1-3\\})\\.(\\d\\{1-3\\})");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        for (int i = 1; i <= regexMatcher.groupCount(); i++) {
            // matched text: regexMatcher.group(i)
            // match start: regexMatcher.start(i)
            // match end: regexMatcher.end(i)
        }
    }
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}


text:
Q: What exactly does !function ($){...}(window.jQuery) do? I'd like to know exactly what's going on here. I know what $(document).ready(function() {...}); does and when it comes into effect. Same goes for jQuery(function($) {...}.
But what does this do?
!function ($) {
  $(function(){
    var $window = $(window)
    //normal jquery stuff
  })
}(window.jQuery)

Is it loaded when jQuery is loaded instead of when the document is 'ready'?

A: It creates a closure in which the variable $ is assigned the value of window.jQuery.
The intention is to allow the uninformatively named variable $ to be used as a shortcut for jQuery without conflicting with the large number of other libraries and custom functions that also use $ as a variable name.

A: Using the ! operator before the function causes it to be treated as an expression
!function () {}()

A: The syntax you're looking at is used for setting up a jQuery closure. This is used to ensure that the jQuery $ variable is garuanteed to be available and correct within the code; ie it can't be overwritten in the global scope by anything else (which is possible if you're using multiple libraries, etc).
This technique is often used by jQuery plugin authors -- if you're interested in finding out more, the docs are here, and explain in more detail why you'd want to wrap your jQuery code in a function like this.
The only point of interest that's different in your example is that in the docs, the function is wrapped in brackets, whereas in the example you've given it's preceded by a !
The ! is a not operator, but doesn't actually get used for anything; I think it's just there instead of the brackets to save a single character of code. Probably helpful if you're into minifying javascript.

A: Not quite sure but I guess this is somewhat equivalent to (function(){})() approach and it's about js closures. And it ensures $ and jQuery are the same thing

A: The '!' is a 'not' operator. It doesn't do anything in the code. The only reason it is there is to signify that the function will execute immediately.
You may also see functions wrapped in parenthesis instead.
(function() {}());

Whatever is used is personal preference.


text:
Q: Debugging GDK with breakpoints I'm experimenting few GDK samples and developed my own GDK app. But having trouble to debug it. Right now I'm left with only log.d option to monitor the logs while testing it with connected glass device. Is there any other way to debug GDK app in eclipse? like step by step..

A: Debugging is the same as in Android all you need to change is that in the manifest file there would be a Launcher Command in intent-filter commented
<category android:name="android.intent.category.LAUNCHER" />

Uncomment it for the activity and then you are good to go for Debugging

A: Debugging with GDK is the same way you would debug a normal android app. Start here http://developer.android.com/tools/debugging/debugging-projects.html


text:
Q: HTML center content in body tag I'm trying to center the content in my body tag in a simple HTML page. I want the body to be 100% width, i have a container div inside of it with a set width, i want the container to be in the center of the screen.
I tried to set the margin to 0 auto; does not work, tried to set align="center" in the body tag, doesnt work.
Here is my page, as you can see it's not in center: http://jsbin.com/vifekivatabo/1/
What am i doing wrong?

A: Hey you forget to this
Define
your .container1 margin:0 auto;
.container1{
margin:0 auto;
}

A: Try thhis to your container class:
.container
{
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

A:    .container1 {
        max-width: 600px;
        width: auto;
        margin:0 auto;
        text-align:center;
    }

ADD
margin:0 auto;//to center the page
text-align:center;
Fiddle
http://jsfiddle.net/7c9wjLy6/1/

A: No problem with margin:0 auto;
here
.container1{
    margin:0 auto;
}

A: Just put before starting the div and  after closing the div.
Like this:

    <title></title>

            Welcome to the xxx mobility enrollment page.

dasdasd

                @*                <select name="DL_MarketChooser" id="DL_MarketChooser" style="width:40%;">
    <option selected="selected" value="Choose Region">Choose Region</option>
    <option value="https://connect.molnlycke.com/ssp/hq">Temporary Enrollment</option>

</select>*@

                    <colgroup>
                        <col>
                    </colgroup>

                            Username:

                                <input type="text" id="userID" size="11" value="">

                            Password:

                                <input type="password" id="Password" size="11" value="">

                                    <button type="button" onclick="performAuth()" tabindex="0">Login</button>

                    <colgroup>
                        <col>
                    </colgroup>

                                <input type="checkbox" id="isPDA" tabindex="0">My device has no phone number

                            Country:

                                <select tabindex="0" id="countrySelect">
                                    <option value="+46">Sweden</option>
                                    <option value="+83">United States</option>
                                </select>

                                    <colgroup>
                                        <col>
                                    </colgroup>

                                            Country

                                                Code
                                            Prefix and Number

                                                (no space, no leading zero)

                            Mobile:

                                    <colgroup>
                                        <col>
                                    </colgroup>

                                                                <input type="text" tabindex="0" id="countryCode" size="1" disabled="" value="+46">

Required field

                                                                                <input type="text" tabindex="0" id="phoneNumber" size="11">

Required field

                            Platform:

                                <select tabindex="0" id="platformSelect">
                                    <option value="no">-Select-</option>
                                    <option value="A">Android</option>
                                    <option value="I">iOS</option>
                                    <option value="W">Windows Phone</option>
                                </select>

                                <input type="checkbox" id="isEmp" tabindex="0" checked="">I own this device

                                    <button type="button" onclick="performRegister()" tabindex="0" id="registerButton" disabled>Register</button>
                                    <button type="button" tabindex="0">Clear</button>

            Application Version 1.5

I've also created a CodePen and a JsFiddle for you.


text:
Q: jQuery slideToggle with bootstrap I am trying to use slideToggle to show sections of my site.  Within each section, I want to use the bootstrap grid system to layout the contents within the section.  The problem is that the slideToggle resets to have no height (which appears to be because of the presence of
{ float: left; }

for bootstrap col-* elements).
Here is an example: http://jsfiddle.net/rcs2tej0/.
I have pasted the bootstrap col-* css into the fiddle along with some of my own at the bottom.  Section 1 is the default bootstrap css.  Section 2 removes the float, but it will now not correctly follow the grid.

A: I guess this is what you want:
Just adding overflow:auto; to .section-body in your CSS will solve your issue.
Replaced Code:
.section-body {
    display: none;
    border: 1px solid black;
    overflow:auto; /* ADDED */
}

Working : Demo

A: why not using collapse from bootstrap ... check this DEMO

                       Section 1

Hello

I

Am

                       Section 2

Kyle

Who

Are

You?
                        <button id='add_word'>Add Word</button>


text:
Q: When ever I check whether service is Running in android it always says no Here is my code
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this, Services.class);
        ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (Services.class.getName().equals(service.service.getClassName())) {
                Toast.makeText(this,"Service is Running",Toast.LENGTH_LONG).show();
            }else {
                Toast.makeText(this,"Service Will run now",Toast.LENGTH_LONG).show();
                startService(intent);
            }
            break;
        }
    }
}

And Service code
package gcmtutorial.androidbegin.com.socket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

/**
 * Created by shuser on 21-07-2016.
 */
public class Services extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    public class Hello implements Runnable{
        public void run(){
            synchronized (this){
                int i=0;
                while (i<100){
                    try {
                        wait(1000);
                        i++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        Thread thread = new Thread(new Hello());
        thread.start();
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

I close the app and starts again It always says Service Will run now. Even my service is running in background. How can i know whether the service is running or not in background in android

A: I have slightly change the code the reason is below,
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
    if (serviceClass.getName().equals(service.service.getClassName())) {
        return true;
    }
}
return false;
}

You are putting toast here,and it takes a time, i.e. another toast appears only after first one is gone, try above function with Log not toast.

Another approach:
Let's make thing simpler.

*

*Create global class.

*Put one  public static boolean variable.

*When service starts change the value of this boolean to TRUE.

*Change the value of this variable to FASLE in onDestroy() of service.

*Now when you want to check the status then just check this boolean variable from global class.


text:
Q: How do I count the number of solutions to an equation with variable conditions? In order to find the number of solutions to the equation $y_1 + y_2 + y_3 = 10$ where $y_i > 0, i \in$ {1,2,3}, then I let $y_i = x_i + 1$ with $x_i \in$ {0} $\cup \mathbb{N}$. Now I have $x_1 + x_2 + x_3 = 10 - 3 = 7$ and the solution is ${7 + 3 - 1 \choose 7}$ (if I'm not mistaken).
However, what if the restriction was that $ 2 <y_i < 8$ ? My way of thinking is that $y_i$ has now only 5 choices out of 11 but I don't know how to interpret this.
How should I think about such problem in order to come up with a solution, knowing how to solve the first problem described at the start of the question? I'm not looking for a direct solution to the problem but rather a way to think about this and understand the solution.
I read this but I don't get why $y_i = 6 - x_i$ (which would translate to $x_i = 5 - y_i$ to my problem [I think]).


text:
Q: Can IOS be upgraded on a Cisco Catalyst 6509 switch without downtime? There's this Cisco Catalyst 6509 switch with 2 (two) supervisor modules; one of them is active, the other is (almost always) in standby.
We need to upgrade IOS; current version is 12.2.something (I can check exactly which one, if this does matter).
Can this be done without service interruption? Something like "upgrade the standby supervisor, activate it, upgrade the other one"?

A: According to Cisco, it is possible to upgrade a 6500 running IOS in native mode without powering down the switch.
However, I have never seen this done in production. The procedure I have seen followed most often is that a supervisor is upgraded off line, and the config pasted in via console. The switch is powered down, both old supervisors are removed, and the switch is booted with the new supervisor. Once it is confirmed to be up and running clean, a second supervisor running the new code version is inserted.
In the document above, Cisco also mention:
Note: This procedure can impact the data traffic.
Cisco recommends that you perform this procedure
during a scheduled maintenance window.

I would suggest that you get an agreed maintenance window, and advise your users that there might be service interruption. This is usually much preferred to advertising no outage, and subsequently causing one. :)

A: You want to do a Enhanced Fast Software Upgrade (eFSU).  It is supported in versions 12.2(33)SXI and later.
http://www.cisco.com/en/US/docs/switches/lan/catalyst6500/ios/12.2SX/configuration/guide/issu_efsu.html


text:
Q: Limit size of a list in python I want to limit the size of a list in python 2.7 I have been trying to do it with a while loop but it doesn't work
l=[]
i=raw_input()//this is the size of the list
count=0
while count<i:
    l.append(raw_input())
    count=count+1

The thing is that it does not finish the loop. I think this problem has an easy answer but I can't find it.
Thanks in advance

A: I think the problem is here:
i=raw_input()//this is the size of the list

raw_input() returns a string, not an integer, so comparisons between i and count don't make sense.  [In Python 3, you'd get the error message TypeError: unorderable types: int() < str(), which would have made things clear.]  If you convert i to an int, though:
i = int(raw_input())

it should do what you expect.  (We'll ignore error handling etc. and possibly converting what you're adding to l if you need to.)
Note though that it would be more Pythonic to write something like
for term_i in range(num_terms):
    s = raw_input()
    l.append(s)

Most of the time you shouldn't need to manually keep track of indices by "+1", so if you find yourself doing it there's probably a better way.

A: That is because i has a string value type, and int < "string" always returns true.
What you want is:
l=[]
i=raw_input() #this is the size of the list
count=0
while count<int(i): #Cast to int
    l.append(raw_input())
    count=count+1

A: You should try changing your code to this:
l = []
i = input() //this is the size of the list
count = 0
while count < i:
    l.append(raw_input())
    count+=1

raw_input() returns a string while input() returns an integer. Also count+=1 is better programming practice than count = count + 1. Good luck


text:
Q: Continuity of l-adic cohomology: is the cohomology of the generic point isomorphic to the completion of the limit of cohomology of open subvarieties? Let $X$ be a variety over an algebraically closed field $k$. Denote by $\eta$ its generic point; it is the inverse limit of the open subvarieties $X_i$ of $X$. It is well known that the etale cohomology of $\eta$ (i.e. the corresponding cohomology of the Galois group of $\eta$) with $\mathbb{Z}/l^n\mathbb{Z}$-coefficients is isomorphic to the direct limit of the $\mathbb{Z}/l^n\mathbb{Z}$-cohomology of $X_i$ (here $l\ne char\, k$, $n>0$). I would like to know: is it true that $H^\ast_{et}(\eta, \mathbb{Z}_l)$ is the $l$-adic completion of $\varinjlim H^\ast_{et}(X_i, \mathbb{Z}_l)$ (here one should consider the continuous etale cohomology of $\eta$ i.e. the continuous $\mathbb{Z}_l$-cohomology of its Galois group, whereas for $X_i$ the continuous etale cohomology is just the 'naive' one)? This seems to be equivalent to: $\varinjlim H^\ast_{et}(X_i, \mathbb{Z}_l)$ contains no infinitely divisible elements. What can one say about this limit? A related question: when does an open dense embedding of varieties necesarily yield an embedding of their $\mathbb{Z}/l\mathbb{Z}$-cohomology?
The problem is that the cohomology of $\eta$ is usually not finitely generated. So I was not able even to find the answer for the corresponding continiuos profinite group cohomology (of the fundamental groups of $X_i$) question (whereas I am not sure at all that one can replace $\varinjlim H^\ast_{et}(X_i, \mathbb{Z}_l)$ by $\varinjlim H^\ast_{cont}(\pi_1(X_i), \mathbb{Z}_l)$ here).
PS. I was silly not to complete $\varinjlim H^\ast_{et}(X_i, \mathbb{Z}_l)$ in the first version of my question.

A: You may consider $X=\mathbf{P}^1_k$, and look at the first cohomology group $\varinjlim H^1_{et}(X_i,\mathbf{Z}_l)$. By the toposic version of Hurewicz theorem, this colimit is the same as $\varinjlim Hom_{cont}(\pi_1(X_i),\mathbf{Z}_l)$ (where $Hom_{cont}$ means continous morphisms of topological groups). Each $X_i$ is $X$ minus a finite set of closed points, so that $\varinjlim H^1_{et}(X_i,\mathbf{Z}_l)$ will look very much like a free $\mathbf{Z}_l$-module on an infinite set (once $\infty$ has been removed, we freely add a generator each time we leave out some point; take $k$ to be the field of complex numbers to fix the ideas). On the other hand, we can do the same computation with finite coefficients, and thus, using the continuity of étale cohomology with finite coefficients, conclude that the $l$-adic Galois cohomology of $\eta$ is (or, at the very least, surjects to) the $l$-adic completion of $\varinjlim H^1_{et}(X_i,\mathbf{Z}_l)$. This clearly provides a counterexample.
As for the question if an open immersion can induce an injective map on cohomology, you can again look at an open subset of a smooth curve: using the Gysin long exact sequence, you will see that the cohomology of the complement has to fit somewhere and that this gives serious obstructions to injectivity (at least if you want such a property in every degree).


text:
Q: ajax call MVC Spring Controller, Not Found error I have a MVC Spring controller. I call this ajax on page load.
$.ajax({
            type:       "get",
            url:        'custom/Service',
            data:       "note1=" + "11",
            dataType:   "json",
            async:   false,
            success:    function() {
                        alert("1");
            },
            error:function (xhr, ajaxOptions, thrownError){
                if(xhr.status == 200 && xhr.statusText == 'parsererror'){
                    window.location.reload();
                } else {
                    alert(xhr.status+","+xhr.statusText);
                    alert(thrownError);
                }
            }
        });

My controller is:
@RequestMapping("/custom")
public class CustomController {

    @RequestMapping(value="/Service", method=RequestMethod.GET)
        public String Service(
                @RequestParam("note1") String note1,
                HttpServletRequest request, HttpServletResponse response, Locale locale,
                Model model) {
            String result = custom.Service(note1, request, response);
        System.out.println("result: " + result);
        return result;
    }
}

The out put is correct in the console for the controller. But I get "Not Found" error. Here is the developers tool error: GET "MySite/custom/Service?note1=11" 404 (Not Found) . What is wrong?

A: Change your code like below:
@RequestMapping(value="/Service", method=RequestMethod.GET)
        public @ResponseBody String Service(
                @RequestParam("note1") String note1,
                HttpServletRequest request, HttpServletResponse response, Locale locale,
                Model model) {
            String result = custom.Service(note1, request, response);
        return result;
    }

You can access the result in your ajax success function.
success:    function(result) {
                        alert(result);
            },

A: you need to add response body annotation to your return parameter
 public @ReponseBody String Service(

A spring controller doesn't have to return a view, it can return data, with the reposnsebody annotation. Your original code will look up the result variable as a jsp according to your view resolver settings.


text:
Q: How physically does blowing air in front of a piece of paper move the piece of paper? Suppose you stand a piece of paper upright on a table and then stand a few inches away parallel to the paper and blow through a straw.  The paper will move towards the air stream.  My question is: Why does this happen?
I am not interested in the answer

"Because there's a higher air pressure behind the paper and a lower air pressure in front of the paper due to the faster air stream and bernoulli's equation says blah blah blah".

I am specifically asking about the cause-and-effect chain that starts with a stream of air particles moving in front of the paper and ends with the paper moving towards the air stream.
My explanation:

*

*Air is blown from the opening of the straw.

*The stream of air particles emitted pushes the atmospheric air in its path along the path of the air stream.

*As the front of the air stream and the sides of the air stream continue to move along the stream path, the closely surrounding air particles move into the stream and are pushed along the stream by the other stream particles.

*This results in a "hole volume" surrounding the air stream where the atmospheric air close to the stream used to be.

*A section of the hole volume between the stream and the paper propagates away from the stream and moves towards the paper.

*Once the section of hole volume reaches the paper, we have the situation where the opposite side of the paper experiences more air particle collisions than the side exposed to the section of hole volume.

*Due the higher number of collisions on the opposite side of the paper, the paper moves in the direction of the collisions which is towards the air stream.

Is this correct?  If this is incorrect or incomplete.  Which step is wrong or needs additional steps?

A: the air parcels flowing over the convex upper surface of the curled piece of paper tend to follow the curved paper surface, which is sagging downwards. the air parcels departing the paper thereby have had their momentum vectors tipped slightly downwards, representing a change in the direction of those vectors. The time derivative of a momentum vector has the units of force, meaning that the curved paper had to have exerted a net force upon those air parcels while they were passing by- and that means the air parcels exerted a net reaction force on the paper surface.
That reaction force tends to pull up on the piece of paper.


text: Q: Charged pendulum oscillations Recently, a question was asked in our school, regarding the calculation of the time period of a charged pendulum bob suspended in an electric field with the help of an insulating thread(gravity also present). Although it is simple at the high school level, shouldn't there be EM radiation from the swinging pendulum ? If that is so, the time period should increase over time as well. Can we obtain an expression as to how the time period changes over time?


text:
Q: Page is getting reload when dynamically adding iframe I have a div inside a page inside, which I want to load the iframe dynamically once user click on the link.
//div code

//link
Load iframe inside div

//javascript code
function loadIframe () {
   var iframe = document.createElement('iframe');
   iframe.frameBorder=0;
   iframe.setAttribute("src", 'myurl here ');
   document.getElementById('cs_feedback_pane').appendChild(iframe);
 }

iframe loads successfully after the click of anchor tag but the entire page gets refresh . does anyone have idea how to avoid page load ?

A: Replace your anchor with
Load iframe inside div

I changed the href and the onclick, to avoid jumping or re-freshing.

A: Try instead of loading it by createElement using
document.getElementById('cs_feedback_pane').innerHtml("");

As far as I know this shouldn't reload a page.


text:
Q: Defining and returning a tree of objects from a Google Endpoints Python server Suppose I have some entity that supports a parent/child relationship. Something like:
class Employee(ndb.Model):
  name = ndb.StringProperty()
  boss = ndb.KeyProperty(kind=Employee)

Such a structure would allow me to nest Boss/Employees arbitrarily deep.
Alternatively, I could use entity keys to define parents, omitting the boss property from the object altogether.
My questions are:

*

*What are the pros and cons of using a KeyProperty versus a
parent key.

*How should I return the whole tree from an Python Google
Endpoints server?

A: A KeyProperty is mutable after entity creation. Parent keys are immutable after creation, which means you have to recreate the Employee record if the boss ever changes. Parent keys allow you to do ancestor queries, so you can say, get all employees directly or indirectly under a manager. However, if that manager gets a new manager, you have to recreate the entire subtree. You probably want the former, unless your data is pretty immutable, without many cross references with other entities.
If you are returning it as part of an API, I would say this is a sub-optimal and non-RESTful decision. Such an operation is expensive and not resource-based. Generally, resources link to other resources rather than embedding them. I'd say a less expensive operation is just to list all employees and let your client reconstruct the tree instead. The response could look something like this:
{
  'items': [
    {
      'id': '/employees/1'
      'name': 'Alice',
      'boss': /employees/2'
    },
  ]
}


text:
Q: Script to insert JSON data into MongoDB? I currently have a JSON file titled "data.json". In this file, I only have an array of people's names, like this:
"data":
[
    {
        {
        "name":"John",
        "age":30,
        }

        {
        "name":"Mark",
        "age":45,
        }
    }
]

My goal is to write a script to insert this data into mongoDB. Could I write this directly in my JSON file? How would I go about this? Thanks!

A: You can make this script with NodeJS
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/"; // Your mongodb url here

enter code here`MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var myobj = { name: "Company Inc", address: "Highway 37" };
  dbo.collection("customers").insertOne(myobj, function(err, res) {
    if (err) throw err;
    console.log("The document got inserted.");
    db.close();
  });
});

You can also insert it manually through the GUI program or directly through your MongoDB command line
db.collection.insert('"data":[{"name":"John","age": 30},{"name": "Mark", "age": 45}]')

A: create a post route using nodejs to add data to your collection in mongodb


text:
Q: XSODATA service doesn't support merge operation? I am using SAP HANA xsodata service to create an ODATA service on a HANA table, which is working fine.
Updating the model with update parameter on sap.ui.model.odata.ODataModel works fine
Code:
 oModel.update(sUrl, oEntry, {
        success : //do something ,
        error : //do something
    });

Now I want to use MERGE in place of PUT while Updating, following the documentation
My code:
oModel.update(sUrl, oEntry, {
        merge: true,
        success : //do something ,
        error : //do something
    });

It's throwing an error as only Get, Post, Put and Delete is supported.
So, my question is, whether XSODATA service doesn't support MERGE?
If it supports MERGE, what is wrong with my code?
Error - The following problem occurred: HTTP request failed405,Method Not Allowed,{ "error": { "code": "", "message": { "lang": "en-US", "value": "Invalid HTTP method. Only GET, POST, PUT, DEL methods are allowed."}}}

A: It very much looks like the XS server only supports the following HTTP methods: GET, HEAD, POST, OPTIONS, PUT, DELETE, TRACE, CONNECT. To see this, visit
https://<your.server:port>/sap/hana/xs/admin/#/package/<your.package.in.dot.notation>

Navigate to the package that contains your ODATA service .xsodata file, not drill into but click the name, chose tab "CORS" and go [Edit]. Down the page you see what methods can be allowed.
The docs, all docs, are a bit vague, but this is the list.
The default settings say GET, HEAD, POST, OPTIONS are allowed, which fits your error message. The settings in that tab are obeyed, as I had to learn the hard way when I tried a PUTonce.
So we can conclude that, funnily, the UI5 docs advertise a method which is not supported by the XS server.


text:
Q: How to pip install pickle under Python 3.9 in Windows? I need the pickle package installed under my Python 3.9 under Windows 10.
What I tried
When trying with pip install pickle I was getting:

ERROR: Could not find a version that satisfies the requirement pickle
(from versions: none) ERROR: No matching distribution found for pickle

Then I tried the solution suggested in this question using pip install pickle5 but got the following error:

error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/

I then tried to install the Tool suggested by the error but got same error message after trying again pip install pickle5.
Question
Which is the correct way to install pickle package under Python 3.9 in Windows 10?
UPDATE
There is no need to install pickle module as it comes already installed along with Python 3.x. Just needed to do import pickle and voila!

A: I found a way that I'm not sure it's the optimal but it works.
I did pip install pickle4
And then in the script just
import pickle4 as pickle

UPDATE
There is no need to install pickle as it's already within Python 3.9. Just needed to import pickle and voila!

A: Cedric UPDATED answer is right. Pickle exists within Python 3.9. You don't need pip install pickle. Just use it.
import pickle

A: For Generalized Summary, for almost all Python versions, you never need to worry for installing 'pickle' as it comes already installed with the python interpreter.
Hence, simple import works:
import pickle

In case this doesn't work, refer to Pickle Install Problems on Stack Overflow.
Another suggested way is to run: pip install pickle-mixin
For other Queries and Info, refer to Python Pickle Documentation.


text:
Q: OpenCV (Python) setMouseCallback preventing program termination I have been writing a program in python using OpenCV. Up to this point, I had not set the mouse callback (cv2.setMouseCallback). To exit the program (which is in fullscreen), I would press the ESC key (Line 70).
I recently added a mouse callback (Line 11) which works as it should, however, now when I press the ESC key, the program does not terminate as it had previously. The while loop finishes, and cv2.destroyAllWindows() and sys.exit(0) are called. The window does close, and no python code after sys.exit(0) is executed, however no prompt is returned in Command Prompt (in which the python program was started).
My first thought was that there was a thread running that had not been stopped, however I have no threads in my code, and the thread that calls the onMouse function (Line 50) is the same as  the main loop thread (i.e. it would not appear that opencv has a seperate thread for mouse callbacks).
My code can be found here: http://pastie.org/9246511
I am stumped, and any help is greatly appreciated.
Please note: You will need a webcam plugged in to test the code

A: Your code seems to exit correctly running it as a script from a prompt and running in Pycharm when using sys.exit().
If you are running it in Ipython you need to use exit() to return to the command prompt:
Just use  exit()  after cv2.destroyAllWindows() and it will terminate.
In [1]: type(exit)
Out[1]: IPython.core.autocall.ExitAutocall

A: Just incase you never got the answer...I just had the same issue.  Turns out it was because in my my config file (Run/Debug Configurations) I had checked the "Show command line afterwards" box.  Once I unchecked that the window was killed correctly.


text:
Q: greatest common divisor in the ring $F(x)[y]$
Assume $F$ is a field (we can assume here $F = \mathbb R$), and let $R = F(x)[y]$. If we now know that two elements $a,b$ in $R$ have no common divisor other than $1$ we can write $\gcd(a,b) = 1$. Is it in this particular ring still true (as it is in $\mathbb Z$) that we can write $1$ as a linear combination of $a$ and $b$? If yes, is there a way to find the coefficients?

I tried it with some simple examples and found for $a=x, b= y^2$  that.
$$(\frac 1 x + y^2) x + (-x)y^2 = 1$$
Further for $a=x+y, b=y^2$:
$$\frac 1 {x^2} (x-y)(x+y)+ \frac 1 {x^2} y^2 = 1$$
For another example $a = x+y^2,b=x^2+xy$ I was not able to come up with a solution.

A: I assume the field $F$ is equal to $K$. Moreover that $K(x)$ is the field of rational functions in $x$. Then the answer to your question is "yes": the polynomial ring $L[y]$ in one variablle (here $y$) over a field $L$ is a principal ideal domain. In such a domain the greatest common divisor of two elements can be written as a linear combination of the two elements involved.
As for your example:
$
\frac{x-y}{x(x^2+x)}(x^2+xy)+\frac{1}{x^2+x}(x+y^2)=1
$


text:
Q: ! Package calc Error: `\let ' invalid at this point \documentclass[11pt,a4paper]{article}
\usepackage{polyglossia}
\setmainlanguage{portuges}
\setotherlanguages{english}

\usepackage{graphicx}
\usepackage{url}
\usepackage{hyperref}
\usepackage{enumitem}
\usepackage{pdfpages}

\def\UrlBreaks{\do-\do\/}
\usepackage{amssymb,latexsym,amsthm,amsfonts,color,fancyhdr}
\setlength{\parindent}{0pt}
\setlength{\parskip}{5pt}

\setlist[enumerate]{noitemsep, topsep=10pt, partopsep=20pt}
\setlist[enumerate,1]{label*=\enspace \arabic*.,before=\normalfont\mdseries,after=\normalfont,leftmargin=1.3em\large}
\setlist[enumerate,2]{label*=\arabic*.,before=\normalfont\upshape\normalsize,after=\normalfont}
\setlist[enumerate,3]{label*=\arabic*.,before=\normalfont\upshape,after=\normalfont}
\setlist[enumerate,4]{label*=\arabic*.,before=\normalfont\upshape,after=\normalfont}

%\makeindex

%\author{Luís Mendes}
\title{Informação }

\begin{document}

\iffalse
\begin{titlepage}
\begin{center}
\textsc{}
\\
\vspace{1cm}
\textsc{}
\\
\vspace{5cm}

\maketitle

\vspace{2cm}

1

{\large \emph{}}
\\
\vspace{5cm}

\begin{tabular}{l p{0.5\linewidth}}
Lu\\
()\\
\end{tabular}
\end{center}
\vspace*{\fill}

\end{titlepage}
\fi
% capa interior com menção dos orientadores
\thispagestyle{empty}

\newpage

\selectlanguage{portuges}
Proc
J

\vspace{1.5cm}

À Ex.\\
Ao Ex

\vspace{2cm}

Vila

\vspace{3.5cm}

E

\begin{enumerate}
\item {Quanto}

\end{enumerate}

\end{document}

What's wrong with this minimal example?

A: Your minimal example was not very minimal, removing packages unrelated to the problem a more specific example is
\documentclass[11pt,a4paper]{article}

\usepackage{enumitem}
\usepackage{calc}

\setlist[enumerate]{noitemsep, topsep=10pt, partopsep=20pt}
\setlist[enumerate,1]{label*=\enspace \arabic*.,before=\normalfont\mdseries,after=\normalfont,leftmargin=1.3em\large}

\begin{document}

\begin{enumerate}
\item {Quanto}

\end{enumerate}

\end{document}

The  setting leftmargin=1.3em\large is in error, leftmargin has to take a length value, without the calc package being loaded the error is not trapped and it accidentally runs to completion, but with the calc package (from pdfpages) you get an error. In either case the spurious \large should be removed.


text:
Q: CakePHP find count of records from associated Models I have a Job model and a Visit model, a Job can have many Visit's. I have set up the relationships appropriately in my Models.
A Visit also belongs to a Supplier, so a Supplier can have many visits.
A subcontractor is a Supplier who has an engineer value of 0 in the database.
I want to return an associative array with the amount of Jobs raised per subcontractor, something like this:
$supplier_job_count = array(
    'Subcontractor1' => 23,
    'Subcontractor2' => 3,
    'Subcontractor3' => 7,
    'Subcontractor4'=> 0
);

Here is what I have:
    $conditions = array();

    // get all the visits in the database
    $visits = $this->Job->Visit->find('all');

    // extract all the visit id's
    $visit_supplier_ids = Hash::extract($visits, '{n}.Visit.supplier_id'); // 11612 records

    // get all the subcontractors in the database
    $subcontractors = $this->Job->Visit->Supplier->find('all', array('order' => 'id ASC', 'conditions' => array('Supplier.engineer' => 0)));

   // extract all the subcontractor id's
   $subcontractor_ids = Hash::extract($subcontractors, '{n}.Supplier.id'); // 1288 records

   // intersect arrays so we only want matching values from both, i.e. only want visits whose supplier is a subcontractor
    $visit_subcontractors = array_values(array_intersect($visit_supplier_ids, $subcontractor_ids));

    // find all visits who is a subcontractor id
    $visits = $this->Job->Visit->find('all', array('conditions' => array('Visit.supplier_id' => $visit_subcontractors)));

    // extract out the job id's for the subcontractor visits
    $visit_jobs_ids = Hash::extract($visits, '{n}.Visit.job_id');

    // pass the job id's to the conditions for the jobs
    $conditions['Job.id'] = $visit_jobs_ids;

    // get all subcontractor jobs
    $subcontractor_jobs = $this->Job->find('all', array('conditions' => $conditions));
    $subcontractor_job_count = array();

    foreach ($subcontractors as $key => $value) {

       // this is where I am getting stuck
       $subcontractor_job_count[$value['Supplier.name']] = ));
    }

I am sort of half way there, just struggling to get a count of how many jobs raised per subcontractor, any ideas?


text:
Q: (Bison) dynamic cast fails while parsing I'm writing a compiler as an assignment and I'm having some critical problems with dynamic_cast.
I will try to share the key pieces of code that fail to work, along with the essential code one might need to understand what's going on here.
Relevant classes:
#define YYSTYPE Node*

class Node {
    public:
        Node(){}
        virtual ~Node() {}
};

class Type : public Node {
    private:
        // some vars
    public:
        Type(/* some vars */) {}
        // more methods
}

And some of the rules in my .ypp file:
M: /* epsilon */    { // Marker, generates new llvm label
                      genLabel();
                      $$ = new Type(/*...*/);
                    }

S: RETURN SC {/* unrelated code */}
  | WHILE LPAREN M E {/* unrelated code */} RPAREN M S {
        Type* m1 = dynamic_cast<Type*>($3);
        if(!m1){
            cout << "m1 bad" << endl;
        }
        Type* m2 = dynamic_cast<Type*>($6);
        if(!m2){
            cout << "m2 bad" << endl;
        }

        // more unrelated code
      }

Note: There are no conflicts with other rules. Bison made sure of that.
The output while parsing some input for example:
Input:
while (true) return;

Output:
m2 bad

I can't figure it out. How does one dynamic cast work fine (based on extra code, and return the right pointer), yet another one that is supposed to do exactly the same fails.


text:
Q: DL180 G6 - ESXI 6.0 - P410 - Lost access to volume Issue We have a DL180 G6 Server with a P410 RAID Card. The server has the following three RAID arrays.

4x2TB - RAID 10
4x2TB - RAID 10
2x2TB - RAID 1

2x2TB HD's are configured as hot spares for the three arrays.
Following is the relevant output from ESXCLI
Smart Array P410 in Slot 1
Bus Interface: PCI
Slot: 1
Serial Number: PACCR9VYJKGQ
Cache Serial Number: PAAVP9VYJCYN
RAID 6 (ADG) Status: Enabled
Controller Status: OK
Hardware Revision: C
Firmware Version: 2.72
Rebuild Priority: Medium
Expand Priority: Medium
Surface Scan Delay: 15 secs
Surface Scan Mode: Idle
Parallel Surface Scan Supported: No
Queue Depth: Automatic
Monitor and Performance Delay: 60  min
Elevator Sort: Enabled
Degraded Performance Optimization: Disabled
Inconsistency Repair Policy: Disabled
Wait for Cache Room: Disabled
Surface Analysis Inconsistency Notification: Disabled
Post Prompt Timeout: 0 secs
Cache Board Present: True
Cache Status: OK
Cache Ratio: 25% Read / 75% Write
Drive Write Cache: Disabled
Total Cache Size: 512 MB
Total Cache Memory Available: 400 MB
No-Battery Write Cache: Disabled
Cache Backup Power Source: Batteries
Battery/Capacitor Count: 1
Battery/Capacitor Status: OK
SATA NCQ Supported: True
Number of Ports: 2 Internal only
Driver Name: HP HPSA
Driver Version: 6.0.0
PCI Address (Domain:Bus:Device.Function): 0000:06:00.0
Host Serial Number: USE626N2XD
Sanitize Erase Supported: False
Primary Boot Volume: None
Secondary Boot Volume: None
Secondary Boot Volume: None

array A (SATA, Unused Space: 0  MB)
  logicaldrive 1 (3.6 TB, RAID 1+0, OK)

  physicaldrive 1I:1:9 (port 1I:box 1:bay 9, SATA, 2 TB, OK)
  physicaldrive 1I:1:10 (port 1I:box 1:bay 10, SATA, 2 TB, OK)
  physicaldrive 1I:1:11 (port 1I:box 1:bay 11, SATA, 2 TB, OK)
  physicaldrive 1I:1:12 (port 1I:box 1:bay 12, SATA, 2 TB, OK)
  physicaldrive 1I:1:5 (port 1I:box 1:bay 5, SATA, 2 TB, OK, spare)
  physicaldrive 1I:1:6 (port 1I:box 1:bay 6, SATA, 2 TB, OK, spare)

array B (SATA, Unused Space: 0  MB)
  logicaldrive 2 (3.6 TB, RAID 1+0, OK)

  physicaldrive 1I:1:1 (port 1I:box 1:bay 1, SATA, 2 TB, OK)
  physicaldrive 1I:1:2 (port 1I:box 1:bay 2, SATA, 2 TB, OK)
  physicaldrive 1I:1:3 (port 1I:box 1:bay 3, SATA, 2 TB, OK)
  physicaldrive 1I:1:4 (port 1I:box 1:bay 4, SATA, 2 TB, OK)
  physicaldrive 1I:1:5 (port 1I:box 1:bay 5, SATA, 2 TB, OK, spare)
  physicaldrive 1I:1:6 (port 1I:box 1:bay 6, SATA, 2 TB, OK, spare)

array C (SATA, Unused Space: 0  MB)
  logicaldrive 3 (1.8 TB, RAID 1, OK)

  physicaldrive 1I:1:7 (port 1I:box 1:bay 7, SATA, 2 TB, OK)
  physicaldrive 1I:1:8 (port 1I:box 1:bay 8, SATA, 2 TB, OK)
  physicaldrive 1I:1:5 (port 1I:box 1:bay 5, SATA, 2 TB, OK, spare)
  physicaldrive 1I:1:6 (port 1I:box 1:bay 6, SATA, 2 TB, OK, spare)

Now in ESXI we are getting the following errors from time to time.

Lost access to volume 5456cb3e-4fbdb59c-a37a-
  d8d385644ec0 (datastore2) due to connectivity
  issues. Recovery attempt is in progress

Keep in mind that it is affecting all the three arrays at the same exact time and in a few seconds all three arrays recover. As per understanding, all of the drives are attached to one single port on the P410 RAID card. Do you think that using both ports could improve performance and potentially remove this recurring issue?
We have tried all software solutions at this point including updating the
firmware(updated to 6.64). What can be the other options?
Update 1
The two spare drives were configured as spares for all the three arrays as described above. I removed the spares from all the arrays for about 15 minutes and the errors stopped. Now I have configured the first spare for the first array and the second for the second array to see if the error appears again.
Update 2
Reattaching the spares has caused the error to return and it is affecting all the three arrays. So i am removing the spares one by one to further troubleshoot this issue. This is probably a known issue described here: http://community.hpe.com/t5/ProLiant-Servers-ML-DL-SL/ESXi5x-HPSA-P410i-WARNING-LinScsi-SCSILinuxAbortCommands-1843/td-p/6818369. Fingers crossed.

A: The two updates posted in the question and further troubleshooting, lead us to the real answer to the problem. We found out that it was related to driver in ESXI for the P410 raid card. We downgraded to version .60 of the driver available from http://h20564.www2.hpe.com/hpsc/swd/public/detail?swItemId=MTX_d18033ac346f468c92062ce127 and the problem was resolved.
Keep in mind that none of the recent drivers work including version .114, .116 and the recently released .118. So this is the only software solution to the issue unless your problem is related to hardware as described by user @ewwhite.
Keep in mind that this issue only occurs if you are using spare drives with a P410 card in a DL180G6 server. I have also seen posts that it occurs with other HP servers as well so you might try .60 version of the driver on those server to see if it fixes your problem.
While facing this issue you might also see periodic spikes in disk latency without any corresponding read/write load on your server, this is better explained through the following picture:

In the above picture the red dots denote the periodic spikes while the spare was attached. The green dots denote the period while the spare was being removed.
As you can see in the above picture, the latency spikes were not associated with the any corresponding read/write loads and were periodic. In our case these were happening exactly five minutes apart. As soon as the spare was removed the spikes stopped.
To downgrade to the .60 version of the driver please put your machine into maintenance mode after gracefully shutting down the VM's and issue the following commands
cd /tmp
wget http://ftp.hp.com/pub/softlib2/software1/pubsw-linux/p964549618/v97400/scsi-hpsa-5.5.0.60-1OEM.550.0.0.1331820.x86_64.vib
esxcli software vib install -v /tmp/scsi-hpsa-5.5.0.60-1OEM.550.0.0.1331820.x86_64.vib

After that reboot your server. Hope this helps someone. I will update this answer when HP releases a stable version of HPSA driver for P410 which does not cause this issue with spare drives.

A: This is probably a backplane or backplane expander issue. There's a slight chance it could be cable. And possibly RAID controller.
The DL180 G6 you're using is probably a 12-bay 3.5" unit, and is connected to the Smart Array P410 via a single 4-lane SAS SFF-8087 cable.
Upgrading firmware was the first thing you should have done. Have you had the same problem since updating the controller firmware? You may want to also do the disks' firmware for good measure.
But seeing the design of this server depends entirely on the SAS backplane, and the fact that all disks are impacted at the same time, you're looking at a connection issue that will likely require service or replacement.


text:
Q: How to select which ones to install on Android SDK Build tools I'd like to know which one is important to put check mark on to install.  I've deselected some and my app stopped working so i re intalled all but i dont know their purpose...

A: Typically the latest production release from Google:

*

*28.0.3 (in this case)

re: https://developer.android.com/studio/releases/build-tools
Unless you specifically need one of the newer release candidates to target a beta version of Android (build tools 29.x support Android Q (but Xamarin.Android does not currently have a matching alpha/beta release yet)


text:
Q: ¿Como se realizaria esta consulta en LinQ? Tengo las siguientes relaciones entre tablas

de las cuales me interesa traer las mesas que no estan reservadas el dia que el cliente marque para realizarla (ademas de que no deberia listar las mesas en las cuales su estado sea igual a 2 que es inactiva, ni tener en cuenta las reservas eliminadas que tendrian el estado 3).
Me recomendaron usar la sentencia any(), con lo que me quedo algo asi, que es mas o menos lo que busco (pero no funciona, ya que me trae las mesas OCUPADAS ese dia)
BBDD.MesaXReserva.Include("Reserva").Include("Mesa").Where(Identificador => !Identificador.Mesa.MesaXReserva.Any()
                        && Identificador.Reserva.ID_EstadoReserva != (int)ClsEstadoReservas.EEstadosReservas.Eliminada
                        && Identificador.Reserva.Fecha == _FechaReservar
                        && Identificador.Mesa.ID_EstadoMesa != (int)ClsEstadosMesas.EEstadosMesas.Inactivo).ToList();

En SQL me quedo la siguiente consulta (que le falta el filtrado por estados de reservas y mesas que seguro lo podria hacer con LinQ una vez traido los datos)
select * from Mesa
LEFT JOIN
(
    select MesaXReserva.ID_Mesa FROM
    MesaXReserva INNER JOIN Reserva
    on Reserva.ID_Reserva = MesaXReserva.ID_Reserva
    WHERE Reserva.Fecha = CAST('21/09/2019' as date)
) as Ocupada
on mesa.ID_Mesa = Ocupada.ID_Mesa
WHERE Ocupada.ID_Mesa is NULL

con la que me devuelve los datos que necesito (con una fecha fija en este caso).

A: Sería una cosa parecida a esto para traer todas las mesas sin reserva
var mesasConReserva = context.Mesa.Include(r => r.Reserva).Where(m => (m.Reserva.Fecha == fechaUsuario) && ( m.Reserva.IdEstadoReserva != 2 && m.Reserva.IdEstadoReserva != 3));

var mesasSinReserva = context.Mesa.Where(m => !mesasConReserva.Any(r => r.IdMesa == m.IdMesa));


text:
Q: Add a condition to run Gitversion when branch is main We are using a Azure yaml pipeline and Gitversion, configured to version up based on PR templates.
- task: gitversion/execute@0
      inputs:
        useConfigFile: true
        configFilePath: 'GitVersion.yml'

- script: echo current version is $(GitVersion.MajorMinorPatch)
      displayName: 'Dispaly calculated version'

- task: PowerShell@2
      inputs:
        targetType: 'inline'
        script: 'echo \##vso[build.updatebuildnumber]$(GitVersion.MajorMinorPatch)'

How do i set a condition to run only on main branch. I have a same setup of pipelines configured in feature branch for different testing. So when Gitversion should execute only when main branch is being used.
Gitversion.yaml:
mode: Mainline
branches:
  feature:
    regex: ^feature?[/-]
    tag: feat-{BranchName}
    source-branches: ['main','master']
  fix:
    regex: bugfix(es)?[/-]
    tag: bugfix-{BranchName}
    source-branches: ['main','master']

ignore:
  sha: []
merge-message-formats: {}

A: This condition helps me to acheive my requriement
and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))


text:
Q: scala play! page only for new users I want to have my registration page available only when visitor is not logged in.
I'd like to accomplish that with Security.Authenticated method. How to do that?

A: Instead of using the Secured trait, maybe define your own Action type? This is untested...
def NotLoggedInAction(f: Request[AnyContent] => Result): Action[AnyContent] = {
    Action { request =>
      if(isLoggedIn(request)) Redirect(views.html.noneForYou)
      else f(request)
    }
}

def isLoggedIn(request: Request) = ??? // You implement this

def mustBeSecured = NotLoggedInAction { implicit request =>
   // Your application logic here.
}


text:
Q: JavaScript - How do I stop a script from working if the screen height smaller than 790px? Here is my code which I would like to stop working if the screen height smaller than 790px:
$(function() {
    if ($("#PopularPosts1").length) {
        var o = $("#PopularPosts1"),
            t = $("#PopularPosts1").offset().top,
            i = $("#PopularPosts1").height();
        $(window).scroll(function() {
            var s = $("#upfooter2").offset().top - i - 20,
                f = $(window).scrollTop();
            if (f > t ? o.css({
                    position: "fixed",
                    top: 48,
                    width: 318
                }) : o.css("position", "static"), f > s) {
                var n = s - f;
                o.css({
                    top: n
                })
            }
        })
    }
});

A: If you want to prevent this code from running then you can use the line below.
$(function() {
    if($(window).height() > 790){ // Evaluate if the height of the window is greater than 790.
      if ($("#PopularPosts1").length) {
          var o = $("#PopularPosts1"),
              t = $("#PopularPosts1").offset().top,
              i = $("#PopularPosts1").height();
          $(window).scroll(function() {
              var s = $("#upfooter2").offset().top - i - 20,
                  f = $(window).scrollTop();
              if (f > t ? o.css({
                      position: "fixed",
                      top: 48,
                      width: 318
                  }) : o.css("position", "static"), f > s) {
                  var n = s - f;
                  o.css({
                      top: n
                  })
              }
          })
      }
    }
});


text:
Q: Why do I see 2 IP addresses in the "fwd" info when looking at Heroku logs? I currently have a PHP application on Heroku and i've been learning all the different features.  Recently, I started to monitor the logs of my application and I am confused about one thing.
I am seeing 2 IP addresses separated by a comma in the "fwd" information while tailing the log.
Could someone explain what could cause this?  I am using Cloudflare as a CDN.


text:
Q: Wampserver Showing Only Red Icon It been four days since my wampserver suddenly stopped working "I mean non of its services is starting" and its just shows red icon and refuses to do any other thing.

I have no skype installed on my pc or any such thing that could occupy my port 80
After running the test port 80 on Apache it got this

and when i run httpd.exe -e debug on the Apache bin directory i got the follow error message


text:
Q: Getting data out of tags (BeautifulSoup) Brief explanation: I have a script which loops through elements of a page, then returns the data. But I want it to return data which is not in an element, but in order.
import argparse, os, socket, urllib2, re
from bs4 import BeautifulSoup
pge = urllib2.urlopen("").read()
src = BeautifulSoup(pge)
body = src.findAll('body')
el = body[0].findChildren()
for s in el:
    cname = s.get('class')
    if cname[0] == "work":
        print s.text

HTML:

1

    tosee
    2
    3
    4
    5
    nothing

It prints 1235 and misses out the 4, but I'd like it to print 12345

A: Simply:
print soup.find('body').text

A: I formatted your html with line breaks to help show why 4 is not printing where you would expect.
You are iterating through the children of  and printing the text from any children that are of the class "work".  The number 4 does not fit this criteria, because it is the text of , not a child with a class of "work".
I don't think BeautifulSoup can decode this particular html as you would expect it to.
One solution would be to parse the html yourself, since this isn't a typical situation.  One way might be to use regex to find instances of something like:
(not_blank)(remember)

Build a dictionary of {remember: not_blank}.  Then as you loop through body.children(), validate s.text() against this dictionary.  If it is a key, print the value, then print s.text().
Depending on what the actual html is this might work...

A: You could do:
arr = []
# Get all text elements
for i in body[0].find_all(text=True):
  # append to array if it's 'work' element or has no class
  if not i.parent.has_attr("class") or "work" in i.parent["class"]:
    arr.append(i)

This of course only works if following two rules are always valid:

*

*a valid text element is inside a class="work", or

*a valid text element is inside a tag that does not have a class attribute


text:
Q: User authorisation on mongodb not working I've created a database user, using the following command on the mongo shell:
use admin
db.addUser({user: 'test', pwd: 'test', roles : ["readWriteAnyDatabase"]});

This seems to work and when I do
show users

using the root admin user I created I can see the test user with the correct roles assigned.
However when i do
use admin
db.auth('test','test');

i get an error in the console saying
Error: 18 { ok: 0.0, errmsg: "auth failed", code: 18 }

Why is this? I can see the user is there but I can't authenticate.

A: The addUser function expects a document. See: addUser documentation. You're missing the curly braces in your parameter.
db.addUser({user: 'test', pwd: 'test', roles : ["readWriteAnyDatabase"]});


text:
Q: Check if a mysgl table exists with php To start with: I know this question has been asked before, but I am looking for a working solution for over a week now and I can't find one. So please can anyone help me instead of just marking my question as a duplicate? Thanks already!!
So the question is this: I'm trying to check if a mysql table exists in my database (with php). Does anyone know how I can solve this problem? This is my code as far as I get:
<form id="newChat" method="post">
    Start a new chat:
    <input type="text" name="name" />
    <input type="submit" value="Search" />
</form>

<?php
function checkChat($me, $friend) {
    global $conn;
    $chatid = findChat($me, $friend);

    $sql  = 'SHOW TABLES FROM chatboxDB LIKE \'chat10\'';
    $result = mysqli_query($conn, $sql) or trigger_error(mysql_error()." in ".$query);

    if ($result > 0) {
        echo '<script>alert("It works.");</script>';
    }
}

if (isset($_POST)) {
    $friend = checkInput($_POST["name"]);
    unset($_POST["name"]);
    checkChat($me, $friend);
}
?>

Some remarks:

*

*the mysqli_query() function works in other parts of my code

*the connection $conn to my database works

*the problem seems to be in if ($result > 0) --> this seems to be always true...

Edit: This is now my code and it is working:
(I found it could be done a lot more simple)
<?php
function checkChat($me, $friend) {
    global $conn, $dbname;
    $chatid = findChat($me, $friend); # the findChat() is a query to find the name of a chat by giving the 2 persons from that chat, if one of those 2 persons does not exist, findChat will return nothing)

    if (!$chatid) {
        # the chat does not exist
    }
}

if (isset($_POST)) {
    $friend = checkInput($_POST["name"]);
    $_POST = array();
    checkChat($me, $friend);
}
?>

A: You can try following:
SELECT *
FROM information_schema.tables
WHERE table_schema = 'yourdb'
    AND table_name = 'testtable'
LIMIT 1;

Alternatively, you can use SHOW TABLES
SHOW TABLES LIKE 'yourtable';

If there is a row in the resultset, table exists otherwise not.

A: mysqli_query should be handled via any mysqli_fetch_XXXXX function
$sqlresult = mysqli_fetch_array($result, MYSQLI_NUM);

and then compared
if ($sqlresult) {
    echo '<script>alert("It works.");</script>';
}