text:
Q: What is the "right way" to signal specific instances of QML objects from C++? Right up-front, I'll apologize:  This is a monster question, but I wanted to provide what I hope is all of the pertinent details.
I've got a QML-based GUI that I was tasked with taking over and developing from proof-of-concept to release.  I believe the GUI is based on an example provided by QT (Automotive, maybe?).  The GUI is being compiled for web-assembly (emscripten) and features a "back-end data-client" which communicates with our hardware controller via a socket and communicates with the GUI via signals.  The GUI is accessed via web browser and communicates with the Data_Client via QWebSocket.

The GUI proof was initially created with a very "flat" hierarchy where every element is created and managed within a single ApplicationWindow object in a single "main" QML file.  A Data_Client object is instantiated there and all the other visual elements are children (at various levels) of the ApplicationWindow:
ApplicationWindow {
id: appWindow

//various properties and stuff

Item {
    id: clientHolder
    property Data_Client client
}

ColumnLayout {
    id: mainLayout
    anchors.fill: parent
    layoutDirection: Qt.LeftToRight
//And so on...

The Data_Client C++ currently emits various signals in response to various things that happen in the controller application.  In the main .QML the signals are handled as follows:
Connections {
        target: client
    onNew_status_port_data:
        {
            textStatusPort.text = qdata;
        }
        onNew_status_data_act_on:
        {
            imageStatusData.source = "../imagine-assets/ledGoodRim.png";
        }
    //and so on...

What I'm trying to do is create a ChannelStatusPanel object that holds the various status fields and handles the updates to those fields (text, images, etc.) when it receives information from the Data_Client backend.  There are multiple instances of this ChannelStatusPanel contained in a MainStatusPanel which is made visible or not from the main ApplicationWindow:

Having said all of that (Phew!), I come finally to my question(s).  What is the correct way to signal a specific instance of the ChannelStatusPanel object from the Data_Client with the various data items needed to drive changes to the visual elements of the ChannelStatusPanel?
I thought I was being clever by defining a ChannelStatusObject to hold the values:
Item {
    id: channelStatusObject

    property int channel
    property int enabled    //Using the EnabledState enum
    property string mode
    property int bitrate
    property int dataActivity   //Using the LedState enum
//and more...
    property int packetCount
}

In the ChannelStatusPanel.qml, I then created a ChannelStatusObject property and a slot to handle the property change:
property ChannelStatusObject statusObject

    onStatusObjectChanged: {
//..do the stuff

From the Data_Client C++ I will get the information from the controller application and determine which "channel" I need to update.  As I see it, I need to be able to do the following things:

*

*I need to determine which instance of ChannelStatusPanel I need to update.  How do I intelligently get a reference to the instance I want to signal?  Is that just accomplished through QObject::findChild()?  Is there a better, faster, or smarter way?

*In the Data_Client C++, do I want to create an instance of ChannelStatusObject, set the various fields within it appropriately, and then set the ChannelStatusPanel instance's ChannelStatusObject property equal to the newly created ChannelStatusObject?  Alternatively, is there a mechanism to get a reference to the Panel's ChannelStatusObject and set each of its properties (fields) to what I want?  In C++, something like this:

QQmlComponent component(&engine, "ChannelStatusObject.qml");
QObject *statObj= component.create();

QQmlProperty::write(statObj, "channel", 1)
QQmlProperty::write(statObj, "bitrate", 5000);
QQmlProperty::write(statObj, "enabled", 0);

//Then something like using the pointer from #1, above, to set the Panel property
//QObject *channelPanel;
QQmlProperty::write(channelPanel, "statusObject", statObj)

Is there some other, more accepted or conventional paradigm for doing this?  Is this too convoluted?

A: I would go about this using Qt's model-view-controller (delegate) paradigm. That is, your C++ code should expose some list-like Q_PROPERTY of channel status objects, which in turn expose their own data as properties. This can be done using a QQmlListProperty, as demonstrated here.
However, if the list itself is controlled from C++ code -- that is, the QML code does not need to directly edit the model, but only control which ones are shown in the view and possibly modify existing elements -- then it can be something simpler like a QList of QObject-derived pointers. As long as you do emit a signal when changing the list, this should be fine:
class ChannelStatus : public QObject
{
    Q_OBJECT
public:
    Q_PROPERTY(int channel READ channel CONSTANT)
    Q_PROPERTY(int enabled READ enabled WRITE setEnabled NOTIFY enabledChanged)
    // etc.
};

class Data_Client : public QObject
{
    Q_OBJECT
public:
    Q_PROPERTY(QList<ChannelStatus*> statusList READ statusList NOTIFY statusListChanged)
    // ...
};

The ChannelStatus class itself must be registered with the QML type system, so that it can be imported in QML documents. Additionally, the list property type will need to be registered as a metatype, either in the main function or as a static variable. Otherwise, only lists of actual QObject pointers are recognised and you would have to provide yours as such.
qmlRegisterUncreatableType<ChannelStatus>("LibraryName", 1, 0,
    "ChannelStatus", "Property access only.");
qRegisterMetaType<QList<ChannelStatus*>>();

You then use this property of the client on the QML side as the model property of a suitable QML component, such as a ListView or a Repeater inside a container like RowLayout. For example:
import LibraryName 1.0
ListView {
    model: client.statusList
    delegate: Column {
        Label { text: modelData.channel }
        Image { source: modelData.enabled ? "foo" : "bar" }
        // ...
    }
}

As you can see, the model data is implicitly attached to the delegate components. Any NOTIFYable properties will have their values automatically updated.

A: Below is how I've setup my application.
Front-end is in QML. Back-end is in Qt C++. H/W Controller application is in C.
In Qt C++ back-end, I have QObject derived database and databasePoint classes.
database object holds a QMap of databasePoint objects.
Each databasePoint object has a unique point name, which is used as an identifier.
database object is created in main.cpp and exposed to QML as a context property.
database class has a method to return a pointer to databasePoint object.
In QML, this method is used to create databasePoint objects.
When this method is called, a databasePoint object is created and added to QMap if it doesn't already exist.
databasePoint class has read-write value properties.
These properties are used for communication between UI, back-end and controller.
In a timer, latest value is polled from controller periodically, whenever there's a change, the value property is updated.
When the value property is updated from UI, the value is written to controller.
class database : public QObject
{
public slots:
    databasePoint* getDbpointObject(QString pointName);
private:
    QMap<QString, databasePoint*> dbPointMap;
};

class databasePoint : public QObject
{
    Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged)
public:
    QVariant value(void);
    void setValue(QVariant value);
    QVariant my_value;
signals:
    void valueChanged();
};

DatabasePointComponent.qml:
Item {
    required property string pointName
    property var pointObj: database.getDbpointObject(pointName)
}

MyScreen.qml:
DatabasePointComponent{
    id: dbTEMP
    pointName: "TEMP"
}
TextInput {
    text: dbTEMP.pointObj.value
    onAccepted: dbTEMP.pointObj.value = text
}


text:
Q: Error: [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client, fetch error This code doesn't allow me to make a fetch request when I invoque sendPushMessages(message) due to HTTP ERRORS but I have no idea why.
The console shows:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Moreover, if I comment:      res.status(200).send({shop: shop[0]}); the code isn't still working.
const {models} = require('../models');
const Sequelize = require('sequelize');

exports.findshop = async (req, res, next) => {

  sendPushMessages = async (message) => {
    try{
      let response = await fetch('https://exp.host/--/api/v2/push/send', {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Accept-encoding': 'gzip, deflate',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(message),
      });

      let responsed = await response.json();
      console.log(responsed);
    }
    catch (error) {
      next(error);
    }
  }

  try {
      console.log(req.body.latitud)
      console.log(req.body.longitud)
      const user = req.user;
      const shops = await models.Shop.findAll({
        include:[{ model: models.Product, as: 'placements'}]
      });

      const shop = shops.filter(shp => {
        if (Math.abs(shp.latitud - req.body.latitud) <= 0.001 && Math.abs(shp.longitud - req.body.longitud) <= 0.001){
          return shp;
        }
      });

      if (shop[0] && user) {
        shop[0].placements.forEach(item => {
          if (item.dataValues.isoffer){
            const message = {
                to: user.pushtoken,
                sound: 'default',
                title: '¡Ofertón! ¡No te lo puedes perder!',
                body: item.productname + ' ' + item.price.toString() + '€',
            };
            sendPushMessages(message);
          }
        })
        res.status(200).send({shop: shop[0]});
      } else {
        res.status(200).send({shop: null});
      }
  } catch (error) {
      next(error);
  }
};

A: From the code you show (it would be useful to see the top level request handler too so we can see the whole flow of the code), there is an issue if sendPushMessages() has an error.  It will call next(err) and keep going in your outer loop which will try to send at least one more response, causing the error message you get for ERR_HTTP_HEADERS_SENT.
You need some error handling upon calling sendPushMessages() so you can stop your loop when it has an error.  So, that needs to be fixed.  One simple way to fix that would be to remove the catch() block from sendPushMessages() and just let that rejection propagate back to the caller.  Then, add an await in front of your call to sendPushMessages(message) like this:
await sendPushMessages(message);

So, when sendPushMessages() rejects, you will hit your own catch block in findshop() and will call next(error) just once and not send any other response.
If the rest of your question is why are you getting an error when you try to access https://exp.host/--/api/v2/push/send', then we can only probably help if you can share what the error is your actually getting.  You should be able to add console.log(error) to your catch() handler so you can log the actual error you are getting.  In my server code, I always log the actual lowest level error that is occurring because that is often needed to debug why a problem is happening.

A: This the error that appears:
fetch is not defined
POST /location 500 8.371 ms - 32
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:526:11)
at ServerResponse.header (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/response.js:170:12)
at done (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/response.js:1004:10)
at Object.exports.renderFile (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/jade/lib/index.js:374:12)
at View.exports.__express [as engine] (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/jade/lib/index.js:417:11)
at View.render (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/view.js:135:8)
at tryRender (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/application.js:640:10)
at Function.render (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/application.js:592:3)
at ServerResponse.render (/home/aitorencinas/Documents/Universidad/TFG/servidor/server_express/node_modules/express/lib/response.js:1008:7)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I allow users to enter html tags in textbox without runtime errors? I have an input textbox on an asp.net page and when a user inputs any tags like break tags or bold an error occurs. I currently am using the following to encode the input:
Server.HtmlEncode(mytextbox.Text)

However this only encodes characters when they aren't phrased as an html tag, like if the input is "<<<>>>>>" is there a way for me to allow the user to put the tags in without it leading to a runtime error?

A: In you ASP.NET page's first line, just disable ValidateRequest:
<%@ Page Title="" Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" ValidateRequest="false" %>


text:
Q: What is the meaning of an inverse of a percentage? Suppose there are 50 marbles (denoted $M$) in a bag. 20 of these marbles are red (denoted $R$).
$$ R / M = 20 / 50 = 0.4 $$
I interpret this as: for every 1 unit of $M$, there are $0.4$ units of $R$.
The inverse is:
$$ M / R = 50 / 20 = 1.25 $$
Which is interpreted as "for every 1 unit of $R$, there are 1.25 units of $M$".
All is good until you translate these back to 'marble-speak'. The percentage suggests that "out of 50 marbles 20 are red". By analogy, inverse percentage suggests that "out of 20 red marbles 50 are marbles." The latter statement seems non-sensical to me and I wonder if there is a better way to phrase the 'marble-speak'.

A: Answering my own question -
Suppose 10 marbles are blue (denoted $B$). Thus, $10/50=0.2$ and $50/10=5$.
Comparing percentages $B$ vs $R$ yields 'prevalence', that is, $R=0.4$ is more prevalent than %B=0.2%
Inverse percentage yields 'uniqueness'. That is, $B=5$ is more unique than $R=1.25$

A: Note that ${\frac{50}{20}=2.5\neq 1.25}$.
It's just the phrasing that's thrown you off. It's not "out of ${20}$ red marbles, ${50}$ are marbles". What the ratio ${\frac{50}{20}=2.5}$ is actually telling you is that for every red marble, there are ${2.5}$ total marbles. So if I have ${2}$ red marbles, I must have ${2.5 + 2.5 = 5}$ total marbles. Then if I have ${3}$ red marbles, I must have ${2.5 + 2.5 + 2.5 = 7.5}$ total marbles...... and if I have ${20}$ red marbles, I must have
$${\underbrace{2.5 + 2.5 + 2.5 + ... + 2.5}_{20 \text{ times}}=2.5\times 20 = 50\text{ total marbles}}$$
Just as you'd expect :D


text:
Q: Set focus on input - React Component I have a react component which has a input field with disable attribute. On click of the component, the input gets enabled and user can type on the field. I'm able to achieve till there, but I need to focus on input field on getting enabled.
Attributes.js
basicAmenitiesList.map(function(item, index){
     return <Attribute key={index}
                       name={item.amenity_id}
                       type={item.title}
                       icon={item.icon}
                       selected={item.isSelected}
                       value={item.value}
                       onClick={_this.handleClick.bind(this)}
                       onChange={_this.handleChange.bind(this)}/>
})

The Attribute file :
<div onClick={this.handleClick.bind(this)}>
...
       <input type="text" name={this.props.name}
              ref={this.props.name}
              placeholder="NO INFO FOUND"
              value={this.props.value}
              disabled={!this.props.selected}
              onChange={this.props.onChange}
       />
</div>

handleClick(e) {
    // I need to focus on enabling., that is when **this.props.selected** is true.
    return this.props.onClick(this.props.name);
}

UPDATE
I tried onFocus for input,
onFocus(){
    this.refs.pets.focus();
}

Right now I'm hard coding the refs name as pets, but is there any way to make it dynamic by sending the name with the onFocus?

A: you can use autoFocus as property for input
<input type="text" name={this.props.name}
              ref={this.props.name}
              placeholder="NO INFO FOUND"
              value={this.props.value}
              disabled={!this.props.selected}
              onChange={this.props.onChange}
              autoFocus
       />


text:
Q: How to distinguish country between the meanings of nation and countryside?
Which country do you come from?

What is the meaning? Which countryside do you come from? or Which nation do you come from?

A: "Which" is used to ask or talk about the choice between two or more things. It means that the noun which follows it must be countable. " The country" meaning "the countryside " is an uncountable noun."Country " as "nation" is a countable noun. I think it's easy to make a choice.

A: How to distinguish?
The country, when it is used to mean any sparsely populated rural area far outside the bounds of a city, cannot be used with "which", because the countryside does not consist of discrete bounded areas but is rather a continuous swath of green. There may be small villages dotting the countryside, but the country and the countryside refer to an anonymous stretch of rurality.
So, if the question contains the word "which", it is almost a certainty that the question is asking about nationality.
Which country do you come from?
--England.
What area of Massachusetts do you come from?
--I'm from the western part of the state, out in the country.
Did you enjoy life in the countryside, or were you eager to get to a big city?


text:
Q: Javascript localStorage and domains Because iPad/iPhone doesn't support cookies from third party sites, I want to store values in localStorage. An example on domainA might be:
<script src="http://domainB/something.js"></script>

this script on domainB can access window.localStorage and it works great. However the values are stored in domainA because that's the document's location.
If I put my script inside an iframe whose source is on domainB, then it works, but I'm trying to avoid frames. So my question is: Is there a way to get/set values in localStorage on a remote domain such that they'll be there when I visit domainB at a later time?

A: This isn't possible without your iframe workaround.
The ability to access the same localStorage object from multiple domains would violate the Same origin policy,and the spec:

User agents must raise a SECURITY_ERR
  exception whenever any of the members
  of a Storage object originally
  returned by the localStorage attribute
  are accessed by scripts whose
  effective script origin is not the
  same as the origin of the Document of
  the Window object on which the
  localStorage attribute was accessed.

http://dev.w3.org/html5/webstorage/#security-localStorage
If this wasn't for iPhone, I would suggest a flash solution. But with localStorage, I think you are out of luck until they implement a cross-domain policy.


text:
Q: What is the Euclidian diameter of the following 'metric ball' in $[0,1)$? Given an $m\in\mathbb{N}_{\geq2}$, define the map $f\colon[0,1)\to[0,1)$ by $f(x):=mx\mod1$. Using this map, for $n\in\mathbb{N}$ we define the metric $$d_n(x,y):=\max_{0\leq i\leq n-1}\min\{|f^{i}(x)-f^{i}(y)|,1-|f^{i}(x)-f^{i}(y)|\}$$ on $[0,1)$. Given $a\in[0,1)$ and $\varepsilon>0$, what is the (Euclidian) diameter of the ball (or actually the interval) $B_{d_n}(a,\varepsilon)$? For simplicity, it is okay to make assumptions on $\varepsilon$ (e.g. $\varepsilon<1/m$, if needed).
Note that $d_{n}$ measures the maximum distance between the first $n$ $f$-iterates of $x$ and $y$.
EDIT: I read somewhere that $$B_{d_n}(x,\varepsilon)=B_d(x,\varepsilon/m^{n-1}),$$ where $d(x,y)=\min\{|x-y|,1-|x-y|\}$ and $0<\varepsilon<1/2$, but I don't see why this is true. This would imply that the Euclidian diameter of $B_{d_n}(x,\varepsilon)$ is $2\varepsilon/m^{n-1}$.


text:
Q: Convert lowercase letter to upper case in javascript I have a code that will convert lower case letters to uppercase but it works only with IE and not in Crome or Firefox.
function ChangeToUpper()
  {
            key = window.event.which || window.event.keyCode;

            if ((key > 0x60) && (key < 0x7B))
            window.event.keyCode = key-0x20;
  }

<asp:TextBox ID="txtJobId" runat="server" MaxLength="10" onKeypress="ChangeToUpper();"></asp:TextBox>

Even I tried with
document.getElementById("txtJobId").value=document.getElementById("txtJobId").value.toUpperCase();

onBlur event of the textbox
What should I do to make it work in all browsers?
Thanks

A: If you don't want to make an explicit JavaScript function, here you can do it in just one line:
Convert to lower and upper case respectively:
<asp:TextBox ID="txt1" onblur='this.value = this.value.toLowerCase();'></asp:TextBox>
<asp:TextBox ID="txt1" onblur='this.value = this.value.toUpperCase();'></asp:TextBox>

A: You can simply use CSS and do text-transform:uppercase and on submit you run toUppercase(). Or you just submit as mixed and you capitalize letters on server side :)

A: <script type="text/javascript">
    function ChangeCase(elem)
    {
        elem.value = elem.value.toUpperCase();
    }
</script>
<input onblur="ChangeCase(this);" type="text" id="txt1" />

separate javascript from your HTML
window.onload = function(){
        var textBx = document.getElementById ( "txt1" );

        textBx.onblur = function() {
            this.value = this.value.toUpperCase();
        };
    };

<asp:TextBox ID="txt1" runat="server"></asp:TextBox>

If the textbox is inside a naming container then use something like this
var textBx = document.getElementById ("<%= txt1.ClientID %>");

            textBx.onblur = function() {
                this.value = this.value.toUpperCase();
            };)

A: Have you tried .toUpperCase()?
Links:

*

*Formatting text using JavaScript

*JAVASCRIPT toUpperCase() METHOD

A: I would say the easiest way is..
<input id="yourid" style="**text-transform: uppercase**" type="text" />

A: Have you tried this?
var myString = "this is a String";
alert(myString.toUpperCase()); // "THIS IS A STRING"
alert(myString.toLowerCase()); // "this is a string"

Thanks... Hope you like it.


text:
Q: Can not connect to Redshift from Airflow - ConnectionRefusedError I am trying to create a connection to AWS Redshift from the Airflow Web UI, but so far it does not work. I always get the error: ('communication error', ConnectionRefusedError(111, 'Connection refused').
My Redshift is in a subnet of a VPC, but I have allowed public access. In its security group I have furthermore added: 0.0.0.0/0 IPV4 incoming access and my own IP as incoming access allowed.
As The input parameters to the airflow connection template, I use:
As the connection-id: An arbitrary name
host:  redshift-clusterxxxxxxxxxxxxxxxxxxxxxxxxxx.redshift.amazonaws.com
The other parameters are also correct.
I have build a little python using redshift_connector to test whether I can connect from there but I am always getting a timeout error.
Has anyone got further ideas on how to solve this issue?


text:
Q: Elasticsearch boosting with should not working I'm trying to boost results that match the should query term by 10 but it's not working.
The mapping for keywords:
      "KEYWORDS" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "text"
          }
        }
      },

And for animaltype:
      "animaltype" : {
        "type" : "text",
        "fields" : {
          "keyword" : {
            "type" : "text"
          }
        }
      },

When I index the data I make sure I index it as arrays.
Here is my query:
        GET /animals/_doc/_search
        {
        "query": {
            "bool":{
                "must":{
                    "terms": {
                        "KEYWORDS.keyword": [ "catnip"]
                            }
                        },
                "should":{
                    "terms": {
                            "boost":10,
                                "animaltype.keyword": [ "cat"]
                                }

                            }
                    }
                }
           }

When I run the query the max score is always 1.0
I need the terms that match the animaltyp "cat" to have a higher score.
What im I doing wrong here?

A: I was using the wrong analyzer, hence the terms were in uppercase and I was using lowercase


text:
Q: Custom sorter grid-column in Ext JS 5 I have a Gridpanel where a column is set as combobox ... I load ID as the valueField and then in renderer I search the store with the ID and display the corresponding name as the displayField
Like this -
view.renderer = function(value) {
        var store = view.getEditor().getStore(),
            record;

        if (value && store) {
            record = store.findRecord(view.valueField, value, 0, false, false, true);

            if (record) {
                return record.get(view.displayField);
            }
        }

        return value;
    };

When I click on sort Ascending/Sort Descending this column gets sorted by ID(valueField) .. I want it to get sorted by Name(displayField)

A: Add a custom sorter to your grid column, e.g.
sorter:function(o1, o2) {
    return ((o1.get(view.displayField)>o2.get(view.displayField)) ? 1 : -1);
}

A: I did the following:
I returned via the ajax the value: id-description
and to show I formatted like the following with Ext.util.Format:
Ext.util.Format.detipolancamento = function(v)
{
  v = v.split("-");
  for (i = 0; i < todastipolancamento.length; i++) {
    desctipolancamento = todastipolancamento[i].toString();
    var tipolancamento = desctipolancamento.split( "," );
    if (v[0] == tipolancamento[0]) {
        return tipolancamento[1];
    }
  }
};

where todastipolancamento is an array with the values of the combobox.
And I used in the column:
formatter: 'detipolancamento',
then in Model -> fields I put the custom sortType:
{name: 'tipolancamento', sortType: 'asPerson2'},
and finally I used the asPerson2 for the sort to be done by the description and no ID, like this:
Ext.apply(Ext.data.SortTypes, {
  asPerson: function(person){
    return  person.toLowerCase();
  },
  asPerson2: function(person){
    var retorno = person.split('-');
    return  retorno[1].toLowerCase();
  }
});


text:
Q: read_mrz error : Could not find a format to read the specified file in mode 'i' The below code is what i am using to read mrz data from a passport, and it works absolutely fine when i run it on my local computer, but when i try to execute it on my server (Windows AWS server) it throws an error.
Can you please help what's this error and how to resolve it.
from PIL import Image
import sys
from passporteye import read_mrz
import pytesseract

mrz = read_mrz("C:/docs/IMG/PASSPORT/abc.png")

Error :
Traceback (most recent call last):
  File "C:/qfc_apps/edocs/PY/PASSPORT/passport.py", line 64, in <module>
    passport()
  File "C:/qfc_apps/edocs/PY/PASSPORT/passport.py", line 19, in passport
    mrz = read_mrz("C:/docs/IMG/PASSPORT/abc.png")
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\mrz\image.py", line 337, in read_mrz
    mrz = p.result
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\mrz\image.py", line 325, in result
    return self['mrz_final']
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 102, in __getitem__
    self._compute(key)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 109, in _compute
    self._compute(d)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 109, in _compute
    self._compute(d)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 109, in _compute
    self._compute(d)
  [Previous line repeated 1 more times]
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 111, in _compute
    results = self.components[cname](*inputs)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\mrz\image.py", line 52, in __call__
    return self._imread(self.file)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\mrz\image.py", line 37, in _imread
    img = skimage_io.imread(file, as_gray=self.as_gray, plugin='imageio')
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\skimage\io\_io.py", line 61, in imread
    img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\skimage\io\manage_plugins.py", line 210, in call_plugin
    return func(*args, **kwargs)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\imageio\core\functions.py", line 221, in imread
    reader = read(uri, format, "i", **kwargs)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\imageio\core\functions.py", line 139, in get_reader
    "Could not find a format to read the specified file " "in mode %r" % mode
ValueError: Could not find a format to read the specified file in mode 'i'

A: Figured out the solution after hours of research so posting my solution for others who might face a similar solution.
I still couldnt figure out what was the problem with the above code but i managed a way out.
Documentation of passporteye mentions that either we pass the path of the image or a byte stream containing image data. As path was not working for me so i opted for the second method.
Using the below code solves our problem :-
image = cv2.imread("path of image")
import PIL.Image as Image
 import io
 pil_im = Image.fromarray(image)
 b = io.BytesIO()
 pil_im.save(b, 'jpeg')
 im_bytes = b.getvalue()

 mrz = read_mrz(im_bytes)


text:
Q: if a buttons text is empty, then In this code I want to make a buttons visibility gone, if the text of the button is "":
        if (button TEXT IS "")
    {
        button.setVisibility(View.GONE);
    }

    else
    {

        button.setVisibility(View.VISIBLE);
    }

How can I form the if-Statement to get a result?
Thank you!

A: Button b = (Button)findViewByID("your button id");
String buttonText = b.getText().toString();

if (buttonText.equals("Your Text"))
    b.setVisibility(View.GONE);

else
    b.setVisibility(View.VISIBLE);

If you want to check if empty you may use
if(buttonText.isEmpty())
    b.setVisibility(View.GONE);

else
    b.setVisibility(View.VISIBLE)

A: The answer is in the question, try with the Empty() method to check if the length of the characters in your String is 0 or greater :
if(text.isEmpty()){

    //String is empty

}else{

    //String includes characters
}

A:    if(button.getText() == null)
    {
        button.setVisibility(View.GONE);
    }

    else
    {

        button.setVisibility(View.VISIBLE);
    }


text:
Q: Error: Fernet key must be 32 url-safe base64-encoded bytes I'm currently working on an ecrypting/decrypting program in Python using Fernet. Here's my code so far:
from cryptography.fernet import Fernet

def decrypter():
  enc_message = input("Input an encrypted string:\n")

  key = input("Input a key:\n")

  fernet = Fernet(key)

  dec_message = fernet.decrypt(enc_message).decode()
  print(dec_message)

def encrypter():
  message = input("Input a string to encrypt:\n")
  key = Fernet.generate_key()
  fernet = Fernet(key)

  enc_message = fernet.encrypt(message.encode())

  print("")
  print("Original string: ", message)
  print("")
  print("Encrypted string: ", repr(enc_message))
  print("")
  print("Key: ", repr(key))
  print("")
  dec_message = fernet.decrypt(enc_message).decode()

  print("Decrypted string: ", dec_message)

encrypter()
decrypter()

Eventually I plan on adding more quality-of-life features, but right now the encrypter function asks you for a string to encrypt, generates a key using Fernet, encrypts your string, and then prints your original string, your newly encrypted string, and the encryption key. (This is not the part that needs fixing.)
The idea of the decrypter function is that it takes an encrypted string and key from the encrypter function. It then decrypts the string using the key and prints it.
My problem is that the key is causing an error. I'm not sure if I've coded the decrypter wrong or if I'm just inputting the key in incorrectly.
My apologies if this is an easily solve-able question, I'm new to Python and couldn't really find any answers specifically for this online. Any help is much appreciated!

A: Your current approach to this is to do all the input and printing within the functions dectrypter and encryptor. That means if you ever wanted to do something slightly different with the results of encrypting you'd have to rewrite those functions.
Your code would be more reusable and modular if your keep the input and printing separate for the functions which do the work, like this:
from cryptography.fernet import Fernet

def encrypter(key,plaintext):
    fernet = Fernet(key)
    enc_message = fernet.encrypt(plaintext.encode())
    return enc_message

def decrypter(key,ciphertext):
    fernet = Fernet(key)
    dec_message = fernet.decrypt(ciphertext).decode()
    return dec_message

def generatekey():
    key = Fernet.generate_key()
    return key

if __name__=="__main__":
    # comment out input() so code can be tested simply
    #plaintext = input("Input a string to encrypt:\n")
    plaintext= "A test message"

    key = generatekey()

    ciphertext = encrypter(key,plaintext)

    print("")
    print("Original string: ", plaintext)
    print("")
    print("Encrypted string: ", repr(ciphertext))
    print("")
    print("Key: ", repr(key))
    print("")

    decoded_message = decrypter(key,ciphertext)

    print("Decrypted string: ", decoded_message)

Now you could write another file which imported the above file and uses the generatekey, encrypter and decrypter, perhaps taking input from the user, without knowing or using fernet at all :-)


text:
Q: decryption DES with ECB using Crypto-es expo project I have asked this question before for React here.
I'm using crypto-es which is based on CryptoJS.
I've used this is react like this
function decryptByDES(ciphertext) {
    var keyHex = CryptoJS.enc.Utf8.parse("38346591");

    // direct decrypt ciphertext
    var decrypted = CryptoJS.DES.decrypt(
      {
        ciphertext: CryptoJS.enc.Base64.parse(ciphertext),
      },
      keyHex,
      {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      }
    );

    return decrypted.toString(CryptoJS.enc.Utf8);
  }

However using the same function in react-native gives me this error:

Test data:
encrypted text: "ID2ieOjCrwfgWvL5sXl4B1ImC5QfbsDycMwuqSNl+oXFQYM2ahEKHjJ8S9AMOijqZzashfXSBli0hxaWMyCdjhw7tS9a8Gtq"
expected decrypted result: https://aac.saavncdn.com/881/374283a91cd721f65f59e3a49e6f5623_96.mp4
secret key: 38346591


text:
Q: Select any particular data from the gridview and dislay it in the label hai pupils
I am doing a project on online education. In my project i display the trainees/trainers in in a gridview. If i select any data from the gridview it has to be dispalyed in the label kept below. How can i do this?
Thanks in advance for those who answers.

A: Use asp:LinkButton to show data in each column. Set commandArgument as the data. set same comandname and handle rowcommand in gridview rowcommand event.
try the following:
in aspx page:
 <asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" runat="server">
                <Columns>
                    <asp:TemplateField HeaderText="CategoryID">
                        <ItemTemplate>
                            <asp:LinkButton ID="lnkID" runat="server" CommandName="sel" CommandArgument='<%# DataBinder.Eval(Container,"DataItem.CategoryID") %>'
                                Text='<%# DataBinder.Eval(Container,"DataItem.CategoryID") %>'></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="CategoryName">
                        <ItemTemplate>
                            <asp:LinkButton ID="lnkName" runat="server" CommandName="sel" CommandArgument='<%# DataBinder.Eval(Container,"DataItem.CategoryName") %>'
                                Text='<%# DataBinder.Eval(Container,"DataItem.CategoryName") %>'></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
           <asp:Label ID="lblCat" runat="server"></asp:Label>

in aspx.cs page:
protected  void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "sel")
        {
            lblCat.Text = e.CommandArgument;
        }
    }


text:
Q: Unknown behaviour due to memset function I'm trying to create a memory eating binary.
So, I used malloc in while loop for allocating 1MB in one iteration.
I find some unkown behaviour, if I just allocate memory using malloc then the MemFree in /proc/meminfo is not decreasing as expected.
If I allocate the memory and do some memset then the MemFree in /proc/meminfo is decreasing properly.
Below is the code :
int main()
{
char *temp,*cmd="cat /proc/meminfo | grep MemFree";
    int i=0;

    while(1)
    {
    temp=malloc(1024*1024);
    //memset(temp,1,1024*1024);  //If not commented then MemFree is updated properly
    if(temp == NULL)
        printf("failed \n");
    else printf("allocated %d   %x MB\n",++i,(unsigned int)temp);
    temp=temp;
    system(cmd);
    usleep(1000*700);
    }
}

Thanks in Advance !!

A: So, I guess your actual question is "why does it look like my program isn't using memory, unless I add code to write to it?" or something.
This is because the kernel is being lazy and hoping your application is over-allocating. Once you actually touch the memory, it has to do the work to make that memory available, and thus the measured actual memory use for that process changes then.

A: Simply allocating memory will not mean the kernel will reserve that much physical memory for your program. Because of the practice of over allocating, which many many applications are regularly guilty of, the kernel just assumes that unless you are currently writing to or reading from that memory, you don't actually need it.
To make your program actually use that memory, have it write to it with random, garbage or even just set values.


text:
Q: How to get a standalone Windows 7 installation to synchronise time (NTP) I am trying to get my Windows 7 Professional machine to synchronise time correctly. This laptop is not a member of any Windows domain.
If I try to go to the clock settings, Internet Time tab, and click on "Update Now", it tells me that an error occurred. Misc. commands / output from my system is below.
What else can I try?
w32tm /monitor /domain:time.windows.com

GetDcList failed with error code:  0x8007054B.
    Exiting with error 0x8007054B

w32tm /query /configuration

  [Configuration]

  EventLogFlags: 2 (Local)
  AnnounceFlags: 10 (Local)
  TimeJumpAuditOffset: 28800 (Local)
  MinPollInterval: 10 (Local)
  MaxPollInterval: 15 (Local)
  MaxNegPhaseCorrection: 54000 (Local)
  MaxPosPhaseCorrection: 54000 (Local)
  MaxAllowedPhaseOffset: 1 (Local)

  FrequencyCorrectRate: 4 (Local)
  PollAdjustFactor: 5 (Local)
  LargePhaseOffset: 50000000 (Local)
  SpikeWatchPeriod: 900 (Local)
  LocalClockDispersion: 10 (Local)
  HoldPeriod: 5 (Local)
  PhaseCorrectRate: 1 (Local)
  UpdateInterval: 360000 (Local)

  [TimeProviders]

  NtpClient (Local)
  DllName: C:\Windows\system32\w32time.DLL (Local)
  Enabled: 1 (Local)
  InputProvider: 1 (Local)
  CrossSiteSyncFlags: 2 (Policy)
  AllowNonstandardModeCombinations: 1 (Local)
  ResolvePeerBackoffMinutes: 15 (Policy)
  ResolvePeerBackoffMaxTimes: 7 (Policy)
  CompatibilityFlags: 2147483648 (Local)
  EventLogFlags: 0 (Policy)
  LargeSampleSkew: 3 (Local)
  SpecialPollInterval: 3600 (Policy)
  Type: NT5DS (Policy)

  VMICTimeProvider (Local)
  DllName: C:\Windows\System32\vmictimeprovider.dll (Local)
  Enabled: 1 (Local)
  InputProvider: 1 (Local)
  NtpServer (Local)
  DllName: C:\Windows\system32\w32time.DLL (Local)
  Enabled: 0 (Local)
  InputProvider: 0 (Local)

w32tm /query /source

Local CMOS Clock

w32tm /monitor /domain:time.windows.com

GetDcList failed with error code:  0x8007054B.
  Exiting with error 0x8007054B

w32tm /monitor /computers:time.nist.gov

time.nist.gov[192.43.244.18:123]:
      ICMP: 439ms delay
      NTP: +11.0631836s offset from local clock
          RefID: 'ACTS' [0x53544341]
          Stratum: 1

  Warning:
  Reverse name resolution is best effort. It may not be
  correct since RefID field in time packets differs across
  NTP implementations and may not be using IP addresses.

A: Mine works fine. The only real differences I could spot if I ran w32tm /query /configuration was that I don't get anything with (policy), and rather than type nt5ds, I get ntp.
Sorry, I don't know much about how to fix it, but hopefully that may be a starting point.


text:
Q: php preg_match_all kills page for unknown reason I am trying to validate a bunch of text and check if there are any emails in it... so i use the following code:
if (preg_match_all("/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+/", $str, $matches)){

}

this will work for TEXT_A in Page1
but when i go in Page2 and try to check again on TEXT_A it will kill the page with "Problem loading page" error...
if i remove this check the page will load fine... i dont get why this is happening...
edit:im using CodeIgniter

A: I see a problem in your regex that could cause Catastrophic Backtracking.
^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+([a-zA-Z])+
                                       ^^^^^^^^^^^^^^^^^^^^^^

What do you want to match in the area I marked?
How should the regex know from which letter on the second group should apply?
If you have a longer sequence of letters that can match, the regex will need a lot of steps to match that ==> you have a performance problem, the regex just don't finish in time!
I would say you can just remove the last group and the regex will match the same, but much faster.
^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\\.([a-zA-Z])+


text:
Q: Find all sequences $x_1,x_2,\dots,x_n$ of distinct positive integers such that $\frac{1}{2}=\frac{1}{x_1^2}+\frac{1}{x_2^2}+\dots+\frac{1}{x_n^2}$
Find all sequences $x_1,x_2,\dots,x_n$ of distinct positive integers such that $$\frac{1}{2}=\frac{1}{x_1^2}+\frac{1}{x_2^2}+\dots+\frac{1}{x_n^2}\tag{1}.$$

This is 3rd problem from 1st day of 16-th Hungary–Israel Binational Mathematical Competition 2005. How to solve this?
I couldn't find official solution, only couple of posts on AoPS with no complete solution, such as aops1 and aops2. Some examples of $(x_1,x_2,\dots,x_n)$ found there are
$$
(2,3,4,5,7,12,15,20,28,35),\\
(2,3,4,6,7,9,12,14,21,36,45,60),\\
(2,3,4,5,8,10,15,20,24,30,40,60,120)
$$
Since $\sum_{i=3}^{\infty} \frac{1}{i^2}<\frac{1}{2}$, we know $\frac{1}{2^2}$ will be always in the sum. Also multiplying out $(1)$ to get rid of fractions and inspecting modulo $x_i^2$, we see $2(x_1\cdots x_{i-1}x_{i+1}\cdots x_n)^2 \equiv 0 \pmod{x_i^2}$, so divisors of each of $x_i$ must "split" among other $x_j$'s (and $2$), but I don't think that helps much.
Edit: As noted by WhatsUp in comments, there is relevant problem in Project Euler. There is actually also one that is almost identical, but with limited search range, specifically https://projecteuler.net/problem=152. So it might help to think about this problem in similar manner, letting $x_n \leq M$ and then characterize solutions with these constrains. Caution, the following spoils the above mentioned Project Euler problem.

 We can convert this to more computationally manageable diophantine equation by multiplying $(1)$ by $2\text{lcm}(x_1,x_2,\dots,x_n)^2$ instead of $2(x_1x_2\cdots x_n)^2$. For example considering $\text{lcm}(2,3,4,5,7,12,15,20,28,35)=420$, first example can be written as $$420^2=2(210^2+140^2+105^2+84^2+60^2+35^2+28^2+21^2+15^2+12^2).$$ Then by the construction, all the squares on the right are divisors of the square on the left. Also, square on the left is just square of one of divisors of $\text{lcm} (2,3,\dots,M)$, if we have $M \geq 35$. This leads to following reformulation of the problem:Find all sequences $y_1,y_2,\dots,y_n$ of distinct positive integers such that $$m^2=2(y_1^2+y_2^2+\dots+y_n^2)\tag{2},$$ where $m=\text{lcm}(y_1,y_2,\dots,y_n)$.So in principle, for fixed $M$ and $x_i \leq M$, we can find $\text{lcm}(2,3,\dots,M)$, and then enumerate its divisors effectively using prime factorization (using that its prime factors will be $p \leq M$). Then additionally, we can notice that not all primes $p$ can be present in these numbers. Indeed, if we have $p> M/2$, then by earlier observation, it would have to divide at least two $x_i$'s. Smallest of them can be $x_i=p$, with next smallest $x_j=2p>M$, impossible. In similar way, lots of other primes can be ruled out for $M=80$, by realizing they would require to be split among at least $3$ of $x_i$'s (try $37$).While these ideas allow us to significantly speed up the search, it is still hard to say which factorizations will satisfy $(2)$ without actually checking the values...

A: I found this paper:
R.Graham, On finite sums of unit fractions.
One of the main corollaries of that paper says the following:

A rational number $p/q$ can be expressed as a finite sum of reciprocals of distinct squares of integers if and only if $$\frac p q \in \left[0,\frac{\pi^2}6 - 1\right)\cup \left[1, \frac{\pi^2}6\right).$$

If this result is correct, then we may conclude that your original problem has infinitely many solutions (just repeatedly write the last term, $\frac 1{x^2}$, as $\frac 1{(x + 1)^2} + r$, where $r < \frac 1{(x + 1)^2}$ and $r$ can again be written as such a sum, by the above result).
Therefore I doubt whether there is a nice answer to this question.
There are only three possibilities:

*

*The proof of Graham contains an error. I consider this unlikely, but I cannot guarantee the correctness, since I haven't thoroughly read the proof (it's quite complicated). This wiki page also cites this result.

*The answer to this question somehow describes infinitely many solution, i.e. one should give a pattern of the solutions, rather than a finite list. This also doesn't look probable to me.

*The question is problematic and cannot be answered properly. As it was published as a binational competition problem, it again sounds unlikely; but I think it's the most probable among the three.
I do want to know, whether the error belongs to the paper of Graham or the design of the problem. If anyone knows how to find the official solution to this problem, please do share it!

A: Other sequences were found.
My method is same as below link's one.
https://artofproblemsolving.com/community/c6h141121p798082
Case :$s=2 \times3 \times4 \times11 \times13 \times17.$
\begin{align}
&(1+\frac{1}{2^2})(1+\frac{1}{3^2})(1+\frac{1}{4^2})(1+\frac{1}{11^2})(1+\frac{1}{13^2})(1+\frac{1}{17^2})-1-\frac{1}{2}\\
&=\frac{1379}{736164}\\
&=\frac{1}{26^2}+\frac{1}{66^2}+\frac{1}{78^2}\\
\end{align}
Exclude $1$, $26$, $66$ and $78$ from the set all divisors of $s=2 \times3 \times4 \times11 \times13 \times17$, then we get a solution.
$(2, 3, 4, 6, 8, 11, 12, 13, 17, 22, 24, 33, 34, 39, 44, 51, 52, 68, 88, 102, 104, 132, 136, 143, 156, 187, 204, 221, 264, 286, 312, 374, 408, 429, 442, 561, 572, 663, 748, 858, 884, 1122, 1144, 1326, 1496, 1716, 1768, 2244, 2431, 2652, 3432, 4488, 4862, 5304, 7293, 9724, 14586, 19448, 29172, 58344)$
Similarly, we get below sequences.
Case :$s=2 \times3 \times4 \times7 \times11 \times13.$
$(2, 3, 4, 6, 8, 11, 12, 14, 21, 22, 24, 26, 28, 33, 42, 44, 52, 56, 77, 78, 84, 88, 91, 104, 132, 143, 154, 156, 168, 182, 264, 273, 286, 308, 312, 364, 429, 572, 616, 728, 858, 924, 1001, 1092, 1144, 1716, 1848, 2002, 2184, 3003, 3432, 4004, 6006, 8008, 12012, 24024)$
Case :$s=2 \times3 \times4 \times11 \times13 \times17.$
$(2, 3, 4, 6, 8, 11, 12, 13, 17, 22, 24, 26, 34, 44, 51, 52, 68, 78, 88, 102, 104, 132, 136, 156, 187, 204, 221, 264, 312, 374, 408, 442, 561, 572, 663, 748, 884, 1122, 1144, 1326, 1496, 1716, 1768, 2244, 2431, 2652, 3432, 4488, 4862, 5304, 7293, 9724, 14586, 19448, 29172, 58344)$
Case :$s=2 \times3 \times4 \times7 \times11 \times19.$
$(2, 3, 4, 6, 8, 11, 12, 14, 19, 21, 22, 24, 28, 33, 44, 56, 76, 84, 88, 132, 133, 152, 154, 168, 209, 228, 231, 264, 266, 308, 399, 456, 532, 616, 627, 798, 836, 924, 1064, 1254, 1463, 1596, 1672, 1848, 2508, 3192, 4389, 5016, 5852, 8778, 11704, 17556, 35112)$
Case :$s=2 \times3 \times4 \times11 \times13 \times19.$
$(2, 3, 4, 6, 8, 11, 12, 13, 19, 22, 24, 26, 33, 38, 44, 52, 57, 66, 76, 88, 104, 114, 132, 143, 152, 156, 209, 228, 247, 264, 312, 418, 429, 456, 572, 627, 741, 836, 988, 1144, 1482, 1672, 1716, 1976, 2508, 2964, 3432, 5016, 5928, 8151, 10868, 21736, 32604, 65208)$
Case :$s=2 \times3 \times4 \times7 \times11 \times23.$
$(2, 3, 4, 6, 8, 11, 12, 14, 21, 22, 23, 24, 28, 33, 42, 44, 56, 69, 77, 84, 88, 92, 132, 138, 154, 161, 168, 184, 231, 253, 264, 276, 308, 462, 483, 552, 616, 644, 759, 924, 1012, 1288, 1771, 1848, 1932, 2024, 3036, 3542, 3864, 6072, 7084, 14168, 21252, 42504)$
Case :$s=2 \times3 \times4 \times7 \times19 \times29.$
$(2, 3, 4, 6, 7, 8, 12, 24, 28, 38, 42, 56, 58, 76, 84, 114, 116, 133, 152, 168, 174, 203, 228, 232, 266, 348, 406, 456, 532, 551, 609, 696, 812, 1064, 1218, 1596, 1624, 1653, 2204, 2436, 3192, 3306, 3857, 4408, 4872, 6612, 7714, 11571, 13224, 15428, 23142, 30856, 46284, 92568)$
Case :$s=2 \times3 \times4 \times7 \times23 \times29.$
$(2, 3, 4, 6, 7, 8, 12, 24, 28, 29, 56, 58, 69, 84, 92, 116, 138, 161, 168, 174, 184, 203, 232, 276, 348, 483, 552, 644, 667, 696, 812, 1218, 1288, 1334, 1624, 1932, 2001, 2436, 2668, 3864, 4002, 4669, 4872, 5336, 8004, 14007, 16008, 18676, 28014, 37352, 56028, 112056)$
Case :$s=2 \times3 \times4 \times7 \times19 \times31.$
$(2, 3, 4, 6, 7, 8, 12, 24, 28, 31, 56, 57, 62, 76, 84, 114, 124, 133, 152, 168, 217, 228, 248, 266, 372, 399, 456, 532, 651, 744, 798, 868, 1064, 1596, 1736, 1767, 2356, 2604, 3192, 3534, 4123, 4712, 5208, 7068, 8246, 12369, 14136, 16492, 24738, 32984, 49476, 98952)$
Case :$s=2 \times3 \times4 \times7 \times29 \times31.$
$(2, 3, 4, 6, 7, 8, 12, 24, 28, 31, 42, 56, 84, 87, 93, 116, 124, 168, 174, 217, 232, 248, 348, 372, 406, 434, 609, 651, 696, 744, 812, 868, 899, 1302, 1624, 1736, 1798, 2436, 2604, 2697, 3596, 4872, 5208, 5394, 6293, 7192, 10788, 21576, 25172, 50344, 75516, 151032)$
Case :$s=2 \times3 \times4 \times7 \times19 \times37.$
$(2, 3, 4, 6, 7, 8, 12, 24, 28, 38, 42, 56, 57, 74, 76, 84, 148, 152, 168, 222, 228, 259, 266, 296, 399, 444, 456, 518, 532, 703, 777, 798, 888, 1036, 1064, 1406, 1554, 1596, 2072, 2109, 2812, 3108, 3192, 4921, 5624, 6216, 8436, 9842, 16872, 19684, 29526, 39368, 59052, 118104)$
Case :$s=2 \times3 \times4 \times7 \times23 \times37.$
$(2, 3, 4, 6, 7, 8, 12, 24, 28, 37, 42, 56, 69, 74, 84, 92, 111, 138, 148, 161, 168, 184, 259, 276, 296, 322, 444, 483, 552, 644, 777, 888, 1036, 1288, 1554, 1702, 1932, 2072, 3108, 3404, 3864, 5106, 5957, 6216, 6808, 10212, 17871, 20424, 23828, 47656, 71484, 142968)$


text:
Q: How to do a full clone of a VM? Environment:

*

*Host machine: Ubuntu 12.04 LTS

*Guest machine: Ubuntu 12.04 LTS

*Virtualization system: VirtualBox last version.

How can I perform a full clone of my VM ?

A: Selecting the full clone option really does make a full clone of the VM. (If you're having specific problems with that, I recommend editing your question with more details.)
After cloning the VM, if you want both virtual machines to access the same network at the same time, you'll probably want to change the MAC address on the virtual network adapter of one of the VMs.
Further reading:

*

*Are there any "traps" in cloning a VirtualBox VM for concurrent use on the same Host/LAN?

*How do I fix broken networking in cloned virtual machines?

A: Click on the sheep icon to clone your VM (including snapshots). The sheep is in reference to Dolly the Sheep.
Alternatively, you can export the entire VM into an OVA file which can then be imported into any other VirtualBox (or even VMWare) installation.


text:
Q: S3 Restore from Java aws SDK fails with no error             RestoreObjectRequest requestRestore_ = new RestoreObjectRequest(bucket, keyy, 2);
            s3Client.restoreObjectV2(requestRestore_);
            ObjectMetadata response_ = s3Client.getObjectMetadata(bucket, keyy);
            Boolean restoreFlag_ = response_.getOngoingRestore();
            System.out.println(response_.getReplicationStatus());
            System.out.format("Restoration status: %s.\n",
                    restoreFlag_ ? "in progress" : "not in progress (finished or failed)");

So, the code is from aws documentation and the first time I run it runs successfully telling me that the file will be moved to Standard storage; However when I check it it is still in glacier and the same snipped below logging "finished or not in progress".
I guess this could be happening because of no AWS permissions to restore, but it should be giving me error in the first place.


text:
Q: Mysql How to multiplication two colums each row I have two tables named test1, test2. I have inserted values into two tables. The problem is, I want to multiply value of two together. Can anyone help me?
table test1
id | cola | colb
1  | 0,5  | 5
2  | 0,6  | 6

table test1
id | colc | cold
1  | 0,7  | 7
2  | 0,8  | 8

SELECT cola,colb,colc,cold,(cola*t2.colc)AS er FROM test1 t1, test2 t2

A: Try to use query like below:
SELECT t1.cola,t1.colb,t2.colc,t2.cold,(t1.colb*t2.cold)AS er FROM test1 t1, test2 t2


text:
Q: How to use promises in jquery? I am pulling in multiple divs via multiple ajax calls. Before the first ajax call I want to display a loading spinner. Once all the divs (which will take an unknown time) have loaded I want to sort them. Finally I want to remove the loading spinner layer.
I think I need to use promises for this (because of the multiple ajax calls) however I don't understand how to implement promises - could someone please show me how to write the promises and if I need to add code to my functions relating to that what to add please?
Thank you very much.
Here is my code:
$(document.body).on('click', "#refresh_view", function(){

    start_spinner();
    load_all_divs(list_of_ids_to_loop_over);

    // once the above is complete
    re_order_divs();

    // once the above is complete
    end_spinner();

});

load_all_divs(list_of_ids_to_loop_over) {

    $.each(list_of_application_ids.split(','), function(index){
        do_ajax_call_for_this_one_item(this)
    });
};

A: If you're loading the divs with jQuery's $.ajax (or $.get, etc.), you can use jQuery's $.when, since those already return jQuery jqXHR objects, which are promise-like:
$.when(
    $.ajax(/*...*/),
    $.ajax(/*...*/),
    $.ajax(/*...*/)
)
.done(() => {
    // All done
})
.fail(error => {
    // Something went wrong
});

If you're using a moderately up-to-date version of jQuery, you can also use the standard Promise.all, since jqXHR objects in modern versions of jQuery are thenable. Promise.all accepts an array:
Promise.all([
    $.ajax(/*...*/),
    $.ajax(/*...*/),
    $.ajax(/*...*/)
])
.then(() => {
    // All done
})
catch(error => {
    // Something went wrong
});


text:
Q: How Can I Always Play HTML5 Audio Reliably on Android? When working with an <audio> element (or <video> element, for that matter) without the controls attribute, mobile devices (both Android and iOS) usually require the user to tap on something in order for the play() call to actually work. For example, this jQuery code will not work on most mobile devices:
$(window).load(function() {
    $('#an_audio_element_without_controls')[0].play();
});

But this will work on most mobile devices:
$(window).load(function() {
    $('#some_link').click(function() {
        $('#an_audio_element_without_controls')[0].play();
        return false;
    });
});

After a specific <audio> element has been play()'d once, it can be play()'d again without the user having to first tap on something. So if you were in a situation where you needed to have certain audio files play at certain points of the user's workflow but didn't want them to always have to tap on something for the audio to play, you could have them tap on something at the very beginning and have that initial tap cause an empty <audio> element to play. Then whenever you actually needed to play audio, you could update that specific <audio> element's source and then play it and it would work.
This trick I have just described works well on iOS devices, but on some Android devices, it doesn't always work. For example, have a look at this code (jsFiddle demo):
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Android Audio Test</title>

Dynamic

                This <audio> tag starts out having no
                <source> tags. Those tags get added when the
                user taps on the "Play Audio" link below. Each subsequent tap
                removes the <source> tags and re-adds them
                again. The audio isn't played until the amount of time
                specified in the "Timeout" dropdown menu has passed.

                Timeout:

                <select id="timeout">
                    <option value="0">None</option>
                    <option value="10">10</option>
                    <option value="20">20</option>
                    <option value="30">30</option>
                    <option value="40">40</option>
                    <option value="50">50</option>
                    <option value="60">60</option>
                    <option value="70">70</option>
                    <option value="80">80</option>
                    <option value="90">90</option>
                    <option value="100">100</option>
                    <option value="150">150</option>
                    <option value="200">200</option>
                    <option value="250">250</option>
                    <option value="300">300</option>
                    <option value="350">350</option>
                    <option value="400">400</option>
                    <option value="450">450</option>
                    <option value="500">500</option>
                </select>

            <audio id="audio_test_dynamic" data-log-id="audio_test_dynamic_log"></audio>

Play Audio

Static

                This <audio> tag's
                <source> tags are hard-coded.

            <audio id="audio_test_static" data-log-id="audio_test_static_log">
                <source src="http://www.html5tutorial.info/media/vincent.mp3" type="audio/mpeg">
                <source src="http://www.html5tutorial.info/media/vincent.ogg" type="audio/ogg">
            </audio>

Play Audio

I tried the above code on a Motorola Xoom running the stock browser on Android 4.1.2. I found that if I load (or refresh) the page, leave the "Timeout" dropdown set to "None", and tap the "Dynamic" section's "Play Audio" link, it usually fails to play. I tried the same thing using various timeout options and found that it starts to get fairly reliable at around 200. It gets to be really reliable at around 400. I don't think I have seen 400 fail. The thing is, I don't want to find a number that never fails on this Motorola Xoom and then assume that it won't ever fail on any other device. I also don't want to have to have such a high delay before the audio plays. It would be nice if I could somehow detect when it's not playing and then force it to try playing again with a limit of five or ten attempts. I don't know what I could do to detect a failed play, though. The output of a successful play looks very similar to the output of a failed play, at least on the Motorola Xoom. Here is the output of a successful play (it's in reverse chronological order):

*

*pause

*ended

*timeupdate (many times in a row)

*durationchange

*timeupdate

*playing

*canplaythrough

*canplay

*loadeddata

*loadedmetadata

*durationchange

*progress

*waiting

*play

*loadstart

*emptied

The only difference between the output of a successful play and the output of a failed play is items 3 and 4 in the above list aren't there (the multiple timeupdates and the durationchange that happens right before). If I tap the "Play Audio" link again after a failed play occurs and it fails again, this is what the output looks like (again, it's in reverse chronological order):

*

*pause

*playing

*canplaythrough

*canplay

*loadeddata

*loadedmetadata

*durationchange

*progress

*waiting

*play

*loadstart

*emptied

*abort

If I tap the link enough times, it will eventually play.
Is there anything I can do to detect when a failed play occurs and have it try to play again?

A: I have used HTML5 audio and video on Android devices and though I can tell the global experience is more reliable on iOS (due to less fragmentation and sometimes lesser design/horsepower) at some point you will need to rely on the manufacturer implementation of Android (though since Chrome is on Android I have to say things got better).
Normally you can bind to the error, abort or stalled event to detect playback/network issues and act on them (either display an error message or force load(), play()). See here for more info.
I have seen Android devices took a dozen of seconds between the moment you touch play and the first timeupdate event where an iPad took 3 seconds ... without any error showing up.
Also I would suggest you bind to the touchstart event rather than the click event for Android touch based device.
Thanks

A: I have been facing the same issue, when I tried to manage a few videos as a flow in an app I am doing with Cordova.js (webview) I have been experimenting weird behaviour when it comes into play video files through js, with no user interaction. Although I was file.load() and then triggering a video.play() when the video triggered a canplaythrough event, the timeupdate of that object shwod me that it stopped at 0 without any further event being triggered. Luckily I found this:
http://blog.blairvanderhoof.com/post/78586868260/getting-the-html5-video-tag-to-work-in-cordova-for
what  pointed me to this
http://developer.android.com/reference/android/webkit/WebSettings.html#setMediaPlaybackRequiresUserGesture(boolean)
It looks to me like it is definitely what is going on here


text:
Q: Why am i encountering an Uncaught ReferenceError in Jquery? Iam creating a js function that will switch the content of the body of my page as follows:
 var BodySwitcher = {

        initBodySwitcher : function(){
            var self = this;
            $(document).on("click", ".bodySwitcher", function() {
                var action = $(this).attr("id");
                self.ajaxCall(action, null, $.proxy(self.showBody, this), $.proxy(self.initCall, this));
            });
        },

        ajaxCall : function(action, data, callback, callback1){
            $.ajax({
                url: action,
                type: "POST",
                data: data,
                error: function(){
                    alert('Please Contact your Administrator');
                },
                success: function(data){
                    callback(data);
                },
                complete: function (data){
                    callback1(data);
                }
            });
        },

        showBody : function(data){
            var $container = $("#body_container");
            $container.empty();
            $container.html(data);
        },

        initCall: function(data){
            var $container = $("#body_container");
            var $table = $container.find(".table");
            if ($table.length > 0){
                initDataTable($table);
            }
            var $form = $container.find("form");
            if ($form.length > 0){
                initForm($form);
            }

        },

        initDataTable : function($table){
            if ($table.length > 0){
                $("#"+$table.attr("id")).dataTable( {
                    "sPaginationType": "full_numbers"
                } );
            }
        },

        initForm: function($form){
            alert("form");
            var self = this;
            $form.form.validate();
            $formSubmit = $form.find(".button");
            $(document).on("click", $formSubmit, function(){
                var formData = $form.serialize();
                var action = $form.attr("id");
                alert(action);
                self.ajaxCall(action, formData, $.proxy(self.showBody, this), $.proxy(self.initCall, this));
            });
        }

    };

But Iam encountering this error:
Uncaught ReferenceError: initForm is not defined

why? How come it can find the initDataTable  but not the initForm?

A: You can't reference object properties as normal variables.
    initCall: function(data){
        var $container = $("#body_container");
        var $table = $container.find(".table");
        if ($table.length > 0){
            BodySwitcher.initDataTable($table);
        }
        var $form = $container.find("form");
        if ($form.length > 0){
            BodySwitcher.initForm($form);
        }

    },

The reason you didn't get the same error for initDataTable is probably because $table.length was 0, so it skipped over that code.


text:
Q: INFA workflow fails when scheduler enabled I am trying to run an Informatica workflow to check database table and write fetched data to a flat file on the server.

*

*source: database table

*target: flat file

*transformations: non

this wf runs fine when "run on demand" but I need to run this continuously so I tried with INFA scheduler to run it every 5 minutes. When the scheduler is enabled the workflow continuously fails. Kindly help with any ideas to run this on scheduler.

A: oops... sorted, this was my mistake. I have not checked in the Target I created for flat file. my bad. Thanks all


text:
Q: Neighborhood of a differentiable function Show that if f is differentiable on a neighborhood of $[a,b]$ and
$f'(a) < m < f'(b)$
then there exists $a$ in $(a,b)$ such that $f'(c) = m.$
First off, what is a neighborhood of an interval? Looking at my books definition of a neighborhood, it defines a neighborhood of a point, like so:
A neighborhood of a point $x \in \mathbb{R}^n$ is a subset $X \subset \mathbb{R}^n$ such that there exists $e>0$ with $B_e(x) \subset X.$
Also, the original statement looks an awful lot like the MVT...

A: Neighborhood of a point $p$ is a set $N_r(p)$ consisting of all points such that $d(p,q)<r$. The number $r$ is called the radius of $N_r(p)$.
Here $d$ is the distance function.

It may look like intermediate value theorem but there are things to be noted.

*

*For Intermediate value theorem to be true, a function should be continuous in the interval

*A function is differentiable does not mean that the derivative is continuous( Unless specified that the function is continuously differentiable). For a counter-example see here

When the function is continuously differentiable as noted earlier intermediate value theorem would prove the result
But surprisingly, the theorem is true without the continuity constraint of derivative.
For a proof of that part see Darboux theorem.


text:
Q: Keep reading lines from socket and save them What I am trying to achieve is to read from a socket, line by line, and save them to a text file.
I have used socket_recv and socket_read. I can view the output on a page but when I save the output, its garbage. Filled with string and garbage binary stuff.
I know why it is because of the length of receiving data. But there is no way to know how much I will receive.
I used a example from the web
$str = "";
        while($read = socket_read($sock, 3,PHP_NORMAL_READ)) {
   $str .= $read;
   if (strpos($str, "\n") !== false) break;  // this stops the loop when a new line is encountered, how to restart the loop and read the rest of the lines
}

echo "Server said: $str";

//echo $this->_buffer;
$output = $str;
//echo "This much bytes ".strlen($this->_buffer);
        $file = 'log.txt';
                $handle = fopen($file,"a") or die("Could not open file for writing");
                fwrite($handle,$output) or die("Could not write");
                fclose($handle);

This snippet will save one line to a text file, but I have around 3 lines to receive.
How can I make this loop read all the receiving lines and write them to a text file.


text:
Q: Receiving Next without For error in Excel VBA I have been receiving a "Next without For" error code on my current VBA project. I do not see where the issue is to fix it. I have a For and If prior to the Next I but have ended both statements prior to the Next I. Any help or fresh pair of eyes would be appreciated.
Code
Private Sub lstLookup_DblClick(ByVal Cancel As MSForms.ReturnBoolean)

On Error GoTo errHandler
Dim ID As String
Dim I As Integer
Dim cNum As Long, X As Long
Dim findvalue As Range

On Error GoTo errHandler:
For I = 0 To lstLookup.ListCount - 1
    If lstLookup.Selected(I) = True Then
     ID = lstLookup.List(I, 14)
    If lstLookup.Selected(I) = False Then
       Exit For
    End If
**Next I**
   If VBA.Len(ID) < 1 Then
    MsgBox "No data found"
    Cancel = True
  Exit Sub
End If"


text:
Q: How can 2 threads access a synchronized block at the same time? Can you describe how in a multithreaded environment, the below code works incorrectly? I took the code from https://www.javacodegeeks.com/2014/11/multithreading-concurrency-interview-questions-answers.html. The description says 2 threads may enter the 2nd synchronized block one after the other. How can this happen? What is the relation by having 2 synchronized blocks?
public Integer getNextInt() {
    Integer retVal = null;
    synchronized (queue) {
        try {
            while (queue.isEmpty()) {
                queue.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    synchronized (queue) {
        retVal = queue.poll();
        if (retVal == null) {
            System.err.println("retVal is null");
            throw new IllegalStateException();
        }
    }
    return retVal;
}

A: It's pretty simple - the first synchronized block (S1) makes a thread wait until the queue becomes non-empty. The second synchronized block (S2) makes a single thread take an item from the queue.

*

*Thread 1 enters S1.

*Thread 1 exists S1 -> queue is not empty

*Thread 2 enters S1

*Thread 2 exists S1 -> queue is still not empty

*Thread 1 enters S2 -> takes an item from the queue and it becomes empty

*Thread 1 exists S2

*Thread 2 enters S2 -> attempts to take an element from the queue, but it's empty -> the exception is thrown.

As you can see, only 1 thread enters a synchronized block as expected, but this does not guarantee proper synchronization.

A: The whole point of using a synchronized block is to create a "transaction" around pieces of code that must be executed together; without the chance of another thread coming in "in between".
Your example has two blocks; and it is very well possible that a first thread leaves the first block; but a second thread kicks in before the first thread can enter the second block.
That is all there is to this.

A: queue.wait() releases the lock, which is applied on synchronized block. In other words, when queue.wait() is reached, other threads are free to enter the synchronized block. Below I include the working example, in which 5 threads enter the same synchronized block at the same time. You can inspect this code to get a feeling how wait() and notiy()/ notifyAll() methods work:
public class Main {
    static Object lock = new Object();
    public static void main(String args[]) throws InterruptedException {

        Runnable r = () -> {
            System.out.println(" ThreadID: " + Thread.currentThread().getId() + " has started");
            synchronizedBlockExecution();
        };

        for (int i = 0; i < 5; i++) {
            Thread t = new Thread(r);
            t.start();
        }

        Thread.sleep(1000);
        System.out.println("------all threads are notifed to stop waiting!---------");
        synchronized (lock) {
            lock.notifyAll();
        }

    }

    public static void synchronizedBlockExecution() {
            System.out.println("Thread: " + Thread.currentThread().getId() + " is entering synchronized block");
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("Thread: " + Thread.currentThread().getId() + " has left synchronized block");
    }
}

A: T1 enters S1
T1 exists S1
T2 wait for T1 to complete from S1
T1 completes and enters S2
S1 is free for T2
T2 enters S1
In this ways T1 and T2 can be in two different synchronize block at a time. This will improve performance. Programmer should write synchronize block instead of methods as it allows two thread to work in two separate block at a time.


text:
Q: User is unable to receive desktop notification for events How come User is able to get notification from task but unable to receive notification for events?

User does not have any permission sets or restriction rule regarding this issue.

A: Have the turned them off in their personal settings
https://help.salesforce.com/s/articleView?id=sf.activities_reminder_lex.htm&type=5


text:
Q: SQL Server How To make A Group Inside A Group - Using GROUP BY I Have A Table has This Structure

EmployeeID | LogDate | LogTime | TerminalID | InOut | Accepted

This Table handle all of the Attending of the Employees

Where InOut Column = 0 --> In (The Employee Just Punch In To Start His
  Shift)
Where Inout Column = 1 --> Out (The Employee Just Punch Out To
  End His Shift)

Sample Of Date When i Make A Select

for Example the previous image has EmployeeID = 1009
have 2 punches at 2015-10-14 (06:56:28) And (16:13:51)
i need in the Result to give me the Time He Attend between these two 2 Times
which is (09:17:23)
I want to have This Structure of Result

EmployeeID | LogDate | NumberOfPunshings | State | HoursAttending

I Tried This Query
       select
Employeeid as EmpID,
logdate as logdt,
count(accepted) NumberOfPunshings,
case    count(accepted)                    WHEN 1 THEN 'No Out Punch'
                                           WHEN 2 THEN 'Perfect'
                                           Else 'Null'
                                           End as State,
CONVERT(varchar(12),
       DATEADD(minute,
       DATEDIFF(minute,
       (select top 1 LogTime from Accesslog where Inout=0),
       (select top 1 LogTime from Accesslog where InOut=1)), 0), 114) as HoursAttending

from Accesslog
where Logdate = CAST('2015-10-14' AS datetime)
group by
employeeid,logdate
order by Employeeid

But It's Not Working As I WANT it's only take one First value (of the Table) in HoursAttending

I've Create SQL Fiddle to Show you how the Data it Looks Like
http://sqlfiddle.com/#!3/0152f9/1
EmpID |           logdt           |  NumberOfPunshings   |  State   |  HoursAttending

1009  | October, 14 2015 00:00:00 |          2           | Perfect  |   08:00:00:000
1088  | October, 15 2015 00:00:00 |          2           | Perfect  |   08:00:00:000

the Expected Result Must be
EmpID |           logdt           |  NumberOfPunshings   |  State   |  HoursAttending

1009  | October, 14 2015 00:00:00 |          2           | Perfect  |   08:00:00:000
1088  | October, 15 2015 00:00:00 |          2           | Perfect  |   06:00:00:000

The differences in these tables in HoursAttending Column because

the first Employee (1009) start working from 08:00 to 16:00 so the
  duration is (08:00) Correct.
the Second Employee (1088) start working from 009:00 to 15:00 so the
  duration is must be (06:00) not (08:00) Correct.

A: Imagine what would be possible if the data was made easily available to us, and we clearly understood what the expected final result should look like.
SQL Fiddle
MS SQL Server 2014 Schema Setup:
CREATE TABLE Accesslog
    ([EmployeeID] int, [LogDate] datetime, [LogTime] datetime, [Terminal] varchar(11), [InOut] int, [Accepted] int)
;

INSERT INTO Accesslog
    ([EmployeeID], [LogDate], [LogTime], [Terminal], [InOut], [Accepted])
VALUES
    (1009, '2015-10-14 00:00:00', '1900-01-01 06:36:06', 'abcdedghijk', 0, 1),
    (1009, '2015-10-14 00:00:00', '1900-01-01 16:22:41', 'abcdedghijk', 1, 1)
;

Query 1:
select
        EmployeeID
      , LogDate
      , MIN(case when InOut = 0 then cast(LogTime as time) end) as LogTimeMin
      , MAX(case when InOut = 1 then cast(LogTime as time) end) as LogTimeMax
      , COUNT(*) as CountPunches
      , CONVERT(varchar(12),
         DATEADD(minute,
         DATEDIFF(minute,
         MIN(case when InOut = 0 then cast(LogTime as time) end),
         MAX(case when InOut = 1 then cast(LogTime as time) end)), 0), 114) as HoursAttending
from Accesslog
group by
        EmployeeID
      , LogDate

Results:
| EmployeeID |          LogDate |  LogTimeMin |  LogTimeMax | CountPunches | HoursAttending |
|------------|------------------|-------------|-------------|--------------|----------------|
|       1009 | October, 14 2015 | 06:36:06.00 | 16:22:41.00 |            2 |   09:46:00:000 |

PART 2
To address the issue of shifts, please try the following. Note if you THEN want only one row per day, use a group by query as well but making the query seen below into a "derived table" (subquery)
SQL Fiddle
MS SQL Server 2014 Schema Setup:
CREATE TABLE Accesslog
    ([EmployeeID] int, [LogDate] datetime, [LogTime] datetime, [Terminal] varchar(11), [InOut] int, [Accepted] int)
;

INSERT INTO Accesslog
    ([EmployeeID], [LogDate], [LogTime], [Terminal], [InOut], [Accepted])
VALUES
    (1209, '2015-10-14 00:00:00', '1900-01-01 07:00:00', 'abcdedghijk', 0, 1),
    (1209, '2015-10-14 00:00:00', '1900-01-01 12:01:00', 'abcdedghijk', 1, 1),
    (1209, '2015-10-14 00:00:00', '1900-01-01 15:00:00', 'abcdedghijk', 0, 1),
    (1209, '2015-10-14 00:00:00', '1900-01-01 20:02:00', 'abcdedghijk', 1, 1),
    (1009, '2015-10-14 00:00:00', '1900-01-01 08:00:00', 'abcdedghijk', 0, 1),
    (1009, '2015-10-14 00:00:00', '1900-01-01 16:00:00', 'abcdedghijk', 1, 1),
    (1088, '2015-10-15 00:00:00', '1900-01-01 09:00:00', 'aaaa', 0, 1),
    (1088, '2015-10-15 00:00:00', '1900-01-01 15:00:00', 'aaaa', 1, 1)
;

Query 1:
/*
 including (07:00 - 12:00) shift two (15:00 - 20:00)
 */

WITH CTE as (
        SELECT *, ROW_NUMBER() OVER(PARTITION BY EmployeeID, LogDate, InOut
                                    ORDER BY LogTime ASC) AS shiftno
        FROM Accesslog
             )
SELECT
        ins.EmployeeID
      , ins.LogDate
      , ins.LogTime  as LogTimeIn
      , outs.LogTime as LogTimeOut
      , ins.Accepted + ISNULL(outs.Accepted,0) as CountPunches
      , CONVERT(varchar(12),
         DATEADD(minute,
         DATEDIFF(minute,
         ins.LogTime,
         outs.LogTime), 0), 114) as HoursAttending
FROM CTE  AS ins
INNER JOIN CTE AS outs ON ins.InOut = 0 AND outs.InOut = 1
                      AND ins.EmployeeID = outs.EmployeeID
                      AND ins.LogDate = outs.LogDate
                      AND ins.shiftno = outs.shiftno

Results:
| EmployeeID |                   LogDate |                 LogTimeIn |                LogTimeOut | CountPunches | HoursAttending |
|------------|---------------------------|---------------------------|---------------------------|--------------|----------------|
|       1009 | October, 14 2015 00:00:00 | January, 01 1900 08:00:00 | January, 01 1900 16:00:00 |            2 |   08:00:00:000 |
|       1088 | October, 15 2015 00:00:00 | January, 01 1900 09:00:00 | January, 01 1900 15:00:00 |            2 |   06:00:00:000 |
|       1209 | October, 14 2015 00:00:00 | January, 01 1900 07:00:00 | January, 01 1900 12:01:00 |            2 |   05:01:00:000 |
|       1209 | October, 14 2015 00:00:00 | January, 01 1900 15:00:00 | January, 01 1900 20:02:00 |            2 |   05:02:00:000 |


text:
Q: AttributeError: 'NoneType' object has no attribute 'group' in googletrans I want to convert unknown language strings to English. For which I'm using googletrans python package that works along with an API to perform the desired task
So, I did following
from googletrans import Translator
translator = Translator()
translator.translate('안녕하세요.', dest='ja')

This gave
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-9a3706f65a29> in <module>()
      1 from googletrans import Translator
      2 translator = Translator()
----> 3 translator.translate('안녕하세요.', dest='ja')

3 frames
/usr/local/lib/python3.7/dist-packages/googletrans/client.py in translate(self, text, dest, src, **kwargs)
    180
    181         origin = text
--> 182         data = self._translate(text, dest, src, kwargs)
    183
    184         # this code will be updated when the format is changed.

/usr/local/lib/python3.7/dist-packages/googletrans/client.py in _translate(self, text, dest, src, override)
     76
     77     def _translate(self, text, dest, src, override):
---> 78         token = self.token_acquirer.do(text)
     79         params = utils.build_params(query=text, src=src, dest=dest,
     80                                     token=token, override=override)

/usr/local/lib/python3.7/dist-packages/googletrans/gtoken.py in do(self, text)
    192
    193     def do(self, text):
--> 194         self._update()
    195         tk = self.acquire(text)
    196         return tk

/usr/local/lib/python3.7/dist-packages/googletrans/gtoken.py in _update(self)
     60
     61         # this will be the same as python code after stripping out a reserved word 'var'
---> 62         code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
     63         # unescape special ascii characters such like a \x3d(=)
     64         code = code.encode().decode('unicode-escape')

AttributeError: 'NoneType' object has no attribute 'group'

What is causing the error? Is there any other way around to achieve the task.

A: As I have tested your scenario using your code, I also encountered the same error as seen in this screenshot.

This is likely due to the old library version that you're using which is googletrans 3.0.0
To resolve the issue you are encountering, you must upgrade your googletrans from 3.0.0 to 4.0.0rc1. You may use below script to upgrade your googletrans version.
pip install googletrans==4.0.0rc1

Please see below successful testing using googletrans 4.0.0rc1 for your reference:

A: Try installing the below version of googletrans;
pip install googletrans==3.1.0a0

This would work!


text:
Q: Why do I get an error from my API but only when I use some requests? I am using an API from this site https://dev.whatismymmr.com, and I want to specifically request for the closestRank but I just get a KeyError: 'ranked.closestRank'. but I can get the entire ['ranked'] object (which contains the closestRank) but I just end up with a lot of information I don't need.
How can I end up with just the Closest rank?
My code
import requests
LeagueName = input ("Summoner name")
base = ("https://eune.whatismymmr.com/api/v1/summoner?name=")
Thething = base + LeagueName
print (Thething)
response = requests.get(Thething)
print(response.status_code)
MMR = response.json()
print (MMR['ranked.closestRank'])

The API command
<queue>.closestRank (the queue is the game mode, it can be normal or ranked)
you can use the summoner name babada27 for testing.

A: Hope this is what you are looking for -

change The last line to
print (MMR["ranked"]["closestRank"])


text:
Q: Circle timer background color change I am using a timer. I want to put a black background at the back of text in the circle shape. right now it is transparent and you can see blue color at the back of text. I want that blue to black in the center part of the circle only.
$("#DateCountdown").TimeCircles();
$("#CountDownTimer").TimeCircles({
    time: {
        Days: {
            show: false
        },
        Hours: {
            show: false
        }
    }
});
$("#PageOpenTimer").TimeCircles();
var updateTime = function () {
    var date = $("#date").val();
    var time = $("#time").val();
    var datetime = date + ' ' + time + ':00';
    j$("#DateCountdown").data('date', datetime).TimeCircles().start();
}
$("#date").change(updateTime).keyup(updateTime);
$("#time").change(updateTime).keyup(updateTime);
$(".startTimer").click(function () {
    $("#CountDownTimer").TimeCircles().start();
});
$(".stopTimer").click(function () {
    $("#CountDownTimer").TimeCircles().stop();
});
$(".fadeIn").click(function () {
    $("#PageOpenTimer").fadeIn();
});
$(".fadeOut").click(function () {
    $("#PageOpenTimer").fadeOut();
});

Fiddle

A: The plugin didn't support it... So what I did was change the plugin.
I added:
    use_inner_background: true,
    circle_inner_bg_color: "#000",

to the standard settings, you can change these as you will to make it transparent or not. I defaulted it to black.
See the working fiddle, here


text:
Q: iphone / ipad Enterprise application Distribution i have enterprise application distribution certificate to distribute application to certain employees in an organization.
Here how to delete a particular device id in that distribution certificate.
for example consider a person is run away from the organization with device means here how'll you restrict user to access the application in that particular device.
ANy idea...

A: You could implement a startup check where the app will contact a server which holds a blacklist of UDIDs of devices known to be AWOL. The app would ask the server for permission to run upon startup by transmitting the UDID of its host device.
This will of course force your devices to be online (or otherwise able to contact the server) in order to run. If this is not possible under all circumstances, the permission to run could be valid for some time. For example, the app would start up for three days after the permission was last granted before requiring a new permit.


text:
Q: Поиск компонент связности С++ ? Пример кода на с++/java? Имеется ввиду, поиск компонент связности с помощью обхода в глубину/ширину. Собираюсь искать по матрице смежности.
A: В Boost есть библиотека для работы с графами, вот о компонентах связности: strong_components.

The strong_components() functions compute the strongly connected components of a directed graph using Tarjan's algorithm based on DFS.

A: Насколько я понимаю автору вопрса нужен алгоритм поиска компонент сязности, а не компонент сильной связности, а это совсем не одно и тоже!
    int n, a[100][100], cur = 0;
    fin >> n;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            fin >> a[i][j];
    vector <int> was(n, -1);
    queue <int> q;
    for (int i = 0; i < n; i++)
    {
        if (was[i] != -1)
           continue;
        q.push(i);
        while (!q.empty())
        {
              int v = q.front();
              q.pop();
              if (was[v] != -1)
                 continue;
              was[v] = cur;
              for (int j = 0; j < n; j++)
                  if (a[i][j] != 0 && was[j] == -1)
                     q.push(j);
        }
        cur++;
    }

Этот код считывает граф заданный матрицей смежности(но советую ипользовть списки смежности).
В итоге в векторе was для каждой вершины будет лежать номер ее компоненты связности, а cur - количесвто компонент связности.


text:
Q: How to create a vector sequencing along nonNA elements In R, given a vector with some elements as NA, how can I count along it skipping NAs?
For example:
let <- letters[1:10]
let[c(2,3,7,9)] <- NA

How would I get the vector?
1,NA,NA,2,3,4,NA,5,NA,6

A: One way is to match all the indices of let to the non-na indices:
> match(seq_along(let), which(!is.na(let)))
 [1]  1 NA NA  2  3  4 NA  5 NA  6

A: Another option using seq_along
let[!is.na(let)] <- seq_along(let[!is.na(let)])
as.numeric(let)
# [1]  1 NA NA  2  3  4 NA  5 NA  6

benchmark
library(microbenchmark)

n <- 1e7
let_long <- seq_len(n)
set.seed(1)
let_long[sample(seq_len(n), size = 1e6)] <- NA

benchmark <- microbenchmark(
  Karolis = Karolis(let_long),
  Markus = Markus(let_long),
  Snoram = Snoram(let_long),
  Alexandra = Alexandra(let_long),
  Frank = Frank(let_long) # see comment under Snoram's answer
)

To get the chart below, type autoplot(benchmark).

#Unit: milliseconds
#      expr       min        lq      mean    median        uq       max neval
#   Karolis 1042.0708 1216.6241 1314.9765 1290.3428 1374.7090 1807.4604   100
#    Markus  210.3860  259.9957  310.0776  293.8244  363.4317  488.2171   100
#    Snoram  714.4514  938.5760 1033.6168 1029.8205 1104.5614 1546.3733   100
# Alexandra 4317.5206 4470.2634 4665.9004 4603.6446 4771.5768 6495.3595   100
#     Frank  103.3624  126.2842  166.7555  159.3568  190.5186  290.0422   100

Functions compared so far.
Karolis <- function(x) {
  match(seq_along(x), which(!is.na(x)))
}

Markus <- function(x) {
  x[!is.na(x)] <- seq_along(x[!is.na(x)])
  as.numeric(x)
}

Snoram <- function(x) {
  ifelse(is.na(x), NA, cumsum(!is.na(x)))
}

Alexandra <- function(x) {
  j = 0
  for (i in 1:length(x)) {
    if(is.na(x[i]) == FALSE){
      j = j + 1
      x[i] <- j
    }
  }
  as.numeric(x)
}

Frank <- function(x) {
  replace(cumsum(!is.na(x)), is.na(x), NA)
}

A: Other options include:
Use ifelse() and cumsum()
ifelse(is.na(let), NA, cumsum(!is.na(let)))
#[1]  1 NA NA  2  3  4 NA  5 NA  6

A: This would get the result you are looking for but isn't efficient
let <- letters[1:10]
let[c(2,3,7,9)] <- NA

j = 0
for (i in 1:length(let)) {
  if(is.na(let[i]) == FALSE){
    j = j + 1
    let[i] <- j
    }
}


text:
Q: Adding an attribute to a ModelAndView I'm writing a HandlerInterceptor that needs to insert a certain session-scoped bean into the Model. postHandle's signature looks like this:
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception

ModelAndView has no addAttribute function. How can I add an attribute to a ModelAndView so that I can access it with request.getAttribute inside my views?

A: Use modelAndView.addObject("key", value)
There are also some other indirect ways, through modelAndView.getModel() or modelAndView.getModelMap(). But you should prefer the addObject(..) version. In fact it invokes getModelMap().addAttribute(..)


text:
Q: How to Delete Specific Multi Records in Codeigniter I want to delete 4,6,8,11,12 records by using model at a time. I also want to know how to do it without deleting the following records 3,5,6,7 by using model.
Controller Function
public function delete_data($id,$value){
    $oris = explode("_", $value);
    $oris = array_filter($oris);
    $this->o->delete_data($oris);
}

Model Function
public function delete_data($id){
    $this->db->where('campus_id', $id);
    $this->db->delete('sections');
}

A: 4,6,8,11,12 records Deleted
public function delete_data($id){
    $this->db->where_in('campus_id', $id);
    $this->db->delete('sections');
}

3,5,6,7 records not Deleted
public function delete_data($id){
    $this->db->where_not_in('campus_id', $id);
    $this->db->delete('sections');
}

Wow I Got It..

A: YOUR MODEL
public function delete_record() //You can pass ID as a parameter here
{
    $this->db->where('column-name', 'your-id'); //id can be 4, 6, 8, 11, 12
    return $this->db->delete('table-name');
}


text:
Q: Placement of quantifiers in a symbolic statement I have the statement:
Let $A_n$ be an indexed set of numbers defined by $A_n = n\mathbb{Z}_{\geq m}$ for $n,m \in \mathbb{Z}$.  Consider the claim C: For all $n$, if $x,y$ is in $A_n$, then $x^{(y+1)}$ is in $A_n$.
I wrote C symbolically as the following.
$$C: \forall n, x,y \in A_n \implies x^{(y+1)} \in A_n.$$
Is this symbolic form correct?  I feel like I need some separation between the universal quantifier and the rest of the statement.  Thanks!

A:
Consider the claim C: For all $n$ , if $x,y$  is in $A_n$  , then $x^{(y+1)}$   is in $A_n$  .

Are the $x,y$ used here arbitrary ("any $x,y$...") or have they been defined earlier ("these $x,y$...")?
If they are predefined constants, then we have:
$$\forall n\; \Big(n\in \Bbb Z\wedge x\in A_n\wedge y\in A_n \;\to\; x^{y+1}\in A_n\Big)$$

If they are arbitrary then you have to bind them to a quantified scope.
That is in full:
$$\forall n\; \forall x\;\forall y\; \Big(n\in \Bbb Z\wedge x\in A_n\wedge y\in A_n \;\to\; x^{y+1}\in A_n\Big)$$
Or in abbreviated form:
$$\forall n\in\Bbb Z\; \forall x\in A_n\;\forall y\in A_n\; \bigl( x^{y+1}\in A_n\bigr)$$


text:
Q: Start video read from a particular frame I have obtained the frame_count of a saved video.
self.frame_count = self.capture.get(cv.CV_CAP_PROP_FRAME_COUNT) - 1

Now, I want to start a frame read from a particular frame_count. How do I do this?
Reason: I need to track an object and I have found the location of the object I want to track using HSV image segmentation. Now to track it, I intend to start the video from that particular frame and set the track window to the objects' coordinates.
Want: It should not be redundant and computationally intensive.

A: Use the below code to accomplish your task.
The Opencv version you are using is old. Use Opencv2.
Link : http://docs.opencv.org/trunk/doc/py_tutorials/py_tutorials.html
import numpy as np
import cv2
import os

cam = cv2.VideoCapture('full_path/bird.avi')
i = 1
initialize_first_frame = cam.read()[1]
start_from_frame = 5
dir =  './testImages/'
os.makedirs(dir)
while True:
    if(i>=start_from_frame):
      cv2.imshow('Frame Conversion',cam.read()[1])
      cv2.imwrite(dir + "/image-"+str(i).zfill(5)+".png",cam.read()[1])
    i = i + 1
    key = cv2.waitKey(10)
    if key == 27:
       cv2.destroyWindow('Frame Conversion')
       break
print "End"

I hope this is the code you want.

A: Try the following:
f = # put here the frame from which you want to start
self.capture.set(CV_CAP_PROP_POS_FRAMES, f)
while f < self.frame_count:
    retval, image = self.capture.read()
    f += 1

A: For any version 3 and 4 of OpenCV Python, follow this -
import cv2
# suppose you want to start reading from frame no 500
frame_set_no = 500
cap = cv2.VideoCapture("full_path/cow.mp4")

# capture is set to the desired frame
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_set_no)

while True:
  ret, frame = cap.read()
  cv2.imshow("Video", frame)
  if cv2.waitKey(1) & 0xFF == ord('q'):
    break
cv2.destroyAllWindows()


text:
Q: Session management with load balancer in Java EE We are developing a Java EE application with Spring. The application will be deployed across multiple web servers with hardware load balancer. Here are my doubts. Please clarify.

*

*Whether load balancer will route all requests in same session to a single web server?

*If not is there anyway to route the requests of same session to particular web server?

EDIT: Removed spring.

A: What you're referring to here are "sticky sessions" and your load balancer should support them. It alllows the load balancer to use the session ID to route all requests for a session to the same server.


text:
Q: Custom rotated polygon labels in ArcMap Can the following be done in ArcMap? It should be formula based without manual formatting as performed by my predecessor (in MapInfo using a lot of manual steps) to get the following output.

So

*

*Grave_No on right parallel to the y axis of the grave.

*Name on top center parallel to the x axis of the grave.

*Date of Death on bottom center parallel to the x axis of the grave.

I expect that we will need to copy the layer three times to apply custom labels for each of these situations
In MI
-I can't autorotate the labels and place them on the left/make sure the angle is the same as the grave. I know it can be done manually per label but this is far to much work.
In QGIS
- See Custom labeling with same angle as rectangular object and specific position using QGIS?
In ArcMap
- In maplex, it seems as if we can only rotate point labels but I have a polygon shape. We can't use centroids as it will go out of the grave site.
So QGIS seems to get the closest...and while I am happy to have a QGIS solution I have asked a new question (as there were no responses) to just have an ArcMap solution.

Note 1. The name sometimes does not show but the Date of Death does, in other cases this is reversed. Both should be shown. 2. Some will have 2 or more people in the grave so the data will be there twice - so grave no will be E-062a and E-062b for example with 2 names and dates of death as well.
So can I do all the above in ArcMap? the example shows how far I could get it.

A: You can have a look at annotations (not grapic elements). When you export your labels to a file-geodatabase the label options becoming columns in the attribut-table of the annotation. There you can calculate the angle field to have your rotations/colors/offsets based on some formula.

When you create your labels in the first place as label-classes for your different offsets/colors/rotations you don´t have to create several layers. The classes will be afterwards in the attribute table and can be used for a conditional calculation of the roatations. Something like "If attribut=5 and labelclass=2 return rotation = 90". The calculated values will automaticly be applied to the annotations.