text:
Q: Creating real-time monitor window of an application I want to create a window that can display the current content of an application, say Powerpoint or Adobe Reader.
When I run my application, I would first select which of the currently running application I need to monitor in realtime. Once done, I need to get the current content of the selected application and display it. Since my application is going to be realtime, it will need to  capture the contents of the selected application as and when they change (with minimal lag), and then display it.
As I understand, this broadly comprise of the following steps:
1. Selecting an application that I want to monitor
2. Get 'notification' when the content of that applicaion (client area) has changed
3. Capture the new content and display it
The steps [1] and [3] are quite easy and I find several methods here to perform them. However, for the stage [2] I am still clueless. Can anybody throw some light on how to acheive this?
Cheers.

A: You might take a look at UltraVNC, which does exactly what you are trying to do (it has a single window mode as well as full-screen).  It has no less than four ways to accomplish your step #2.

A: The one obvious approach I can think of is to periodically take snapshots of the app's window and compare it to the previous one for changes.


text:
Q: Jquery and iFrame update I want to create a page that has a dropdown and an iframe, so that the iframe location will change based on the url in the dropdown. What is the correct syntax to get jquery to update the iframe's url?
thanks

A: I think this will work:
$('#dropdownid').bind('change', function() {
    $('#iframeid').attr('src', $(this).val());
});

A: To change an iframe's url, you update its src attribute.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Открытие сформированных документов в MS Office 2007 и более ранней версии Использую OpenXML SDK для последующего формирования word файла на с#, полученный сформированный файл имеет расширение .docx и без проблем открывается в MS Office 2010 и MS Office 2016, но не открывается в MS Office 2007 (пишет документ был поврежден).
Может быть кто-то сталкивался?
Есть идея, что там были разные стандарты OXML. Но хотелось бы получить более развернутый ответ.


text:
Q: Listen to UDP broadcast with Cordova plugin I'm really new to the whole UDP concept, so I'm sorry If I say something stupid.
I want my app that runs on Android only to listen for UDP broadcasts.
I installed this plugin Cordova Chrome UDP
So my problem starts with that question:
If I want only to listen for messages do I have to create a socket or I just have to add listener like that:
chrome.sockets.udp.onReceive.addListener(receiveListener);
Maybe I have to create a socket first so it will know where to listen for broadcasts?
And is there an easy way to test the connection. I tried several things one of which was to connect one of the devices to the other's hotspot. Then I tried to send broadcast signal from one of the devices (after using setBroadcast to enable the broadcast of the socket) but the other didn't receive it. The onReceive event actually fired but only on the device which sent the broadcast message (which is pretty obvious but I don't know if that could be a good news so I mention it).
Here is some code :
function sendBroadcast() {
    console.log("Sending broadcast");
    var port = 1667;
    var arr = new Uint8Array(256);
    for (var i = 0; i < arr.length; i++) {
      arr[i] = i;
    }

    chrome.sockets.udp.create(function(createInfo) {
      chrome.sockets.udp.bind(createInfo.socketId, '0.0.0.0', port, function(result) {
        chrome.sockets.udp.setBroadcast(createInfo.socketId, true, function(result){
          chrome.sockets.udp.send(createInfo.socketId, arr.buffer, '255.255.255.255', port, function(result) {
            if (result < 0) {
              chrome.sockets.udp.close(createInfo.socketId);
            } else {
              chrome.sockets.udp.close(createInfo.socketId);
            }
          });
        });
      });
    });
}

function createSocket(){
    chrome.sockets.udp.create(function(createInfo) {
      chrome.sockets.udp.bind(createInfo.socketId, '0.0.0.0', 0, function(result) {
        chrome.sockets.udp.setBroadcast(createInfo.socketId, true, function(result){
             console.log("The socket with id: " + createInfo.socketId + " is created");
        });
      });
    });
}

On both devices I first call createSocket() and then from one of them I call sendBroadcast() but nothing is received on the other device.


text:
Q: Hide table row if td is empty I want to hide tr with class cell if td with class emp is empty. How to do it using jquery/javascript?
Html

         Date
         Employee

         2022-04-02

         2022-04-07

Employee 1

         2022-04-09

         2022-04-13

Employee 1

         2022-04-16

I've tried something like code bellow, but still not working.
Jquery
$('#tblNodes > tbody  > tr').each(function () {
   if ($(this).find('td').is(':empty')) {
      $(this).hide();
   }
});

A: We can iterate over each cell and check its text value. Then we hide its parent if the text is empty. We need to use trim() because jquery returns empty spaces and new lines sometimes for empty elements.

$('#tblNodes td').each(function () {
   if ($(this).text().trim() === '') {
     $(this).parent().hide();
   }
});

         Date
         Employee

         2022-04-02

         2022-04-07

Employee 1

         2022-04-09

         2022-04-13

Employee 1

         2022-04-16

A: What causes your code to not work are 2 things
first, you need to each directly through td instead of tr
secondly, i noticed from your code that you have a lot of white spaces here which will fail :empty test

$('#tblNodes > tbody td').each(function () {
   if ($(this).hasClass('emp') && $(this).is(':empty')) {
      $(this).parent().hide();
   }
});

A: Try This:

$('#tblNodes > tbody td').each(function() {
    if ($(this).html().trim() == '') {
        $(this).parent().hide();
    }
})

         Date
         Employee

         2022-04-02

         2022-04-07

Employee 1

         2022-04-09

         2022-04-13

Employee 1

         2022-04-16


text:
Q: Derivation of the volume preserving mean curvature flow

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Picture above is from
Huisken, Gerhard, The volume preserving mean curvature flow, J. Reine Angew. Math. 382, 35-48 (1987). ZBL0621.53007..
I want to get the (2) from (1) . First , choice a positive function $\varphi(t)$ such that the volume enclosed by  surface $\widetilde M_t$ given by
$$
\widetilde F(x,t) = \varphi(t)F(x,t) ~~~~~~~~~~~~~~~~~~~~~(3)
$$
is equal to the volume enclosed by $M_0$. So I have
$$
\frac{1}{n+1}\int _U \widetilde F(x,t)\cdot \widetilde\nu(x,t) \sqrt{\widetilde g(x,t)} dx =\frac{1}{n+1}\int_U F(x,0)\cdot \nu(x,0) \sqrt{g(x,0)} dx          ~~~~~~~~~~~~~~(4)
$$
And
$$
\widetilde g_{ij}=\varphi^2 g_{ij}
 ~~~~~~~~~~~~~~~\widetilde h_{ij}=\varphi h_{ij}  \\
~~~~~~\widetilde H=\varphi^{-1} H
~~~~~~~~~~~~~~\sqrt{\widetilde g}= \varphi^n\sqrt{g}~~~~  \\
~~~~~~~\widetilde\nu(x,t)   =\nu(x,t)
~~~~~~~~~~~~~~\partial_t \nu(x,t)=\nabla H(x,t)  \\
\partial_t\sqrt g =-H^2 \sqrt g~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$$
Differentiate (4), I have
$$
0=\int_U (n+1)\varphi^n\varphi' F\cdot\nu\sqrt g - \varphi^{n+1} H \sqrt g
+\varphi^{n+1}F\cdot \nabla H \sqrt g   -\varphi ^{n+1} F\cdot\nu H^2 \sqrt g
dx
$$
so I have
$$
\frac{\varphi ' }{\varphi} =\frac{1}{n+1} \frac{\int_U (H-F\cdot \nabla H +F\cdot \nu H^2 )\sqrt g}{\int_U F\cdot \nu \sqrt g }
$$
define $h(t)$ as
$$
h(t)\triangleq\frac{\int_U (H-F\cdot \nabla H +F\cdot \nu H^2 )\sqrt g}{\int_U F\cdot \nu \sqrt g }
$$
introduce a new time
$$
\widetilde t (t) = \int _0^t  \varphi^2(\tau) d\tau
$$
so I have
$$
\frac{d\widetilde t}{dt}=\varphi^2(t)  ~~~~~~~~~~~  \frac{d t}{d\widetilde t}=\varphi^{-2}(t(\widetilde t))
$$
So , I have
$$
\partial_{\widetilde t} \widetilde F =\partial _t \widetilde F \varphi^{-2}
=\varphi^{-2}[\partial_t\varphi F+\varphi \partial_t F]
=\varphi^{-1}Fh-\varphi H\nu
=\widetilde F\widetilde h-\widetilde H \widetilde \nu
$$
So , I have the volume preserving mean curvature flow
$$
\partial_t F =Fh-H\nu
$$
In fact, it really be preserving volume. Because
$$
\partial_t \int _U F\cdot \nu \sqrt g dx  =0
$$
But it is not same with (2) in above picture. How to get the (2) ? I think the form of (2) is better than mine.
PS: After long time, I can't deal it. Thanks for any help.


text:
Q: Error : minSDK(API27) > deviceSDK(API23) Hola estoy usando la versión 3 de Android Studio, tuve muchos problemas pero pude hacer que un programa funcionara, ahora estoy creando otro, pero me sale este error:
minSDK(API27) > deviceSDK(API23) lo raro es que cambié varias veces los valores, pero nada me funciona.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.jhon.pasardatosentreactivities"
        minSdkVersion 27
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

A: El mensaje de error:

minSdk(API 27) > device Sdk(API 23)

indica que tu dispositivo ya sea emulador o físico tiene sistema operativo Android 6.0 (API 23) y en la definición de tu proyecto estas definiendo como minima version la API 27, por lo tanto no se podrá instalar la aplicación.
 minSdkVersion 27

puedes cambiar este valor a :
minSdkVersion 23

para que pueda funcionar en tu dispositivo la aplicación.

Para mas información relacionada a minSdkVersion , revisa esta respuesta
Duda sobre APIs y versiones de Android : minSdkVersion


text:
Q: log parser error I have never used log parser before..
well I am getting this error now.. i don't know the reason..
Retrieving the COM class factory for component with CLSID {8CFEBA94-3FC2-45CA-B9A5-9EDACF704F66} failed due to the following error: 80040154.
can ya help me out with this..
:)

A: The error code means the class in not registered. Running the following command will probably solve the problem:
regsvr32 <path>\LogParser.dll

If you move the DLL around (install it with your app, for instance), you'll have to repeat the call each time. Or, if you'd like to install it from your app, you can call the exported DLLRegisterServer, which is what regsvr32 calls.

A: Other answer:
Download and install Log Parser 2.2


text:
Q: unix command to merge same coloums and take the average Can anyone help me out to solve this i have started learning Unix recently
name     class  physics chemistry   maths
mayank   xi      55        89        38
bhawna   xi      56        65        85
ashish   xi      69        96        69
ashankar xii     84        86        97
ankush   xi      87        68        85
meghna   xi      69        78        84
chaitra  xi      63        87        48
pavithra xii     72        48        59
akshat   xii     87        84        67
somesh   xii     88        82        57

consider the above data is a tab delimited file. You have to prepare 3 reports as a tab delimited file from the data provided
classwise_data.txt
class_xii.txt
class_xi.txt

Your script should generate these three tab delimited files as the name given (with space )  and should have data as given on the right.
classwise data.txt

class   no of students  phy avg     che avg   maths avg
xi        6             66.5         80.5     68.16667
Xii       4             82.75        75        70

class xii.txt

name         class  physics chemistry   maths   avg
ashankar       xii  84         86        97     89
pavithra       xii  72         48        59     59.66666667
akshat         xii  87         84        67     79.33333333
somesh         xii  88         82        57     75.66666667

class xi.txt

name    class   physics chemistry   maths   avg
mayank  xi       55         89       38     60.66666667
bhawna  xi       56         65       85     68.66666667
ashish  xi       69         96       69     78
ankush  xi       87         68       85     80
meghna  xi       69         78       84     77
chaitra xi       63         87       48     66


text:
Q: Finding furthest distance between two UK buildings that share same postcode? What is the furthest distance between two UK buildings that share the same postcode?
I'm not sure how to find this out myself.

A: You will need postcode unit polygons (should be a free version - premium version is available to public agencies*).
You will need UK buildings (not free but available to public agencies if you are one*).
If you have no money then you can try Open Street Map (OSM) for non-authoritative data.
Then it's just a distance between buildings in the same postcode unit measurement. Probably cycle through them and keep the largest as you go.  Then you will have the largest per postcode unit and then you just look for the largest of those.
This is going to be quite intensive and there are strategies you could adopt to reduce the workload here but that's beyond the scope of my answer.
*PMSA
For some context the largest area postcode unit is "IV27 4NZ" in the code point data set which is 443.5 square km.  If it were square this would have sides of 21km and a diagonal of 30km. It's unlikely that there is building at each of the far ends of this but your answer is probably less than 30 km.
EDIT
I looked at the largest postcode units in QGIS and the elongated shape results in max distance closer to 40km but these are all in the Scottish Highlands with not many buildings.  Also, it really depends on what you classify as a building since a bothy or a shed is a building although I doubt they have a postal address i.e. don't have a postcode. So would you count this?
You have a lot to think about if you are serious about answering this question.  Still, I hope I have at least given some indication of the order of magnitude your looking at is around 20-30km.


text:
Q: How to use async await in nodejs I made an api like below.
I think it works asyncrously well without doubt.
exports.query = async(req, res) => {
   try{
      const result = await user.findOne({})
      res.send(result);
   } catch(error) {
      res.send(error)
   }
}

But when I try this like below, I am not sure it works asyncrously or not.
exports.query = async(req, res) => {
   try{
      user.findOne({})
         .then(async(result) =>{
               order.findOne({id: result.id})
         .catch(e => res.send(e)
   } catch(error) {
      res.send(error)
   }
}

I have to attach 'await' in front of user.findOne({}) like below?
exports.query = async(req, res) => {
       try{
          await user.findOne({})
             .then(async(result) =>{

Or it doesn't matter? That is, it works same asycrously, even though I don't write await in front to user.findOne using 'then'?
thank you so much for reading.

A: Generally, inside a single block, you should either use await, or use .then, but not both - similarly, using Promise.prototype.catch is really weird in combination with try/catch where you can already await.
For your exports.query to resolve once the second findOne finishes, await or return both Promises, and connect the inner findOne connected to the outer Promise chain. Consider something like this instead:
exports.query = async (req, res) => {
  try {
    const userResult = await user.findOne({});
    const orderResult = await userResult.findOne({ id: userResult.id });
    // do something with orderResult
  } catch (error) {
    res.send(error)
  }
}

If you use .then and catch without await, then it would look like:
exports.query = (req, res) => {
  return user.findOne({})
    .then((result) => {
      return order.findOne({
          id: result.id
        })
        .then((orderResult) => {
          // do something with orderResult
        })
        .catch(e => res.send(e))
    });
}

With the code in the second snippet in your question, your try/catch block will never do anything useful, because any problem will trigger the .catch method, and because the Promise isn't being awaited. Better not to mix the two styles - either pick await and try/catchor .then and .catch, but not both, else the control flow may become difficult to make sense of.

A: First of all, async-await can be used in functions which returns a promise.
Why we have to use await instead of then. await process the code asynchronously by  making the execution feel like synchronous.
In your first example, everything works fine as expected. But in the second one, you need to await the findOne query. Here the fineOne will work asynchronously
exports.query = async(req, res) => {
   try{
      user.findOne({})
         .then(async(result) =>{
              let orderResult = await order.findOne({id: result.id})
         .catch(e => res.send(e)
   } catch(error) {
      res.send(error)
   }
}

which can be again simplified to
exports.query = async(req, res) => {
   try{
      let result = await user.findOne({});
      let orderResult  = order.findOne({id: result.id});

   } catch(error) {
      res.send(error)
   }
}


text:
Q: How to pass string format as a variable to an f-string I am using f-strings, and I need to define a format that depends upon a variable.
def display_pattern(n):
    temp = ''
    for i in range(1, n + 1):
        temp = f'{i:>3}' + temp
        print(temp)

If it is relevant, the output of display_pattern(5) is:
  1
  2  1
  3  2  1
  4  3  2  1
  5  4  3  2  1

I wonder if it is possible to manipulate the format >3, and pass a variable instead. For example, I have tried the following:
def display_pattern(n):
    spacing = 4
    format_string = f'>{spacing}' # this is '>4'
    temp = ''
    for i in range(1, n + 1):
        temp = f'{i:format_string}' + temp
        print(temp)

However, I am getting the following error:
Traceback (most recent call last):
  File "pyramid.py", line 15, in <module>
    display_pattern(8)
  File "pyramid.py", line 9, in display_pattern
    temp = f'{i:format_string}' + temp
ValueError: Invalid format specifier

Is there any way I can make this code work? The main point is being able to control the spacing using a variable to determine the amount of padding.

A: you should to put the format_string as variable
temp = f'{i:{format_string}}' + temp

the next code after : is not parsed as variable until you clearly indicate.
And thank @timpietzcker for the link to the docs: formatted-string-literals

A: You need to keep the alignment and padding tokens separate from each other:
def display_pattern(n):
    padding = 4
    align = ">"
    temp = ''
    for i in range(1, n + 1):
        temp = f'{i:{align}{padding}}' + temp
        print(temp)

EDIT:
I think this isn't quite correct. I've done some testing and the following works as well:
def display_pattern(n):
    align = ">4"
    temp = ''
    for i in range(1, n + 1):
        temp = f'{i:{align}}' + temp
        print(temp)

So I can't really say why your method wouldn't work...


text:
Q: jquery replacing one div with another In the following, I want to remove class "item1" and add class item2 to maindiv. The code below is not working. What is wrong with the code and how do I include item2 in maindiv?
HTML:

item2

 item1

jQuery:
if (selection) {
    if ($('.maindiv').hasClass('item1')) {
        $('.maindiv').removeClass('item1').addClass('item2');
    }
}

A: In your example, .maindiv doesn't have a class named item1, it has a
child  that has that class. You're testing if it has it.
You may want to revise to something like:
if($('.maindiv > div').hasClass('item1')) {
    $('.maindiv > div')
        .removeClass('item1')
        .addClass('item2');
}

Or
if($('.maindiv .item1').length > 0) {
    $('.maindiv .item1')
        .removeClass('item1')
        .addClass('item2');
}

... whichever you find more readable.

A: You must have to target inner div like
    $(document).ready(function() {
       if(selection) {
           $('.maindiv .item1').removeClass('item1').addClass('item2');
     }
});

A: The .hasClass() function checks that the element(s) it's being called on have that class (in your case it doesn't). It does not check that those elements contain an element with that class.

 and
 are elements, not classes; item1 and item2 are classes on those elements. You seem to be confused about what a class is and what the .hasClass(), .addClass() and .removeClass() functions do, so I'd suggest you go back and cover the basics.

A: $('#maindiv').find('item1') and than you can chain it.

A: use id comparator for better solution like

  item1

  item1

if(selection)
            {
                if ( $('#test').hasClass('item1') ) {
                            $('#test').removeClass('item1').addClass('item2');

                }

            }


text:
Q: Missing vertical line using tabu I create a single column table using tabu.
\documentclass[preprint,5p,12pt]{elsarticle}
\usepackage{tabu}

\begin{document}

\begin{table}[htbp]
    \footnotesize
    \begin{center}
        \label{T:my_table}
        \everyrow{\hline}
        \tabulinesep=1.2mm
        \begin{tabu} to \linewidth {|X{l}|}
            \textbf{Headline 1} \\
            a \\
            b \\
            c \\
            \hline \hline
            \textbf{Headline 2} \\
            d \\
            e \\
            f \\
            g \\
        \end{tabu}
        \caption{Meaningful caption}
    \end{center}
\end{table}

\end{document}

This renders without a line on the right. How can i get a right border for all rows?

A: If you want an X column with left alignment (ragged right), use
X[l]

With X{l} you're asking for two columns, rather than one.
Full example:
\documentclass[preprint,5p,12pt]{elsarticle}
\usepackage{tabu}
\usepackage{lipsum}

\begin{document}

\begin{table}[htbp]
\centering
\footnotesize

\everyrow{\hline}
\tabulinesep=1.2mm

\begin{tabu} to \linewidth {|X[l]|}
\textbf{Headline 1} \\
\lipsum*[4] \\
b \\
c \\
\hline\hline
\textbf{Headline 2} \\
d \\
e \\
f \\
g \\
\end{tabu}

\caption{Meaningful caption}
\label{T:my_table}

\end{table}

\end{document}

*

*\lipsum is just for showing the final result for a long text in the column

*Don't use \begin{center}, but \centering as shown.

*The \label should go after \caption.


text:
Q: splitting dictionay values in a for loop in nested json conversion into a csv file I have this nested json file converted into csv file. The json file is shown below:
jsonFile = {
         '7': {
               '11': {'ref1': 1}
              },

         '5': {
               '15':  {'ref1':0, 'ref3':1},
               '17':  {'ref2':1},
               '19':  {'ref1':1,'ref4':0}
              },

        '3': {
               '21':  {'ref3':1, 'ref2':1},
               '14':  {'ref5':0}
             },
      .... so on
        }

The desired csv file structure is:
    key,  subKey,  references, values
     7,    11,       ref1,       1
     5,    15,       ref1,       0
     5,    15        ref3,       1
     5,    17,       ref2,       1
     5,    19,       ref1,       1
     5,    19,       ref4,       0
     3,    21,       ref3,       1
     3,    21,       ref2,       1
     3,    14,       ref5,       0
     ...... and so on

I used the following code:
 all_data = []
   for k, v in jsonFile.items():
      for t, val in v.items():
          for p, vall in val.items():
            all_data.append({
              'key': k,
              'subKey': t,
              'references': val,
              #'values': vall
            })

 df = pd.DataFrame(all_data)
 df.to_csv('outPutFile3.csv', encoding='utf-8')
 print(df)

The output of the code is given below. I am not able to further split the dictionaries with ref values in the third loop as shown below:
    key,  subKey,     references
     7,    11,       {'ref1':1}
     5,    15,       {'ref1':0, 'ref3':1}
     5,    17,       {'ref2':1}
     5,    19,       {'ref1':1,'ref4':0}
     3,    21,       {'ref3':1, 'ref2':1},
     3,    14,       {'ref5':0}
     ..........

How can i further split the dictionaries into further columns in the required format?
Thank you..

A: Looks like you are quite close. You can try following where I noted the change in comments. You need p and vall instead.
all_data = []
for k, v in jsonFile.items():
    for t, val in v.items():
        for p, vall in val.items():
            all_data.append({
              'key': k,
              'subKey': t,
              'references': p, #  <- change here
              'values':vall   #  <- change here
            })

A: Here's a recursive solution that descends into the dict. You should of course make sure that the structure is homogeneous enough to support this apprach (will fail if you are missing nested dictionaries):
import pandas as pd

jsonFile = {
         '7': {
               '11': {'ref1': 1}
              },

         '5': {
               '15':  {'ref1':0, 'ref3':1},
               '17':  {'ref2':1},
               '19':  {'ref1':1,'ref4':0}
              },

        '3': {
               '21':  {'ref3':1, 'ref2':1},
               '14':  {'ref5':0}
             }
}

def flatten_dict(d, parent_keys=None):
    parent_keys = parent_keys or []
    for k, v in d.items():
        if isinstance(v, dict):
            for values in flatten_dict(v, parent_keys=parent_keys + [k]):
                yield values
        else:
            yield parent_keys + [k, v]

df = pd.DataFrame(list(flatten_dict(jsonFile)), columns=("key", "subkey", "references", "values"))
df

Output:
    key subkey  references  values
0   7   11      ref1        1
1   5   15      ref1        0
2   5   15      ref3        1
3   5   17      ref2        1
4   5   19      ref1        1
5   5   19      ref4        0
6   3   21      ref3        1
7   3   21      ref2        1
8   3   14      ref5        0

Then you can finish this up with df.to_csv().


text:
Q: How do I stop Refit encoding my querystring? I'm using an API that's in beta and it's essentially a querystring for a Mongodb db as a parameter. Refit is encoding my url, which included plenty of curly braces, and their server doesn't like it and it essentially ignores all of my query attributes.
I've tried passing the entire query as a string, which doesn't work but also doesn't chuck an error. I've found a commit to Refit which directly addresses this issue here.
That says to use the header [QueryUriFormat(UriFormat.Unescaped)], which sounds great, but I'm clearly not using the library the QueryUriFormat attribute is in and I can't find it in a google search.
In the interface:
[QueryUriFormat(UriFormat.Unescaped)]
[Headers("Authorization: Basic")]
[Get("/stuff/etc")]
Task<myModel> GetStuff(string q);

The string:
"filter={name:'THENAME',timestamp:{$gt:1571238110000},TOTAL_MB: {$gt:0},thingyId:{$eq:2500}}";

The call:
var result = client.GetUsageSince(stringB).Result;

I tried the link on the first comment (below)
 var HttpClient = new HttpClient(new UriQueryUnescapingHandler()) { BaseAddress = new Uri(url) };
        HttpClient.DefaultRequestHeaders.Add("Accept", "application/json");
        HttpClient.DefaultRequestHeaders.Add("Content", "application/json");
        var byteArray = Encoding.UTF8.GetBytes($"{username}:{password}");
        HttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
        Stuff = RestService.For<IStuff>(HttpClient, refitSettings);

After doing this it looks like the absolute Uri is now correct, but the basic auth header is not working on my customer HttpClient.


text:
Q: Extract detected faces in DlibDotNet I'm using DlibDotNet and I'm new in it. I have the following code from Detect Faces With C# And Dlib In Only 40 Lines Of Code:
        static void Main(string[] args)
        {
            // set up Dlib facedetector
            using (var fd = Dlib.GetFrontalFaceDetector())
            {
                var img = Dlib.LoadImage<RgbPixel>(inputFilePath);

                // find all faces in the image
                var faces = fd.Operator(img);
                foreach (var face in faces)
                {
                    // draw a rectangle for each face
                    Dlib.DrawRectangle(img, face, color: new RgbPixel(0, 255, 255), thickness: 4);
                }
                Dlib.SaveJpeg(img, "output.jpg");
            }
        }

The question is that how can I extract all the faces detected in image?
I've tested Dlib.ExtractImageChips() Method but I don't know how to use it correctly.
Thanks In Advance.

A: I found the method after diging into the library. Here is the implementation:
DPoint[] dPoint = new DPoint[] {
                    new DPoint(face.TopLeft.X, face.TopLeft.Y),
                    new DPoint(face.TopRight.X, face.TopRight.Y),
                    new DPoint(face.BottomLeft.X, face.BottomLeft.Y),
                    new DPoint(face.BottomRight.X, face.BottomRight.Y),
                };
                    int width = (int)dRectangle.Width;
                    int height = (int)dRectangle.Height;

                    img = Dlib.ExtractImage4Points(img, dPoint, width, height);

Where img is the source image, dPoint is an array of four point that represent four corners of extracted piece of image an width and height are size of extracted image in pixles.

A: After using Dlib.GetFaceChipDetails() and Dlib.ExtractImageChips() you should be getting face images from a given image, just need to convert as Bitmap. To convert
Array2D to Bitmap, you should be added DlibDotNet.Extensions DLL latest version in your project. Code looks like
List<Image> images = new List<Image>();

using (var faceChips = Dlib.ExtractImageChips<RgbPixel>(img, chipLocations))
{
    Image image = null;
    //Iterate face chips and add image one by one if multiple images existed
    foreach (var face in faceChips)
    {
        image = face.ToBitmap();
        images.Add(image);
    }
}

Here is a sample application where shown how to extract face images from an image file.


text:
Q: ERROR - Android Push Notification using Google Cloud Messaging (GCM) I am working on android push notification and try to get the registration id so that I can send push notification from my asp.net admin page to my android device, but my application crashed whenever I try to run the application, please help me.
My XML file
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.gcmdemo.MainActivity" >

<TextView
    android:id="@+id/display"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />

</RelativeLayout>

My Java file
package com.example.gcmdemo;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "GCMDEMO";
//My sender ID
protected String SENDER_ID = "10xxxxxxxxx53";
TextView mDisplay;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
SharedPreferences prefs;
Context context;

String regid;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     mDisplay = (TextView) findViewById(R.id.display);
     context = getApplicationContext();
     if (checkPlayServices()) {
            gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(context);
            if (regid.isEmpty())
            {
                 registerInBackground();
            }
            else
            {
            Log.d(TAG, "No valid Google Play Services APK found.");
            }
      }
    }

private void registerInBackground() {
     new AsyncTask() {

          protected Object doInBackground(Object... params)
          {
               String msg = "";
               try
               {
                    if (gcm == null)
                    {
                             gcm = GoogleCloudMessaging.getInstance(context);
                    }
                    regid = gcm.register(SENDER_ID);               Log.d(TAG, "########################################");
                    Log.d(TAG, "Current Device's Registration ID is: "+msg);
               }
               catch (IOException ex)
               {
                   msg = "Error :" + ex.getMessage();
               }
               return null;
          }     protected void onPostExecute(Object result)
          { //to do here };
       }}.execute(null, null, null);
         }

private String getRegistrationId(Context context) {
    // TODO Auto-generated method stub
     final SharedPreferences prefs = getGCMPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }

        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }
private int getAppVersion(Context context) {
    // TODO Auto-generated method stub
    try {
        PackageInfo packageInfo = context.getPackageManager()
                .getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionCode;
    } catch (NameNotFoundException e) {
        // should never happen
        throw new RuntimeException("Could not get package name: " + e);
    }
}
private SharedPreferences getGCMPreferences(Context context) {
    // TODO Auto-generated method stub
      return getSharedPreferences(MainActivity.class.getSimpleName(),
                Context.MODE_PRIVATE);
}
private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Log.d(TAG, "This device is not supported - Google Play Services.");
            finish();
        }
        return false;
    }
    return true;
}
protected void onResume()
{
       super.onResume();
       checkPlayServices();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

My Android Manifest

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />

  <uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/>
<uses-permission android:name="com.example.gcmdemo.permission.C2D_MESSAGE"/>

<permission
    android:name="com.example.gcmdemo.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".GcmIntentService" />

    <receiver
        android:name=".GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <actionandroid:name="com.google.android.c2dm.intent.REGISTRATION" />

            <category android:name="com.example.gcmdemo" />
        </intent-filter>
    </receiver>
</application>

MY ERROR LOG
 10-22 20:55:05.360: E/SoundPool(389): error loading /system/media/audio/ui/Effect_Tick.ogg
10-22 20:55:05.360: E/SoundPool(389): error loading /system/media/audio/ui/Effect_Tick.ogg
10-22 20:55:05.370: E/SoundPool(389): error loading /system/media/audio/ui/Effect_Tick.ogg
10-22 20:55:05.370: E/SoundPool(389): error loading /system/media/audio/ui/Effect_Tick.ogg
10-22 20:55:05.480: E/SoundPool(389): error loading /system/media/audio/ui/Effect_Tick.ogg
10-22 20:55:05.500: E/SoundPool(389): error loading /system/media/audio/ui/KeypressStandard.ogg
10-22 20:55:05.520: E/SoundPool(389): error loading /system/media/audio/ui/KeypressSpacebar.ogg
10-22 20:55:05.530: E/SoundPool(389): error loading /system/media/audio/ui/KeypressDelete.ogg
10-22 20:55:05.530: E/SoundPool(389): error loading /system/media/audio/ui/KeypressReturn.ogg
10-22 20:55:05.530: E/SoundPool(389): error loading /system/media/audio/ui/KeypressInvalid.ogg
10-22 20:55:05.680: E/libEGL(54): called unimplemented OpenGL ES API
10-22 20:55:05.690: E/libEGL(54): called unimplemented OpenGL ES API
10-22 20:55:05.690: E/libEGL(54): called unimplemented OpenGL ES API
10-22 20:55:05.690: E/libEGL(54): called unimplemented OpenGL ES API
10-22 20:55:05.690: E/SurfaceFlinger(54): glCheckFramebufferStatusOES error 760856444
10-22 20:55:05.700: E/SurfaceFlinger(54): got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot
10-22 20:55:05.700: E/libEGL(54): called unimplemented OpenGL ES API
10-22 20:55:05.700: E/libEGL(54): called unimplemented OpenGL ES API
10-22 20:55:07.080: E/AndroidRuntime(1311): FATAL EXCEPTION: main
10-22 20:55:07.080: E/AndroidRuntime(1311): Process: com.example.gcmdemo, PID: 1311
10-22 20:55:07.080: E/AndroidRuntime(1311): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gcmdemo/com.example.gcmdemo.MainActivity}: java.lang.IllegalStateException: A required meta-data tag in your app's AndroidManifest.xml does not exist.  You must have the following declaration within the <application> element:     <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
10-22 20:55:07.080: E/AndroidRuntime(1311):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at android.os.Handler.dispatchMessage(Handler.java:102)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at android.os.Looper.loop(Looper.java:136)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at android.app.ActivityThread.main(ActivityThread.java:5017)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at java.lang.reflect.Method.invokeNative(Native Method)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at java.lang.reflect.Method.invoke(Method.java:515)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at dalvik.system.NativeStart.main(Native Method)
10-22 20:55:07.080: E/AndroidRuntime(1311): Caused by: java.lang.IllegalStateException: A required meta-data tag in your app's AndroidManifest.xml does not exist.  You must have the following declaration within the <application> element:     <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
10-22 20:55:07.080: E/AndroidRuntime(1311):     at com.google.android.gms.common.GooglePlayServicesUtil.zzad(Unknown Source)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable(Unknown Source)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at com.example.gcmdemo.MainActivity.checkPlayServices(MainActivity.java:118)
10-22 20:55:07.080: E/AndroidRuntime(1311):     at com.example.gcmdemo.MainActivity.onCreate(MainActivity.java:44)

10-22 20:55:07.080: E/AndroidRuntime(1311):     at android.app.Activity.performCreate(Activity.java:5231)
    10-22 20:55:07.080: E/AndroidRuntime(1311):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    10-22 20:55:07.080: E/AndroidRuntime(1311):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
    10-22 20:55:07.080: E/AndroidRuntime(1311):     ... 11 more
    10-22 20:55:09.490: E/SoundPool(389): error loading /system/media/audio/ui/Effect_Tick.ogg
10-22 20:55:09.490: E/SoundPool(389): error loading /system/media/audio/ui/Effect_Tick.ogg
10-22 20:55:09.500: E/SoundPool(389): error loading /system/media/audio/ui/Effect_Tick.ogg
    10-22 20:55:09.500: E/SoundPool(389): error loading /system/media/audio/ui/Effect_Tick.ogg
    10-22 20:55:09.530: E/SoundPool(389): error loading /system/media/audio/ui/Effect_Tick.ogg
    10-22 20:55:09.530: E/SoundPool(389): error loading /system/media/audio/ui/KeypressStandard.ogg
    10-22 20:55:09.540: E/SoundPool(389): error loading /system/media/audio/ui/KeypressSpacebar.ogg
    10-22 20:55:09.540: E/SoundPool(389): error loading /system/media/audio/ui/KeypressDelete.ogg
    10-22 20:55:09.540: E/SoundPool(389): error loading /system/media/audio/ui/KeypressReturn.ogg
    10-22 20:55:09.540: E/SoundPool(389): error loading /system/media/audio/ui/KeypressInvalid.ogg
    10-22 20:55:19.560: E/Drm(57): Failed to open plugin directory /vendor/lib/mediadrm
    10-22 20:55:20.140: E/StrictMode(693): A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    10-22 20:55:20.140: E/StrictMode(693): java.lang.Throwable: Explicit termination method 'end' not called
    10-22 20:55:20.140: E/StrictMode(693):  at dalvik.system.CloseGuard.open(CloseGuard.java:184)
    10-22 20:55:20.140: E/StrictMode(693):  at java.util.zip.Inflater.(Inflater.java:82)
    10-22 20:55:20.140: E/StrictMode(693):  at java.util.zip.GZIPInputStream.(GZIPInputStream.java:96)
    10-22 20:55:20.140: E/StrictMode(693):  at java.util.zip.GZIPInputStream.(GZIPInputStream.java:81)
    10-22 20:55:20.140: E/StrictMode(693):  at com.android.okhttp.internal.http.HttpEngine.initContentStream(HttpEngine.java:468)
    10-22 20:55:20.140: E/StrictMode(693):  at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:666)
    10-22 20:55:20.140: E/StrictMode(693):  at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:347)
    10-22 20:55:20.140: E/StrictMode(693):  at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
    10-22 20:55:20.140: E/StrictMode(693):  at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:503)
    10-22 20:55:20.140: E/StrictMode(693):  at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:136)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.http.GoogleHttpClient.a(SourceFile:811)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.http.GoogleHttpClient.a(SourceFile:776)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.http.GoogleHttpClient.execute(SourceFile:676)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.http.GoogleHttpClient.execute(SourceFile:660)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.auth.be.j.a(SourceFile:220)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.auth.be.appcert.a.a(SourceFile:263)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.auth.be.appcert.a.a(SourceFile:132)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.auth.be.appcert.b.a(SourceFile:43)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.auth.b.b.a(SourceFile:62)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.auth.b.a.a(SourceFile:120)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.auth.b.a.a(SourceFile:61)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.auth.be.cron.AuthCronService.a(SourceFile:44)
    10-22 20:55:20.140: E/StrictMode(693):  at com.google.android.gms.gcm.al.run(SourceFile:135)

A: From your logcat, it shows that you need to do as follows:
In your Android Manifestadd the following tag as a child of the  element:
<meta-data android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

You can add the lines between </receiver> and </application> in your AndroidManifest file.


text:
Q: The inception_v1 model does not conform to the paper I am reading the code of GoogLeNet inception_v1 model here. If I understand it correctly, 5x5 convolution is included in the inception structure. But the 5x5 convolution is replaced by 3x3 convolution everywhere in the model. For example:
 end_point = 'Mixed_3b'
 with tf.variable_scope(end_point):
     with tf.variable_scope('Branch_0'):
         branch_0 = slim.conv2d(net, 64, [1, 1], scope='Conv2d_0a_1x1')
     with tf.variable_scope('Branch_1'):
         branch_1 = slim.conv2d(net, 96, [1, 1], scope='Conv2d_0a_1x1')
         branch_1 = slim.conv2d(branch_1, 128, [3, 3], scope='Conv2d_0b_3x3')
     with tf.variable_scope('Branch_2'):
         branch_2 = slim.conv2d(net, 16, [1, 1], scope='Conv2d_0a_1x1')
         branch_2 = slim.conv2d(branch_2, 32, [3, 3], scope='Conv2d_0b_3x3')
     with tf.variable_scope('Branch_3'):
         branch_3 = slim.max_pool2d(net, [3, 3], scope='MaxPool_0a_3x3')
         branch_3 = slim.conv2d(branch_3, 32, [1, 1], scope='Conv2d_0b_1x1')
     net = tf.concat(axis=3, values=[branch_0, branch_1, branch_2, branch_3])
 end_points[end_point] = net
 if final_endpoint == end_point: return net, end_points

where I think the branch_2 should be like this:
with tf.variable_scope('Branch_2'):
     branch_2 = slim.conv2d(net, 16, [1, 1], scope='Conv2d_0a_1x1')
     branch_2 = slim.conv2d(branch_2, 32, [5, 5], scope='Conv2d_0b_5x5')

I do not believe the author would make such an obvious mistake, so could somebody tell me the reason or I just have a wrong understanding?

A: It's a bug in the published repo - see https://github.com/tensorflow/models/issues/443. The published snapshot actually contains 5x5 convs. Having 3x3 convolutions instead of 5x5 convolutions makes no sense there (then two branches of the inception network would be structurally the same).


text:
Q: Azure Durable Function fails after deploying to production (Python) I have an Azure Durable Function developed using Python (plus some other related libraries). The function Has a typical architecture:
contains an HTTP trigger which invokes the orchestrator. The orchestrator invokes some Activity Functions (some activity functions contain requests-POST and GET within them) along the way. The purpose of the whole function is to receive an image and read the characters on the image (OCR) (Azure Vision OCR is used) and give the result back.
The logic is like this:
Start
Section 1: (Takes about 30secs on my local machine)

*

*Get the image

*Process it (image processing techniques)

*Send it to Azure OCR (I have an activity for this, lets call it OCRActivity)

*Get the result

*See if the result is good enough (I have some conditions for this)

*If it's good, return the result (Using a call-back activity)

*If it's not, go to section 2

Section 2: (Takes about 2mins on my local machine)

*

*Make 20 different images by applying various processing techniques to the original image

*Send those 20 images to Azure OCR using a fan-out architecture (multiple "OCRActivity" activities in parallel)

*Get the results

*Compare results with the result from Section 1 and choose the best one

*Return the result (Using a call-back activity)

End
(The whole process takes about 3-4 mins on my local machine)
The issue is, everything works as expected on my local machine (Using Azure Storage Emulator etc.) and when it is deployed into production, some requests get processed and a response is received perfectly - (typically, these are the images which return a result after Section 1 without going into Section 2). Some requests run for a long time (Almost all of them are the ones that go into Section 2 and uses the fan-out to process the 20 different images) and return a response after 40mins or so (even more in some cases). Sometimes, a response is not received at all.
The exceptions that are received are not related to my code logic but of durable-function related ones which are hard to debug. Any help would be appreciated.


text:
Q: Why is React Component render counter getting incremented by 2? I came across this when I was experimenting with react components. I have a component:
window.renderCount=1;

export function Soundscapes() {

    const soundscape = useSelector((s) => s.tasks.soundscape);
    const dispatch = useDispatch();

    const [soundscapeAudioElement, setSoundscapeAudioElement] = useState(undefined);
    useEffect(()=>{
        console.log('state just changed to: ', soundscapeAudioElement )
    },[soundscapeAudioElement])

    console.log(window.renderCount);
    window.renderCount=window.renderCount+1;

    return (<SomeJSXUnrelatedToQuestion/>)
}

In the console, I noticed that the logs are 1,3,5,7,9 on subsequent re-rendering. I expected it to print renderCount everytime it is incremented by 1 on the screen like 1,2,3,4,5, each time the component got rendered to screen. But it seems to be incrementing it, but not printing it to console everytime.
Am I missing something here?

A: You probably have StrictMode on. StrictMode will intentionally double invoke "render" and some other lifecycle methods to detect side-effects. Strict mode checks are run in development mode only; they do not impact the production build. Check the below snippet. Also, note that I have used React development CDNs.

function App() {
    const [foo, setFoo] = React.useState(false)
    const counter = React.useRef(0)
    console.log(counter.current++)
    return (
      <button onClick={() => setFoo(f => !f)} > Click </button>
     )
}

ReactDOM.render(<React.StrictMode><App /></React.StrictMode>, document.getElementById('mydiv'))


text:
Q: Docker container cannot connect to azure via MSI I have an azure function which has this code:
run = Run.get_context()
ws = Workspace.from_config('config.json',auth=MsiAuthentication()) if not hasattr(run, 'experiment') else run.experiment.workspace

This works when I test the function locally using func start
but when I build docker image for the azure function and run the docker, it gives following error:
Message: Failed to connect to MSI. Please make sure MSI is configured correctly.
      Get Token request returned http error: 400, reason: Bad Request
        InnerException None
        ErrorResponse
      {
          "error": {
              "message": "Failed to connect to MSI. Please make sure MSI is configured correctly.\nGet Token request returned http error: 400, reason: Bad Request"
          }
      }

The identity configuration for azure function has the required roles:

Or, is there any other authentication method that I should use?


text:
Q: menu Items not listed under visual studio 2017 When I log into Visual Studio 2017. I am trying to associate a test case. The option is greyed out.  Is there something I have to do before to make it enabled.? See screenshot.

A: For those who need help in future.
Solution =
  Click on Tools ==>> Options ==>> Work Items ==>
 ==>> Select the option "Compatibility Mode"
This should fix the Issue.
Thanks

A: That is an interesting workaround but the option wasn't available because VS 2017 is defaulting to MSTestV2 and this option was only available in MSTestV1.  As of Visual Studio 2017 15.7.1, this option is available without running in compatibility mode and will work for all unit test frameworks such as MSTestV2, xUnit, and NUnit test cases.  Here is some more information on this.  http://www.deliveron.com/blog/test-case-association-xunit-nunit-and-mstestv2-tests-available-visual-studio-2017-1571/


text:
Q: I am struggling to create a dictionary from a CSV file I have a CSV file, called 'scores.csv'. The format of it is like so.
Username,Score
I've tried using the code below to put the Username as a key in a dictionary, and the subsequent Score as the value, however when this code is run, and I print the dictionary, it will only print 3 random Username:Score combinations every time.
import csv
import operator

reader = csv.reader(open("scores.csv"))
d={}
for row in reader:
    d[row[0]]=row[1:]

print(d)

Does anyone have any idea how to fix this issue?

A: Using Pandas (not header in scores.csv):
import pandas as pd

df = pd.read_csv("scores.csv", header=None)
dicc= pd.Series(df[1].values,index=df[0]).to_dict()

Using csv.reader, for my works, I recommend use ".strip()":
import csv

reader = csv.reader(open("scores.csv"))
d={}
for row in reader:
    d[row[0].strip()]=row[1].strip()

print(d)


text:
Q: How to show a power series is defined? One way I can think of is using radius of convergence. Since inside the interval of convergence, the series converges, i.e. not diverges to $\pm\infty$
For example I have $\cos x=\sum^{\infty}_{n=0}\frac{(-1)^n}{(2n)!}x^{2n}$, so $a_{2k}=\frac{(-1)^k}{(2k)!}$ when $n$ is even, then $R=\lim|\frac{a_{n}}{a_{n+1}}|=\lim (2n+2)(2n+1)=\infty$, so $\cos x$ is convergent for all real numbers and therefore defined everywhere.
Is my logic correct?

A: You just use D'alembert test for numerical series.
$$\lim_{n\to+\infty}\frac { | \frac {(-1)^{n+1}x^{2n+2 }  }{  (2n+2)! }  |  }{|\frac {  (-1)^nx^{2n}}{ (2n)! }  |   }$$
$$=0$$
thus

$R=+\infty$

A: Your logic may be correct, but I cannot tell, so compare to this logic.
The ratio between two nonzero terms of the expansion is $R = \lim_{n \to \infty} \left|\displaystyle \frac{x^2}{(2n+1)(2n+2)}\right|$.
$x$ is a constant, and is the input of the function. For each $x$, as far as we are concerned when taking the limit with respect to $n$, $x$ is a constant.
Because the bottom converges to $\infty$, the ratio between two consecutive terms converges to zero.
If the ratio between terms of a power series converges to zero, then the series is convergent for all values of $x$ by the ratio test.
And if the ratio converges to a certain $R$, then the radius of convergence is $\displaystyle \frac{1}{R}$.


text:
Q: pattern matching in RewriteMap text file I am looking to do some pattern matching inside the rewrite text file using RewriteMap and it doesn't seem to work.  Below is the apache configuration.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteLog "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/logs/apache1.log"
RewriteLogLevel 5
RewriteMap lowercase int:tolower
RewriteMap escape int:escape
RewriteMap sitelevel_external "txt:C:/Program Files (x86)/Apache Software Foundation/Apache2.2/conf/html1/content/dam/redirect.txt"
RewriteCond %{REQUEST_URI} ^(.*)$
RewriteCond ${lowercase:%1} ^(.*)$
RewriteCond ${escape:%1} ^(.*)$
RewriteCond ${sitelevel_external:%1|NOT_FOUND} !NOT_FOUND
RewriteRule ^(.*) ${sitelevel_external:%1} [QSA,NC,NE,L,R=301,E=nocache:1]

The redirect.txt file contents are
^/delivery-delay.html$ http://www.yahoo.com // doesn't work
/delivery-delay.html$ http://www.yahoo.com  // doesn't work
/delivery-delay.html http://www.yahoo.com  // Works

If i use the URL http://localhost/delivery-delay.html, the redirection to yahoo only happens when the third rule is in there. Apache doesn't redirects and throws a 404 if i have the first two conditions.
Apache Logs attached

A: With a Standard Plain Text (sitelevel_external) file you cannot handle regular expression, the text file will be translated just in a key map.
RewriteMap handles different types of matches, but if you use a text file you can just look for an exact match. May be an External Rewriting Program could fit your needs, but pay attention and keep it simple,

"If this program hangs, it will cause Apache to hang when trying to
  use the relevant rewrite rule."


text:
Q: private static final double is 0 I am trying to use the following line to specify a double constant, can anybody help explain to me why at runtime this constant has a value of 0.0:
private static final double CONSTANT = 1/2;

A: The constant ends up with a value of 0.0 because the result of integer division is an integer, truncated. So your the value of your initialization is 0, not 0.5. To force a double result, make one or both of the operands a double:
private static final double CONSTANT = 1/2.0;  // or 1/2D, or even 1D/2D

A: 1 and 2 are interpreted as integers and produce integer result of division. Add D at the end to make them interpreted as doubles.
private static final double CONSTANT = 1D/2D;


text:
Q: Do I Need to Call .AcceptChanges() before .Update() After a delete Operation Hello I'm making a small database application with MS Access database. I add to database from a textbox and delete from a database using a combobox and showing the database in datagridview adding seems to work fine except for autoincrement not showing before a restart and i cant delete because when i call update after deletion it gives me a DBConcurrencyException i tried to add acceptchanges before update and that is not gave any error but the changes didn't saved to database.
Here is my two questions

*

*How to make autoincrement show without restarting application.(this is not so important i can hide ID column)

*And most importantly how to make deletes work.
additionally i use OleDbCommandBuilder for update methods

A: You have 2 queries

AutoIncrements: Please refer here which states that you should perform a select query to fill the db autogenerated values back into the dataset tables.
Regarding the deletes, just delete the row in the datatable, its rowstate will be marked as Deleted. When you update this to the DB using adapter, it will find the rows to be deleted and will perform the deletion in the db accordingly. When you call acceptchanges(), it will mark that all rows are in the original state and will result in no db updates.

EDIT
The DBConcurrency exception occurs when there is no effect of a CRUD operation. for more details refer here


text:
Q: Import excel file in sql server 2008 I know this question might be repeated. But what I get issue with this is different. I have already created table "CRM_Doctor_Budget" with no data.

I want to insert data in this table from excel file.
I am using import and export data (32-bit).
Following step I do:

Error which I am getting :
- Validating (Error)
Messages
Error 0xc0202049: Data Flow Task 1: Failure inserting into the read-only column "Id".
 (SQL Server Import and Export Wizard)

Error 0xc0202045: Data Flow Task 1: Column metadata validation failed.
 (SQL Server Import and Export Wizard)

Error 0xc004706b: Data Flow Task 1: "component "Destination - CRM_Doctor_Budget" (59)" failed validation and returned validation status "VS_ISBROKEN".
 (SQL Server Import and Export Wizard)

Error 0xc004700c: Data Flow Task 1: One or more component failed validation.
 (SQL Server Import and Export Wizard)

Error 0xc0024107: Data Flow Task 1: There were errors during task validation.
 (SQL Server Import and Export Wizard)

I am getting error in converting varchar,int,smallint,bit data type. Because excel file has general datatype for all data. And In my already created table I have varchar, int, float, smallint and bit.
After checked "Enable Identity Insert" I get less error but errors are as follow :
Copying to [dbo].[CRM_Doctor_Budget] (Error)
Messages
Error 0xc0202009: Data Flow Task 1: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80004005.
An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 10.0"  Hresult: 0x80004005  Description: "Unspecified error".
 (SQL Server Import and Export Wizard)

Error 0xc020901c: Data Flow Task 1: There was an error with input column "Id" (143) on input "Destination Input" (72). The column status returned was: "The value violated the integrity constraints for the column.".
 (SQL Server Import and Export Wizard)

Error 0xc0209029: Data Flow Task 1: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "input "Destination Input" (72)" failed because error code 0xC020907D occurred, and the error row disposition on "input "Destination Input" (72)" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.
 (SQL Server Import and Export Wizard)

Error 0xc0047022: Data Flow Task 1: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "Destination - CRM_Doctor_Budget" (59) failed with error code 0xC0209029 while processing input "Destination Input" (72). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure.
 (SQL Server Import and Export Wizard)

A: I have solved the problem. I had made some changes like:
In Edit Mapping : As I have ID as an identity column and it is auto generated column.
As previously I have mapped Id column.
Now This time I did not map ID column and make unchecked the "Enable I identity Insert"
Else I perform step as it is .. this minor change I have done and I get records import successfully. :) thank you all for helping.

A: Is the ID column an identity column?  Because if it is, you need to click the "Enable Identity Insert" checkbox to get this to work.


text:
Q: extract array value on click jQuery Trying to achieve the following with extractAssets();

*

*When clicking on .clickable extract asset (lists[i].assets) value by itself to 0 (something like lists[i].assets - lists[i].assets).

As you may see I'm not extracting but doing a .html("$0"), so a dynamic extraction would be desired.
see JSFiddle
Working fiddle example is appreciated, thank you.

var list1 = {
  id: 7,
  assets: 74651.90,
  ratePercent: 0.02,
  rateUSD: 24.03
};
var list2 = {
  id: 8,
  assets: 86735.79,
  ratePercent: -0.06,
  rateUSD: 2.41
};

var lists = [list1, list2];

$(document).ready(function() {
  show();
  extractAssets();
});

function extractAssets() {
  for (var i = 0; i < lists.length; i++) {
    //var text = $(".coin" + [i]).text();
    $(".clickable" + [i]).click(function() {
      //$(".coin" + [i]).text(text == $(this).text() - $(this).text() ? $(this).text() - $(this).text() : $(this).text());
      $(this).find(".coin").html("$0");
      //$(".coin" + [i]).text(text == $(this).text() ? "$0" : $(this).text());
    })
  }
}

function show() {
  for (var i = 0; i < lists.length; i++) {
    $(".DataContent").append('

' + lists[i].id + '

$' + lists[i].assets + '

' + lists[i].ratePercent.toFixed(2) + '% / $' + lists[i].rateUSD.toFixed(2) + '

');
  }
}

A: Seems a bit weird to me that you're using the data for reference, but using the html dom elements for operations. I hardly recommend to us a templating language. Anyways... with your actual code this is what I would update:
function extractAssets() {
    $(".clickable").click(function(){
        var currentCoin = $(this).find('.coin');
      var difference = (Number($(currentCoin).text().replace('$','')) - Number($(currentCoin).text().replace('$','')));
      $(currentCoin).html('$' + difference);
        });
}

function show() {
  for (var i = 0; i < lists.length; i++) {
    $(".DataContent").append('

' + lists[i].id + '

$' + lists[i].assets + '

' + lists[i].ratePercent.toFixed(2) + '% / $' + lists[i].rateUSD.toFixed(2) + '

');
  }
}

Keep in mind that this does not format the amount at the end.
Regards


text:
Q: ASP.NET MVC Data Annotations Regular expression works in .NET but not in JS I am trying to use the UK Post code regular expression given in this answer https://stackoverflow.com/a/164994/4950 in a RegularExpression Data Annotation for Model validation in ASP.NET MVC.
Here's the RegEx:
(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})

This works fine serverside and when tested in Regex hero (http://regexhero.net/tester/) but on the client side the regular expression does not seem to work.
I have looked at the code that the Jquery.validate.unobtrusive plugin is using:
$jQval.addMethod("regex", function (value, element, params) {
    var match;
    if (this.optional(element)) {
        return true;
    }

    match = new RegExp(params).exec(value);
    return (match && (match.index === 0) && (match[0].length === value.length));
});

and sort of replicated the same situation here: http://jsfiddle.net/cEGsj/ (I added the gi params later).
Can anyone tell me why this Regular expression is failing in JS? I thought initially it was to do with casing but adding the ignore case option does not seem to change anything.
Also doesn't seem to work here: http://regexpal.com/ So there must be some syntax issue..
Update: I have managed to get something satisfactorily working by removing the nested character sets. See working example here: http://jsfiddle.net/Asyqh/1/

A: I have managed to get something satisfactorily working by removing the nested character sets which Javascript does not seem to like. See working example here: http://jsfiddle.net/Asyqh/1/
var regex = "(GIR 0AA)|((([A-Z][0-9][0-9]?)|(([A-Z][A-Z][0-9][0-9]?)|(([A-Z][0-9][A-HJKSTUW])|([A-Z][A-Z][0-9][ABEHMNPRVWXY])))) [0-9][A-Z]{2})";


text:
Q: Problem creating a mongoose schema from a JSON file Is it possible to create this JSON file structure as a mongoose schema? mongoose doesn't offer an object type and I don't know how to implement it.
{
  "Mountainbike": {
    "Cross": {
      "size": [
        "395 mm",
        "440 mm",
        "480 mm",
        "535 mm"
      ],
      "color": [
        "Himmelblau",
        "Grasgrün",
        "Stahlgrau",
        "Weinrot"
      ],
      "brake": [
        "Shimano Deore BRM6000",
        "Shimano Deore BRM7000",
        "Shimano RX810 1x11"
      ],
}
}
}

A: In mongoose this will look like:

new mongoose.Schema({
  Mountainbike: {
     type: {
        Cross: {
          type: {
            size: [String],
            color: [String],
            brake: [String]
          }
        }
     }
   }
})


text:
Q: Normalizr – is it possible to conditionally remove an entity? So I'm using normalizr to massage some data how I see fit. However, some of the entities that are passed through normalizr are not needed by my application. Is there a way to throw out an entity using process strategy or something similar? Thanks!
const testSchema = new schema.Entity('things', {}, {
  idAttribute: thing => `${thing.id}`,
  processStrategy: (value, parent, key) => {

  if(!obj.mapping[value.fields.id]){
    // If we get in here, this entity is not needed as
    // there is no mapping available.
    // How can i throw this entity out?
  }

  return {
    ...value.fields,
    prop: obj.mapping[value.fields.id].mapped_thing,
    prop2: obj.mapping[value.fields.id].mapped_thing2,
    prop3: obj.mapping[value.fields.id].mapped_thing3
  }
 }
});

Is something like this possible? Or is there a better method to remove entities?


text:
Q: How to check if data being added to an array already exists in a different array? I am looking to create a simple script for a Google sheet in which array 1 will already be populated with a list of names. As a new name gets added to array 2, array 1 is checked for the name. If the name which was entered into array 2 is present in array 1 an action will be performed. This search function must take place each time a new name is added to array 2 to determine if it exists in array 1.
function findPlayer() {
var ss = SpreadsheetApp.getActiveSpreadsheet()

var picksRange = ss.getRange("B2:M15");
var poolRange = ss.getRange("B21:G96");

var picksPlayerName = picksRange.getValues();
var poolPlayerName = poolRange.getValues();

for (var i = 0; i < picksRange.length; i++)
for (var j = 0; j < poolRange.lenth; j++)

if (picksPlayerName[i] == poolPlayerName[j]) {
 poolPlayerName[i].setBackground("red")}
else {
 poolPlayerName[j].setBackground("blue");}
}

A: This is not a complete answer, nor does it perfectly fit your use-case, but you should be able to take it from here, or perhaps come back with another question when you have a question about a specific part of your code.
const existingNames = ["Carl", "Emma", "Sarah", "Ahmad"];
const newNames = ["Emma", "Sarah", "Isa", "Igor", "Kent"];

// go through the new names and check against existing ones
newNames.forEach(newName => {
    if(existingNames.includes(newName)) {
    // handle duplicates: do nothing?
   } else {
    // handle new names: maybe add them to the existing names?
    existingNames.push(newName);
   }
});

console.log('After going through all new names, the complete list of known names are: ' + existingNames);

Demo where you can play with the code and learn: https://jsfiddle.net/jonahe/11uom4cu/


text:
Q: Using Snappy to render LavaChart on a PDF in Laravel I am trying to use the snappy library with wkhtmltopdf to render a chart (LavaChart) on a generated PDF but I have not been able. The PDF generates fine but the chart does not show. If the view is not converted to PDF, the Chart is rendered as expected.
Below is my code for the LavaChart and Snappy.
The Chart Part
         $chart = Lava::ColumnChart('Performance', $table, [
            'title' => 'Performance Chart',
            'png' => true,
            'animation' => [
               'startup' => true,
               'easing' => 'inAndOut'
            ],
            'titleTextStyle' => [
                'fontName' => 'Arial',
                'fontColor' => 'blue'
            ],
            'legend' => [
                'position' => 'top'
            ],
            'vAxis' => [
                'title' => 'Total Score'
            ],
            'hAxis' => [
                'title' => 'Class'
            ],
            'events' => [
                'ready' => 'getImageCallback'
            ],
            'colors' => ['#3366CC','#DC2912', '#FF9900']
        ]);

The Snappy Part
    $pdf = PDF::loadView('print.charts')->setPaper('portrait');
    $pdf->setOption('enable-javascript', true);
    $pdf->setOption('javascript-delay', 10000);
    $pdf->setOption('no-stop-slow-scripts', true);
    $pdf->setOption('page-size', 'A4');
    $pdf->setOption('margin-left', 0);
    $pdf->setOption('margin-right', 0);
    $pdf->setOption('margin-top', 0);
    $pdf->setOption('margin-bottom', 0);
    $pdf->setOption('lowquality', false);
    $pdf->setTimeout(1500);
    $pdf->setOption('disable-smart-shrinking', true);

The View Part

 {!! Lava::render('ColumnChart', 'Performance', 'chart') !!}

Since the chart renders as expected when the view is not converted to pdf, I have reasons to believe the wkhtmltopdf does not execute the javascript has expected in the pdf version. I have the latest wkhtmltopdfinstalled but still no luck.
Library Version:
barryvdh/laravel-snappy: ^0.4.3
khill/lavacharts: 3.0.*

Any help will be appreciated, thanks.

A: I can show with a simple example, At first I have shown the chart on browser, The chart example is taken from Lavacharts docs(you can use yours). Keep a Note on
events with callback getImageCallback.
public function index(){
        $lava = new Lavacharts;
        $data = $lava->DataTable();

        $data->addDateColumn('Day of Month')
            ->addNumberColumn('Projected')
            ->addNumberColumn('Official');

        // Random Data For Example
        for ($a = 1; $a < 20; $a++) {
            $rowData = [
            "2020-10-$a", rand(800,1000), rand(800,1000)
            ];

            $data->addRow($rowData);
        }

        $lava->LineChart('Stocks', $data, [
            'elementId' => 'stocks-div',
            'title' => 'Stock Market Trends',
            'animation' => [
                'startup' => true,
                'easing' => 'inAndOut'
            ],
            'colors' => ['blue', '#F4C1D8'],
            'events' => [
                'ready' => 'getImageCallback'
            ]
        ]);

        return view('charts-view', ['lava' => $lava]);
    }

In view charts-view,

        <?= $lava->render('LineChart', 'Stocks', 'stocks-div'); ?>

    <form action="{{ url('export-pdf') }}" method="post">
        @csrf

            <input type="hidden" name="exportpdf" id="exportPDF">
            <button class="btn btn-info" type="submit">Export as PDF</button>

    </form>

note the function name in script must be same as the value set for ready key in events in the controller. Upto this step you have done as well. I have passed the result obtained by as a hidden input field and posted the form to the controller.You can see in the diagram button export as PDF.

The url export-pdf calls the controller function exportPdf which willfinally generate the PDF. You need to pass the image (obtained as data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB .....) to the controller to pass it to the view as image.
In exportPdf,
      public function exportPdf(Request $request){
        $imageData = $request->get('exportpdf');
        $pdf = SnappyPDF::loadView('export-pdf', ['imageData' => $imageData])->setPaper('a4')->setOrientation('portrait');
        $pdf->setOption('lowquality', false);
        $pdf->setTimeout(1500);
        $pdf->setOption('disable-smart-shrinking', true);
        return $pdf->download('stock-market.pdf');
    }

The export-pdf blade view
<!DOCTYPE html>

    <title>Stock Market</title>

Stock Market Detail

Oct 2020

The final PDF obtained looks like,


text:
Q: phpmyadmin BUG:A comma or a closing bracket was expected My PHPMyAdmin always warn me

A comma or a closing bracket was expected

when I try to use a function.
Although it displays warnings, the SQL statements can be successfully executed.
For example ,here's a piece of SQL code
    INSERT INTO payments (`amount`,`alloted`, `dateadded`, `modified`, `userid`)
    VALUES ( 100, DATE_ADD( NOW(), INTERVAL 6 MONTH),NOW(),NOW(),139107 )

When typing the function 'NOW()', the red underline comes up, it's really, REAAALYYY annoying
Same errors come up when typing all kinds of sql functions

I've tried re-installing phpmyadmin but it doesn't work at all.
This bug only occurs when I'm using ubuntu on my web server,
the warning messages never comes up when I debuggling on localhost.
here's the common error message.
Error

Static analysis:

4 errors were found during analysis.

A comma or a closing bracket was expected (near "(" at position 40)
Unexpected token. (near "'123'" at position 41)
Unexpected token. (near ")" at position 46)
Unexpected token. (near ")" at position 47)

SQL query:

INSERT INTO accounts(pw) VALUES(PASSWORD('123'))

A: *

*What version of PHPMyAdmin are you running?

*And with what version of MySQL?

You probably need to post this on the PHPMyAdmin bugs repository.
It is not a bug with the SQL processing itself; it is a bug with the new PhpMyAdmin SQL validator javasscript and its inferance of the structure of SQL queries.
SQL can be very complex (part of its attraction) so it's to be expected that there will be cases where the validator gets confused.

Also;

INSERT INTO accounts(pw) VALUES(PASSWORD('123'))

Should be:
INSERT INTO accounts(`pw`) VALUES(PASSWORD('123'))

note the backticks. PHPMyAdmin is extremely pernickerty that column names (and table names) be always backtick quoted.

A: One cause is: If you have columns/fields defined as not null, make sure that corresponding  variables in sql are not null or empty as this would prevent the insert


text:
Q: jquery function not working using jquery-layout on asp.net template conent page I am using this jQuery splitter library because on a non-master aspx web form I am able to duplicate this example and insert gridviews, ajax tabs, etc and all the other content I need no problem. But, I am unable to do the same thing using a content page from the VS2012 ASP.NET Web Forms Site template. If anyone is aware of a better splitter option that can create a layout that can incorporate asp controls with ajax, please let me know. I have tried w2ui but I can't insert asp controls. I have also been able to insert asp controls using jeasyui and dhtml-suite. But can't get any working in the content page. Thanks for any input...
link to jquery-dev demo page

and a rough idea of what I am going for is something like this:
link to complex layout using splitters

I have been reading a lot of the other answers based on applying javascript to a content page and it seems the most straightforward method is to link to the css in the content page header and reference the javascript in the content page content section. So my master page is unchanged from the template default .
Here is the code for my content page:
    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="nested_sidebars_master.aspx.cs" Inherits="layout_master_demos_nested_sidebars_master" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
    <link type="text/css" rel="stylesheet" href="css/layout-default-latest.css" />

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">

        Center

Go to the Demos page

North

South

East

West

</asp:Content>

When I run without without
   $(document).ready(function () {
        $("#container").layout();

I can at least see my divs:

But when I include the that javascript, I get nothing:

When I run a simple alert javascript like:
>         $(document).ready(function () {;
>             alert('hey!');

I get a result, so I know the javascript is running:

So, it seems something is wrong with the .layout method. If anyone can tip me off as to a good way to trouble shoot javascript (I am a newbie) that would be helpful, like writing to a label in asp.net or using a message box in C#.net.

A: Found out what I was going wrong:

*

*I needed to reference the css from the same content place holder. The was referenced at:
http://forums.asp.net/t/1581173.aspx?Jquery+UI+layout+and+Asp+net+master+page

*For some reason, it didn't accept 100% as the height in the css applied to the content container and was considering it 0. Once I changed the height to pixels, it worked.

The updated working code:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="nested_sidebars_master.aspx.cs" Inherits="layout_master_demos_nested_sidebars_master" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">
    <link type="text/css" rel="stylesheet" href="css/layout-default-latest.css"/>

Center

North

South

East

West

</asp:Content>

and the result:


text:
Q: can we pass alias name in reference on join condition in sqlserver i have following query but when i pass reference name of this alias column name it is showing invalid column name how can i do this
select OM.*,
       convert(int,Replace(Ltrim(Replace(left(OM.mstrefc,6), '0', ' ')), ' ', '0')) as partycode,
       OI.*,
       Ac.AcctName,
       Ac.acctaddr,
       UN.UnitName
from ordemst OM
  join ordeitd OI
    on OM.mstCode = OI.ItdCode
  join Account Ac
    on OM.partycode = Ac.acctcode
  left join unitdet UN
    on OI.ItdUnit = UN.unitcode and
       OI.CompCode = UN.CompCode
where OM.MstCode = 47 and
      OM.MstType =79 and
      OM.CompCode =117 and
      AC.compcode =117 and
      OI.Compcode=117

A: You can't use an alias from a select clause in a join clause.

column_alias can be used in an ORDER BY clause, but it cannot be used in a WHERE, GROUP BY, or HAVING clause

and apparently not in a join clause.
You have to replace the alias with the real thing:
join Account Ac
on convert(int,Replace(Ltrim(Replace(left(OM.mstrefc,6), '0', ' ')), ' ', '0')) = Ac.acctcode

Taken from the MSSQL Doc


text:
Q: C++ - how to push objects to std::stack of std::shared_ptr? I've got a problem with stack of shared pointers.
GameState.hpp:
class GameState : std::enable_shared_from_this<GameState>
{
public:
    virtual void update(float delta) = 0;
    virtual void render() = 0;
    virtual void handleInput() = 0;
protected:
    Game* mGame;

StatesManager.hpp:
class StatesManager
{
public:
    StatesManager();
    ~StatesManager();

    void pushState(std::shared_ptr<GameState> state);
    void changeState(std::shared_ptr<GameState> state);
    void popState();
    std::shared_ptr<GameState> peekState();
private:
    std::stack<std::shared_ptr<GameState> > mStates;
};

Here's how I'm trying to push:
statesManager.pushState(new StateSplash(this));

But that's gives me this error:
no suitable constructor exists to convert from "StateSplash *" to "std::shared_ptr<GameState>"

What's correct way of pushing object onto std::stack of std::shared_ptrs?
I want to use them, because it provides "garbage collector", which I need, because if I pop element from stack when object is C-like pointer, it doesn't call destructor.

A: Assuming that StateSplash is a child of GameState.
Your method accepts a std::shared_ptr and you are trying to pass a normal pointer into it. Your compiler does not know how to get from StateSplash * to std::shared_ptr<GameStage>.
You have to construct a std::shared_ptr by either
statesManager.pushState(std::make_shared<GameState>(this));
or
statesManager.pushState(std::shared_ptr<GameState>(new StateSplash(this)));


text:
Q: Returned aggregated result as an array : mongodb I have this function in my db.js wrapper library for mongodb:
findAllSorted: function(name, sortBy, callback) {
  db.createCollection(name, function(err, collection) {
    collection.aggregate([{$sort: sortBy}], function(err, result) {
      console.log(result); // I want to return result as an array.
    });
  });
},

I would like to return result as an array via a callback. How would I do this? For instance I invoke this function with db.findAllSorted('quotes', {unitprice: -1}, callback); which as I understand should return my list of stock quotes in highest-to-lowest unitprice descending order.
Thanks.

A: collection.aggregate(query, callback) returns the result as an array. All you need to do in the function above is call the callback. Assuming you want to let the function caller handle the error too:
findAllSorted: function(name, sortBy, callback) {
    db.createCollection(name, function(err, collection) {
        collection.aggregate([{$sort: sortBy}], function(err, result) {
            callback(err, result);
        });
    });
},


text:
Q: A form that has it's display set to none keeps on appearing when the page is opened Here is the form in the html file
<form  id="rescheduleD" action="">

 Select a date:
 <input type="date" name="choosedate">

Pick a time :
  <select name = "choosetime">
     <option>10 AM</option>
     <option>11 AM</option>
     <option>12 PM</option>
   </select>

<input type="submit" onclick="closeReschedule();" value="Reserve Vaccination">
</form>

here is the button that is supposed to make the form appear
<button type="button" value ="Reschedule" onclick="rescheduleApp();"> Reschedule</button>

here is the css for the form
#rescheduleD{
  display: none;
}

here is the javascript function connected to the button
function rescheduleApp(){
      document.getElementById('rescheduleD').style.display = 'block';

    }


text:
Q: Spring: Testing view-controllers created with ViewControllerRegistry.addViewController() This is my first time carrying out junit testing so forgive me if this is a stupid question. The class from my Spring web application which I wish to test is below. The class extends WebMcvConfigurerAdapter to add view controllers.
I just want to test if each of the view controllers maps to the correct view. In every tutorial I've looked at, the test is carried out for a controller which has it's own separate class. it wouldn't make sense for the controllers below to have their own class as there is no logic involved in them. Can anyone direct me for the way i should approach this or give sample code? Do controllers like these which only link to a view even require testing?
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("greeting");
    registry.addViewController("/portal").setViewName("portal");
    registry.addViewController("/login").setViewName("login");
}

}

A: It depends on the type of testing you are implementing. For unit testing its not necessary since you will be testing Spring internal workings. However for integration testing its necessary so that you can check if your application is wired correctly.
An example of an integration test for your view controllers could be
@RunWith(SpringJunitClassRunner.class)
@ContextConfiguration(classes = MvcConfig.class)
public class ViewControllerIT{

   @Autowired
   private WebApplicationContext wac;

   @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testLogin() throws Exception {
        this.mockMvc.perform(get("/login")
        .andExpect(status().isOk())
        .andExpect(view().name("login"));
    }
}


text:
Q: unable to open STS aft regular intervals I am working on spring tool suite.I am unable to start STS aft regular intervals say in an interval of 0ne week.STS is not getting opened.can anyone please help me to resolve this?
The log file looks like this..
org.eclipse.swt.SWTError: No more handles

A: No more handles is the issue I've seen on Win platform sometimes. SWT uses native platform widgets and hence every widget created with SWT has an OS/Platform resource backing the widget. On Windows this backend resource is called GDI handle or GDI+ handle. If these resources aren't disposed correctly by Eclipse or any other app on your platform you'll eventually get "no more handles" error.
Fixing this such that you could start STS would be to restart the machine i guess.
You can also try increasing the number of handles in Windows. (There is plenty of posts about that. Here is one: http://weblogs.asp.net/mikedopp/increasing-user-handle-and-gdi-handle-limits)
The real issue however must be an application that doesn't dispose GDI resources. For Eclipse application every SWT widget must be disposed at the end.


text:
Q: Find the start and end date of consecutive days in a column of the same index using pandas I have a data frame df:
df =

index  date        hats
A1     01-01-2020  5
A1     02-01-2020  10
A1     03-01-2020  16
A1     04-01-2020  16
A1     21-01-2020  9
A1     22-01-2020  8
A1     23-01-2020  7
A6     20-03-2020  5
A6     21-03-2020  5
A8     30-07-2020  12

Here, the first four rows are consecutive days. I want to know the start date and end date of all such consecutive days in the data frame. If there is only one day in a series like wise A8 index in the df then the start date and and end will be same. Moreover, I am also interested in knowing the highest value in df['hats'] column in the series of consecutive days and return its date in a seperate column high_hat along with its date high_hat_date. If there are two or more equal high values in a series of consecutive days then write the number of occurrence of high value in a new column num_hat, and write the first occurrence date in high_hat_date.
The example output for the above data frame is as follows:
index   start_date    end_date    high_hat    high_hat_date   num_hat
A1      01-01-2020    04-01-2020  16          03-01-2020      2
A1      21-01-2020    23-01-2020  9           21-01-2020      1
A6      20-03-2020    21-03-2020  5           20-03-2020      2
A8      30-07-2020    30-07-2020  12          30-07-2020      1

Any help in this regard is highly appreciated.

A: First using pd.to_datetime convert the date column to pandas datetime series:
df['date'] = pd.to_datetime(df['date'], dayfirst=True)

Then use:
g = df.groupby('index')['date'].diff().dt.days.ne(1).cumsum() # STEP A
m = df.groupby(['index', g])['hats'].transform('max').eq(df['hats']) # STEP B

df = df.assign(high_hats=df['hats'].mask(~m), high_date=df['date'].mask(~m)) # STEP C

dct = {'start_date': ('date', 'first'), 'end_date': ('date', 'last'), 'high_hat': ('hats', 'max'),
       'high_hat_date': ('high_date', 'first'), 'num_hats': ('high_hats', 'count')}
df1 = df.groupby(['index', g]).agg(**dct).reset_index().drop('date', 1) # STEP D

Details:
STEP A: Use DataFrame.groupby on index and use groupby.diff on date to calculate the the days elapsed between successive dates then use Series.dt.days + Series.ne along with Series.cumsum to create a grouping series g which will be needed to group the dataframe on consecutive dates.
# print(g)
0    1
1    1
2    1
3    1
4    2
5    2
6    2
7    3
8    3
9    4
Name: date, dtype: int64

STEP B: Use DataFrame.groupby on index and g and use groupby.transform to transform the column hats using max then using Series.eq equate it with hats column to create a boolean mask m.
# print(m)
0    False
1    False
2     True
3     True
4     True
5    False
6    False
7     True
8     True
9     True
Name: hats, dtype: bool

STEP C: Next use DataFrame.assign to assign two new columns high_hats and high_date which will be used in STEP D for calculation of high_hat_date and num_hats.
# print(df)
  index       date  hats  high_hats  high_date
0    A1 2020-01-01     5        NaN        NaT
1    A1 2020-01-02    10        NaN        NaT
2    A1 2020-01-03    16       16.0 2020-01-03
3    A1 2020-01-04    16       16.0 2020-01-04
4    A1 2020-01-21     9        9.0 2020-01-21
5    A1 2020-01-22     8        NaN        NaT
6    A1 2020-01-23     7        NaN        NaT
7    A6 2020-03-20     5        5.0 2020-03-20
8    A6 2020-03-21     5        5.0 2020-03-21
9    A8 2020-07-30    12       12.0 2020-07-30

STEP D: Using DataFrame.groupby on index and g and aggregate the dataframe using the aggregation dictionary dct which contains all the columns and their corresponding agg functions to be applied.
# print(df1)
  index start_date   end_date  high_hat high_hat_date  num_hats
0    A1 2020-01-01 2020-01-04        16    2020-01-03         2
1    A1 2020-01-21 2020-01-23         9    2020-01-21         1
2    A6 2020-03-20 2020-03-21         5    2020-03-20         2
3    A8 2020-07-30 2020-07-30        12    2020-07-30         1

A: This required a lot of data transformation:

*

*use np.where(), .shift and .groupby + .transform to create some intermediary columns to calculate the data ranges of the groups.

*Create an intermediary dataframe df2 to calculate some more metrics including high_hat_date and num_hat. These calculations require a focus on the max values (i.e. high hat), so it was easier to create this new dataframe this way.

*Merge df2 back into df1, take only the required columns and drop duplicate rows

code:
import pandas as pd, numpy as np
df1=df.copy()
df1['date'] = pd.to_datetime(df1['date'], dayfirst=True)
df1['date_diff'] = df1['date'] - df1.shift()['date']
df1['date_first'] = ''
df1['date_first'] = np.where((df1['date_diff'].isnull()) |
                             ((df1['date_diff'] != '1 days') & (df1.shift()['date_diff'] == '1 days')),
                              'start_date', df1['date_first'])
df1['date_first'] = np.where((df1['date_diff'] == '1 days') & (df1.shift(-1)['date_diff'] != '1 days'),
                             'end_date', df1['date_first'])
df1['date_group'] = df1.groupby(df1['date_first'])['date_first'].transform('cumcount')
df1['date_group2'] = df1.groupby(df1['date_first'])['date_group'].transform('cumsum').replace(0,np.nan).ffill().astype(int)
df1['start_date'] = df1.groupby('date_group2')['date'].transform('min')
df1['end_date'] = df1.groupby('date_group2')['date'].transform('max')
df1['high_hat'] = df1.groupby(df1['date_group2'])['hats'].transform('max')
df2 = df1.loc[df1['high_hat'] == df1['hats']]
df2['high_hat_date'] = df2.groupby('date_group2')['date'].transform('first')
df2['num_hat'] = df2.groupby('date_group2')['hats'].transform('count')
df2 = df2.drop_duplicates(subset='date_group2')
df1 = pd.merge(df1, df2[['date_group2', 'high_hat_date', 'num_hat']], how='outer', on=['date_group2'])
df1 = df1[['index', 'start_date', 'end_date', 'high_hat', 'high_hat_date', 'num_hat']].drop_duplicates()
df1

output:
    index   start_date  end_date    high_hat    high_hat_date   num_hat
0   A1      2020-01-01  2020-01-04  16          2020-01-03      2
4   A1      2020-01-21  2020-01-23  9           2020-01-21      1
7   A6      2020-03-20  2020-03-21  5           2020-03-20      2
9   A8      2020-07-30  2020-07-30  12         2020-07-30       1


text:
Q: Как еще можно сделать привязку ListView к Adarter? Пытаюсь создать динамическое добавление списка Listview. Нашла решение на java. Вроде все работает, но вот привязку сделать не получается. Пишу в Xamarin на C#, он выдает, что SetAdapter устарел. ;(
Опиралась на это решение: http://developer.alexanderklimov.ru/android/views/listview.php
A: Скорее всего Xamarin намекает вам, что вместо
myListview.SetAdapter(adapter)

Вы должны использовать синтаксис сеттера, то есть что-то вроде
myListview.Adapter = adapter;

A: @DreamChild Как-то так, получается  (http://developer.xamarin.com/releases/android/xamarin.android_4/xamarin.android_4.10/level_17_diff/mono.android.dll/)

Namespace Android.Widget

Type Changed: Android.Widget.AbsListView
Added properties:

public override IListAdapter Adapter { get; set; }

Removed methods:

public virtual void SetAdapter (IListAdapter adapter);

Added methods:

[Obsolete ("Please use the Adapter property setter")]
public virtual void SetAdapter (IListAdapter adapter);


text:
Q: In my registry I have the 4.5 .NET framework indicated as installed, but I can still patch 4.5.2 manually I was trying to patch my Windows Server 2012s through a patching service, however the 4.5.2 patch was not showing up as applicable. After some digging with the service, we figured out that the registry key was indicating we only had 4.5 installed. However, I can manually patch the 4.5.2 framework just fine with a standalone installer. Shouldn't Windows Updates find this not applicable or why would this be?

A: The Windows Update detection logic is correct. .NET 4.5 is no longer supported, so it should be expected there would be no offering. You may want to consider updating to a version that is not end of life.
https://devblogs.microsoft.com/dotnet/support-ending-for-the-net-framework-4-4-5-and-4-5-1/

A: 4.5.2 is technically a different version of .Net than 4.5 and not just a patch. So it would be correct to not be offered a patch for 4.5.2 when 4.5 is installed but still be able to update to 4.5.2 with a 4.5.2 installer.
As @greg askew has said however, 4.5 is no longer supported. I would recommend updating to 4.8 which is the current version. See https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies for the available versions and the detection registry keys.