text:
Q: Define the accuracy of transformation estimation in 3-D space I am using Umeyama's SVD method to estimate the rigid transformation between two 3-D point sets. See the code snippet below-
Eigen::Matrix4f T_svd;
const pcl::registration::TransformationEstimationSVD<pcl::PointXYZ, pcl::PointXYZ> trans_est_svd;
trans_est_svd.estimateRigidTransformation(source, target, T_svd);

Later on, the source point set was converted using above estimated transformation matrix
pcl::PointCloud<pcl::PointXYZ> target_est;
pcl::transformPointCloud(source, target_est, T_svd);

In order to calculate the accuracy of above transformation estimation, this is how I am proceeding:
import numpy as np

# target and target_est clouds were saved as csv
y = np.loadtxt(target, delimiter=',')
y_est = np.loadtxt(target_est, delimiter=',')

y_est = np.sqrt(np.sum((y_est)**2, axis=1))
y_sum = np.sqrt(np.sum((y)**2, axis=1))

acc = y_est/y_sum
mean_acc = acc.mean()

The mean accuracy from the above code is shown 1.0001, which makes me suspect about my approach.
I want to know that how to define the accuracy of transformation estimation in 3-D space.

A: Providing more insight on the answer I already gave at the pcl users forum.
Have a look at equation 1 and 2 of the Model Based Training, Detection and Pose
Estimation of Texture-Less 3D Objects in Heavily Cluttered Scenes from Hinsterstoisser et al. commonly known as LineMOD. This is a common used method for pose estimation problem with rigid objects.
Equation 1 is for non-symetric objects and 2 for symmetric ones. I can't type the expressions because Stack Overflow doens't support mathjax but the general idea is:

*

*The norm of the difference between the location where your point is estimated to be and where it actually is, summed over all points, normalized by the number of points

*The difference for the first one is that you no longer enforce you point correspondences. Each point from the source cloud,  picks the closest point on the target cloud. Then perform the sum and averaging like before.

This is not exactly a stack overflow question, it's a math exchange one.


text:
Q: Set default tab in ionic2 On my login page I am using this.nav.setRoot(TabsPage); to navigate to the 'main app'. However, this makes the first tab the default page. On the other hand, if i use this.nav.setRoot(HomePage); I get the correct page but am missing the tabs. How do I set the default tab on page switch?

A: After further googling, I found the solution in the ionic2 documents. If anyone else in the future is wondering the same thing, the solution is to add selectedIndex="X" to the <ion-tabs> tag. (http://ionicframework.com/docs/v2/api/components/tabs/Tabs/)
UPDATE for clarity:
your code will look like this for selecting the 3rd tab:
<ion-tabs selectedIndex="2">
and like this fore selecting the 2nd tab:
<ion-tabs selectedIndex="1">

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add base64 data to an image after the data loads? (In React Native) How to add base64 data to an image after the data loads? (In React Native)
I am trying to make a social media app in React Native with images in it. I am trying to download base64 data, and then use that data in an image. The problem is, I can't add the data to the image after the base64 data downloads, because you can't change the data of an image after the image has "loaded" with null data. How can I either only load/create the image after the data downloads, or add data to an image once the data downloads?
What I have tried
I've tried creating a variable for the image data, and changing that variable.
I've tried putting the URL directly into the image data.
I've tried setting the image data to {loading: './loading.png',uri: actualdata}.


text:
Q: How to receive DTMF receive during call in iOS? I am new in linphone. Anyone can guide me how to receive dtmf during call in
iOS. I puted method this in LinphoneCoreVTable.
.dtmf_received = linphone_iphone_notify_dtmf_received.
But when this method call I don't know.

A: you have to implement function which get called when dtmf is received.
Interface of function is following:
/**
 * Callback for being notified of DTMFs received.
 * @param lc the linphone core
 * @param call the call that received the dtmf
 * @param dtmf the ascii code of the dtmf
 */
typedef void (*LinphoneCoreCbsDtmfReceivedCb)(LinphoneCore* lc, LinphoneCall *call, int dtmf);

Is a same as for call state change:
VTable
.call_state_changed = (LinphoneCoreCallStateChangedCb)linphone_iphone_call_state,

Interface
/**
 * Call state notification callback.
 * @param lc the LinphoneCore
 * @param call the call object whose state is changed.
 * @param cstate the new state of the call
 * @param message a non NULL informational message about the state.
 */
typedef void (*LinphoneCoreCbsCallStateChangedCb)(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState cstate, const char *message);

And method
static void linphone_iphone_call_state(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState state, const char *message) {
    [(__bridge LinphoneManager *)linphone_core_get_user_data(lc) onCall:call StateChanged:state withMessage:message];
}


text:
Q: Parse json fields to variables I'm trying to parse fields of a json output from an API query.
Example json:
{
   "_id":"611a7b651571d300074b9875",
   "Details":{
      "Source":{
         "Type":"WHOIS servers",
         "URL":"http://tiktea.com.au",
         "NetworkType":"ClearWeb"
      },
      "Type":"Phishing",
      "SubType":"RegisteredSuspiciousDomain",
      "Severity":"Medium"
   },
   "Assignees":[

   ],
   "FoundDate":"2021-08-16T14:51:17.747Z",
   "Assets":[
      {
         "Type":"Domains",
         "Value":"iktea.net"
      }
   ],
   "TakedownStatus":"NotSent",
   "IsFlagged":false,
   "Closed":{
      "IsClosed":false
   }
}

I want to parse some fields, and get something like:
URL: http://tiktea.com.au
FoundDate: 2021-08-16T14:51:17.747Z"

so I tried this, but didn't work: Selecting fields from JSON output
This is my python code:
import requests
import json

#UserID + Api Key
auth = ('USERID','APIKEY')
headers = {    'Content-Type': "application/json",    }

url = "https://api.intsights.com/public/v1/data/alerts/alerts-list?alertType=Phishing
alerts = requests.request("GET", url, auth = auth, headers=headers)

for alertID in alerts.text.split('","'):
  url = "https://api.intsights.com/public/v1/data/alerts/get-alert/"+alertID #<-----This is the request that extract the JSON
  alertDetails = requests.request("GET", url, auth = auth, headers=headers)

  dict = alertDetails.text
  url=dict['Assets'][0]['Value'] #<---------Trying to parse the desired value
  print(url)

This is the result:
Traceback (most recent call last):
  File "cefexample.py", line 73, in <module>
    url=dict['Assets'][0]['Value']
TypeError: string indices must be integers

Any suggestion?

A: First you need to parse the JSON that comes as response.
data = alertDetails.json() # use convenience method

Then access fields you want like a nested dict.
url = data['Details']['Source'].get('URL')
print (f'Phishing URL: {url}')
found_date = data.get('FoundDate')
print(f'Found date: {found_date}')

This assumes (based on error you show) that Deatails and Source will always be present, ony URL key may be missing. To be on the safe side you can do
url = data.get('Details', {}).get('Source', {}).get('URL')
print (f'Phishing URL: {url}')

or use try/except:
try:
    url = data['Details']['Source']['URL']
except KeyError:
    url = None
print (f'Phishing URL: {url}')


text:
Q: Some help needed with pseudocode in LaTeX Hello trying to writte pseudocode in Latex
I cant fix mistake in line 8
code:
\begin{algorithm} \caption{Učící mechanismus všech obcí}
\begin{algorithmic}[1]
\While {Obce ještě nedokonvergovaly}
\State t=t+1
\ForEach {KNIES_p $\in$ Population}
\For{$X_i$ $\in$ Zařazené body}
\State KNIES_p.\quad \textbf{Learn}($X_i$, $\beta_t = \frac{t\beta_T}{T}$)
\EndFor
\If{KNIES_p {$\qaq$} KNIES}
\State KNIES(t) = KNIES_p
\end{algorithmic}
\end{algorithm}

A: You have many errors, mostly due to improper treatment of math symbols.
There is no predefined \ForEach block, you have to define it yourself.
Supply a definition for \qaq, that's not a standard command.
\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[czech]{babel}

\usepackage{algorithm,algpseudocode}

\algblockx{ForEach}{EndForEach}{\textbf{foreach} }{\textbf{end foreach}}
\newcommand{\ivar}[1]{\mathit{#1}}
\newcommand{\tvar}[1]{\textrm{#1}}

\newcommand{\qaq}{???} % what's this?

\begin{document}

\begin{algorithm} \caption{Učící mechanismus všech obcí}
\begin{algorithmic}[1]
\While {Obce ještě nedokonvergovaly}
  \State $t=t+1$
  \ForEach {$\ivar{KNIES}_p \in \tvar{Population}$}
    \For{$X_i\in\tvar{Zařazené body}$}
      \State $\ivar{KNIES}_p$.\quad
             \textbf{Learn}($X_i$, $\beta_t = \frac{t\beta_T}{T}$)
    \EndFor
  \EndForEach
  \If{$\ivar{KNIES}_p \qaq \ivar{KNIES}$}
    \State $\ivar{KNIES}(t) = \ivar{KNIES}_p$
  \EndIf
\EndWhile
\end{algorithmic}
\end{algorithm}

\end{document}


text:
Q: Calculating the sub total from a list of check boxes in vb.net Hello I have written the following codes to handle the selection of check boxes in a form. the grand total should be incremented based on the slections and then displayed. Would someone please help me on how to ago about with this. Here is how I am processing the selections and trying to calculate the grand total.
    Private Sub computeCurrentSelection()
    If chkugalis.Checked = True Then 'ugali fish selected
        orderAmt = lab.Text
        total = ugalif * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " plates of" & " Ugali n fish " & " Kshs" & total)
    End If

    If chkGitheri.Checked = True Then 'ugali dengu slected
        orderAmt = lab3.Text
        total = ugalid * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " plates of " & "Ugali n dengu " & " Kshs" & total)
    End If
    If chkUgaliB.Checked = True Then 'githeri selected
        orderAmt = lab2.Text
        total = githeri * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " plates of " & "Githeri " & " Kshs" & total)
    End If
    If chkPilau.Checked = True Then
        orderAmt = lab4.Text
        total = chapo * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " plates of " & "Pilau " & " Kshs" & total)
    End If
    If chkPizza.Checked = True Then
        orderAmt = lab5.Text
        total = pilau * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " plates of " & "Pizza " & " Kshs" & total)
    End If
    If chkMandazi.Checked = True Then
        orderAmt = lab6.Text
        total = pizza * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & "mandazi " & " Kshs" & total)
    End If
    If chkSamosa.Checked = True Then
        orderAmt = lab7.Text
        total = mandazi * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & "Samosa " & " Kshs" & total)
    End If
    If chkChapon.Checked = True Then
        orderAmt = lab8.Text
        total = samosa * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & "Chapati " & " Kshs" & total)
    End If
    If chkWater.Checked = True And chk300ml.Checked = True Then
        orderAmt = lab9.Text
        total = water1 * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " Bottles of 300ml Water " & " Kshs" & total)
    End If
    If chkWater.Checked = True And chk500ml.Checked = True Then
        orderAmt = lab9.Text
        total = water2 * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " Bottles of 500ml Water " & " Kshs" & total)
    ElseIf chkWater.Checked = True And chk1l.Checked = True Then
        orderAmt = lab9.Text
        total = water3 * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " Bottles of 1l Water " & " Kshs" & total)
    End If
    If chkWater.Checked = True And chk2l.Checked = True Then
        orderAmt = lab9.Text
        total = water4 * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " Bottles of 2l Water " & " Kshs" & total)
    End If
    If chkSoda.Checked = True And chk300ml.Checked = True Then
        orderAmt = lab10.Text
        total = soda1 * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " Bottles of 300ml Soda " & " Kshs" & total)
    End If
    If chkSoda.Checked = True And chk500ml.Checked = True Then
        orderAmt = lab10.Text
        total = soda2 * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " Bottles of 500ml Soda " & " Kshs" & total)
    End If
    If chkSoda.Checked = True And chk1l.Checked = True Then
        orderAmt = lab10.Text
        total = soda3 * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " Bottles of 1l Soda " & " Kshs" & total)
    End If
    If chkSoda.Checked = True And chk2l.Checked = True Then
        orderAmt = lab10.Text
        total = soda4 * orderAmt
        lstReceipt.Items.Add(orderAmt & " Bottles of 2l Soda " & " Kshs" & total)
    End If
    If chkJuice.Checked = True And chk300ml.Checked = True Then
        orderAmt = lab11.Text
        total = juice1 * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " Bottles of 300ml juice " & " Kshs" & total)
    End If
    If chkJuice.Checked = True And chk500ml.Checked = True Then
        orderAmt = lab11.Text
        total = juice2 * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " Bottles of 500ml juice " & " Kshs" & total)
    End If
    If chkJuice.Checked = True And chk1l.Checked = True Then
        orderAmt = lab11.Text
        total = juice3 * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " Bottles of 1l juice " & " Kshs" & total)
    End If
    If chkJuice.Checked = True And chk2l.Checked = True Then
        orderAmt = lab11.Text
        total = juice4 * orderAmt
        subtotal = total
        lstReceipt.Items.Add(orderAmt & " Bottles of 2l juice " & " Kshs" & total)
    End If
End Sub

A: I'm not sure if I understood correctly but I will give it a go.
Try this:
Private Function ComputeCurrentSelection() As Integer ' not sure for data type, you decide
    Dim total As Integer
    If chkugalis.Checked = True Then 'ugali fish selected
        orderAmt = lab.Text
        total += ugalif * orderAmt
        lstReceipt.Items.Add(orderAmt & " plates of" & " Ugali n fish " & " Kshs" & total)
    End If

    If chkGitheri.Checked = True Then 'ugali dengu slected
        orderAmt = lab3.Text
        total += ugalid * orderAmt
        lstReceipt.Items.Add(orderAmt & " plates of " & "Ugali n dengu " & " Kshs" & total)
    End If
    If chkUgaliB.Checked = True Then 'githeri selected
        orderAmt = lab2.Text
        total += githeri * orderAmt
        lstReceipt.Items.Add(orderAmt & " plates of " & "Githeri " & " Kshs" & total)
    End If ...

    Return total
End Function

A: I have tried this
      Private Sub computeCurrentSelection()
    If chkugalis.Checked = True Then 'ugali fish selected
        orderAmt = lab.Text
        total = ugalif * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " plates of" & " Ugali n fish " & " Kshs" & total)
    End If

    If chkGitheri.Checked = True Then 'ugali dengu slected
        orderAmt = lab3.Text
        total = ugalid * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " plates of " & "Ugali n dengu " & " Kshs" & total)
    End If
    If chkUgaliB.Checked = True Then 'githeri selected
        orderAmt = lab2.Text
        total = githeri * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " plates of " & "Githeri " & " Kshs" & total)
    End If
    If chkPilau.Checked = True Then
        orderAmt = lab4.Text
        total = chapo * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " plates of " & "Pilau " & " Kshs" & total)
    End If
    If chkPizza.Checked = True Then
        orderAmt = lab5.Text
        total = pilau * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " plates of " & "Pizza " & " Kshs" & total)
    End If
    If chkMandazi.Checked = True Then
        orderAmt = lab6.Text
        total = pizza * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & "mandazi " & " Kshs" & total)
    End If
    If chkSamosa.Checked = True Then
        orderAmt = lab7.Text
        total = mandazi * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & "Samosa " & " Kshs" & total)
    End If
    If chkChapon.Checked = True Then
        orderAmt = lab8.Text
        total = samosa * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & "Chapati " & " Kshs" & total)
    End If
    If chkWater.Checked = True And chk300ml.Checked = True Then
        orderAmt = lab9.Text
        total = water1 * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " Bottles of 300ml Water " & " Kshs" & total)
    End If
    If chkWater.Checked = True And chk500ml.Checked = True Then
        orderAmt = lab9.Text
        total = water2 * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " Bottles of 500ml Water " & " Kshs" & total)
    ElseIf chkWater.Checked = True And chk1l.Checked = True Then
        orderAmt = lab9.Text
        total = water3 * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " Bottles of 1l Water " & " Kshs" & total)
    End If
    If chkWater.Checked = True And chk2l.Checked = True Then
        orderAmt = lab9.Text
        total = water4 * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " Bottles of 2l Water " & " Kshs" & total)
    End If
    If chkSoda.Checked = True And chk300ml.Checked = True Then
        orderAmt = lab10.Text
        total = soda1 * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " Bottles of 300ml Soda " & " Kshs" & total)
    End If
    If chkSoda.Checked = True And chk500ml.Checked = True Then
        orderAmt = lab10.Text
        total = soda2 * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " Bottles of 500ml Soda " & " Kshs" & total)
    End If
    If chkSoda.Checked = True And chk1l.Checked = True Then
        orderAmt = lab10.Text
        total = soda3 * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " Bottles of 1l Soda " & " Kshs" & total)
    End If
    If chkSoda.Checked = True And chk2l.Checked = True Then
        orderAmt = lab10.Text
        total += soda4 * orderAmt
        lstReceipt.Items.Add(orderAmt & " Bottles of 2l Soda " & " Kshs" & total)
    End If
    If chkJuice.Checked = True And chk300ml.Checked = True Then
        orderAmt = lab11.Text
        total = juice1 * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " Bottles of 300ml juice " & " Kshs" & total)
    End If
    If chkJuice.Checked = True And chk500ml.Checked = True Then
        orderAmt = lab11.Text
        total = juice2 * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " Bottles of 500ml juice " & " Kshs" & total)
    End If
    If chkJuice.Checked = True And chk1l.Checked = True Then
        orderAmt = lab11.Text
        total = juice3 * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " Bottles of 1l juice " & " Kshs" & total)
    End If
    If chkJuice.Checked = True And chk2l.Checked = True Then
        orderAmt = lab11.Text
        total = juice4 * orderAmt
        subtotal += total
        lstReceipt.Items.Add(orderAmt & " Bottles of 2l juice " & " Kshs" & total)
    End If
End Sub

and it has worked but it computes and stores the subtotal thus updating it wherever I call computeCurrentSelection(), for example if on the first call the subtotal was 10, try clearing the previous total and updating it like this
    Private Sub updateTotal()
    lstTotal.Items.Clear()
    lstTotal.Items.Add("Sub Total =" & subtotal)
End Sub

the clearing does not work but instead keeps on incrementing the current value of the sub total by the previous one until I refresh the program.
How can I solve that?


text:
Q: Is it possible to pin the input window in Web Chat at the end (Microsoft Bot Framework)? i am building a Chatbot using the Microsoft Bot Framework.
Currently i am working on the design of the webchat (Webchat V4 -> https://github.com/microsoft/BotFramework-WebChat)
I have noticed, however, that with every new message the input window is moved further down and I have to scroll down to write another message.
Now to my question: Is it possible that you can pin the input window at the bottom and only the chat scrolls?
-

A: Yes you can, you can pin it using CSS. Just reference the webchat class in your CSS and you can customise it. Below is an excerpt from something I've implemented in Office Fabric UI panel.
#webchat {
  margin: 0 auto;
  clear: both;
  padding: 0 10px;
  position: fixed;
  bottom: 0;
  top: 38px;
  padding-bottom: 53px;
  max-width: 87%;
  max-height: 90%;

}

You also have the built in styling options as well, which are really useful

*

*https://bisser.io/bot-framework-v4-webchat-styling-options/

*https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-webchat-customization?view=azure-bot-service-4.0


text:
Q: Internet Explorer 10 canvas clipping unexpected behavior In an html5 canvas application I use clipping to redraw damaged parts of the canvas like so:
ctx.beginPath();
ctx.rect(30, 30, 100, 100);
ctx.rect(100, 100, 100, 100);
ctx.clip();
ctx.clearRect(0, 0, 600, 400);

I also created a fiddle which illustrates the problem. On every capable browser except IE10 it will display two black overlapping rectangles.
Now the question is whether this is a IE10 bug or because it adheres to the standards more closely it is actually expected behavior and just luck that it works in every other browser. If so, what would be the correct way of doing this?

A: one possible circumvention of this obvious IE10 bug is to clear the rectangles one by one. one advantage: its faster as it doesn't require setting a clip

A: You need to call ctx.fill(); at the end

A: This is a bug in IE10. I posted a similar issue here:
https://connect.microsoft.com/IE/feedback/details/782736/canvas-clearrect-fails-with-non-rectangular-yet-simple-clipping-paths
MS says, "Yeah its a bug. Wait several years for us to fix it." Too bad for MS all the other browsers work now.


text:
Q: What is the manifold structure of smooth path on infinite dimensional manifolds? What is the manifold structure of smooth path on infinite dimensional manifolds?
In the the paper "manifolds of smooth maps by Michor", it was mentioned that it is possible to put manifold structure on
$C^{\infty}(M,N)$ for some infinite dimensional manifolds N but there is no more information. I could not find much information if M is infinite dimensioanl.
After some search I have got impression that they could be diffeology space (which is new to me) and if I am not mistaken they are not manifold.

A: Peter Michor may have been referring to the theory of infinite dimensional differential geometry expounded in his book with Andreas Kriegl The Convenient Setting of Global Analysis, which considers such spaces.


text:
Q: Managed Identity in B2B scenario across different subscription? Can managed identity be configured for accessing Azure resources across different Azure subscriptions?
Could you point me out in right direction, isn't Azure federation supposed to take care of this?
Seems not feasible based on my R & D as well.
Do I seem to be overestimating this Azure AD feature.
Accounts in any organizational directory?

A: Based on your and my comment:

*

*Comment Question: is those subscriptions on same Azure AD tenants?

*Comment Answer: No. Thinks of all together different Business Org. Different subscription

My Answer to your question is:
Managed identities exist in the Azure AD tenant as service principals. It is therefore can only be assigned access to any subscription connected to that Azure AD tenant.
So in short, if the subscriptions are connected to different Azure AD tenants, it wont be possible to achieve what you are asking about as far as I know.
EDIT
In addition to your comment
Comment: Can managed identity be used if all tenants were in same subscription?
My answer is: Each subscription can only belong to one tenant. please check Microsoft doc https://learn.microsoft.com/en-us/microsoft-365/enterprise/subscriptions-licenses-accounts-and-tenants-for-microsoft-cloud-offerings?view=o365-worldwide

Note: if this is feasible by one or other way and there are answer that can show the opposite of my experience and knowledge, I will be glad to know that as well.


text:
Q: Use character code in regex for JS with slashes notation I can replace a character in JS with this code:
str = str.replace(new RegExp('\u{92}', 'g'), `'`);

But it does not work with the "slashes" notation:
str = str.replace(/\u{92}/g, `'`);

I mean, nothing is replaced. Did I miss something?

A: (From Pointy comments)  :
str = str.replace(/\u0092/g, `'`);

works.


text:
Q: Incoherence in the biblatex package I apologize in advance if these questions have been asked and answered before.  I have trouble with biblatex package and I am very confused about it.
In short, here is a minimal code that I am trying to achieve.
\documentclass[11pt,twoside]{book}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{biblatex}
\usepackage[english]{babel}
\usepackage{biblatex}

 \addbibresource{Reference1.bib}

\begin{document}

Lorem \cite{RuizHerrera1993b},
ipsum \cite{Bibitemmr1880658Niculescu2001b}

\printbibliography
\end{document}

With the following reference
@Article{RuizHerrera1993b,
  author    = {Ruiz-Herrera, Alfonso},
  journal   = {Discrete & Continuous Dynamical Systems - A},
  title     = {Chaos in delay differential equations with applications in population dynamics},
  year      = {1993},
  number    = {4},
  pages     = {1633-1644},
  volume    = {33},
  address   = {Boston, MA, USA},
  date      = {1993},
  doi       = {10.3934/dcds.2013.33.1633},
  publisher = {American Institute of Mathematical Sciences (AIMS)},
}

@Article{Bibitemmr1880658Niculescu2001b,
  author    = {Bibitem{mr1880658} Niculescu, , S.-I and {it}, journal = {Delay Effects on Stability}; Lecture Notes in Control and Information Sciences},
  year      = {2001},
  pages     = {269},
  address   = {London, UK},
  date      = {2001},
  publisher = {Springer},
}

@Article{Bibitemmr1433374Shampineb,
  author = {Bibitem{mr1433374} Shampine, L and Reichelt, M},
  title  = {The MATLAB ODE suite. {em SIAM}, journal = {J. Sci. Comput.} {bf}, date = {1997}, year = {1997}, pages = {1--22}, volume = {18}, doi = {10.1137/S1064827594276424}},
}

When I enter this into winedt console i receive an error message:
No file Question.bbl.
Package biblatex Info: Reference section=0 on input line 10.
Package biblatex Info: Reference segment=0 on input line 10.

LaTeX Warning: Citation 'RuizHerrera1993b' on page 1 undefined on input line 13
.

LaTeX Warning: Citation 'Bibitemmr1880658Niculescu2001b' on page 1 undefined on
 input line 14

I tried to solve the problem but I haven't been able to resolve it so far.
I apologise in advance if the question isn't that clear.
Any help would be immensely apreciated!!!


text:
Q: Javafx - change Theme (CSS) on active window I want a Button that allows me to switch between Dark/Light-mode.
But I have the problem If I switch, the active windows will not change their Style.
First of the Code snippets to easy recreate the problem.
For Maven projects starter class:
package testapp;

//This Class is Required in mavenproject to Start the Application

public class GUIStarter {
    public static void main(final String[] args) {
        try{
            TestApp.main(args);
        }catch (Exception e){
            System.out.println("GUIStarter Errror:\n"+e);
        }
    }
}

The primary Window class:
public class TestApp extends Application {
    //stylepaths
    public static String mainLightModePath = ".\\style_lightmode.css";
    public static String mainDarkModePath = ".\\style-Darkmode.css";
    public static boolean isItDarkmode = true;

    public static void toggleMode(){
        if(isItDarkmode){
            isItDarkmode  = false;
        }else if(!isItDarkmode){
            isItDarkmode = true;
        }

    }

    //This is required to get the primary Stage in other Stages (Controllers)
    private static Stage pStage;

    public static Stage getPrimaryStage() {
        return pStage;
    }

    private void setPrimaryStage(Stage pStage) {
        TestApp.pStage = pStage;
    }

    public void setPrimaryWindow(Stage primaryStage){

        try{
            FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Mainframe.fxml"));

            Parent root = (Parent) fxmlLoader.load();
            Scene scene = new Scene(root);

            primaryStage.setTitle("TestApp");

            //scene.setMoveControl(titleBar);
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch (Exception e){
            e.printStackTrace();
        }

    }

    //Start of Application
    @Override
    public void start(Stage primaryStage) {
        setPrimaryStage(primaryStage);
        pStage = primaryStage;
        setPrimaryWindow(primaryStage);
    }

    public static void main(String[] args) {
        launch(args);
    }
}

The maincontroller Class:
public class Mainframe {
        public static Timeline time;

        @FXML
        public void options(ActionEvent event){
            try{
                TestApp.toggleMode();
                Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();
                Stage changer = TestApp.getPrimaryStage();
                stage.close();
                changer.hide();
                //My idea was to initialize again and load the styles in that way again but does not change anything
                FXMLLoader loader = new FXMLLoader(getClass().getResource("Mainframe.fxml"));
                loader.load();
                Mainframe ctrl = loader.getController();
                ctrl.initialize();
                changer.show();

            }catch (Exception e) {
                System.out.println("Error bei der App Klicken von ModeButton. \n error is: "+e);
            e.printStackTrace();
            }
        }

    @FXML
    public BorderPane primaryparent;

    //get and set for elements
    @FXML
    void initialize() {
        //Check Theme
        if(TestApp.isItDarkmode){
            primaryparent.getStylesheets().clear();
            primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainDarkModePath).toString());
        }else if(!TestApp.isItDarkmode){
            primaryparent.getStylesheets().clear();
            primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainLightModePath).toString());
        }
    }

}

Mainframe.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.text.Font?>

<BorderPane fx:id="primaryparent" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="0.0" minWidth="0.0" prefHeight="224.0" prefWidth="515.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="testapp.Mainframe">

      <AnchorPane prefHeight="200.0" prefWidth="200.0" styleClass="rootBackground" BorderPane.alignment="CENTER">
         <children>
            <Button fx:id="setDarkModeButton" layoutX="175.0" layoutY="99.0" mnemonicParsing="false" onAction="#options" styleClass="settingsButton" text="toggle Dark/LightMode">

               <padding>
                  <Insets bottom="5.0" left="17.0" right="17.0" top="5.0" />
               </padding>
            </Button>
         </children>
      </AnchorPane>

</BorderPane>

Before I just overwrote the "style.css" file and used .stop() & .show(). This worked fine. But it can get complicated the more css-files you have and after it is packed into a .jar file it doesn't work anymore.
I hope anyone can help me. Because now I have really no Idea...
UPDATE:
I want to control it from another controller:
package testapp;
public class Mainframe {
        public static Timeline time;

        @FXML Button setDarkModeButton;

        @FXML
        public void options(ActionEvent event){
            try{
                try{
                    Stage secSTAGE = new Stage();
                    FXMLLoader fxmlLoader = new FXMLLoader(TestApp.class.getResource("Mainframe2.fxml"));
                    Parent root = (Parent) fxmlLoader.load();
                    Scene scene = new Scene(root);

                    secSTAGE.setTitle("TestAppw2");

                    //scene.setMoveControl(titleBar);
                    secSTAGE.setScene(scene);
                    secSTAGE.show();
                } catch (Exception e){
                    e.printStackTrace();
                }

            }catch (Exception e) {
                System.out.println("Error bei der App Klicken von ModeButton. \n error is: "+e);
            e.printStackTrace();
            }
        }

    @FXML
    public BorderPane primaryparent;

    //get and set for elements
    @FXML
    void initialize() {
        //Check Theme
        if(TestApp.isItDarkmode){
            primaryparent.getStylesheets().clear();
            primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainDarkModePath).toString());
            primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainLightModePath).toString());
        }
    }

}

public class Mainframe2 {
        public static Timeline time;

        @FXML Button setDarkModeButton;

        @FXML
        public void options(ActionEvent event){
            try{
                TestApp.toggleMode();
                Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();

                FXMLLoader loader = new FXMLLoader(getClass().getResource("Mainframe.fxml"));
                Parent root = (Parent) loader.load();
                Mainframe ctrl = loader.getController();

                //setDarkModeButton.getStylesheets().set(0, "style_lightmode.css");
                if(TestApp.isItDarkmode){
                    root.getStylesheets().set(0, Mainframe.class.getResource(TestApp.mainDarkModePath).toString());
                }else{
                    root.getStylesheets().set(0, Mainframe.class.getResource(TestApp.mainLightModePath).toString());
                }
            }catch (Exception e) {
                System.out.println("Error bei der App Klicken von ModeButton. \n error is: "+e);
            e.printStackTrace();
            }
        }

    @FXML
    public BorderPane primaryparent;

    //get and set for elements
    @FXML
    void initialize() {
        //Check Theme
        if(TestApp.isItDarkmode){
            primaryparent.getStylesheets().clear();
            primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainDarkModePath).toString());

        }else if(!TestApp.isItDarkmode){
            primaryparent.getStylesheets().clear();
            primaryparent.getStylesheets().add(getClass().getResource(TestApp.mainLightModePath).toString());
        }
    }

}

A: Css file can be changed on the run without reloading or setting a new stage
replacing the styleSheet with set()  method for observableList

App.java
public class App extends Application {

    @Override
    public void start(Stage stage) {

        Button button = new Button("change");
        button.setOnAction(e ->button.getScene().getStylesheets().set(0, "1.css"));

        Button button1 = new Button("default");
        button1.setOnAction(e ->button.getScene().getStylesheets().set(0, "0.css"));
        HBox hBox = new HBox(button,button1);

        AnchorPane anchorPane =new AnchorPane(hBox);
        anchorPane.getStyleClass().add("pane");

        var scene = new Scene(anchorPane, 640, 480);
        scene.getStylesheets().add("0.css");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

}

0.css
.pane{
    -fx-background-color:cyan;

}

1.css
.pane{
    -fx-background-color:orange;

    }

A: Seen that kind of nobody is interested in my question.
It is not what I wanted but as long as nobody has a better solution:
You can close the old stage and create a new one with the new Theme-style.
So in the TestApp.class the setPrimaryWindow() method must be set public and static. So you can't use .getClass() and the pStage must be set to the new Stage in the setPrimaryWindow():
public static void setPrimaryWindow(Stage primaryStage){

    try{
        pStage = primaryStage;
        FXMLLoader fxmlLoader = new FXMLLoader(TestApp.class.getResource("Mainframe.fxml"));

        Parent root = (Parent) fxmlLoader.load();
        Scene scene = new Scene(root);

        primaryStage.setTitle("TestApp");

        //scene.setMoveControl(titleBar);
        primaryStage.setScene(scene);
        primaryStage.show();
    } catch (Exception e){
        e.printStackTrace();
    }

}

@Override
public void start(Stage primaryStage) {
    setPrimaryStage(primaryStage);
    setPrimaryWindow(primaryStage);
}

In the options maincontroller.class you just close() the old window and call setPrimaryWindow():
@FXML
public void options(ActionEvent event){
    try{
        TestApp.toggleMode();
        Stage stage = (Stage) ((Node)event.getSource()).getScene().getWindow();
        Stage changer = TestApp.getPrimaryStage();
        stage.close();
        changer.close();

        //create new Window on Theme switch
        Stage nStage = new Stage();
        TestApp.setPrimaryWindow(nStage);

    }catch (Exception e) {
        System.out.println("Error bei der App Klicken von ModeButton. \n error is: "+e);
    e.printStackTrace();
    }
}


text:
Q: disable-gpu-vsync flag: initially > 300 FPS, but FPS goes back to 60 after touch a UI element or window resize I am trying to run the CefSharp.WinForms.Example with no VSync on.
In CefEamples.cs, method Init() I have added:
            settings.CefCommandLineArgs.Add("disable-gpu-vsync", "disable-gpu-vsync");
The VSync is turned off in the NVidia control panel.
I'm using http://www.vsynctester.com to test the VSync.
All goes well (FPS is roughly 300 FPS), until I touch an element of the UI (eg click on the Tear helper or resize the window), then the FPS goes back to the default 60FPS!
Question: what can i do to avoid this?


text:
Q: postfix: automatically save emails as eml or msg in a separate folder For my business activity I have a very simple Debian + Postfix + Dovecot mail server.

*

*Mails are saved under /var/mail/ in an MBox file.

*procmail is not installed.

*For spam filtering I have a mail gateway - scrollout on a virtual machine.

*Mail users are Linux users, so there is no mysql or database connection.

What I want is that a specific account's emails will be stored in a format like eml or msg in a folder on my NAS. This is useful for me for several reasons.
I know that this will be done through Procmail... but I don't know the right way.

A: This particular user could have a simple .procmailrc which specifies
DEFAULT=/path/to/your/NAS/dir

but as indicated in comments, I don't think Procmail is really necessary or useful here.
(Specifying a directory just tells Procmail to save a unique file in the directory.  Add a trailing slash to make Procmail deliver to a Maildir with the customary new, tmp, and cur subdirectories; or a trailing slash and a dot to have the next available numbered file à la MH.  See procmailrc(5) for details.)


text:
Q: Write a C# code to return a string with case of every letter reversed Do we have any proper function in C# to do it?
 private void button1_Click(object sender, EventArgs e)
 {
     string s1 = textBox1.Text;
 }

A: string s1 = new string(
    textBox1.Text.Select(ch => char.IsLetter(ch) ? (char.IsUpper(ch) ?
                      char.ToLower(ch) : char.ToUpper(ch)) : ch).ToArray());

A: public string RevString()
{
    var s = "TestThisString";
    StringBuilder sb = new StringBuilder();
    var arr = s.ToCharArray();

    foreach (var c in arr)
    {
        if (c.ToString() == c.ToString().ToLower())
        { sb.Append(c.ToString().ToUpper());}
        else
        { sb.Append(c.ToString().ToLower()); }
    }
    return sb.ToString();
}


text:
Q: Why do my accelerometers respond so slowly? I'm asking them at 50Hz / 50 times per second for data. When I suddenly flip the device on the x-axis by 90 degrees while the device was flat on a table with display facing up bevore, the values move pretty slowly to the "target" value for that position.
Now the weird thing is: If I increase the measurement-rate, the value will move faster to that new value upon suddenly flipping the device by 90 degrees. But if I just ask once per second for the new value, it take's very long until the value reaches the target. What can be the reason for this?
I don't do any kind of data aggregation, and don't accumulate anything. I just do some simple filtering to get rid of the noise. My method looks like this:
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    // Use a basic low-pass filter to only keep the gravity in the accelerometer values for the X and Y axes
    // accelerationX is an instance variable
    accelerationX = acceleration.x * 0.05 + accelerationX * (1.0 - 0.05);

    // round
    int i = accelerationX * 100;
    float clippedAccelerationValue = i;
    clippedAccelerationValue /= 100;

    [self moveViews:clippedAccelerationValue];
}

later on, in my -moveViews: method, I do this:
-(IBAction)moveSceneForPseudo3D:(float)accelerationValue {
    if(fabs(lastAccelerationValue - accelerationValue) > 0.02) { // some little treshold to prevent flickering when it lays on a table
        float viewAccelerationOffset = accelerationValue * 19 * -1;

        newXPos = initialViewOrigin + viewAccelerationOffset;
        myView.frame = CGRectMake(newXPos, myView.frame.origin.y, myView.frame.size.width, myView.frame.size.height);

        lastAccelerationValue = accelerationValue;
    }
}

As a result, of the device gets turned 90 degrees on the x-achsis, or 180 degrees, the view just moves pretty slowly to it's target position. I don't know if that's because of the physics of the accelerometers, or if it's a bug in my filtering code. I only know that there are fast paced games where the accelerometers are used for steering, so I almost can't imagine that's a hardware problem.

A: This line:
accelerationX = acceleration.x * 0.05 + accelerationX * (1.0 - 0.05);

is a low-pass filter, which works by computing a moving average of the x acceleration.  In other words, each time that callback is called, you're only moving the accelerationX by 5% towards the new accelerometer value.  That's why it takes many iterations before accelerationX reflects the new orientation.
What you should do is increase the 0.05 value, to say 0.2.  I'd make a global #define and play around with different values along with different refresh rates.


text:
Q: Disable/Hide the Filter ability in the Options Dialog in netbeans Does anybody know how to Disable/Hide the Filter ability in Options Dialog in Netbeans applucation development.

A: The NetBeans Options Dialog and SPI does not support removing the Quick Search panel (as of version 1.43). I came to this conclusion by reading the source code of the OptionsPanel. The quick search panel is always added to the dialog.


text:
Q: Discord.py Embed not sending I have this Cog, but it's not sending the embed, I even tried with embeds, but its only sending the first text and I'm not sure why.
from discord.ext import commands

class HelpCommand(commands.Cog):
def __init__(self, client):
    self.client = client

@commands.Cog.listener()
async def on_ready(self):
    print("Test Ready")

@commands.command(aliases=["h"])
async def command(self, ctx):
    await ctx.send(f'Please wait')
    embed = discord.Embed(title="Help for the bot",
                          description="", color=discord.Colour.purple())
    embed.set_footer(icon_url=ctx.author.avatar_url,
                     text=f"Requested by {ctx.author.name}")
    await ctx.send(embed=embed)
async def setup(client):
    await client.add_cog(HelpCommand(client))

A: You should be getting an error for this so you probably didn't configure logging properly, but avatar_url was removed in 2.0.
Migration guide: https://discordpy.readthedocs.io/en/stable/migrating.html#asset-redesign-and-changes

Member.avatar_url (replaced by Member.avatar)

*

*this new attribute may now be None

This now returns an Asset, and if you look at the docs for that you'll see that it has a url attribute. Note that you won't be able to access it if the avatar is None, so you'll have to check that first.


text:
Q: Estimating when it's done in excel Can I, somehow, based on time stamp and how much is done, estimate time and date for when a job is complete? I got this log that a bot I've made writes in column A time [yyy-mm-dd hh:mm], and in column B it wrights how much is done. It sorts it all with newest on top.

A: Consider:

In this example the time span is 1 hour and the percent complete in the time span is 78%Cell C1 contains:
=100-B1

the percent remaining to be done.
In cell D1 is the formula:
=(A1-A2)/B1

D1 yields the time required to complete 1%
Finally in E1:
=D1*C1

the time required to complete the work!(Note...C1,D1,E1 can be combined into a single formula)
EDIT#1
The formats of E1 and D1 were picked to display the relevent parts of the dataThe format  of D1,E1 is:   mm-dd hh:mm:ss.00
Change this format to suit your needs!

A: Gary's answer is correct, but for convenience if the 2nd row of data can be an arbitrary progress status (not just start of task = implicitly 0%), and if you use percentage number format (or decimals) and you would like to get the end date instead of just the duration, use following formula:
=A1+(A1-A2)/(B1-B2)*(1-B1)


text:
Q: How to Integrate react-native to iOS with separate folders. (Not inside react root directory).? I already have a project on iOS and Android. I would like to implement some new features in react-native. I have done integration in sample apps as well and its working like a charm.
But my doubt is, this is working when I have iOS and Android code in react root directory. when I move the iOS and Android in a separate folder unable to install pod in ios. Getting error in "use_native_modules".
Working Folder Structure

But I need

I have changed the path in Podfile pointing to the react directory. When I use
require_relative '../ReactNative/node_modules/@react-native-community/cli-platform-ios/native_modules
use_native_modules!

I am unable to install the pods. getting
[!] Invalid `Podfile` file: [!] /usr/local/bin/node -e try {console.log(require('@react-native-community/cli').bin);} catch (e) {console.log(require('react-native/cli').bin);}

internal/modules/cjs/loader.js:1032
 throw err;
 ^

Error: Cannot find module 'react-native/cli'
Require stack:
- /Users/user/Documents/Sample ReactNative Projects/SeperateFolders/iOS/[eval]
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1029:15)
    at Function.Module._load (internal/modules/cjs/loader.js:898:27)
    at Module.require (internal/modules/cjs/loader.js:1089:19)
    at require (internal/modules/cjs/helpers.js:73:18)
    at [eval]:1:87
    at Script.runInThisContext (vm.js:131:18)
    at Object.runInThisContext (vm.js:295:38)
    at Object.<anonymous> ([eval]-wrapper:10:26)
    at Module._compile (internal/modules/cjs/loader.js:1200:30)
    at evalScript (internal/process/execution.js:98:25) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/user/Documents/Sample ReactNative Projects/SeperateFolders/iOS/[eval]'
  ]
}
.

 #  from /Users/user/Documents/Sample ReactNative Projects/SeperateFolders/iOS/Podfile:48
 #  -------------------------------------------
 #
 >    use_native_modules!
 #
 #  -------------------------------------------

Also when I comment those 2 lines in pod file auto-linked pods are not getting installed.
Is there any way to achieve this?
or Is this the structure we need to follow?
Kindly help.
Thanks in advance.

A: Try executing pod install in React directory with flag --project-directory
In your case based on provided image of directory structure.
cd React/
pod install --project-directory=../iOS


text:
Q: Conversion failed when converting the varchar value 'COL' to data type int Estou tentando cadastrar um projeto em uma determinada área, porem toda vez que tento cadastrar ele retorna uma exceção.
Exceção:

An exception of type
  'System.Data.Entity.Infrastructure.DbUpdateException' occurred in
  EntityFramework.dll but was not handled in user code
Conversion failed when converting the varchar value 'COL' to data type
  int.

Meu controller:
// GET: Projeto/Create
public ActionResult Create()
    {
      ViewBag.proArea = new SelectList(db.tblArea, "areIdArea", "areArea");
      return View();
    }

// POST: Projeto/Create
   [HttpPost]
   [ValidateAntiForgeryToken]
   public ActionResult Create([Bind(Include = "proIdProjeto,proNome,proArea")] tblProjeto tblProjeto)
   {
     if (ModelState.IsValid)
      {
         db.tblProjeto.Add(tblProjeto);
         db.SaveChanges();
         return RedirectToAction("Index");
      }

      ViewBag.proArea = new SelectList(db.tblArea, "areIdArea", "areArea", tblProjeto.proArea);
        return View(tblProjeto);
     }

Minha Classe:
public partial class tblProjeto
    {

        [Key]
        public int proIdProjeto { get; set; }
        [Required(ErrorMessage = "Inform o nome deo projeto")]
        [Display(Name = "Nome")]
        public string proNome { get; set; }
        [Required(ErrorMessage = "informe a area")]
        [Display(Name = "Area")]
        public Nullable<int> proArea { get; set; }

        public virtual tblArea tblArea { get; set; }
     }

Eu realmente não sei como arrumar, pesquisei por aqui, mas não encontrei nenhum exemplo que chegasse próximo da minha necessidade.
Gostaria de saber por que fica dando esta exceção e como posso arruma-la?
Peço a ajuda de vcs e me desculpe caso algo esteja errado.

A: Na sua View, o campo onde está sendo preenchido com 'COL' no Visual Studio pode estar como string, mas ao mandar o comando para inserir no banco, ha um conflito de tipos, provavelmente no banco esta como int... Ou se estiver mandando como FK, você deve estar passando o value ao invés do ID.
Verifique as tipagem dos dados, se caso precisar mandar para a View de uma outra forma, crie uma ViewModel assim você pode fazer, de grosso modo, do jeito que quiser...


text:
Q: Group By Day and Section SQL I want to get sale stats day by day and count which section sold how much.
I'm really confused about "EVERYTHING".
$em = $this->getEntityManager()->getConnection();

$stmt = $em->prepare("
        SELECT
            COUNT(o.id) AS `all`,
            (
              SELECT COUNT(id) FROM order_panoramic_orders WHERE DAY(created_at) = DAY(NOW()) AND status_id NOT IN (7,9)
            ) AS `day`
        FROM
          order_panoramic_orders as o
        WHERE
         status_id NOT IN (7,9)
        ");

I can get daily stats but i have no idea how to deal with section seperation.
The results must be as much as like this:

Day: 1 - Total: 10 - Section1: 3, Section2: 5, Section3: 2

Any idea?
By th way;
Section and user tables are seperated.
I have to join these two tables, i guess.
First table: orders
Second table: users
Third table: sections

A: Strange query.  Your query should just be conditional aggregation.  No subquery is needed:
SELECT COUNT(*) AS `all`,
       SUM(DAY(created_at) = DAY(NOW())) as day
FROM order_panoramic_orders o
WHERE status_id NOT IN (7, 9);

Then, you can get sections using the same idea:
SELECT COUNT(*) AS `all`,
       SUM(DAY(created_at) = DAY(NOW())) as day,
       SUM(section = 1) as section1,
       SUM(section = 2) as section2,
       SUM(section = 3) as section3
FROM order_panoramic_orders o
WHERE status_id NOT IN (7, 9);


text:
Q: Copy tabs of similar partial name to another workbook Would appreciate if there's any help anywhere. Let's say, I have the following tabs: Data Set 001, Data Set 002, Data Set 003, so long the tab names contain Data Set, it should copy over to another workbook (let's say Main File). Any help with regards to this is welcomed. Thanks all in advance!
Best Regards,
Josh

A: Did you have a go at any code?
Sub Whatever()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = Workbooks("AnyOpenWorkbookName.xlsx")
For Each ws In ThisWorkbook.Sheets
    If ws.Name Like "Data Set" & "*" Then
        Call ws.Copy(after:=wb.Sheets(wb.Sheets.Count))
    End If
Next ws
End Sub

A: You need to loop through all Worksheets of your 1st Workbook, test if its name contains Data set with Worksheet.Name and InStr.
If the InStr function returns something else than 0 (meaning your Worksheet name contains Data Set), you can copy the current Worksheet to the 2nd Workbook.
Adapt this sample to your needs:
'Loop through all worksheets

If InStr(wsCurrent.Name,"Data Set") <> 0 Then
    ' Copy wsCurrent to new WorkBook
End If

' End of loop

A: I used this in Workbook containing worksheet, "ASSESSMENT FORMxx":
Sub CopyWorksheetsToNewWorkbook()

'This macro is to be in the ActiveWorkbook

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Dim wb As Workbook
Dim ws As Worksheet

Set wb = Workbooks.Add
wb.SaveAs Filename:="Book10" & ".xlsx"
Workbooks.Open ("Book10.xlsx")

For Each ws In Workbooks("ActiveWorkbookName.xlsm").Sheets
If ws.Name Like ("ASSESSMENT FORM*") Then ws.Copy Before:=Workbooks("Book10.xlsx").Worksheets("Sheet1")
Next ws

Workbooks("Book10.xlsx").Worksheets("Sheet1").Move Before:=Workbooks("Book10.xlsx").Sheets(1)

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub

Note that both workbook with worksheet "ASSESSMENT FORMxx" and Book10.xlsx must be open.


text:
Q: How do I convert a float to a string that is nested inside a hash, and then puts? I'm new to ruby. I have successfully printed "title" using puts in this code below, thats pulling from the data of "inventory".
hash["inventory"].each do |key|
  puts key["title"]
end

However, when I try to do the same for the "price" it's not printing to STDOUT. I don't know if the problem is because it's a float, or because it's in a different array. My code is as follows:
puts "#{key["price"]}"

Any insight would be greatly appreciated.

Data
{
  "inventory": [{
    "title": "ProductOne",
    "description": "This is a description for product one",
    "brand": "ProductBrandName",
    "stock": 30,
    "full-price": "24.99",
    "purchases": [{
      "channel": "online",
      "date": "2011-12-31T23:59:59+00:00",
      "price": 15.99,
      "shipping": 0.0,
      "currency": "USD",
      "user": {
        "name": "John Brown",
        "state": "KY"
      }
    }, {
      "channel": "online",
      "date": "2012-12-31T23:59:59+00:00",
      "price": 18.99,
      "shipping": 7.50,
      "currency": "USD",
      "user": {
        "name": "Jack Black",
        "state": "NY"
      }
    }]
  }]
}

A: Firstly, proper indentation (note necessarily what I've used below) will help you understand the object's structure.
h = { inventory: [
        {
          title: "ProductOne",
          description: "This is a description for product one",
          brand: "ProductBrandName",
          stock: 30,
          "full-price": "24.99",
          purchases: [
            {
              channel: "online",
              date: "2011-12-31T23:59:59+00:00",
              price: 15.99,
              shipping: 0.0,
              currency: "USD",
              user: { name: "John Brown", state: "KY" }
            },
            {
              channel: "online",
              date: "2012-12-31T23:59:59+00:00",
              price: 18.99,
              shipping: 7.50,
              currency: "USD",
              user: { name: "Jack Black", state: "NY" }
            }
          ]
        }
      ]
    }

We can print the prices as follows:
h[:inventory].first[:purchases].each { |g| puts g[:price] }
15.99
18.99

Let's go through the calculations.
a = h[:inventory]
  #=> [
  #     { :title=>"ProductOne", :description=>"This is a description for product one",
  #       :brand=>"ProductBrandName", :stock=>30, :"full-price"=>"24.99",
  #       :purchases=>[{ :channel=>"online", :date=>"2011-12-31T23:59:59+00:00",
  #                      :price=>15.99, :shipping=>0.0, :currency=>"USD",
  #                      :user=>{:name=>"John Brown", :state=>"KY"}
  #                    },
  #                    { :channel=>"online", :date=>"2012-12-31T23:59:59+00:00",
  #                      :price=>18.99, :shipping=>7.5, :currency=>"USD",
  #                      :user=>{:name=>"Jack Black", :state=>"NY"}
  #                    }
  #                   ]
  #     }
  #   ]

As you see, a is an array containing one element, a hash. To obtain that hash we select the first element of a.
b = a.first
  #=> { :title=>"ProductOne", :description=>"This is a description for product one",
  #     :brand=>"ProductBrandName", :stock=>30, :"full-price"=>"24.99",
  #     :purchases=>[{ :channel=>"online", :date=>"2011-12-31T23:59:59+00:00",
  #                    :price=>15.99, :shipping=>0.0, :currency=>"USD",
  #                    :user=>{:name=>"John Brown", :state=>"KY"}
  #                  },
  #                  { :channel=>"online", :date=>"2012-12-31T23:59:59+00:00",
  #                    :price=>18.99, :shipping=>7.5, :currency=>"USD",
  #                    :user=>{:name=>"Jack Black", :state=>"NY"}
  #                  }
  #                 ]
  #   }

Next we want the value of the key :purchases in the hash b.
c = b[:purchases]
  #=> [
  #    { :channel=>"online", :date=>"2011-12-31T23:59:59+00:00",
  #      :price=>15.99, :shipping=>0.0, :currency=>"USD",
  #      :user=>{ :name=>"John Brown", :state=>"KY" }
  #    },
  #    { :channel=>"online", :date=>"2012-12-31T23:59:59+00:00",
  #      :price=>18.99, :shipping=>7.5, :currency=>"USD",
  #      :user=>{:name=>"Jack Black", :state=>"NY" }
  #    }
  #   ]

Since each of the three elements of c is a hash with key :price, we can print the values of that keys by looping through the hashes:
c.each { |g| puts g[:price] }
15.99
18.99

Note that:
{ "a": 1 }
  #=> {:a=>1}
{ a: 1 }
  #=> {:a=>1}

This shows you that the double quotes are unnecessary, but that's only when the symbol comprises a single word. Consider this:
{ full price: "24.99" }
  #=>SyntaxError:...
{ full-price: "24.99" }
  #=>SyntaxError:...

Here we need the quotes:
{ "full price": "24.99" }
  #=> {:"full price"=>"24.99"}
{ "full-price": "24.99" }
  #=> {:"full-price"=>"24.99"}

A: In ["inventory"].each do |key|, key is just a normal string, not the inventory you expected.
inventory seems like json, first you need to use JSON.parse(a string)/JSON.load(or file) to convert it to json object in ruby, then you can use each to traverse the object.

A: DATA
require 'json'

hash = JSON.parse <<EOS
{
  "inventory": [{
    "title": "ProductOne",
    "description": "This is a description for product one",
    "brand": "ProductBrandName",
    "stock": 30,
    "full-price": "24.99",
    "purchases": [{
      "channel": "online",
      "date": "2011-12-31T23:59:59+00:00",
      "price": 15.99,
      "shipping": 0.0,
      "currency": "USD",
      "user": {
        "name": "John Brown",
        "state": "KY"
      }
    }, {
      "channel": "online",
      "date": "2012-12-31T23:59:59+00:00",
      "price": 18.99,
      "shipping": 7.50,
      "currency": "USD",
      "user": {
        "name": "Jack Black",
        "state": "NY"
      }
    }]
  }]
}
EOS

ANSWER
Here are two ways to access price:
1) Use exact hash address to access nested value:
hash['inventory'].each do |k|
  puts k['title']
  puts k['purchases'][0]['price']
  puts k['purchases'][1]['price']
end

# ProductOne
# 15.99
# 18.99

2) Loop through child nodes:
hash['inventory'].each do |k|
  puts k['title']

  k['purchases'].each do |x|
    puts x['price']
  end
end

# ProductOne
# 15.99
# 18.99


text:
Q: Name in one2many field form does not same with name in input field I have created a related field on the custom payroll form and I use odoo 10. I can not get the same name in one2many form field with input field.
I have attached picture in below. Hope in here, I want to make the name in black pen same with the name in blue pen. But in the picture, I can't get the name from blue pen show in the black pen.

Here my code :
gaji.py
  emp_id = fields.Many2one('karyawan', 'Karyawan')

karyawan.py
  nama = fields.Char(string="Nama Karyawan")
  gaji_ids = fields.One2many('gaji', 'emp_id', 'Gaji')

karyawan_view.xml
   <page string="Gaji" name="gaji">
                        <field name="gaji_ids" context="{'default_emp_id':nama}" widget="one2many_list">
                            <tree editable="bottom">
                                <field name="emp_id" attrs="{'readonly': [('emp_id', '!=', False)]}"/>
                                <field name="gaji_pokok"/>
                                <field name="jumlah_hari_kerja"/>
                                <field name="jumlah_kerja"/>
                                <field name="libur"/>
                                <field name="jam_lembur"/>
                                <field name="t_lembur"/>
                                <field name="t_transportasi"/>
                                <field name="total_pendapatan"/>
                            </tree>
                        </field>
                    </page>

Anyone can help me about this?

A: You have two different field labels:
emp_id = fields.Many2one('karyawan', 'Karyawan')  # second parameter is the label

and
nama = fields.Char(string="Nama Karyawan")  # string parameter is the label

So change one of the two.

A: Rename field name nama to name in karyawan.py
karyawan.py
name = fields.Char(string="Nama Karyawan")

In many2one field, the system will fetch value of name field in a comodel. If field name doesn't exist will display model name with id (karyawan,2).
Hope it will help you.

A: add this in your model
 _rec_name= 'nama'

nama = fields.Char(string="Nama Karyawan")
  gaji_ids = fields.One2many('gaji', 'emp_id', 'Gaji')


text:
Q: Python: Copy files with specific extension in a tree of directory I need to copy files with extension of .jpg from a folder tree.
The folder tree is like this:
-folder_A
    -folder_1
        -1.txt
        -1.jpg
    -folder_2
        -2.txt
        -2.jpg
    -folder_3
        -3.txt
        -4.jpg
-folder_B

How can I copy all the x.jpg to folder_B?
i.e. All the files are the same in folder_A, and in folder_B, files are 1.jpg, 2.jpg...

A: Have a look at the python os module.
import os
import shutil as sh

root_path = "./folder_A"
dest_path = "./folder_B"

for dirpath, dnames, fnames in os.walk(root_path):
    for f in fnames:
        if f.endswith(".jpg"):
            source_file_path =  os.path.join(dirpath, f)
            dest_file_path   =  os.path.join(dest_path, f)
            sh.copyfile(source_file_path, dest_file_path)

A: Or if you know your OS you can just execute the according shell-command.
(But I think the solution of @stellasia is cleaner)
Example (Linux):
import os

os.system('cp -r folder_A/*/*.jpg folder_B/')


text:
Q: When referenced by name,where is the name stored? For example, after we define a variable:
int a=2;

we can use "a" as 2 afterwards.
At the time when I first learned c/c++, I took it for granted.
But after I have learned the concept of "pointer" and the address of variables, I am confused.
If int* p=&i;, where "i" is an int. I know that p have the address of i, so we can use *p to get the value of i. But if we go further, how is "p" accessed? It seemed that p must be referenced by name,right?
By now, to access a variable via its address seems more natural to me and easier to understand.
But now , I'm a confused about the mechanism when using the most simple way to access a variable.
As in the case of int a=2; , where is the name "a" stored?
Why if we use "a", it is equivalent to the behavior of accessing the memory where the "a" or the "2" is stored?

A: Here a is just a symbolic name. If it's a local variable, it ain't stored anywhere. Compiler simply uses it during the compilation phase, referencing the actual value (which can be on the stack or in register), then discards.
If you looked at the assembly generated by compiler, you'd notice that a isn't appearing there (or maybe in comments). Compiler will fit your variable somewhere, and just use that location afterwards (like the eax register on x86).
If you looked at an LLVM assembly (which is quite interesting), you'd notice that the compiler just treats your variables as @1, @2, @3...
On the other hand, if a would be a global variable (and a non-static one), the name would actually be used in the symbol table to reference the variable. But it'd be the other way around — variable would be placed somewhere without the name, and the symbol table would map that name to the location so that other programs could find it.

As a side note: if the program is compiled with debug data, the name a is stored there so that the debugger could display it to help you understanding what's happening.

A: This is called abstraction. How and where a is stored is deliberately not specified. The compiler will take care of it for you.
In practice, if a is a local variable inside of a function, it will be store in the stack-frame of that function at the time of the call. The layout of the stack-frame is determined at compile time, and does not change after that. In effect, the compiler will generate a relative address for a (relative to the start of the stack-frame), that will be converted to an absolute address at the time the function is actually executed, and the starting-address of the stack-frame is known.

A: All symbols like "a" and "p" will be converted to addresses after the compiling and linking process. The symbols are just for the functions to use them by name. It's like a tag for the memory address. Even though "p" holds the address of "a", the pointer "p" is also changed to an address by the compiler.


text:
Q: unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal' I am trying to calculate the subtotal, VAT and Total for creating an invoice. I`ve got an error
unsupported operand type(s) for *: 'NoneType' and 'decimal.Decimal'

models.py
class InvoiceLine(models.Model):

    TAX_RATE = (
        (0, '20% (VAT on Expenses)'),
        (1, '5% (VAT on Expenses)'),
        (2, 'EC Aquisitions (20%)'),
        (3, 'EC Aquisitions (Zero Rated)'),
        (4, 'Exempt Expenses'),
        (5, 'No VAT'),
        (6, 'Reverse Charge Expenses (20%)'),
        (7, 'Zero Rated Expenses'),
    )

    invoice = models.ForeignKey(Invoice,related_name="has_lines",on_delete=models.CASCADE, blank=True, null=True, unique=False)
    invoice_item = models.CharField(max_length=100, verbose_name="Line")
    tax_rate = models.IntegerField(choices=TAX_RATE,default=0, blank=True, null=True)
    total = models.CharField(max_length=250, null=True, blank=True)
    description = models.CharField(max_length=100, blank=True, null=True)
    unit_price_excl_tax = models.DecimalField(max_digits=8,decimal_places=2, null=True, blank=True)
    quantity = models.DecimalField(max_digits=8,decimal_places=2,default=1, null=True, blank=True)
    unit_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True)
    vat = models.CharField(max_length=250, null=True, blank=True)

    def subtotal(self):
        subtotal = Decimal(str(self.unit_price * self.quantity))
        return subtotal.quantize(Decimal('0.01'))

    def __unicode__(self):
        return self.description

subtotal will calculate the unit price X quantity but give me an unsupported operand type error.
Then, I`ll have the total_lines and VAT by adding 20%.
Can I just calculate them using?
def total(self):
    total = Decimal(str(self.subtotal * (self.tax_rate/100)+ (self.tax_rate/100)))
    return total.quantize(Decimal('0.01'))

A: The error says you are using a * operation where the first number is actually not a number, but None.
Since the last one is just a suggestion I assume the error will be on the first time you use it, when you calculate the subtotal.
def subtotal(self):
    subtotal = Decimal(str(self.unit_price * self.quantity))
    return subtotal.quantize(Decimal('0.01'))

And this would mean that unit_price is not set, thus is None.
You can do different things to avoid the error. You can either define a default value for the unit_price field:
class InvoiceLine(models.Model):

    TAX_RATE = (
        (0, '20% (VAT on Expenses)'),
        (1, '5% (VAT on Expenses)'),
        (2, 'EC Aquisitions (20%)'),
        (3, 'EC Aquisitions (Zero Rated)'),
        (4, 'Exempt Expenses'),
        (5, 'No VAT'),
        (6, 'Reverse Charge Expenses (20%)'),
        (7, 'Zero Rated Expenses'),
    )

    invoice = models.ForeignKey(Invoice,related_name="has_lines",on_delete=models.CASCADE, blank=True, null=True, unique=False)
    invoice_item = models.CharField(max_length=100, verbose_name="Line")
    tax_rate = models.IntegerField(choices=TAX_RATE,default=0, blank=True, null=True)
    total = models.CharField(max_length=250, null=True, blank=True)
    description = models.CharField(max_length=100, blank=True, null=True)
    unit_price_excl_tax = models.DecimalField(max_digits=8,decimal_places=2, null=True, blank=True)
    quantity = models.DecimalField(max_digits=8,decimal_places=2,default=1, null=True, blank=True)
    unit_price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True, default=0)
    vat = models.CharField(max_length=250, null=True, blank=True)

You can also prevent the null value to happen if you don't allow null values at the database level:
class InvoiceLine(models.Model):

    TAX_RATE = (
        (0, '20% (VAT on Expenses)'),
        (1, '5% (VAT on Expenses)'),
        (2, 'EC Aquisitions (20%)'),
        (3, 'EC Aquisitions (Zero Rated)'),
        (4, 'Exempt Expenses'),
        (5, 'No VAT'),
        (6, 'Reverse Charge Expenses (20%)'),
        (7, 'Zero Rated Expenses'),
    )

    invoice = models.ForeignKey(Invoice,related_name="has_lines",on_delete=models.CASCADE, blank=True, null=True, unique=False)
    invoice_item = models.CharField(max_length=100, verbose_name="Line")
    tax_rate = models.IntegerField(choices=TAX_RATE,default=0, blank=True, null=True)
    total = models.CharField(max_length=250, null=True, blank=True)
    description = models.CharField(max_length=100, blank=True, null=True)
    unit_price_excl_tax = models.DecimalField(max_digits=8,decimal_places=2, null=True, blank=True)
    quantity = models.DecimalField(max_digits=8,decimal_places=2,default=1, null=True, blank=True)
    unit_price = models.DecimalField(max_digits=8, decimal_places=2, null=False, blank=False)
    vat = models.CharField(max_length=250, null=True, blank=True)

Or, you could leave this part untouched and do a check on you subtotal calculation:
def subtotal(self):
    if self.unit_price and self.quantity:
        subtotal = Decimal(str(self.unit_price * self.quantity))
        return subtotal.quantize(Decimal('0.01'))
    else:
        return None


text:
Q: PHP XPath to return parent nodes based on 'child' values Is it possible to run just a single query to replace multiple queries?
 //host_info[hostname="localhost" and vulnerability_id="remote_execution"][1]
 //host_info[hostname="localhost" and vulnerability_id="remote_execution"][1]/@exclude
 //host_info[hostname="localhost" and vulnerability_id="remote_execution"][1]/../problem[1]
 //host_info[hostname="localhost" and vulnerability_id="remote_execution"][1]/../reference[1]
 //host_info[hostname="localhost" and vulnerability_id="remote_execution"][1]/../impact[1]
 //host_info[hostname="localhost" and vulnerability_id="remote_execution"][1]/../background[1]
 //host_info[hostname="localhost" and vulnerability_id="remote_execution"][1]/../resolution[1]

For some reason this doesn't work in PHP's xpath() function.
//host_info[hostname="localhost" and vulnerability_id="remote_execution"]/(*, ../background, ../impact, ../problem)

I feel there has to be a better way here.  Please note it's possible to have multiple <host_info> nodes which is why I'm targeting the hostname and vulnerability_id.  But there are only one <background>, <resolution> nodes contained in the parent <vulnerability_id> node.
<report>
<vulnerability>
   <host_info>
      <hostname></hostname>
      <vulnerability_id></vulnerability_id>
   </host_info>
   <host_info>
      <hostname></hostname>
      <vulnerability_id></vulnerability_id>
   </host_info>
   <background></background>
   <resolution></resolution>
</vulnerability>
<vulnerability>
   <host_info></host_info>
   <host_info></host_info>
   <host_info></host_info>
   <host_info></host_info>
   <background></background>
   <resolution></resolution>
</vulnerability>
</report>

A: A node list has only a single dimension, so it is not really useful to serialize details of multiple items into a single list.
Typically you would use one Xpath expression to identify your list nodes and then DOM methods and relative expressions to fetch data related to these nodes:
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMxpath($document);

foreach ($xpath->evaluate('//host_info[hostname="localhost" and vulnerability_id="remote_execution"]') as $hostInfo) {
    var_dump(
      [
          $hostInfo->getAttribute('exclude'),
          $xpath->evaluate('string(parent::*/background)', $hostInfo),
          $xpath->evaluate('string(parent::*/resolution)', $hostInfo)
        ]
    );
}

For a single item it is possible to fetch all the detail nodes into a single result list. However an expression like that will get complex fast and you then have to add logic that recognizes the different detail nodes.
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMxpath($document);

$expression = <<<'XPATH'
//host_info[hostname="localhost" and vulnerability_id="remote_execution"][1]/@exclude|
(//host_info[hostname="localhost" and vulnerability_id="remote_execution"][1]/parent::*/background)[1]|
(//host_info[hostname="localhost" and vulnerability_id="remote_execution"][1]/parent::*/resolution)[1]
XPATH;

foreach ($xpath->evaluate($expression) as $detail) {
    var_dump(
       $detail->localName, $detail->textContent
    );
}


text:
Q: partial loop in zend framework I am trying to print some products using partial loops in Zend Framework. I am using this code in my view:
echo $this->partialLoop()->setObjectKey('product') >partialLoop('/_loops/singleProduct.phtml', $this->last_products);

It works, but I don't know how to use that parameter $this->last_products. I tried in singleProduct.php this code:
echo $this->product['name'];

but I've got an error:
Notice: Key "product" does not exist in /usr/share/php/libzend-framework-php/Zend/View/Abstract.php on line 270
Actually, what I am triyng to write is $this->last_products['name'], but because I have partialLoop()->setObjectKey('product') I tought this is how it works. What am I doing wrong?
Thank you!

A: You can write it using $this->name


text:
Q: Mariadb Galera Cluster Cannot Start Up I built a mariadb galera cluster on CentOS7. Below is the galera node information:
10.200.67.27    MariaDB-Node1
10.200.67.29    MariaDB-Node2
10.200.67.26    MariaDB-Node3

However, MariaDB-Node2 and MariaDB-Node3 were unexpected stopped.  I tried to restart mysql service on the two servers, but they didn't start up. Then I removed the wsrep_on=1 setting and restart mysql on MariaDB-Node2, it shows error as below:
[xiaofang@sd-vm-0003929 ~]$ sudo systemctl start mysql
[xiaofang@sd-vm-0003929 ~]$
[xiaofang@sd-vm-0003929 ~]$
[xiaofang@sd-vm-0003929 ~]$ sudo systemctl status mysql
● mariadb.service - MariaDB 10.6.2 database server
   Loaded: loaded (/usr/lib/systemd/system/mariadb.service; enabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/mariadb.service.d
           └─migrated-from-my.cnf-settings.conf
   Active: activating (start) since Fri 2022-05-27 16:34:16 CST; 402ms ago
     Docs: man:mariadbd(8)
           https://mariadb.com/kb/en/library/systemd/
  Process: 13569 ExecStartPost=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
  Process: 13580 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`cd /usr/bin/..; /usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl set-environment _WSREP_START_POSITION=$VAR || exit 1 (code=exited, status=0/SUCCESS)
  Process: 13578 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
 Main PID: 13606 (mariadbd)
   CGroup: /system.slice/mariadb.service
           └─13606 /usr/sbin/mariadbd

May 27 16:34:16 sd-vm-0003929.novalocal systemd[1]: Starting MariaDB 10.6.2 database server...
May 27 16:34:16 sd-vm-0003929.novalocal mariadbd[13606]: 2022-05-27 16:34:16 0 [Note] /usr/sbin/mariadbd (mysqld 10.6.2-MariaDB) starting as process 13606 ...
May 27 16:34:16 sd-vm-0003929.novalocal mariadbd[13606]: 2022-05-27 16:34:16 0 [Warning] You need to use --log-bin to make --binlog-format work.
May 27 16:34:16 sd-vm-0003929.novalocal mariadbd[13606]: 2022-05-27 16:34:16 0 [Note] InnoDB: Compressed tables use zlib 1.2.7
May 27 16:34:16 sd-vm-0003929.novalocal mariadbd[13606]: 2022-05-27 16:34:16 0 [Note] InnoDB: Number of pools: 1
May 27 16:34:16 sd-vm-0003929.novalocal mariadbd[13606]: 2022-05-27 16:34:16 0 [Note] InnoDB: Using crc32 + pclmulqdq instructions
May 27 16:34:16 sd-vm-0003929.novalocal mariadbd[13606]: 2022-05-27 16:34:16 0 [Note] InnoDB: Using Linux native AIO
May 27 16:34:16 sd-vm-0003929.novalocal mariadbd[13606]: 2022-05-27 16:34:16 0 [Note] InnoDB: Initializing buffer pool, total size = 134217728, chunk size = 134217728
May 27 16:34:16 sd-vm-0003929.novalocal mariadbd[13606]: 2022-05-27 16:34:16 0 [Note] InnoDB: Completed initialization of buffer pool
May 27 16:34:16 sd-vm-0003929.novalocal mariadbd[13606]: 2022-05-27 16:34:16 0 [Note] InnoDB: Starting crash recovery from checkpoint LSN=34426674408,34426674408

So how can I start the mysql service again?


text:
Q: Bootstrap treeview nodes do not expand I have a problem with a specific bootstrap treeview, I have tried everything but the node does not expand, I use ajax request through a load file where I retrieve the information coming from the database, the data appears normally, the only one I have already tried all the methods that the treeview bootstrap provides, but it returns that it does not know the method used, below I will send the specific code that I use.
Function that calls a tree:

var levelTree = 2;

    function getTree() {
        var data = '';
        $.ajax({
            url: 'atividades/atividades_load.php',
            data: {idObraAtiva: <?php echo $idObra; ?>},
            async: false,
            dataType: 'json',
            type: 'post',
            beforeSend: function () {
            },
            success: function (retorno) {
                data = retorno;
                console.log(retorno);
            },
            error: function () {
                bootbox.alert('Erro, contate o suporte!');
            }
        });
        return data;
    }

    $('#atividadeTree').treeview({
        data: getTree(),
        levels: levelTree,
        backColor: "#C4E3F3",
        onNodeSelected: function (event, data) {

            if (data.qtdfilhos == 0) {
                $('#table_Andamento').bootstrapTable('refresh', {url: 'atividades/atividade_andamento_load.php?q=' + data.id});
            }
            $('#table_AtividadeFilha').bootstrapTable('refresh', {url: 'atividades/atividade_filha_load.php?p=' + data.id});

            $('#fmAndamento_idatividade').val(data.id);
            $('#fmAtividadeSub_idAtividade').val(data.id);

        },
        onNodeExpanded: function (event, data) {
            $.ajax({
                url: 'atividades/atividades_load.php',
                data: {idObraAtiva: <?php echo $idObra; ?>,idNo:data.id},
                async: false,
                dataType: 'JSON',
                type: 'POST',
                beforeSend: function (){
                },
                success: function (filho){

                $('#atividadeTree').treeview('addNode',[filho, data.id,
{silent: false} ]);
                    console.log(filho);

                },
                error: function () {
                    bootbox.alert('Erro, contate o suporte!');
                }
            });

        }
    });

Function that calls the data, and reorganizes the treeview

<?php
include('../../sessao.php');
require_once('../../J3_FrameWork/Conexao.php');

function getItemPai($_arrLista, $_id)
{
    foreach ($_arrLista as $item) {
        if ($item->id == $_id) {
            if (!property_exists($item, 'nodes')) $item->nodes = array();
            return $item;
        }else
            if (property_exists($item, 'nodes')) {
                if (is_array($item->nodes)) {
                    $aux = getItemPai($item->nodes, $_id);
                    if ($aux != null)
                        return $aux;
                }
            }
    }
    return null;
}

$idObra = $_REQUEST['idObraAtiva'];

if (isset($_REQUEST['idNo'])) {
    $idNo = $_REQUEST['idNo'];
}else{
    $idNo = -1;
}

$conexao = Proxy::mrObra();

$param = array("_parameters" => array($idObra, $idNo));
$resultado = $conexao->comando('GetAtividadesArvore', json_encode($param));
$resultado = json_decode($resultado);

$lista = $resultado->result[0];

$listanova = array();

foreach ($lista as $item) {

    $novoitem = new stdClass();
    $novoitem->id = $item->ID;
    $novoitem->text = $item->DESCRICAO. ' - ' .$item->QTDFILHOS;
    $novoitem->qtdfilhos = $item->QTDFILHOS;
    $novoitem->valor = $item->VALOR;
    $novoitem->qtdativsub = $item->QTDATIVSUB;

    if($item->QTDFILHOS > 0)
    {
        $novoitem->nodes = array();
    }

    if ($item->IDPAI == -1) {
        array_push($listanova, $novoitem);
    } else {
        array_push($listanova, $novoitem);
    }
}

echo json_encode($listanova);
?>

Função que chama os dados, e reorganiza a treeview

<?php
include('../../sessao.php');
require_once('../../J3_FrameWork/Conexao.php');

function getItemPai($_arrLista, $_id)
{
    foreach ($_arrLista as $item) {
        if ($item->id == $_id) {
            if (!property_exists($item, 'nodes')) $item->nodes = array();
            return $item;
        }else
            if (property_exists($item, 'nodes')) {
                if (is_array($item->nodes)) {
                    $aux = getItemPai($item->nodes, $_id);
                    if ($aux != null)
                        return $aux;
                }
            }
    }
    return null;
}

$idObra = $_REQUEST['idObraAtiva'];

if (isset($_REQUEST['idNo'])) {
    $idNo = $_REQUEST['idNo'];
}else{
    $idNo = -1;
}

$conexao = Proxy::mrObra();

$param = array("_parameters" => array($idObra, $idNo));
$resultado = $conexao->comando('GetAtividadesArvore', json_encode($param));
$resultado = json_decode($resultado);

$lista = $resultado->result[0];

$listanova = array();

foreach ($lista as $item) {

    $novoitem = new stdClass();
    $novoitem->id = $item->ID;
    $novoitem->text = $item->DESCRICAO. ' - ' .$item->QTDFILHOS;
    $novoitem->qtdfilhos = $item->QTDFILHOS;
    $novoitem->valor = $item->VALOR;
    $novoitem->qtdativsub = $item->QTDATIVSUB;

    if($item->QTDFILHOS > 0)
    {
        **$novoitem->nodes = array();**
    }

    if ($item->IDPAI == -1) {
        array_push($listanova, $novoitem);
    } else {
        array_push($listanova, $novoitem);
    }
}

echo json_encode($listanova);
?>


text:
Q: Drupal: Create view image field from first img-tag from the nodes body field I have a view in Drupal 7 that renders a nodequeue. Now I want each node to be rendered with a title, text summary and an image if an image is available inside that nodes body field.
I'm thinking of creating a module that uses regular expression like:
/<img.+src="([^"]+)/i

...to find the fist image in the body field for that node and present it as a view field and call that field something like "Content: First image".
I would also like to have the image style options ect. as available for the already existing image fields.
How should I create a module like that, which hooks should I use to make that field available for views?

A: I would do this using field templates.
Create a body field and then apply a template on it. Something like this :
<?php
preg_match_all("/<img[^']*?src=\"([^']*?)\"[^']*?>/", $output, $image);

if(isset($image[1][0]) && trim($image[1][0])!='') {
  echo theme('image_style', array('style_name' => 'Large', 'path' => $image[1][0]));
}
?>

You can also probably achieve the same result using a display suite code field.


text:
Q: trying to execute a file in my jar file I am trying to execute a pdf file, which is included in my jar file.
I tried this code but it doesn't work:
File afile =new File(strs+"o.jpg");
Desktop.getDesktop().open(afile);

strs is the path of the jar file and the directory inside it
strs="C:\Users\Buba\Documents\NetBeansProjects\done\dist\done.jar\done\images\"
What am I doing wrong here?

A: You have to:

*

*open the pdf as a resource

*read the file

*write it to a physical temp location

*execute the file from the temp location


text:
Q: Firefox doesn't support H.264 on Windows 7 Something is not right with my Firefox and Windows 7 combo because reportedly, it should work, but Youtube's test page says otherwise:

The problem I'm having is on certain videos Youtube gives me this cheeky message which suggests to use other combinations of browsers and OSes:

I'm using Firefox Developer Edition 51 (latest to date) and I'm on Windows 7 Ultimate 64 bit with no "N" suffix. Many mention the "N" as it means there are no media codecs installed, and I'd have to get a special ~300mb installation from Microsoft's site (it's free). I tried it and it says it's not applicable for my case.
There are also outdated suggestions to change some bool flags in about:config which are already enabled at this point.
I have K-lite codec pack installed with maximal options, and I don't have media player uninstalled or missing checkboxes in any media-related options in the Windows Features list (available through the uninstallation control panel).
What's missing?


text:
Q: How to replace string inside MySQL field/column? I'm using a shell script to launch SQL query, works fine.
I would like to replace, inside MySQL database, a specific code, which is different depending of the website.
See image below :

My query is the following :
mysql -D DATABASE_NAME -e "UPDATE TABLE SET params = REPLACE(params, '%OLD_CODE%', 'NEW_CODE') WHERE element = 'EXTENSION'"

The problem is : the% OLD_CODE% zone does not work. I have to enter the exact string.
Below the content of PARAMS field from MySQL database :
{"com_difficulty":"3","clubcode":"OLD_CODE","shownews":"1","com_calViewName":"flat","darktemplate":"0"}

I need to replace OLD_CODE by a NEW_CODE, without loosing settings inside PARAMS field.
Problem, since OLD_CODE string is different for each site, how to replace each OLD_CODE string ?
I have laso tried with * caracter to take everything but does not work.
Example:
how to replace this
{"com_difficulty":"3","clubcode":"546465-595gfd-gfgfds65-5654gfd","shownews":"1","com_calViewName":"flat","darktemplate":"0"}

by this :
{"com_difficulty":"3","clubcode":"fg5gfdgfq-grefdg-gredfgfd","shownews":"1","com_calViewName":"flat","darktemplate":"0"}

Thanks
L.

A: this query works :
mysql -D DATABASE_NAME -e "UPDATE TABLE SET params = REGEXP_REPLACE(params, '\"clubcode\":\".+?\"', '\"clubcode\":\"TOTO\"') WHERE element = 'EXTENSION'"


text:
Q: Over-current-protecting a single-ended solid-state switch A previous circuit used a ULN2003 Darlington pair as a single-ended (N-side) solid-state switch with a maximum current capacity of about 500mA.
http://www.st.com/resource/en/datasheet/uln2001.pdf
However, it has no over-current protection, so I'm researching either a replacement or a surrounding circuit to do so. Protection would ideally apply to the channels individually, but a simple solution for the entire circuit would also do. I've found these options:

*

*Add a PPTC self-resetting fuse on the output of each of the channels. Cheap, simple, but I'm not thrilled with the prospect of waiting >2s for it to trip. The switch can easily be destroyed in that time - especially since the ULN200x datasheet does not specify a max time for the peak current, only a duty cycle, and the duty cycle in this application will be 100%.

*Add a 1R res to the output channels, and then either an ADC or a comparator with further shut-off circuitry. More complex and expensive, but faster and more precise.

*Rely on the Vcesat parameter of the ULN2003. If Vce exceeds about 1.4 V, infer that the current exceeds 500mA and then add the same circuitry as #2.

*Replace with a switch that has current protection built-in. Haven't been able to find something nearly as affordable as the ULN200x.

I'm leaning toward #3. Something like:

simulate this circuit – Schematic created using CircuitLab
Questions:

*

*Is the above circuit safe, stable, and an appropriate way to implement current protection?

*Among my other listed alternatives (or not), is there a better way? I usually lean toward simplicity.

A: That's not an impossibly bad circuit, but it has a few problems.
1) Most obviously, the LM339 needs a pullup resistor on its output.
2) A ULN2003 has a turn-on delay of as much as 1 usec. During this time the comparator will be seeing a high input and will be generating a fault indicator. If the delay capacitor is not large enough, this will prevent the load from ever turning on.
3) Once a fault is detected, clearing it will not cause the circuit to allow operation. It will be necessary to set Sw in low for the recovery time of your output delay RC, and only then apply it to drive the load.
4) This is OK as a gross fault detector, but be aware that the ULN2003 output voltage Vce(sat) is not well-defined. At 350 mA, typical is 1.2, but max is 1.7, and there is no minimum defined. As long as your desired loads are much less than your nominal trip point you'll be OK, but if you want to drive anywhere near the ULN limits you'll run the risk of getting a ULN2003 with a weak output which trips under normal load.
5) Unless you use a 74HC132 for your input gate, the operation may not be clean. As the capacitor voltage changes near the trip point, the gate will not get a sharp transition, and there is the possiblity that (for instance) the loop may oscillate. This will depend on all sorts of peripheral effects, including decoupling. It may not be a problem in this case, but whenever you're doing this sort of limiting hysteresis is your friend.

A: Depending on what kinds of faults you are expecting s simple current limit might do.  I Don't have a model for UNL2003 but you'll get the idea.  Would this work for you?

If you need to fold back the current everything will get more complicated.
The pulse source is only here as a simple way to test two currents.  One below the limit, one above.

A: The trick to using a PTC is to choose one with a thermal mass much less than the device being protected including heatsink.
Thus an SMD PTC will suffice for protection for this purpose.  Some radial parts reach a temperature of around 85'C worst case for most devices when short circuited and operated within specified limits.  This means the PPTC will reach 85'C before the part will. Some SMD parts trip up from 50'C to 120'C depending on optional Curie Point (C.P.)of the part. See ref below.
The exception might be if a very large short circuit current from a high voltage load and the pulse current*time exceeds SOA ratings.

Ref
- Rev 2 Answer

*

*with new design input... protection from abrupt short to Vcc  or Gnd.

*Uses High Enable output from  logic. Adjust Vout or fixed (opt.)

Or simply use a fully protected Low side Smart Switch like **VNN3NV04P-E**

This is a good example of how a design can evolve drastically from poorly defined inputs for fault conditions.