text:
Q: How can I render one whole teapot in four viewports (each viewport render one part of the teapot) with OpenGL(GLUT) As stated in the title, I need to render one part of the teapot in each of the four viewports, and the four parts together are a complete teapot. I can now complete the effect in gluOrtho2D. But in gluPerspective, I cannot use gluLookAt to change the observation position.
This is my result Without gluLookAt:

A: Did you by chance try to emplace the rendering in each viewport by trying to transform it there using modelview and projection matrices?
If so, here's a hint: Consider why the function glViewport is called that way and not glWindow (nonexistent). Just use glViewport to define the subset of the window you want to render to.


text:
Q: Ubuntu 12.4 Will Not update [Unmet Dependencies] The following packages have unmet dependencies:

libc6: Depends: libc-bin (= 2.15-0ubuntu10.3) but 2.15-0ubuntu10.4 is installed
libc6-dev: Depends: libc6 (= 2.15-0ubuntu10.4) but 2.15-0ubuntu10.3 is installed
           Depends: libc-dev-bin (= 2.15-0ubuntu10.4) but 2.15-0ubuntu10.4 is installed
libc6:i386: Depends: libc-bin (= 2.15-0ubuntu10.4) but 2.15-0ubuntu10.4 is installed

Any idea how to fix this? I am new to Ubuntu so lets take baby steps.

A: Your libc6 package is an older version than the rest, execute the following commands:
sudo apt-get update
sudo apt-get upgrade
After this, sudo apt-get dist-upgrade should run fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: A closed form of Eulerian numbers The following identity involving Eulerian numbers is well-known:
\begin{equation}
A(n,m)=\sum_{k=0}^{m}(-1)^k \binom{n+1}{k} (m+1-k)^n.
\end{equation}
where $A(n,m)$ is the number of permutations $(\pi_1~\pi_2~\cdots~\pi_n)$ of $\{1,2,\ldots,n\}$ having $m$ ascents, namely, $m$ places where $\pi_j < \pi_{j+1}$.
Does anyone know how to prove the above identity? (I found this identity on a research paper which contains no proof.)

A: Start from the bivariate generating function of the Eulerian numbers:
$$G(z, u) = \frac{u-1}{u-\exp((u-1)z)}
= \left(1-\frac{1}{u}\right)\frac{1}{1-\exp((u-1)z)/u}.$$
This is
$$\left(1-\frac{1}{u}\right)
\sum_{q\ge 0} \frac{\exp(q(u-1)z)}{u^q}.$$
This implies that
$$\left\langle {n\atop  k}\right\rangle
= n! [u^k] \left(1-\frac{1}{u}\right)
\sum_{q\ge 0} \frac{q^n(u-1)^n}{n!\times u^q}$$
which is
$$[u^k] \frac{(u-1)^{n+1}}{u}
\sum_{q\ge 0} \frac{q^n}{u^q}
= [u^{k+1}] (u-1)^{n+1} \sum_{q\ge 0} \frac{q^n}{u^q}.$$
Extracting coefficients from this we obtain
$$\sum_{p=k+1}^{n+1} {n+1\choose p} (-1)^{n+1-p} (p-(k+1))^n
= \sum_{p=k+1}^{n+1} {n+1\choose n+1-p} (-1)^{n+1-p} (p-(k+1))^n.$$
Re-index the sum putting $n+1-p = q$
to get
$$\sum_{q=0}^{n-k} {n+1\choose q} (-1)^q (n+1-q-(k+1))^n
\\ = \sum_{q=0}^{n-k} {n+1\choose q} (-1)^q (n-k-q)^n$$
We digress for a moment to evaluate
$$\sum_{q=0}^{n+1} {n+1\choose q} (-1)^q (n-k-q)^n$$
using the integral
$$(n-k-q)^n = \frac{n!}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{n+1}} \exp((n-k-q)z) \; dz.$$
We get for the sum
$$\frac{n!}{2\pi i}
\int_{|z|=\epsilon}
\frac{1}{z^{n+1}}
\sum_{q=0}^{n+1} {n+1\choose q} (-1)^q \exp((n-k-q)z) \; dz
\\ = \frac{n!}{2\pi i}
\int_{|z|=\epsilon}
\frac{\exp((n-k)z)}{z^{n+1}}
\sum_{q=0}^{n+1} {n+1\choose q} (-1)^q \exp(-qz) \; dz
\\ = \frac{n!}{2\pi i}
\int_{|z|=\epsilon}
\frac{\exp((n-k)z)}{z^{n+1}}
\left(1-\exp(-z)\right)^{n+1} \; dz.$$
Now   note   that   $1-\exp(-z)$   starts   at   $z$   and   therefore
$(1-\exp(-z))^{n+1}$  starts   at  $z^{n+1}$  which   means  that  the
integrand is entire, making the  integral evaluate to zero, so the sum
is zero.

Ending the digression we now  observe that the sum from the generating
function is in fact
$$-\sum_{q=n-k+1}^{n+1} {n+1\choose q} (-1)^q (n-k-q)^n.$$
Re-index one more time to get
$$-\sum_{q=0}^k {n+1\choose n+1-q}
(-1)^{n+1-q} (n-k-(n+1-q))^n
\\ = \sum_{q=0}^k {n+1\choose q}
(-1)^{n-q} (q-1-k)^n
= \sum_{q=0}^k {n+1\choose q}
(-1)^q (k+1-q)^n.$$
This is what was required. QED.

A: (We count descents instead of ascents. Let $A(n, k)$ denote the number of permutations on $[n]$ with $k-1$ descents)
Here's a combinatorial proof via inclusion-exclusion the essence of which can be found in Miklos Bona's Combinatorics of Permutations. He attributes this proof to Richard Stanley and Hugh Thomas (independently).
Define a "$k$-augmented word on $[n]$" to be an object you get by writing down $k-1$ bars and allocating each element of $[n] = \{1,2, \ldots , n\}$ to one of the $k$ compartments created by the bars and then ordering the set of numbers in each compartment in ascending order. For example, if $n=5$ and $k =4$, then each of the following is a $4$-augmented word on $[5]$: $$ w_{1} = 12||34|5, \qquad w_{2}= |15|4|23, \qquad w_{3}=1|23|5|4 $$
We make two further definitions involving bars:
1) Wall: A bar that is not immediately followed by another bar. (For example, all the bars in the above examples are walls except for the first bar in $w_{1}.$)
2) Extraneous: A bar in a $k$-augmented word is called extraneous if after its deletion, it produces a $(k-1)$-augmented word. (For example, the third bar in the $w_{1}$ is extraneous because the resultant object is a $2$-augmented word. Similarly, so is the first bar in $w_{2}$. However, the second bar in $w_{2}$ is not extraneous.)
In this above vocabulary, it can be clearly seen that the permutations on $[n]$ with $k-1$ descents are in bijection with the $k$-augmented words on $[n]$ that have no extraneous walls. (Each such permutation gives rise to a $k$-augmented word by placing a bar at each of the descent indices. Conversely, the deletion of all the bars in a $k$-augmented word gives rise to a permutation with $k-1$ descents.)
We are now ready to use the principle of inclusion-exclusion on $X$, the set of all possible $k$-augmented words. Note that since each of the $n$ numbers have one of $k$ compartments to live in, then $|X| = k^{n}.$ Below, we use "position" to mean one of the $n+1$ gaps in between a permutation written as a word.
Let $w \in X$ have property $P_{i}$ (for a given $i \in \left\{0,1,\ldots,n\right\}$) if there is an extraneous wall after the $i^{\text{th}}$ symbol of the word. Note that not more than $k-1$ properties can hold simultaneously. Let $S = \{i_{1}< \ldots < i_{j}\}$ be a subset of $\left\{0,1,\ldots,n\right\}$ with $j \leq k-1$, and let $A_S= \left|\{w \in X \text{ satisfying } P_{i_{1}}, \ldots , P_{i_{j}}\}\right|$; then, we claim that $|A_{S}| = (k-j)^{n}$. Indeed, it suffices to find a bijective correspondence between $A_{S}$ and the set of all $(k-j)$-augmented words on $[n]$. If $w \in A_{S}$, then deleting a bar in $w$ at each position belonging to $S$ we get a $(k-j)$-augmented word on $[n]$. Conversely, starting with a $(k-j)$-augmented word on $[n]$, insert a bar at each position belonging to $S$ (and if a bar already exists at that position, insert it to the immediate right of this bar); then, each position of $S$ contains an extraneous wall giving rise to $w \in A_{S}$. Recall that the set of permutations on $n$ with $k-1$ descents equals the number of $k$-augmented words on $[n]$ with no extraneous walls which, by the principle of inclusion-exclusion (using the claim we just showed), equals:
$$A(n, k) = \displaystyle \sum_{j=0}^{k-1}(-1)^{j}\binom{n+1}{j}(k-j)^{n} .$$


text:
Q: Array of objects and i want to return true if any key value pair in the object is duplicate I am fairly new to JS, I am struggling with a problem where there is an array of objects and i want to return true if any key value pair in the object is duplicate
var lookupValues = [{"key":"xiomi","value":"phone","id":1},{"key":"samsung","value":"tab",id:2},{"key":"blackberry","value":"phone","id":3},{"key":"xiomi","value":"tab","id":4},{"key":"asus","value":"phone",id:5}]}

Since key: "Xiomi" came twice so function should return true
i tried using lodash functions
var uniqueLookup =_uniqBy(lookupValues,'key')
if(_.isEqual(uniqueLookup, lookup)) return true

works but i guess i am missing something

A: You are on the right track. Compare the length of the array to the array shortened by checking if the key is unique.

var lookupValues = [{"key":"xiomi","value":"phone","id":1},{"key":"samsung","value":"tab",id:2},{"key":"blackberry","value":"phone","id":3},{"key":"xiomi","value":"tab","id":4},{"key":"asus","value":"phone",id:5}];
console.log(_.uniqBy(lookupValues,"key").length !== lookupValues.length);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.19/lodash.min.js"></script>

A: Here how you can do this in VanillaJs.
Set is a new data structure that JavaScript got in ES6. It's a collection of unique values. We put into that the list of property values we get from using map(), which how we used it will return this array:
[xiomi,Samsung,blackberry,xiomi,asus]
Passing through Set, we'll remove the duplicates i.e xiomi and at last ... is the spread operator, which will expand the Set values into an array.
Now if length of this new array is equal to your lookupValues.length then it has no duplicates else duplicates are present.

var lookupValues = [{"key":"xiomi","value":"phone","id":1},{"key":"samsung","value":"tab",id:2},{"key":"blackberry","value":"phone","id":3},{"key":"xiomi","value":"tab","id":4},{"key":"asus","value":"phone",id:5}]

const isDuplicate = (lookupValues) => !([...new Set(lookupValues.map(obj => obj.key))].length === lookupValues.length)

console.log(isDuplicate(lookupValues))

A: I made a vanilla Javascript code snippet with es6 Set object.
var lookupValues = [{"key":"xiomi","value":"phone","id":1},{"key":"samsung","value":"tab",id:2},{"key":"blackberry","value":"phone","id":3},{"key":"xiomi","value":"tab","id":4},{"key":"asus","value":"phone",id:5}]
const keys = lookupValues.map((v) => v.key)
const keySetSize = new Set(keys).size
const hasDuplicate = keys.length > keySetSize
console.log(hasDuplicate)


text:
Q: How to manage decimals in c++ The issue that i encounter is when i try to separate the integer and fractional part of a real number.
long double x,y;
x=121.09;
y=(long)x;
x=x-(long)x;

Y becomes 121, x in the debugger appears as 0.08999999 but writing it to console shows 0.09.
Also,
double x;
int y;
x=121.09;
y=x;
x=x-y;

Gives the same results. Why is that? I would need a clean 0.09 as i want to get that as an integer (0.09 -> 9)
How can i get the fractional part of the number without modf?


text:
Q: webScraping ¿ Como obtengo el href y el src de esta pagina dinámica? Python + Selenium Buen día amigos, Estoy haciendo web scraping a  una pagina para  mi proyecto, pero no logro sacar los href y el src de la pagina :

He intentado hacer:
elems = driver.find_elements_by_xpath('//a[@href]')
for elem in elems:
print(elem.get_attribute("href"))

Pero nada
al igual que usar selectores

A: Puedes probar con la librería BeautifulSoup https://www.crummy.com/software/BeautifulSoup/bs4/doc/ algo como:

import requests
from bs4 import BeautifulSoup
phtml = 'tupagina.com'

page = requests.get(phtml)
soup = BeautifulSoup(page.text,'html.parser')
links = soup.findAll('a', {'class': 'listing__link'})
imgs = soup.findAll('img', {'class':'listing-img__img'})

for l in links:
    try:
        print(l['href'])
    except KeyError:
        pass

for i in imgs:
    try:
        print(i['src'])
    except KeyError:
        pass


text:
Q: Alternative to Group_concat in MS SQL Server I have a simple query that does group concat very well in SQL workbench.
id hobby
 1 dance
 1 sing
 2 play
 2 sing

Expected output:
id hobby
1 dance,sing
2 play,sing

How can I get this output using MS SQL Server?


text:
Q: Will Loading Up My PCI Express Slots Affect GPU Performance? I wanted to know if loading up my PCI bus with different cards will affect my GPU's gaming performance.
I have a ASUS Maximus VI Formula with 3 PCIe x16 3.0 slots and 3 PCIe x1 slots. I have a single GPU in the first x16 slot (GTX 780ti), and a sound card in the first x1 (Creative XFi Titanium). I know the x16 slots can run in 3 modes: x16, x8 x8, and x8 x4 x4.
My question is if I add more cards in the x1 slots, or possibly non-graphics cards in the x16 slots, will it make my GPU run in x8 mode? Will that affect gaming performance? How much?

A: If you use the other "x16" slots (quotes because they have the x16 physical connector but not the wiring), 8 PCIe lanes will be stolen from the GPU connection to provide a link to the other two slots.
You won't notice a performance drop in games running at PCIe 3.0 x8 (which the 780Ti supports), and probably wouldn't even notice any slowdown in PCIe 2.0 mode on x8.


text:
Q: What is the Best Way to Keep Bootstrap Columns All of Even Height The image below come from this url.
What is the best way to make all the columns in a Bootstrap keep themselves at the same height, given that the content within the columns can vary in height?   What is needed is  a style that says, "make this this column at least as tall as the tallest column in this row."

A: Flexbox is your friend!
CSS:
#container {
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
}

#container div {
    border: 1px solid silver;
}

HTML:

Box 1

Box 2

Box Box Box Box 3

Box 4

Box 5

Box 6

Box 7

Box 8

Box 9

Box 10

Box 11

Box Box 12

example


text:
Q: How do you make a bar a different color in KendoUI bar chart? I'm am replacing my dot net charting with KendoUI. I'm showing a Score Distribution chart. I want all of the bars to be the same color except the bar with the median score and the Legend. How do I color a single bar a unique color? How would I color the Legend this new color?
Below is my old dotnet charting bar chart and below that is the new KendoUI chart I'm trying to replace it with. I just need to get that coloring right and we'll be in business. Any help is appreciated.

A: Update: I'm leaving the answer below this line intact in case there are those out there who are using an older version, but per a later comment, KendoUI now allows you to override styles for individual points in a series.

I don't believe you can, in the current version. That said, you can hack your way around the limitation.
You'll need to create two data series - one for your highlighted data, and one for everything else. Add both to you chart, and set them to stacked.
Here's a jsFiddle I put together to illustrate: http://jsfiddle.net/LyndsySimon/9VZdS/. It depends on KendoUI's CDN, so if it breaks in the future I apologize.
Here is the Javascript for reference:
$(function() {
    var dataset = new Array(1,2,3,null,5,6);
    var highlighted = new Array(null,null,null,4,null,null);

    $('#chart').kendoChart({
        theme: 'metro',
        seriesDefaults: {
            type: 'column',
            stack: true
        },
        series: [
            {
                name: 'Not Highlighted',
                data: dataset,
                color: '#609'
            },
            {
                name: 'Highlighted',
                data: highlighted,
                color: '#f03'
            }
        ]
    })
});

A: Starting with the 2012 Q2 release, bar series support binding the point color to a data item field.
This is done through the colorField option. The Binding to local data online example demonstrates it.
Both the Kendo UI and the legacy wrappers for ASP.NET MVC expose it as an option:
.Series(series =>
{
    series.Bar(model => model.Value, model => model.Color)
        .Name("United States");
})

All series overloads can be seen here.

A: You could hack the SVG generated by the system.  I have supplied the chart with a model which contains the colour for each bar. eg:
public class Model
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public string Colour { get; set; }
    public decimal Score { get; set; }
}

Which is used as a series on the chart.  The view then looks like:
@(Html.Telerik().Chart(Model)
    .Name("AverageScores")
    .Theme("Simple")
    .HtmlAttributes(new {style = "height: 500px"})
    .Series(series => series.Column(s => s.Score).Name("Name").Color("Blue"))
    .SeriesDefaults(sd => sd.Column().Labels(l =>
                                                 {
                                                     l.Visible(true);
                                                     l.Format("{0}%");
                                                 }))
    .Title("Mean Percentage Scores")
    .Legend(builder =>
                {
                    builder.Position(ChartLegendPosition.Bottom);
                    builder.Visible(false);
                })
    .CategoryAxis(ca => ca.Categories(x => x.Code))
    .Tooltip(builder =>
                 {
                     builder.Visible(true);
                     builder.Format("{0}%");
                     builder.Template("<#= dataItem.Name #>
<#= value #>%");
                 })
    .ValueAxis(va => va.Numeric().Labels(a => a.Format("{0}%")).Min(0).Max(100)
    )
)

@section BelowTelerikScriptRegistrar
{

}

The section BelowTelerikScriptRegistrar must happen after the Html.Telerik().ScriptRegistrar() is called.
This will work in Chrome, Firefox and IE10.  I have noticed there is a problem with multiple chart and the timings around the generation of the SVG.  Unfortunately you might have to wrap setAverageScoresColours() in a setTimeout function to ensure the SVG has been generated, but it seems to work with just one chart.
A bit hacky, but easier than managing lots of series.
And for KendoUI (which I have edited for...):

A: Another way you can do it at runtime is using function which returns color.
API reference
Here is an example code:

A: This is not currently possible with current KendoUI version.
It's on their todo-list.
http://www.kendoui.com/forums/dataviz/chart/change-bar-column-color-for-each-point.aspx
There can be a kind of workaround, as said in the thread I've put here, it would be to describe a series for each color you need. It looks very inefficient to me, but it's currently the only way to do it. If you have only 1 chart, you could do it. Else, wait for a new version of KendoUI with this feature.

A: Telerik have recently released a Kendo UI Data Vis Theme Roller
http://demos.kendoui.com/themebuilder/dataviz.html


text:
Q: Ldap server return result control? Hi I'm implementing an ldap query api. I would like to do it in such a way that I set a limit to 10 (say). I need ldap to return the first 10 values with a continuation-context-parameter that can be used to continue to return the next 10 results with a new query(with continuation-context-parameter passed as argument). Is this possible in ldap server?
Im trying to implement the api in java. I know that the SearchControl's setCountLimit() method can be used to set the number of elements but Im not able to find any methods that allow the results to be returned from where is originally left off.

A: You're looking for the PagedResultsControl.
For more sophistication you can use the VirtualListViewControl available in the JNDI LDAP Booster Back, if you can find it. For this, with OpenLDAP you need to install and configure the sssvlv overlay.


text:
Q: Azure media service live stream how to implement stream from android app I am trying to find any code sample on live streaming in java.
I want implement it in an android app by azure media service.
currently I have MediaRecorder instance which configured like this:
    mMediaRecorder = new MediaRecorder();
        mMediaRecorder.setCamera(mServiceCamera);
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

        public String filePath = Environment.getExternalStorageDirectory().getPath() + "/video.mp4";

        mMediaRecorder.setOutputFile(filePath);

I searched way to integrate with azure media service in my app to broadcast live streaming to cloud and delivery link to the stream in push notification to other app
I exposed this . the dependency there is not valid in android gradle file. how we need to work with that?
also does need to use RTMP? or because the file content was saved directly in asset file in the azure storage it is doing the job?
how much I am understood the locator create endpoint.
can I get this endpoint url in the app for send it or it is existing only in azure portal?
is the broadcaster need to be user in AAD?
does it possible to give the user in the app the  ability to create credentials?

A: I'm no Java expert but from what I've read about MediaRecorder it does not have the ability to stream an output in the RTMP protocol.  The phone needs to act like a client and push the RTMP protocol to the AMS server endpoint.  I believe the MediaRecorder api only output mpeg 2 TS from what I see in the API Docs.
I've seen projects that re wrap the output from the MediaRecorder into an RTMP stream. See https://github.com/octiplex/Android-RTMP-Muxer as an example.  No endorsement by me.
For your other questions.

*

*Never include your azure credentials in a mobile application!  You need to use a middle tier to do the work for your app.  That means you would build an api to talk to the app front end, and that api would call the backend services it needs.   In this case a simple Azure Functions app would be sufficient or you can build and host your api in any framework you like.  The credentials to AMS will be an AAD service principal client id and secret that needs to be secured in the mid tier for your api to use.  The api would then return information like the RTMP ingest url.

*When you create a live event in the v3 api for AMS you get back an object that contains the "ingest url" endpoint. That has a RTMP://server dns name :1935 port .   This is the url you connect to.   Make sure you start the live event first of course before connecting.

*I recommend testing with OBS studio first until you understand the flow of connecting to an RTMP server. Go through the OBS studio tutorial in our documentation
When going through that tutorial consider that the OBS studio is acting like your android app.

*In your code for MediaRecorder I see you set the audio to AMR.   You need to use AAC LC audio format.  That is the only audio format that we support for ingest, and it is the most widely used format for HLS and Dash streaming. It will provide the most compatibility on delivery to devices and browsers.


text:
Q: How to express alternating $-1,0,1$ in a series I am dealing with a series that has a term: $$\sum\limits_{n=1}^\infty\sin\left(\frac{n\pi}{2}\right)$$
How would I express this without the sine function?
I know it alternates $1, 0, -1, 0, 1, \dots$
Can I express this as $-1$ raised to some power?

A: I believe (with $n$ starting at 0)
$$ \frac{i^n (1 + (-1)^n)}{2} $$
does the trick.  If you want the index to begin at $1$ then simply replace $n$ with $n-1$ above.

A: The series $\sum_{n=1}^{\infty} \sin\left(\frac{n \pi}{2}\right)$ does not converge. If you're dealing with something like $\sum_{n=1}^{\infty} \sin\left(\frac{n \pi}{2}\right) f(n)$ with $f$ some function, then you could replace the series by $\sum_{i=1}^{\infty}(-1)^{n-1}f(2n-1)$, since all other terms in the series are $0$ anyway.


text:
Q: Get data row by filter from database and add to datagridview Hi I am trying to read the row of a database .accdb and add it to my datagridview
I am getting this error

System.InvalidCastException: Unable to cast object of type
  'WhereEnumerableIterator`1[System.Data.DataRow]' to type
  'System.Data.DataRow'.

I have tried for hours and no joy.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
            Dim chk = (From dr As DataRow In Test1DataSet.Tables(0).Rows Select dr Where dr("SN:").ToString = "" & SN_TextBox.Text.ToString() & "").Count
            Dim c As Integer
            c = chk
            Try
                Dim aa As DataRow
                aa = (From dr As DataRow In Test1DataSet.Tables(0).Rows Select dr Where dr("SN:").ToString = "" & SN_TextBox.Text.ToString() & "" AndAlso dr("times tested").ToString = c.ToString)
                DataGridView1.Rows.Add(aa)
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub

A: Use FirstOrDefault:
aa = (From dr As DataRow...ToString).FirstOrDefault


text: Q: Amazon Macie Amazon Macie is a security service that uses machine learning to automatically discover, classify, and protect sensitive data in AWS. Amazon Macie recognizes sensitive data such as personally identifiable information (PII) or intellectual property, and provides dashboards and alerts that give visibility into how this data is being accessed or moved.


text:
Q: On $n$-connected simplicial complex and vanishing of reduced homology Let $X=|\Delta|$ be the geometric realization of an abstract simplicial complex $\Delta$. Let $k$ be a field. Assume that $X$ is path connected .
Consider the following two conditions:
(1) $\pi_i (X)=0, \forall 1\le i\le n$
(2) $\tilde H_i(X,k)=0, \forall 0\le i\le n$
I know that (1) implies (2) by Hurewicz theorem and Universal coefficient theorem. My question is : Does (2) imply (1) ? If not, then would some other vanishing result on (reduced) Homology imply (1) ?

A: The Poincare Homology sphere has $\tilde H_0$, $H_1$ and $H_2$
trivial, yet has non-trivial $\pi_1$. But the Abelianisation
of $\pi_1$ is trivial. I suspect that "(2) implies (1)" is far too optimistic,
even if you replace $\pi_1(X)$ by its Abelianisation in (1).

A: If we use $\mathbb Z$-coefficients, then the Hurewicz theorem tells us that (2) implies (1) provided $X$ is simply connected. If it is not, then there are counterexamples (see Lord Shark the Unknown's answer).
If we use coefficients in a field $k$, then it is possible that (2) is satisfied, but $\tilde{H}_i(X) \ne 0$ for some $i \le n$. As an example take the space $X$ obtained by attaching to $S^2$ a cell $D^3$ via map $f : S^2 \to S^2$ of degree $2$. This space is simply connected and has $\pi_2(X) = \mathbb Z_2$. By the Hurewicz theorem $H_2(X) = \mathbb Z_2$ and by the universal coefficient theorem $H_2(X,\mathbb Q) = 0$. See An abelian group A is torsion iff A ⊗ Q = 0.
This example shows that (for $k = \mathbb Q$) even for simply connected $X$ (2) does not imply (1).
However, there exists a "rational Hurewicz theorem" which allows to get information about $\pi_i(X) \otimes \mathbb Q$. See https://en.wikipedia.org/wiki/Hurewicz_theorem.


text:
Q: React: Import Js with from and curly braces part I am currently thinking of using "fabric-webpack" and looking at the demo using react "https://codesandbox.io/s/8k7kvwqx70?file=/src/index.js"
I under import { ... } from '....'
But not sure how this work if typing like this
import 'fabric-webpack'

A: You need to use import { fabric } from "fabric"; as shown here
The demo imports globally the library, that attaches the interface to window, window.fabric


text:
Q: how can i fetch the parent class primary id and store it in child's table which is stored under the user as parent in hibernate I have hospital entity and doctor entity and doctors are registered under hospital user. i have mapped one to many unidirectional between these but when i register a doctor through a form it's Hospital Id column shows null.
this is my hospital class where i have defined various attributes and also have mapped in between them

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="hospital")
public class Hospital {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="hospitalid")
    private int hospital_id;

    @OneToMany(mappedBy="hospital",cascade={CascadeType.DETACH,CascadeType.MERGE,
            CascadeType.PERSIST,CascadeType.PERSIST})
    private List<HospitalDoctorEntity> doctorList;

    public List<HospitalDoctorEntity> getDoctorList() {
        return doctorList;
    }

    public void setDoctorList(List<HospitalDoctorEntity> doctorList) {
        this.doctorList = doctorList;
    }

    public int getAccount_status() {
        return account_status;
    }

    public void setAccount_status(int account_status) {
        this.account_status = account_status;
    }

    public void setHospital_id(int hospital_id) {
        this.hospital_id = hospital_id;
    }
    @Column(name="password")
    private String password;
    @Column(name="hospitalname")
    private String hospitalName;
    @Column(name="addressline1")
    private String addressLine1;
    @Column(name="addressline2")
    private String addressLine2;
    @Column(name="city")
    private String city;
    @Column(name="state")
    private String state;
    @GeneratedValue()
    @Column(name="achievements")
    private String achievements;
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    @Column(name="accountstatus")
    private int account_status =0;
    public int getHospital_id() {
        return hospital_id;
    }

    public String getHospitalName() {
        return hospitalName;
    }
    public void setHospitalName(String hospitalName) {
        this.hospitalName = hospitalName;
    }
    public String getAddressLine1() {
        return addressLine1;
    }
    public void setAddressLine1(String addressLine1) {
        this.addressLine1 = addressLine1;
    }
    public String getAddressLine2() {
        return addressLine2;
    }
    public void setAddressLine2(String addressLine2) {
        this.addressLine2 = addressLine2;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }

    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getAchievements() {
        return achievements;
    }
    public void setAchievements(String achievements) {
        this.achievements = achievements;
    }
}```


text:
Q: Specify valid values for arguments using docopt I am trying to use docopt for the first time.  So far, this is the usage statement I have:
Test Control Program

Usage:
  test.py bitwrite ([--off=<bits>...][--on=<bits>...])
  test.py regwrite ([regA | regB]<value>)

Options:
  -o <bits>... --off <bits>...  #Turn bits off
  -i <bits>... --on <bits>...   #Turns bits on

So, not I have no problem with test.py bitwrite -o bitA, bitB, bitC, bitD
Let's say that there is a user unfamiliar with my system and they need to know the proper values for the bits values.
Is there any way to specify this using the usage statement?  I have tried several things and get nothing to work.

A: You can specify them in a separate part of the __doc__ , as an Example -
Test Control Program

Usage:
  test.py bitwrite ([--off=<bits>...][--on=<bits>...])
  test.py regwrite ([regA | regB]<value>)

Options:
  -o <bits>... --off <bits>...  #Turn bits off
  -i <bits>... --on <bits>...   #Turns bits on

Arguments:

      bits: 1 - on
            0 - off

Please note Arguments is not any special name recognized by docopt , its just any name, you can use any such appropriate name you want.
In the above the Arguments section would show the valid values for bits, and other arguments .
Then when running the above doc with --help option, you would get result as -
>>>> python a.py --help
Test Control Program

Usage:
  test.py bitwrite ([--off=<bits>...][--on=<bits>...])
  test.py regwrite ([regA | regB]<value>)

Options:
  -o <bits>... --off <bits>...  #Turn bits off
  -i <bits>... --on <bits>...   #Turns bits on

Arguments:

      bits: 1 - on
            0 - off

If you want to show the complete __doc__ without having to specify the --help or -h option, you can catch DocoptExit exception when calling the docopt() function and print the __doc__ at that time.
Example -
"""Test Control Program

Usage:
  test.py bitwrite ([--off=<bits>...][--on=<bits>...])
  test.py regwrite ([regA | regB]<value>)

Options:
  -o <bits>... --off <bits>...  #Turn bits off
  -i <bits>... --on <bits>...   #Turns bits on

Arguments:

      bits: 1 - on
            0 - off

"""
from docopt import docopt, DocoptExit

if __name__ == '__main__':
    try:
        arguments = docopt(__doc__, version='Test Control Program')
        print(arguments)
    except DocoptExit:
        print(__doc__)


text:
Q: Assigning Folder Permissions with JSOM Is it possible to use JSOM to assign unique folder permissions?
I found the SP.BasePermissions.set() method but can't seem to find much documentation on it. Much more out there using C# but unfortunately I'm limited to using JavaScript.
EDIT: Sorry if this was unclear - In addition to breaking the role inheritance I also need to assign permissions to the folder programmatically.

A: Use SP.SecurableObject.breakRoleInheritance method to create unique role assignments for Folder.
How to create unique role assignments for a Folder using JSOM
function getFolder(url,success,error) {

   var ctx = SP.ClientContext.get_current();
   var folder = ctx.get_web().getFolderByServerRelativeUrl(url);
   ctx.load(folder,'ListItemAllFields');
   ctx.executeQueryAsync(
      function () {
         success(folder);
      },
      error
   );
}

function breakFolderRoleInheritance(url,success,error)
{
    getFolder(url,function(folder){
       var ctx = SP.ClientContext.get_current();
       var folderItem = folder.get_listItemAllFields();
       folderItem.breakRoleInheritance(false,false);

       ctx.executeQueryAsync(
         function () {
           success(folder);
         },
         error);
    },
    error);
}

Usage
Set unique role assignments for a folder named Orders located in Documents library:
breakFolderRoleInheritance('/Documents/Orders',
  function(folder){
      var folderItem = folder.get_listItemAllFields();
      console.log(String.format('Folder {0} has unique permissions',folderItem.get_item('Title')));
  },
  function(sender,args){
      console.log(args.get_message());
  }
);


text:
Q: C: Cannot read from a pipe attached to the stdout of a child process I am attempting a create a front end to a console music player and I have to interact with it by sending it commands to its stdin while reading its status back from its stdout, so I set up 2 pipes just for that. Sending commands to the child process' stdin works, but I cannot read any data from its stdout (read() always returns -1, errno is set to Resource temporarily unavailable).
When starting the music player by itself in the terminal with the same arguments, it outputs the following:
S05:05
T00:00
T00:01
T00:02
T00:03
T00:04
T00:05
...

Every line from that music player is guaranteed to be 6 lines + newline, so the expected output from the parent program should be:
S05:05 T00:00 T00:01 T00:02 T00:03 T00:04 T00:05...

(newlines do not work when the terminal is set to raw mode)
However, nothing at all is ever read from the child process. Any help as to why this happens and how to solve this would be much appreciated.
Here is the code of the parent program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

int main() {
    system("/bin/stty raw");            // Set up the terminal so that stdin is non-blocking

    pid_t p;
    int pipe_stdin[2], pipe_stdout[2];

    if(pipe(pipe_stdin)) return -1;     // Initialize child stdin pipe
    if(pipe(pipe_stdout)) return -1;    // Initialize child stdout pipe

    // Make reading from the pipe non-blocking
    fcntl(pipe_stdout[0], F_SETFL, fcntl(pipe_stdout[0], F_GETFL) | O_NONBLOCK);

    if((p = fork()) == 0) {             // Create the child process
        close(pipe_stdin[1]);           // Close unnecessary pipe ends to the child
        close(pipe_stdout[0]);

        dup2(pipe_stdin[0], 0);         // Redirect stdin to a pipe
        dup2(pipe_stdout[1], 1);        // Redirect stdout to a pipe

        // Start the process
        execl("/bin/sh", "sh", "-c", "./openmpt ./spacedeb.mod 2>/dev/null", NULL);
        exit(1);
    }

    close(pipe_stdin[0]);               // Close unnecessary pipe ends to the parent
    close(pipe_stdout[1]);

    int codec_write = pipe_stdin[1], codec_read = pipe_stdout[0], playing = 1;
    char buf[8];

    while(playing) {
        // Read input from the child process (read() always returns -1 here!)
        while(read(codec_read, buf, 7) >= 0) {
            printf("%s ", buf);
        }

        // Send user data to the child process (this part works!)
        switch(getchar()) {
            case ' ': write(codec_write, "P\n", 2); break;  // Play & Pause
            case 13: write(codec_write, "R\n", 2); break;   // Reset
            case 27: playing = 0; break;                    // Exit
        }
    }

    close(codec_write);                 // Close the pipes
    close(codec_read);
    system("killall -9 openmpt");       // Kill the child process

    system("/bin/stty cooked");         // Reset the terminal back to its original state
}

And here is the code of the player (if necessary, it should not be a problem though):
#include <memory.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <libopenmpt/libopenmpt.h>
#include <libopenmpt/libopenmpt_stream_callbacks_file.h>
#include "portaudio.h"

#define BUFFERSIZE 512
#define SAMPLERATE 48000

static int16_t buffer[BUFFERSIZE * 2];

int main(int argc, char *argv[]) {
    // Initialize OpenMPT and load the module
    FILE *file = fopen(argv[1], "rb");
    openmpt_module *mod = openmpt_module_create2(openmpt_stream_get_file_callbacks(), file, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
    fclose(file);

    // Output the length of the tune
    printf("T%02d:%02d\n", (int)openmpt_module_get_duration_seconds(mod) / 60, (int)openmpt_module_get_duration_seconds(mod) % 60);

    // Initialize PortAudio
    PaStream *stream;
    Pa_Initialize();
    Pa_OpenDefaultStream(&stream, 0, 2, paInt16, SAMPLERATE, BUFFERSIZE, NULL, NULL);
    Pa_StartStream(stream);

    unsigned long i, count = 0, prev = -1, paused = 0;
    char buf[3] = { 0 };

    // Set stdin to non-blocking
    fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);

    while (1) {
        // Read commands from the parent program
        while(read(0, buf, 2) >= 0) {
            switch(buf[0]) {
                case 'P':
                    paused ^= 1;
                    printf("%s--:--\n", paused ? "P" : "R");
                    break;

                case 'R':
                    openmpt_module_set_position_order_row(mod, 0, 0);
                    break;
            }
        }

        // Display the current position of the tune
        if((int)openmpt_module_get_position_seconds(mod) != prev) {
            printf("T%02d:%02d\n", (int)openmpt_module_get_position_seconds(mod) / 60, (int)openmpt_module_get_position_seconds(mod) % 60);
            prev = (int)openmpt_module_get_position_seconds(mod);
        }

        // Play audio, if not paused
        if(!paused) {
            count = openmpt_module_read_interleaved_stereo(mod, SAMPLERATE, BUFFERSIZE, buffer);

            if (!count) {
                break;
            }

            Pa_WriteStream(stream, buffer, count);
        }
    }

    // Tell the parent that we're done
    printf("E--:--\n");

    // Stop PortAudio
    Pa_StopStream(stream);
    Pa_CloseStream(stream);
    Pa_Terminate();

    // Stop OpenMPT
    openmpt_module_destroy(mod);
}

A: Nevermind, I figured it out myself, the player needed fflush(stdout); after the printf statements. Now everything works as intended.


text:
Q: Spring data jpa search filter by foreign key and type Model Class Vehicle
@Column(name="type",nullable=false)
private String type;

@Column(name="last_service_date",nullable=false)
private String lastServiceDate;

@Column(name="seats",nullable=false)
private Long seats;

@Column(name="bags_capacity",nullable=false)
private Long bagsCapacity;

@Column(name="milage",nullable=false)
private Long milage;

//for Franchise object id
private transient Long fId;

@ManyToOne
 @JoinColumn(name="franchise_id")
 private Franchise fkFranchiseId;

@Repository
public interface VehicleRepository extends JpaRepository<Vehicle,Long>
{

 }

I am using spring data jpa repositories and want to search Vehicle by type and foreignKey=>(zipcode) how can i find

A: Just add a method in your Vehicle JPA repository interface as follow:
findAllByTypeAndFkFranchiseIdZipCode(String type, String zipCode);

And also you are welcome to check docs of Spring Data Jpa

A: You can use JPA repo method name query  documented here    https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
public interface VehicleRepo extends JpaRepository<Vehicle, String> {

  List<Vehicle> findAllByTypeAndFkFranchiseIdZipCode((String type, String zipCode);

  Page<Vehicle> findAllByTypeAndFkFranchiseIdZipCode((String type, String zipCode,Pageable page);

 }

A:  List<Vehicle> findAllByTypeAndFkFranchiseId_ZipCode(String type, String zipCode);

A: for those who have a more complex object and want to keep their code, u can also use @Query for fetching data.
u just need to do this like this:
@Repository
public interface VehicleRepo extends JpaRepository<Vehicle, String> {
  @Query("from Vehicle v where v.type = :type and v.fkFranchise.zipCode = :zipCode")
  List<Vehicle> findAllByTypeAndZipCode(String type, String zipCode);
 }


text:
Q: Search in flat array based double link list when element in between head and tail I have a double link list using arrays and while inserting elements I maintain order, something like this.  I am treating new values (nodes) as array indices and store them directly to their location. The link list is quite long. Everything is working as required but is there any algorithm or ideas that can help me to reduce number of iterations when a node falls between head and tail?
That is
if (new_node > head && new_node < tail) {
        search from head()
}

So to reduce iteration; I added search from tail() after finding new-node is closer to which head or tail. Then I added a mid-node that is somewhere in mid of head and tail. But still I am still not able to reduce iterations when node needs to be linked. Will knowing range of values help? What else can be done to reduce number of iteration while inserting (due to sorted nature)?
I hope I am able to explain this properly.

A: Here is a SO answer discussing the difference between array and linked list: insert/delete functions.
tldr; It is a limitation of double linked lists. Even if you wrap it inside an array to do stuff.
Understanding the underlying methods of how a linked list and array works will help identify the impossible issue you are solving. Unless you utilize a different structure, you will typically have the issues you are describing.
I would do the following:

*

*Consider your problem, what do you CARE about

*

*Searching?

*Insert/Delete?

*Memory size?

*Then decide a data structure that best solves your problem

*

*Array

*Linked List

*Trees

*Hash


text:
Q: C++ very weird behavior of double comparison Simple double value comparison isn't working..

as seen in the screenshot,
double mag = 0.109981
double radius = 0.002

thus,
if(mag > radius) {
    // it's always false?
}

should be obviously true, but it isn't. How is 0.109981 not greater than 0.002?
What am I doing wrong here? It gives architecture warning, but I still don't understand what's going on here..
double mag = dVec.magnitude();
double radius = TOOL_TIP_RADIUS;
double diff = mag - radius;
cout << "mag: " << mag << endl << "radius: " << radius << endl << "diff: " << diff << endl << "mag > radius : " << (mag > radius) << endl;
if (mag > radius) {
    // no collision
    fve == (int) OUTSIDE;
}

A: If you're assuming the line:
fve == (int) OUTSIDE;

does nothing because fve is not being set to OUTSIDE, it's because you're not setting fve to OUTSIDE.
You're comparing fve and OUTSIDE for equality then throwing away the result.
I suspect you should have written (with one =):
fve = (int) OUTSIDE;


text:
Q: vTiger Contacts - Change Default View Is it possible to change the default view when a user selects a Contact from the system to display their info? By default the 'Contact Summary' is displayed whereas I'd like to display the 'Contact Details' as seen when the user clicks on Contact Details from the right side menu. I cannot find where in the system this choice is set...thanks.

A: Yes you can change the default record view user wise but that will be for all modules. Go to My Preference page which you can get by clicking on User name in Top Right corner.
Now on that page find a block "More Information" and set the value of "Default record View" field to Detail so when ever you will open any module record it will get detail view of that record.

A: Yes. You can.

*

*Go to the Admin section

*Studio

*Module manager

*Select Contacts module

*Click on field which you want to appear on Summary page.

*Select "Summary View"

For more details you can refer vTiger Summary Page info


text:
Q: How to get this sequence list I hope to get a list whose elements decrease by $2$ or increase by $1$, in turn, until the last element is $0$. For instance, starting with $4$ the sequence would be {4, 2, 3, 1, 2, 0}. If you gave me $5$ instead, the sequence would be {5, 3, 4, 2, 3, 1, 2, 0}.
This is my current method:
i = 1;
NestWhileList[If[++i; EvenQ[i], # - 2, # + 1]&, 5, UnequalTo[0]]

{5, 3, 4, 2, 3, 1, 2, 0}

But I am not very satisfied with that intermediate variable i. I would like to find other methods.

A: f = FoldList[Plus, #, {-2, 1}[[Mod[Range[2 # - 3], 2, 1]]]] &

f @ 5

{5, 3, 4, 2, 3, 1, 2, 0}

f @ 4

{4, 2, 3, 1, 2, 0}

A: A combination of Range and Riffle produces the desired result.
sequence[n_Integer] := Riffle[Range[n, 2, -1], Range[n - 2, 0, -1]]

Applying to 5
sequence[5]
(* {5, 3, 4, 2, 3, 1, 2, 0} *)

A: seq[n_ /; n > 1] := Reverse[Riffle[Range[0, n - 2], Range[2, n]]]
seq[6]

{6, 4, 5, 3, 4, 2, 3, 1, 2, 0}

A: f[{x_, y_}] := {x + 1 - 3 Mod[y, 2], y + 1}
func[a_] := NestWhileList[f, {a, 1}, #[[1]] != 0 &][[All, 1]]

e.g.func[10] yields:
{10, 8, 9, 7, 8, 6, 7, 5, 6, 4, 5, 3, 4, 2, 3, 1, 2, 0}


text:
Q: "kubectl describe ingress ..." could not find the requested resource I am trying to execute describe on ingress but does not work. Get command works fine but not describe. Is anything that I am doing wrong? I am running this against AKS.
usr@test:/mnt/c/Repos/user/charts/canary$ kubectl get ingress
NAME            HOSTS                              ADDRESS   PORTS   AGE
ingress-route   xyz.westus.cloudapp.azure.com                80      6h

usr@test:/mnt/c/Repos/user/charts/canary$ kubectl describe ingress ingress-route
Error from server (NotFound): the server could not find the requested resource

Version seems fine:
Client Version: version.Info{Major:"1", Minor:"15", GitVersion:"v1.15.3", ..}
Server Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.10"...}

A: This could be caused by the incompatibility between the Kubernetes cluster version and the kubectl version.
Run kubectl version to print the client and server versions for the current context, example:
$ kubectl version

Client Version: version.Info{Major:"1", Minor:"16", GitVersion:"v1.16.1", GitCommit:"d647ddbd755faf07169599a625faf302ffc34458", GitTreeState:"clean", BuildDate:"2019-10-02T17:01:15Z", GoVersion:"go1.12.10", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"13+", GitVersion:"v1.13.10-gke.0", GitCommit:"569511c9540f78a94cc6a41d895c382d0946c11a", GitTreeState:"clean", BuildDate:"2019-08-21T23:28:44Z", GoVersion:"go1.11.13b4", Compiler:"gc", Platform:"linux/amd64"}

You might want to upgrade your cluster version or downgrade your kubectl version. See more details in https://github.com/kubernetes/kubectl/issues/675


text:
Q: Why is my excel reader class reading every field correctly except for the date field? I am reading in multiple fields from an excel sheet using Interop and it is working almost perfectly. Every field is read in except for the date field, which is populated by a weird number that has nothing to do with anything on the excel document. My code that is needed to run the program is below. In order to see the problem the test class must be run in order to see the results that are printed out on the console as well as the tests in the test class. The excel file must be on the desktop and titled TEST.xlsx. If you need to check my Excel sheet it is linked here on a google document.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApplication1
{
    /// <summary>
    /// This class reads data from an excel sheet and stores the data in Sales objects
    /// and then places each Sale into a List of Sales.
    /// </summary>
    public class Reader
    {
        public string path;
        public _Application excel;
        public _Workbook wb;
        public _Worksheet ws;
        public List<Sales> salesList { get; set; }

        /// <summary>
        /// This constructor opens the excel file, creates a list of sales, creates a modifier
        /// object.
        /// </summary>
        /// <param name="path"> Name of the excel file to be opened.  </param>
        /// <param name="sheet"> Sheet number within the excel file. </param>
        public Reader(string path, int sheet)
        {

            this.path = path;

            excel = new _Excel.Application();
            wb = excel.Workbooks.Open(path);
            ws = wb.Worksheets[sheet];

            salesList = new List<Sales>();
            createSales();

            // Console output test to ensure the excel file is being read correctly.
            for (int i = 0; i < salesList.Count; i++ )
            {
                Console.WriteLine("Row: " + (i + 1).ToString());
                Console.WriteLine(salesList[i].salesNum);
                Console.WriteLine(salesList[i].material);
                Console.WriteLine(salesList[i].description);
                Console.WriteLine(salesList[i].MSPS);
                Console.WriteLine(salesList[i].MRPC);
                Console.WriteLine(salesList[i].quantity);
                Console.WriteLine(salesList[i].date);
                Console.WriteLine("");
            }
        }

        public Reader()
        {
            new Reader("", 1);
        }

        /// <summary>
        /// This method creates a new Sale for every row in the excel file.
        /// </summary>
        /// <returns> Number of rows (sales) in the excel sheet. </returns>
        public int createSales()
        {
            int rows = 1; // Excel sheets start at 1 not 0.

            while (ws.Cells[rows, 1].Value2 != null)
            {
                Sales sale = new Sales();
                addFields(sale, rows);
                salesList.Add(sale);

                rows++;
            }

            return rows;
        }

        /// <summary>
        /// This helper method adds fields to all of the sales.
        /// </summary>
        /// <param name="sale"> Sale that is getting fields filled. </param>
        /// <param name="row"> Row to look for fields on </param>
        private void addFields(Sales sale, int row)
        {
            int i = 1;

            sale.salesNum = readCell(row, i);              // Sales Number field
            i++;

            sale.material = readCell(row, i);              // material field
            i++;

            sale.description = readCell(row, i);           // Description field
            i++;

            sale.MSPS = readCell(row, i);                  // MSPS field
            i++;

            sale.MRPC = readCell(row, i);                  // MRPC field
            i++;

            sale.quantity = readCell(row, i);              // Quantity field
            i++;

            sale.date = readCell(row, i);                  // Date field
        }

        /// <summary>
        /// This method reads a cell from the excel document.
        /// </summary>
        /// <param name="i"> The x-coordinate of the cell to read. </param>
        /// <param name="j"> The y-coordinate of the cell to read. </param>
        /// <returns> Data in the cell in a string. </returns>
        private string readCell(int i, int j)
        {
            if (ws.Cells[i, j].Value2 != null)
            {
                return ws.Cells[i, j].Value2.ToString();
            }
            else
            {
                return "";
            }
        }

    }
}

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections;
using System.Collections.Generic;
using ConsoleApplication1;

namespace AutomationProgramTests
{
    [TestClass]
    public class ReaderTest
    {

        Reader reader;

        [TestMethod]
        public void testCreateSales()
        {
            reader = new Reader(@"C:\Users\abochel\Desktop\TEST.xlsx", 1);

            // Check if the list added every sale.
            Assert.AreEqual(90, reader.salesList.Count);

            // Check contents of sales[0].
            Assert.AreEqual("5/11/2017", reader.salesList[0].date);

            // Check contents of sales[1]
            Assert.AreEqual("5/11/2017", reader.salesList[1].date);

            // Check contents of sales[89]
            Assert.AreEqual("5/22/2017", reader.salesList[0].date);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;

namespace ConsoleApplication1
{
    /// <summary>
    /// Created and tested by Alexander James Bochel.
    /// Last Updated: 6/7/2017
    /// </summary>
    class Program
    {

        /// <summary>
        /// This will call the rest of the classes in the program.
        /// </summary>
        /// <param name="args"> Command line arguments. </param>
        static void Main(string[] args)
        {
            openAndExecute();
        }

        public static void openAndExecute()
        {
            Reader reader = new Reader(@"C:\Users\abochel\Desktop\TEST.xlsx", 1);
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    /// <summary>
    /// This class contains information about each individual row on the excel sheet.
    /// </summary>
    public class Sales
    {
        // Each variable is a cell in the row for each sales order in excel.
        public String salesNum { get; set; }
        public String material { get; set; }
        public String description { get; set; }
        public String MSPS { get; set; }
        public String MRPC { get; set; }
        public String quantity { get; set; }
        public String date { get; set; }

        /// <summary>
        /// Basic Constructor.
        /// </summary>
        public Sales()
        {
            // TODO finish basic constructor.
        }

        /// <summary>
        /// This constructor sets up all of the variables within each sale.
        /// </summary>
        /// <param name="salesN"> Sales number </param>
        /// <param name="mat"> Type of material </param>
        /// <param name="desc"> Description </param>
        /// <param name="MS"> IDK </param>
        /// <param name="MR"> IDK </param>
        /// <param name="quant"> How many </param>
        /// <param name="dat"> IDK </param>
        public Sales(String salesN, String mat, String desc, String MS, String MR, String quant,
                     String dat)
        {
            // Can these be deleted.
            salesNum = salesN;
            material = mat;
            description = desc;
            MSPS = MS;
            MRPC = MR;
            quantity = quant;
            date = dat;
        }
    }
}

A: That weird number is actually just a representation of the date in a different format. You can try using the CDate() function on that number and that should give you the date you are looking for. Another option would be to set it to a variable that is explicitly defined as a date type.


text:
Q: How to dispose browser in CEF to load the next one in I'm having some CefSharp issues on my WinForm application, after reading the CefSharp guide and doing some extensive googling i'm unable to solve this issue.
Basically, i'm feeding through a couple of URLs to a second form, I am looking to load url1.com into a panel containing the browser panelBrowserMain.Controls.Add(browser); once i'm finished with that url i'll load in url2.com extract the data then close the form altogether.
I 'm not looking for multiple browser panels just to re-use the main one.
Code:
        public FormBrowser(string[] sitesList, string mode, FormMain formMain, Project _project, Func<string, Tuple<string, string, string>> getUserPassEmail)
        {
            InitializeComponent();
            CefSharpSettings.SubprocessExitIfParentProcessClosed = true;
            if (!Cef.IsInitialized) // Check before Initialized.
            {
                // Init CEF.
                CefSettings settings = new CefSettings
                {
                    CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"cache")
                    //UserAgent = "Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20121202 Firefox/20.0"
                };
                Cef.Initialize(settings);
            }

            _sitesToProcess = sitesList; // Array of sites [ url1.com , url2.com ] etc.
            _modeToUse = mode;           // Mode either [REG] or [LAP].
            _formMain = formMain;        // Main UI object.

            foreach (var siteToProcess in sitesList) {
                string _mode = _modeToUse == "MODE_REG" ? "-[REG]" : "-[LAP]";
                // Load the macro code to use depending on the mode selected.
                string[] _macroCode = File.ReadAllLines(@"engines\" + siteToProcess + _mode);
                browser = new ChromiumWebBrowser(siteToProcess);
                InitializeChromeBrowser(browser, _mode, _macroCode, siteToProcess, _sitesToProcess.Count(), _project, getUserPassEmail);
            }
        }

        public bool InitializeChromeBrowser(ChromiumWebBrowser browser, string _modeToUse, string[] _macroCode, string _site, int _sitesCount, Project _project, Func<string, Tuple<string, string, string>> getUserPassEmail)
        {
            bool complete = false;
            try
            {
                    if (_modeToUse == "-[REG]")
                    {
                        foreach (string _macroCodeReg in _macroCode)
                        {
                            string[] code = _macroCodeReg.Split('|');

                            switch (code[0])
                            {
                                case "RJ_U":
                                    string cleanUrl = code[1].Replace("{HOSTNAME}", _site);
                                    browser.Load(cleanUrl);
                                    panelBrowserMain.Controls.Add(browser);
                                    browser.Dock = DockStyle.Fill;
                                    browserMain.Text = cleanUrl;
                                    browser.AddressChanged += Browser_AddressChanged;
                                    break;
                                case "RJ_I":
                                    browser.ExecuteScriptAsyncWhenPageLoaded(GetAndReplaceMacro(code[1], _project));
                                    break;
                            }
                        }

                    complete = true;
                    }
            }
            catch (Exception ex)
            {
                Helpers.DebugLogging($"[{DateTime.Now}]-[{ex}]");
            }
            return complete;
        }

        private void FormBrowser_Load(object sender, EventArgs e)
        {
            try
            {
                Text = "Chrome Version: [ " + Cef.CefSharpVersion + " ]";
            }
            catch (Exception ex)
            {
                Helpers.DebugLogging($"[{DateTime.Now}]-[{ex}]");
            }
        }

What I can't seem to work out is, once a url loads and i visually can see what needs extracted done, how do I (or cefsharp) know the work is done and to dispose of the window? currently it just hangs there after the extracted data is taken, on FormClose i do browser.Dispose(); but that requires it to be manually clicked on as opposed to automatically disposing itself (if this makes sense!)
If anyone can point me in the right direction that would be great.


text:
Q: PHP date format, AM and PM reversed I am echoing out a date with the following code:
<?php echo date('h:i A', strtotime($catch[0]['catch_date'])); ?>

If I add it at 1:50PM it shows as: 1:50AM when echo'd out instead of showing PM.
I am stumped on this one. Any ideas?
Dates are being entered at the time of addition as:
'catch_date' => date('Y-m-d h:i:s')

A: You are using the wrong format.
From the manual:-

h 12-hour format of an hour with leading zeros    01 through 12
  H 24-hour format of an hour with leading zeros    00 through 23

So you need to change your code to:-
'catch_date' => date('Y-m-d H:i:s')

A: You should set the default time zone before printing out the date. Example:
date_default_timezone_set('Pacific/Auckland');

And here is a full list of supported time zones:
https://www.php.net/manual/en/timezones.php


text:
Q: Angular: Maximum call stack size exceeded with multiple valueChanges Note - I included a stackblitz link of this at the end.
I am having an issue with my code where I want a formcontrol to essentially be disabled if another formcontrol is currently populated.  Example, if field A is populated then input fields B and C will be disabled.  If field A is cleared out, then field B and C will re-enable.  This occurs on all of the three fields in their respective order meaning if you populate B then A and C will be disabled, etc.
this.SearchForm.get('a').valueChanges
    .subscribe( ( value ) => {
      if ( value ) {
        this.SearchForm.get('b').disable();
        this.SearchForm.get('c').disable();
      } else {
        this.SearchForm.get('b').enable();
        this.SearchForm.get('c').enable();
      }
    });

If I only setup this on one field, this works great.  However, if I change it to include setting up the other fields as followed:
this.SearchForm.get('a').valueChanges
    .subscribe( ( value ) => {
      if ( value ) {
        this.SearchForm.get('b').disable();
        this.SearchForm.get('c').disable();
      } else {
        this.SearchForm.get('b').enable();
        this.SearchForm.get('c').enable();
      }
    });

    this.SearchForm.get('b').valueChanges
    .subscribe( ( value ) => {
      if ( value ) {
        this.SearchForm.get('a').disable();
        this.SearchForm.get('c').disable();
      } else {
        this.SearchForm.get('a').enable();
        this.SearchForm.get('c').enable();
      }
    });

    this.SearchForm.get('c').valueChanges
    .subscribe( ( value ) => {
      if ( value ) {
        this.SearchForm.get('a').disable();
        this.SearchForm.get('b').disable();
      } else {
        this.SearchForm.get('a').enable();
        this.SearchForm.get('b').enable();
      }
    });

I get the "Maximum call stack size exceeded" error.  Maybe there is a better way of doing this with reactive forms, but I haven't come across anything yet.  Part of the reason I took this approach is because once the field is empty it will re-enable the other fields easily with less code.
Link of Stackblitz
If you comment out the valueChanges of b and c and just have one, you can see the kind of behavior I am looking for, but if you add even one additional valuechanges it gets the error.

A: There is an emitEvent option for the disable() / enable() method:
disable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
enable(opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void

https://angular.io/api/forms/AbstractControl
Try passing in { emitEvent: false }
const disableEnableOptions = {emitEvent: false };
this.SearchForm.get('a').valueChanges
    .subscribe( ( value ) => {
      if ( value ) {
        this.SearchForm.get('b').disable(disableEnableOptions);
        this.SearchForm.get('c').disable(disableEnableOptions);
      } else {
        this.SearchForm.get('b').enable(disableEnableOptions);
        this.SearchForm.get('c').enable(disableEnableOptions);
      }
    });

This should stop your changes from triggering your other subscribers. You should be able to implement this throughout the rest of your code.
Here is my fork of your stackblitz: https://stackblitz.com/edit/angular-w5r29c

A: When you call value change "a", you call another value change and so forth, until you hit the call stack limit.
Basically complete form is mapped on a model, so whenever you enable/disable any control, the form model's property changes. And because the model is changing so valueChanges event will be triggered.
If you use new version angular, you probably can use
this.form.get('b').setValue(newValue, {onlySelf: true, emitEvent: false});


text:
Q: How to remove the stand connector from the display - Samsung P2770H I have to return my monitor, Samsung P2770H, for servicing. So, I have to package it in its original packaging. My problem is, I cant remove the stand connector from the display. It is stuck.
Removing the stand from the connector is simple and OK, but I can't pull out the connector from the display. According to the user manual, it should come out fairly easily.
Can anyone suggest a safe way to remove it? The monitor is in warranty, so I do not want under any circumstances to damage it, because it would void my warranty.

A: I own this monitor (P2770H), and it is relatively easy to remove the stand. Here's how:
Remove all the cables, and leave the circular base attached.  Set the monitor on the floor, tilt the monitor face back as far as it will go.  Stand over the monitor, with your feet on top of either side of the circular base, firmly grasp the bottom edge of the monitor with both hands.  Pull upwards at a slight angle, along the tilt line of monitor.  The monitor should release from the circular base and stem easily.
This stand is designed to be removed in this manner.  You can re-attach the stand and remove it again as you need, without using any tools.

A: So, according to the user manual, you just have to push the stand out of the display. Well, both the description and the pictures are misleading in the users manual.
Let's say your monitor is on the table, lying face down. Now, you have to pull the stand out from it, parallel to the monitor (horizontally), but upwards in the same time, so that the end of the connector which is in the display gets pushed a little bit downwards. There is a metallic arch inside the hole which keeps the connector firmly inside and the only way to get it out without braking something is as I described.

A: You are absolutely correct. Pushing it down as the S24B30BL instructions show will not work, and could damage the monitor. I pushed very down very hard as shown, fearing it would break something.
Pulling up on the stand with the monitor screen down on a table and pulling up worked easily. With moderate force, it popped right out. No pixels were harmed in the removal of the stand.
I took a flat-blade screwdriver and put a bevel on the little "catch" molded into the stand connection area. It won't be hard to remove next time.

A: The base stem is indeed removable but not without some sweat. I pushed the base very firmly to one side which created a small gap on the other side. I forced a piece of thin but rigid plastic into the gap and then applied pressure on the base stem in the other direction. The stem then popped out. I would file the edge from the corner of the tooth that clips into the monitor if I ever assemble something similar.

A: The following instructions are for Samsung monitors in general and for my Samsung S22C150N monitor, I found the following instructions most helpful:
https://youtu.be/qcA2c7O0E0A
Actually a lifesaver because the textual explanations did not provide enough confidence in using the right kind of force and tilting.
All is well now. Thanks for all who contributed to this thread.


text:
Q: jest spyOn navigator.mediaDevices I am writing a small library at the moment to help with connecting to media devices, it would be nice if I could unit test the library, I have a function in my typescript library that looks like this,
static connectAudioDevice(device?: InputDeviceInfo) : Promise<MediaStream> {
    return new Promise<MediaStream>((resolve, reject) => {
        navigator.mediaDevices.getUserMedia({audio: true})
            .then(stream => {
                resolve(stream);
            })
            .catch(error => {
                resolve(error);
            })
    })
}

I want to use jest.spyOn to mock the getUserMedia is this possible? Something like,
import devices from '@/assets/lib/devices.ts';

test('Resolves with valid audio mediaStream', () => {

    const audioStream = {};
    let promise = devices.connectAudioDevice();

    jest.spyOn(window.navigator.mediaDevices, 'getUserMedia', promise);

})

But I am getting the error:

Cannot spyOn on a primitive value; undefined given

Can anyone offer me some help?

A: The navigator.mediaDevices is not implemented by JSDOM. So window.navigator.mediaDevices is undefined, that's why you got the error. Take a look at Mocking methods which are not implemented in JSDOM.
The solution is:
device.ts:
export default class Devices {
  public static connectAudioDevice(device?: InputDeviceInfo): Promise<MediaStream> {
    return new Promise<MediaStream>((resolve, reject) => {
      navigator.mediaDevices
        .getUserMedia({ audio: true })
        .then((stream) => {
          resolve(stream);
        })
        .catch((error) => {
          resolve(error);
        });
    });
  }
}

device.test.ts:
import devices from './deivce';

describe('65112057', () => {
  test('Resolves with valid audio mediaStream', async () => {
    const mockMediaDevices = {
      getUserMedia: jest.fn().mockResolvedValueOnce('fake data' as any),
    };
    Object.defineProperty(window.navigator, 'mediaDevices', {
      writable: true,
      value: mockMediaDevices,
    });
    const actual = await devices.connectAudioDevice();
    expect(actual).toBe('fake data');
    expect(mockMediaDevices.getUserMedia).toBeCalledWith({ audio: true });
  });
});

unit test result:

 PASS  src/stackoverflow/65112057/device.test.ts
  65112057
    ✓ Resolves with valid audio mediaStream (7ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |       80 |      100 |       75 |       80 |                   |
 deivce.ts |       80 |      100 |       75 |       80 |                10 |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.994s, estimated 13s


text:
Q: Как частично поменять содержимое компонента при получении ответа от сервера? (react/redux-saga) Есть компонент Header:
import * as React from 'react';
import { Link, NavLink } from 'react-router-dom';

import AppBar from '@mui/material/AppBar';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import IconButton from '@mui/material/IconButton';
import MenuIcon from '@mui/icons-material/Menu';

export default function ButtonAppBar() {
  return (
    <Box sx={{ flexGrow: 1 }}>
      <AppBar position="static">
        <Toolbar>
          <IconButton
            size="large"
            edge="start"
            color="inherit"
            aria-label="menu"
            sx={{ mr: 2 }}
          >
            <MenuIcon />
          </IconButton>
          <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
            <NavLink to="/">
              Home
            </NavLink>
            <Box style={{ display: 'flex', justifyContent: 'space-between', width: '150px' }}>
              <Link to="/login" color="inherit" className="links">Login</Link>
              <Link to="/registration" color="inherit" className="links">Registration</Link>
            </Box>
          </div>
        </Toolbar>
      </AppBar>
    </Box>
  );
}

Нужно при получении успешного статуса ответа от сервера поменять Link'и регистарции/логина на Link личного кабинета пользователя.
Примерно представляю себе это так:
isAuth
? <Link to="/profile" color="inherit" className="links">Profile</Link>
:(
<>
<Link to="/login" color="inherit" className="links">Login</Link>
<Link to="/registration" color="inherit" className="links">Registration</Link>
</>
)

Так вот, как мне получать isAuth true, когда клиент авторизован?


text:
Q: How to send http request to android emulator i've created small http server in android , code is from this link just copy pasted in eclipse.
http://www.java2s.com/Open-Source/Android/Samples/android-jp-kobe/net/cattaka/teamredwhite/HTTPServer.java.htm
How do i send simple request from browser to server now?  I would like something like this 127.0.0.1:12345?x=100&y=50 for example. Browsers always says that he didnt make connection with that url.
In on create of main activity i just created a server with port 12345 and run .listen()

A: 127.0.0.1 on is your local computer, not the emulator.
The emulator has its own network address space:
You're most likely looking for 10.0.2.15, "the emulated device's own network/ethernet interface", e.g. http://10.0.2.15:12345?x=100&y=50.


text:
Q: Using a factory in config I know the config phase runs before the services are available, but I have a situation where I need to use a myJsonDateTimeService to inject a $httpProvider.defaults.transformResponse like that:
angular.module('myJsonDateTimeInterceptor', ['myJsonDateTime'])
.config(function($httpProvider, myJsonDateTimeService){
    $httpProvider.defaults.transformResponse.push(function(responseData){
        myJsonDateTime.format(responseData); // Logic to change DateTime.
        return responseData;
    });
});

angular.module('myJsonDateTime', [])
.factory('myJsonDateTimeService', function(){
    var factory = {
        format: function(data) { ... }
    };
    return factory;
});

The problem is that myJsonDateTimeService is used as service in other places and I would like to reuse the same logic in the config of my interceptor instead just replicate the format code.
I also don't know how to create a myJsonDateTimeProvider that could use the same logic of the factory.
Edit 1
As suggested, I rebuild this factory in a provider like that:
angular.module('myJsonDateTime', [])
.provider('myJsonDateTimeService', function(){
    var format = function(data) { ... };
    this.format = format;

    this.$get = function() {
        return { format: format };
    };
});

Not sure if that's the best way as the provider should be used to configure and not provide functions like formatting.


text:
Q: Generate all ordered combinations of a list, where each combination includes all items Whats the best way to generate all combinations of a list, where each combinations contains every item from the list and where you can combine other items.
For example, for a list ['a','b','c'], I like to generate:
['a','b','c']
['ab','c']
['a','bc']
['abc']

I find it a bit similar to: Python: Generating all ordered combinations of a list.  But this one only cares about the slices.  I want all the combinations that takes every item from the list.  Is there a built in function from itertools that can be used to generate the answer?
The list could also be numbers, that could have duplicates values.  For example: [1,2,1] should generate:
[1,2,1]
[12,1]
[1,21]
[121]

I could try to use the code from the link, but instead of generating combinations of the items, I would generate the combinations base on the index of the list. Where I take all combinations that start with 0, then look for the next item and look for all combinations that start with that item and so on.  I dont think that would be efficient though.

A: You can think of two adjacent characters in your string as being either "separated" or "concatenated". Using itertools.product() you can generate all combinations of separated/concatenated between two characters and then use a simple function to generate a list of strings from this information:
import itertools

l = ['a','b','c']

def generate_combination(source, comb):
    res = []
    for x, action in zip(source,comb + (0,)):
        res.append(x)
        if action == 0:
            yield "".join(res)
            res = []

print [list(generate_combination(l,c))
       for c in itertools.product((0,1), repeat=len(l)-1)]

This doesn't work for numbers though unless you convert them to strings first.

A: Here is additional code to make  @acidtobi answer work for both int and char with the help of .isdigit().
final = [list(generate_combination(l,c))
       for c in itertools.product((0,1), repeat=len(l)-1)]

print [[int(i) if i.isdigit() else i for i in alist ] for alist in final]

So for  l = [ 1,2,3] , it will show
>>>
[[1, 2, 3], [1, 23], [12, 3], [123]]

And for l = ['a','b','c']
>>>
[['a', 'b', 'c'], ['a', 'bc'], ['ab', 'c'], ['abc']]

A: import numpy as np
l = ['a','b','c','d']
#l = [0,1,2,3]
d = np.arange(2**(len(l)-1))
#create a separator array for all possible combinations
sep = np.where((d[:,None] & (1 << np.arange(len(l))[::-1])) > 0, ',','')
#merge the separator to the strings
merged = np.core.defchararray.add(sep,np.asarray(l,dtype=str)).tolist()
#reformat and split
[''.join(e).split(',') for e in merged]

#works for any characters
[['abcd'],
 ['abc', 'd'],
 ['ab', 'cd'],
 ['ab', 'c', 'd'],
 ['a', 'bcd'],
 ['a', 'bc', 'd'],
 ['a', 'b', 'cd'],
 ['a', 'b', 'c', 'd']]

Out[128]:
[['0123'],
 ['012', '3'],
 ['01', '23'],
 ['01', '2', '3'],
 ['0', '123'],
 ['0', '12', '3'],
 ['0', '1', '23'],
 ['0', '1', '2', '3']]


text:
Q: openLDAP N Way Multimaster Does anyone know what the maximum number of nodes can be configured in a OpenLDAP N Way Multimaster configuration?
I have been looking through the internet and all I see in the number of database transactions replicated and not the actual number of nodes that can be used to communicate with each other.

A: I have confirmed, there is no limitation in nodes with N way mirror mode configuration in OpenLDAP.
Just some information related to mirror-mode, Mirror mode is not Multiple master replication as some people thinks. This is because writes have to go to just one of the mirror nodes at a time.
Refer arguments against mirror-mode in http://www.openldap.org/doc/admin24/guide.html#MirrorMode%20replication


text:
Q: Jquery animation loop problem I am trying to execute an animation function in a loop. I have manged to figure out one iteration of it but i am unable to figure out how to repeat the loop a set number of time. Below is my animation function. Please help me figure out how do i run this any number of times or even make it a never ending loop.
<script type="text/javascript">
$(document).ready(function(){
    var delay = 150;
    var times = 4;
    var i = 1;

    doMove = function() {
        if( i < times ){
            $('#lip').removeClass('lip'+i);
            $('#lip').addClass('lip'+(i+1));
        } else if ( i == times ) {
            $('#lip').removeClass('lip4');
            $('#lip').addClass('lip1');
        }

        ++i;
        if( i >= times ) {
            clearInterval( interval ) ;
        }
    }

    var interval = setInterval ( "doMove()", delay );

});
</script>

Thanks a lot. I am new to jquery.

A: The delay is very short in your script - so perhaps you are not seeing the changes take place. Try changing
var delay = 150;

To
var delay = 1000; // 1 second

UPDATE
Ah - you want it to run again on completion... here is an example:
repeats = 0 will be infinite loops, 1 will run once, 2 will run twice and so on...
var delay = 150;
var times = 4;
var repeats = 3;
var i = 1;
var j = 0;

doMove = function() {
    if( i < times ){
        $('#lip').removeClass('lip'+i);
        $('#lip').addClass('lip'+(i+1));
    } else if ( i == times ) {
        $('#lip').removeClass('lip4');
        $('#lip').addClass('lip1');
    }

    ++i;
    if( i >= times ) {
        if (j < repeats || repeats == 0) {
            i = 1;
        } else {
            clearInterval( interval ) ;
        }
    }
    ++j;
}

var interval = setInterval ( "doMove()", delay );


text:
Q: How to show PDF document in a View and allow the user to manipulate it in c# MVC Here is the situation: I have a PDF documents that have input fields. When the user enters the inputs and push the "Calculate"button(outside the pdf) the "result" field must be calculated. I have a logics that makes the calculations already defined. Simple example in pseudo code:
int firstValue = the_first_input_on_the_pdf.Value;
int seconValue = the_secon_input_on_the_pdf.Value;

int result = firstValue + secondValue;

the_result_input_of_the_pdf.Value = result.ToString();

Something like that, but I want to keep the formatting of the PDF file. I already have it ready for filling. Just the calculations have to be done. I have been looking for third party libraries and this is what I stopped at: iTextSharp and I want to know if this is possible to do with with it or there is a better way.
PS:I need to implement that in a MVC application.


text:
Q: How fast layout is drawn? How can one calculate how fast it takes for a specific layout to be drawn (From A-Z)? And.. Is there a possibility to calculate every part of layout building - measure, layout, draw.

A: Do you need profiling for layout? I'll start here:
https://developer.android.com/studio/profile/hierarchy-viewer.html


text:
Q: The opposite of paper being a dead-tree In this question, John Y refers to a printed version of a book as "dead-tree book". I found that amuzing and started to wonder what the opposite of such term would be.
Of course, the popular term would be "electronic book". However, I'd like to retain the style of the original wording.

A: How about a live-wire book? The e-book can't appear without electricity, and that's going to involve a live wire somewhere. (though we might need to allow a conductive trace on a circuit board to be signfied as a "wire")
The trouble with any "clever" alternative to the standard term "e-book", is that you're probably going to spend so much time explaining your alternative, that its snappiness is wasted.

A: How about tree-friendly books, paper-free books, and save-a-tree books?

A: How about  :-
"No-tree-dead book"


text:
Q: Testing DOM, Phantom, Sinon, Mocha - How to check if element was clicked I need test if text on the button was change, after click. But I can't find anywhere - how to do it.
Please help :(,
I run test
mocha-phantomjs TestRunner.html
My code is :
TestRunner.html
 <!doctype html>

    <title>Tests</title>
    <link rel="stylesheet" href="mocha.css" />

    <button data-text="SomeText"> Button </button>

myscript.js
var button = document.querySelector('button');

 button.addEventListener('click' , function(){
     this.innerText = this.dataset.text;
 });

test.js
describe("Change text on button", function () {

    var clickElement = function (el){
       var ev = document.createEvent("MouseEvent");
       ev.initMouseEvent(
         "click",
         true /* bubble */, true /* cancelable */,
         window, null,
         0, 0, 0, 0, /* coordinates */
         false, false, false, false, /* modifier keys */
         0 /*left*/, null
       );
       el.dispatchEvent(ev);
   };

    var button = document.querySelector('button');

    before(function(){
       clickElement(button);
    })

   it("Click on button - change text: 'SomeText'",
         function () {
             expect(button.innerText).to.equal("SomeText");
   });

});


text:
Q: Does nanomsg have the concept of 'frames' as zeromq? I have been using zeromq for some time and use multipart message extensively. In C++, I use zmq_sendiov/zmq_recviov to send/recv multipart message. The benefit is I can put each message 'frame' in one iovec, and use the call to send/recv in one go.
Recently I decide to give nanomsg a try, I realize nanomsg has nn_sendmsg/nn_sendmsg which also use iovec. The question is: does nanomsg make sure that the structure of the iovec that is received being the same as the one gets sent? e.g., suppose I put
msg[0].iov_base = "Hello";
msg[0].iov_len = 5;
msg[1].iov_base = "World";
msg[1].iov_len = 5;

and send, will the receiving end get the same iovec array, with "Hello" and "World" in each element, or nanomsg is free to reassemble the buffer?
Thanks
Ralph

A: Currently in the documentation about this says nothing, but I sure that nanomsg make sure that the structure of the iovec that is received being the same as the one gets sent, because exist one unit test (see https://github.com/nanomsg/nanomsg/blob/fb5670c952c53834c5c7c989eace7c6bd54bd4c5/tests/iovec.c), which confirms my assumptions.

A: nanomsg-1.0.0 already support iov
nn_sendmsg


text:
Q: OPENROWSET error accessing XLSX if not manually saved Good day,
Apologies if this is in the wrong forum. Please refer me to the correct one if this is the case, thank you.
I have a bunch of excel files that are added to a Dropbox folder on a monthly basis. These files should then be imported to a SQL Server Database.
My problem is that, when I try and import data from SOME of these XLSX files, OPENROWSET gives me the following error:
Msg 7399, Level 16, State 1, Line 14
The OLE DB provider "Microsoft.Ace.OLEDB.12.0" for linked server "(null)" reported an error. The provider did not give any information about the error.
Msg 7303, Level 16, State 1, Line 14
Cannot initialize the data source object of OLE DB provider "Microsoft.Ace.OLEDB.12.0" for linked server "(null)".
This is a general error message and I was not able to find a solution related to my problem in another thread.
Once I open a file and SAVE it MANUALLY, then OPENROWSET SUCCESSFULLY reads the selected range from the XLSX file.
I think that means OPENROWSET has some kind of access or permition restriction to these files, but I do not know why as other files with the same format does not produce this error.
Is there a way to give OPENROWSET power to read these files even if they have not been manually saved? Any alternate suggestion on how to overcome this problem in SQL will be much appreciated.
Thanks,
Raynard


text:
Q: I am getting this error: MermaidExtension.extendMarkdown() missing 1 required positional argument: 'md_globals' This was working not too long ago (probably inadvertently upgraded a library somewhere.)  All of my libraries are up to date.
Here is the stack trace:
 File "C:\Users\jorda\Documents\projects\python\poolBoy\flaskApp.py", line 422, in about
    html += markdown.markdown(text, extensions=['md_mermaid', 'fenced_code', 'tables'])
  File "C:\Users\jorda\Documents\projects\python\poolBoy\venv\lib\site-packages\markdown\core.py", line 386, in markdown
    md = Markdown(**kwargs)
  File "C:\Users\jorda\Documents\projects\python\poolBoy\venv\lib\site-packages\markdown\core.py", line 96, in __init__
    self.registerExtensions(extensions=kwargs.get('extensions', []),
  File "C:\Users\jorda\Documents\projects\python\poolBoy\venv\lib\site-packages\markdown\core.py", line 125, in registerExtensions
    ext.extendMarkdown(self)
TypeError: MermaidExtension.extendMarkdown() missing 1 required positional argument: 'md_globals'

Any suggestions would be most appreciated!

A: Must have upgraded Markdown inadvertently.  I added the following to my requirements and it is working fine now:
Markdown<3.2


text:
Q: How to get CMFEditions "view this revision" working for items that use a BrowserView in Plone I have a custom template for news items defined using a BrowserView overriding the default template in Plone's skin layer.  We also have CMFEditions installed.  Trying to view a previous revision results in an error as discussed in this Plone bug.  We're in the process of upgrading to Plone 3.3.6 so the "fix" describe there is in place but I'm still seeing the "view this revision" link and it still results in an error
Traceback (innermost last):
  Module ZPublisher.Publish, line 119, in publish
  Module ZPublisher.mapply, line 88, in mapply
  Module ZPublisher.Publish, line 42, in call_object
  Module Shared.DC.Scripts.Bindings, line 313, in __call__
  Module Products.PloneHotfix20110531, line 106, in _patched_bindAndExec
  Module Shared.DC.Scripts.Bindings, line 350, in _bindAndExec
  Module Products.CMFCore.FSPageTemplate, line 216, in _exec
  Module Products.CacheSetup.patch_cmf, line 51, in FSPT_pt_render
  Module Products.CacheSetup.patch_cmf, line 126, in PT_pt_render
   - Warning: Macro expansion failed
   - Warning: exceptions.KeyError: 'view_macro'
  Module zope.tal.talinterpreter, line 271, in __call__
  Module zope.tal.talinterpreter, line 346, in interpret
  Module zope.tal.talinterpreter, line 891, in do_useMacro
  Module zope.tal.talinterpreter, line 346, in interpret
  Module zope.tal.talinterpreter, line 536, in do_optTag_tal
  Module zope.tal.talinterpreter, line 521, in do_optTag
  Module zope.tal.talinterpreter, line 516, in no_tag
  Module zope.tal.talinterpreter, line 346, in interpret
  Module zope.tal.talinterpreter, line 957, in do_defineSlot
  Module zope.tal.talinterpreter, line 346, in interpret
  Module zope.tal.talinterpreter, line 536, in do_optTag_tal
  Module zope.tal.talinterpreter, line 521, in do_optTag
  Module zope.tal.talinterpreter, line 516, in no_tag
  Module zope.tal.talinterpreter, line 346, in interpret
  Module zope.tal.talinterpreter, line 861, in do_defineMacro
  Module zope.tal.talinterpreter, line 346, in interpret
  Module zope.tal.talinterpreter, line 957, in do_defineSlot
  Module zope.tal.talinterpreter, line 346, in interpret
  Module zope.tal.talinterpreter, line 536, in do_optTag_tal
  Module zope.tal.talinterpreter, line 521, in do_optTag
  Module zope.tal.talinterpreter, line 516, in no_tag
  Module zope.tal.talinterpreter, line 346, in interpret
  Module zope.tal.talinterpreter, line 949, in do_defineSlot
  Module zope.tal.talinterpreter, line 346, in interpret
  Module zope.tal.talinterpreter, line 855, in do_condition
  Module zope.tal.talinterpreter, line 346, in interpret
  Module zope.tal.talinterpreter, line 822, in do_loop_tal
  Module zope.tales.tales, line 685, in setRepeat
  Module zope.tales.tales, line 101, in __init__
TypeError: iteration over non-sequence

My question is how do I change my template to get this working.  The template file used by the BrowserView is a close match to the original and defines a main macro.  I'm pretty sure there is no problem with it as if I replace it with the following blank template I still get exactly the same error.
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
      xmlns:tal="http://xml.zope.org/namespaces/tal"
      xmlns:metal="http://xml.zope.org/namespaces/metal"
      xmlns:i18n="http://xml.zope.org/namespaces/i18n"
      lang="en"
      metal:use-macro="context/main_template/macros/master"
      i18n:domain="plone">
<body>
<div metal:fill-slot="main">
    <tal:main-macro metal:define-macro="main">
    </tal:main-macro>
</div>
</body>
</html>

Using Products.PDBDebugMode I can debug further and find
TypeError: iteration over non-sequence
> c:\plone\parts\zope2\lib\python\zope\tales\tales.py(101)__init__()
-> self._iter = i = iter(seq)
(Pdb) a
self = <Products.PageTemplates.Expressions.PathIterator object at 0x0B2FE350>
name = vdata
seq = <Products.CMFEditions.ZVCStorageTool.ShadowHistory object at 0x0B28C370>
context = <Products.PageTemplates.Expressions.ZopeContext object at 0x0B2E3DD0>

seq here has no iter or getitem method and so iter() raises a TypeError.  This error is originating from the versions_history_form.pt
<tal:block repeat="vdata history">

A: This error is not the same error as the one in that Plone bug.  This is happening because you have a tal:repeat somewhere that is trying to loop over something that isn't a sequence (or some other iterator).

A: Sorry looks like this is a bug in my code rather than anything else.  I was overriding the template and the bug was originating in the bit of code where the override was - I hadn't synchronized changes in Plone 3.3.6 correctly.
This question should probably be deleted


text:
Q: Updating a ListView on MainActivity from Asynctask I have a list view on the main Ui that I wish to update through an Asynctask which connects to a Mikrotik device to retrieve details.
I am passing the activity too, so that I can update the UI from a separate class file, however I keep getting the error "Class name expected here" for the activity (mActivity) in the ListAdapter constructor.
Here is the Asynctask code:
public class MikrotikReader extends AsyncTask<String, Void, ArrayList<String>> {

    //Default connection details for mikrotik
    private int mkPort = 8728;
    private int mkTimeout = 5000;
    private String userName;
    private String userPass;
    private String mkIpAddress;
    private String mkCommand;
    private ListView listView;
    private Activity mActivity;

    public MikrotikReader(String user, String pass, String ipaddress, String command, Activity activity) {
        this.userName = user;
        this.userPass = pass;
        this.mkIpAddress = ipaddress;
        this.mkCommand = command;
        this.mActivity = activity;
    }

    @Override
    protected ArrayList<String> doInBackground(String... params) {

        ArrayList<String> mylist = new ArrayList<String>();

        try {
            ApiConnection con = ApiConnection.connect(SocketFactory.getDefault(), mkIpAddress, mkPort, mkTimeout);
            con.login(userName, userPass); // log in to router
            if (con.isConnected()) {
                List<Map<String, String>> rs1 = con.execute(mkCommand);
                for (Map<String, String> results1 : rs1) {
                    getResults[0] = new String(results1.get("comment"));
                    mylist.add(getResults[0]);
                }
                con.close();
            }
        } catch (MikrotikApiException e) {
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return mylist;
    }

@Override
    protected void onPostExecute(ArrayList<String> mylist) {

        System.out.println("This is the array content " + mylist.get(0));

        listView = (ListView) mActivity.this.findViewById(R.id.listView);
        listView.setAdapter(new ArrayAdapter<String>(mActivity.this,android.R.layout.simple_list_item_1,new ArrayList<String>())); }

This is how I call the Asynctask from the MainActivity class file, passing "this" as the activity:
new MikrotikReader(user_name, password, ipaddress,"/ip/firewall/filter/print where comment=Test", this).execute();

Here is the listview in the mainactivity.xml file:
<ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/gradient_bg" />

A: try to use only mActivity instead mActivity.this in yout AsyncTask class

A: Don't do like this.
Make interface like
    public interface ListPreparingListener {
void onListPrepared(ArrayList<String> mylist);
}

And implement it on your main activity like
@Override
onListPrepared(ArrayList<String> myList) {
 listView.setAdapter(new ArrayAdapter<String>(mActivity.this,android.R.layout.simple_list_item_1,new ArrayList<String>()));
}

Then, pass this interface to you reader's constructor and call this method on post execute
Upd:
Actually it could produce memory leak, if you store a reference to your activity inside other objects. The most proper way is to make methods subscribeListener and unsubsucribeListener and subscribe when you need it from main activity, unsubscribe onStop. Also on your onPostExecute should be check if there are available listeners