text:
Q: Will Apple reject application if I call receipt validation after finishing all pending transaction inside removeTransaction delegate? I am developing Auto-Renewable In-App Purchase. Right now I am calling the Receipt Validation function inside of updatedTransactions delegate like this :
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    transactions.forEach { (transaction) in
        switch transaction.transactionState {
        case .purchased:
            self.IAPResponseCheck(iapReceiptValidationFrom: .purchaseButton)
            KeychainWrapper.standard.set(false, forKey: receiptValidationAllow)
            SKPaymentQueue.default().finishTransaction(transaction)

        case .restored:
            totalRestoredPurchases += 1
            self.IAPResponseCheck(iapReceiptValidationFrom: .restoreButton)
            KeychainWrapper.standard.set(false, forKey: receiptValidationAllow)
            SKPaymentQueue.default().finishTransaction(transaction)

        case .failed:
            if let error = transaction.error as? SKError {
                if error.code != .paymentCancelled {
                    onBuyProductHandler?(.failure(error))
                } else {
                    onBuyProductHandler?(.failure(IAPManagerError.paymentWasCancelled))
                }
                PrintUtility.printLog(tag: String(describing: type(of: self)), text: "IAPError: \(error.localizedDescription)")
            }
            SKPaymentQueue.default().finishTransaction(transaction)

        case .deferred, .purchasing: break
        @unknown default: break
        }
    }
}

First I am calling the Receipt Validation function where I am simply getting all the previous transactions list and calculating expiration dates and purchase dates to unlock my premium features from the lastest Info Receipt response array. In this function, I am checking the Purchase Status according to my logic and returning true or false. If it's true I take the user inside of my app and if it's false I take him to the purchase screen.
Then I am finishing the transaction immediately like this:
SKPaymentQueue.default().finishTransaction(transaction)

But what I have noticed is that If the user has a long transaction list (100+), It takes a long time to finish all the transactions. I print the finished transactions and remain transactions in the removedTransactions delegate like this:
func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
    PrintUtility.printLog(tag: String(describing: type(of: self)), text: "Removed transactions: \(transactions.count)")
    PrintUtility.printLog(tag: String(describing: type(of: self)), text: "Unfinished transaction: \(queue.transactions.count)")
}

The problem is If I try to restore or purchase a new product before finishing all pending transactions it triggers updatedTransactions weirdly. It works fine If I wait till it finishes all transactions one by one. So my question is, If I call receipt validation inside of removedTransactions delegate, and finish each transaction inside updateTransactions delegate will it be considered as a possible reason for app rejection on Apple?
Finally, It will look like this:
updatedTransactions delegate:
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    transactions.forEach { (transaction) in
        switch transaction.transactionState {
        case .purchased:
            SKPaymentQueue.default().finishTransaction(transaction)

        case .restored:
            totalRestoredPurchases += 1
            SKPaymentQueue.default().finishTransaction(transaction)

        case .failed:
            totalPurchaseOrRestoreFailed += 1
            SKPaymentQueue.default().finishTransaction(transaction)

        case .deferred, .purchasing: break
        @unknown default: break
        }
    }
}

removedTransactions delegate:
func paymentQueue(_ queue: SKPaymentQueue, removedTransactions transactions: [SKPaymentTransaction]) {
    print("Removed transactions: \(transactions.count)")
    print("Unfinished transaction: \(queue.transactions.count)")
    //This will be called after finishing all transactions
    if queue.transactions.count == 0 {
        if totalPurchaseOrRestoreFailed != 0 {
            transactions.forEach { (transaction) in
                switch transaction.transactionState {
                case .purchased:break
                case .restored: break
                case .failed:
                    if let error = transaction.error as? SKError {
                        if error.code != .paymentCancelled {
                            onBuyProductHandler?(.failure(error))
                        } else {
                            onBuyProductHandler?(.failure(IAPManagerError.paymentWasCancelled))
                        }
                        print("IAP Error:", error.localizedDescription)
                        totalPurchaseOrRestoreFailed = 0
                    }

                case .deferred, .purchasing: break
                @unknown default: break
                }
            }
        } else {
            self.IAPResponseCheck(iapReceiptValidationFrom: .purchaseAndRestoreButton)
            UserDefaults.standard.set(false, forKey: "receiptValidationAllow")
        }
    }
}

A: I believe the issue is exactly like in this SO question:
SKPaymentTransaction's stuck in queue after finishTransaction called
The problem isn't that Apple rejects your App because you finish each transaction inside updateTransactions, it's because Apple's framework introduces bugs if you do, and the payment simply doesn't work. It's important to realize that real users will never have this issue, because they won't have 100+ subscriptions. Because only in debugging/simulators a year-long-subscription will be considered as a 1 hour-subscription. So the solution is easy, just start the payment after the queue is empty. It's just a bug in Apple's framework, and real users won't have an issue. This is the code that I'm using, and Apple has not rejected my App since I used this:
while self.paymentQueue.transactions.count > 0 {
        DLog("Still busy removing previous transactions: \(self.paymentQueue.transactions.count)")
        delay(1) {
            self.checkTransactions()
        }
    }
    self.startPaymentRequest()


text:
Q: Remove non-ASCII characters from a string in Snowflake How do I remove all the non-ASCII characters from a string in Snowflake SQL?
I have come across solutions using T-SQL etc but no article on how to do it in snowflake.

A: A regular expression should be enough, unless you have other cases in mind:
select regexp_replace('Snéowñflake', '[^\x00-\x7F]', '')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Designing nav menu database for a cms This relates to my previous question -> How do I create nav menu for a cms?
How do I design the database for it?

A: depend what do you want to appear in that navigation menu, for example if you follow wordpress logic you can have categories or pages in the navigation menu.
if you decide to have pages there, ten you simply create a tblPages database table and in it you create the following basic columns: id, title, description, date, order.
the title will be shown in navmenu, description will be shown on click as well as the date, the order will be used to specify the order in the navmenu.
If you decide to have categories in the navigation menu, then you will need categories table with those columns id, title, order, and another table posts with the following fields: id, titile, shorttext, fulltext, views, categoryid (this is foreign key of id in categories table), publicationdate, author ...


text:
Q: Utilização de um join para junção de duas tables Gostaria de saber se é possível e indicavel usar um join para "juntar" valores  contidos em duas tables feitas em um banco de dados do SQL Server. Eu criei duas tables e uma delas tem informações gerais de um cliente e a outra tem informações de contato. O que acontece é que eu separei essas duas informações em duas tables pois vou colocar essas informações dividias nas abas de um tabControl (duas pages, no caso).
Estava pensando em fazer um join pelo ID da tabela com informações gerais, pois assim eu poderia conectar todos os dados de cada registro.
E além disso, gostaria de saber se é necessário criar alguma classe para fazer a inserção dessas tables no tabControl ou tem como fazer só um select ou algo do tipo.
CREATE TABLE tblClientes (
ID int IDENTITY(1,1) PRIMARY KEY NOT NULL,
Nome varchar(255) NOT NULL,
Telefone varchar(255) NOT NULL,
Tipo varchar(255) NOT NULL, );

SELECT * FROM tblContato
INNER JOIN tblClientes
ON tblContato.ID=tblClientes.ID;

A: Depois de escrever a SQL da forma que gere a tabela com os resultados pretendidos, você pode retornar essa tabela em um DataTable:
DataTable dt = ConexaoBancoDados.ExecReader(sql);

Depois você deve criar um elemento gridView para exibir os dados:
gridView.DataSource = dt;


text:
Q: Linearly independent set Suppose I have $f\in L(V,V)$ such that $f^n=0$ but $f^k\neq 0\,\,\forall k<n$. Would I be right in thinking that there exists $v\in V$  such that $\{f^k(v)|0\leq k\leq n-1\}$ is linearly independent? If I am right, how could I find this $v$?
Thanks

A: If $f^n=0$ but $f^k\neq 0$ for any $k\lt n$, then the minimal polynomial of $f$ is $t^n$; the characteristic polynomial is $t^{\dim (V)}$.
As Davide Giraudo notes, the fact that $f^{n-1}\neq 0$ guarantees the existence of a vector $v\in V$ such that $f^{n-1}(v)\neq\mathbf{0}$. The claim now is that $v$, $f(v),\ldots, f^{n-1}(v)$ are linearly independent.
One way to see this is to note that the $f$-annihilator of $v$ (the polynomial $p(t)$ of least degree such that $p(f)(v) = 0$) must divide the minimal polynomial, and hence must be of the form $t^k$ for some $k\leq n$; but if $f^k(v)=\mathbf{0}$, then $f^{k+i}(v)=\mathbf{0}$ for all $i\geq 0$. Since $f^{n-1}(v)\neq\mathbf{0}$ by choice of $v$, the $f$-annihilator must be $x^n$.
Now, if $\alpha_0,\ldots,\alpha_{n-1}$ are scalars such that
$$\alpha_0 v + \alpha_1f(v)+\cdots \alpha_{n-1}f^{n-1}(v)=\mathbf{0},$$
then $p(f)(v)=\mathbf{0}$, where $p(t) = \alpha_0+\alpha_1t+\cdots + \alpha_{n-1}t^{n-1}$. Since this must be a multiple of $t^n$, the only possibility is that $p(t)=0$, so $\alpha_0=\cdots=\alpha_{n-1}=0$, proving that $v$, $f(v),\ldots,f^{n-1}(v)$ are indeed linearly independent.
If you don't have the theory of $f$-annihilators, assume that
$$a_0v + \cdots + a_{n-1}f^{n-1}(v)=\mathbf{0}$$
Applying $f$ to both sides $n-1$ times; using the fact that $f^{n+i}(v) = \mathbf{0}$ for all $i\geq 0$ and $f^{n-1}(v)\neq \mathbf{0}$, we get $a_0f^{n-1}(v) = \mathbf{0}$, and so we can deduce that $a_0=0$. This leaves
$$a_1f(v) + \cdots + a_{n-1}f^{n-1}(v)=\mathbf{0}.$$
Now apply $f$ again $n-2$ times to conclude $a_1=0$; proceed in this manner to show $a_0=\cdots=a_{n-2}=0$; this leaves $a_{n-1}f^{n-1}(v)=\mathbf{0}$, and since $f^{n-1}(v)\neq \mathbf{0}$, then $a_{n-1}=0$. This proves linear independence.


text:
Q: Solving a Fredholm Equation of the second kind I'm trying to solve the Fredholm equation,
$$
\phi(x) = 3 + \lambda \int_{0}^{\pi} \text{cos}(x-s) \, \phi(s) \,ds.
$$
I began by using the method of successive approximations and found the iterated kernels,
$$
\begin{split}
K_1 (x,s) &= \text{cos}(x-s)\\
K_2 (x,s) &= \int_0^\pi \text{cos}(x-t) \, \text{cos}(t-s)\,dt \equiv \frac{\pi}{2}\text{cos}(x-s)\\
K_3(x,s) &= \int_0^\pi \text{cos}(x-t) \, \frac{\pi}{2}\text{cos}(t-s) \,dt \equiv (\frac{\pi}{2})^2 \,\text{cos}(x-s)\\
&\vdots \\
K_{n+1} (x,s) &= (\frac{\pi}{2})^n \,\text{cos}(x-s)\\
&\vdots
\end{split}
\quad\text{ for}\,\, n=0,1,2,\dots.
$$
Noting that the resolvent kernel is given by
$$
R(x,s;\lambda) = \sum_{n=0}^\infty \lambda^n\,K_{n+1}(x,s)
$$
then we find,
$$R(x,s;\lambda) = \frac{\text{cos}(x-s)}{1-\frac{\lambda \pi}{2}}.$$
The equation to be solved is then,
$$
\phi(x) = 3 + \lambda\int_0^\pi R(x,s;\lambda) \, ds
$$
which is solved and found to be,
$$\phi(x) = 3 + \frac{\lambda}{1-\frac{\lambda \pi}{2}} 2 \,\text{sin}(x)$$
I have tried confirming this solution by transforming the initial question to a differential equation but cannot find the same solution as shown above. However, I am certain that the answer above is correct. Can anyone see a flaw in my solution?

A: There is only a tiny mistake: we have
$$ \phi(x) = 3 + \lambda \int \limits_0^\pi R(x,s;\lambda) \color{red}{3} \, \mathrm {d} s = 3 + \frac{\color{red}{6} \lambda}{1 - \lambda \frac{\pi}{2}} \sin(x) \, .$$
This is the correct solution for all $\lambda \in \mathbb{R} \setminus {\frac{2}{\pi}}$. For $\lambda = \frac{2}{\pi}$ there is no solution, since $\frac{\pi}{2}$ is an eigenvalue of the integral operator. Note, however, that your series only converges for $|\lambda| < \frac{2}{\pi}$.
In order to confirm the above result and to extend its validity to all $\lambda \in \mathbb{R} \setminus {\frac{2}{\pi}}$, we can employ the method of degenerate kernels. Using a trigonometric addition formula we may write the integral equation as
$$ \phi (x) = 3 + \lambda \cos(x) \int \limits_0^\pi \cos(s) \phi(s) \, \mathrm{d} s + \lambda \sin(x) \int \limits_0^\pi \sin(s) \phi(s) \, \mathrm{d} s \, . $$
Therefore, the solution must have the form $\phi(x) = 3 + a \cos(x) + b \sin(x)$ for some $a,b \in \mathbb{R}$. Plugging this result back into the equation we obtain a system of linear equations for $a$ and $b$, which has no solution for $\lambda = \frac{2}{\pi}$ and the unique solution $a = 0$ and $b = \frac{6 \lambda}{1-\lambda \frac{\pi}{2}}$ for $\lambda \in \mathbb{R} \setminus {\frac{2}{\pi}}$ as expected. Alternatively, we can derive a differential equation for $\phi$. Its general solution has the form given above and suitable boundary conditions lead to the same linear system.


text:
Q: How can I pass a cloud-config script for post-installation configuration in SoftLayer? My question has 2 parts:

*

*Is there any way at all to pass a cloud-config formatted script to a machine? I do not mean a post installation script in Python, or in Bash etc. I want it to be cloud-config formatted (e.g. #cloud-config).

*If there is a way to use the REST API to pass this script as a parameter, then the postInstallScriptUri parameter does not suit my case. All the examples that I've found are examples of remotely fetched scripts, that are not in cloud-config format.

A: You can pass the cloud config formatted data in "metadata"(userData), but I think it will only run during a core os provision. I've never tested the provisions with cloud-init but It should work, core os has to use it.
Here a REST API example to specify "metadata(userData)":
https://$user:$apiKey@api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest/createObject

Payload:
 {
       "parameters":[
          {
             "hostname":"hostnameTest",
             "domain":"softlayer.com",
             "maxMemory":2048,
             "startCpus":1,
             "hourlyBillingFlag":false,
             "localDiskFlag":false,
             "operatingSystemReferenceCode":"UBUNTU_LATEST",
             "datacenter":{
                "name":"dal05"
             },
             "userData":[
                {
                   "value":"someValue"
                }
             ]
          }
       ]
    }

References:

*

*SoftLayer_Virtual_Guest::createObject


text:
Q: how to parse time from time function with bash and grep? I have this bit of info from a bash script.
How can I keep only the time?
"real\t0m0.001s"

Needs to be
0m0.001s

or even count of milliseconds.. The output is produced from
time function.

A: You can use sed with a simple regular expression that replaces from the start of the string through the '\t' (tab) character with nothing (removing that part of the string), e.g.
sed 's/^.*\t//'

Using grep you would use:
grep -o '[^[:space:]]*$'

(to only match non-space characters to end of string)
Example Use/Output
$ printf "real\t0m0.001s" | sed 's/^.*\t//'
0m0.001s

or
$ printf "real\t0m0.001s" | grep -o '[^[:space:]]*$'
0m0.001s

A: cut is meant for exactly this:
$ printf 'real\t0m0.001s' | cut --fields=2
0m0.001s

A: Maybe this helps :
grep -o '.\{8\}$' test.txt


text:
Q: gremlin - how to update vertex property with another vertex's property testing data:
vertex A has property 'a' value '1'
vertex B has outEdge  'e' to A
vertex B had property 'b' value '2'

how do I update 'a' to be value from 'b' in this case '2'?
I have tried this but not working
g.V().hasLabel('A').property('a', inE('e').outV().project('b').by('b').unfold())

A: Building the graph using...
gremlin> g.addV('A').property('a','1').as('a').
   ......1>   addV('B').property('b','2').as('b').
   ......2>   addE('e').from('b').to('a')

gremlin> g.V().valueMap()
==>[a:[1]]
==>[b:[2]]

You can use values from A to update B as follows (this is one way to write the query, there are alternative ways)
gremlin> g.V().hasLabel('B').as('b').V().hasLabel('A').property('a',select('b').values('b'))
==>v[42790]

gremlin> g.V().valueMap()
==>[a:[2]]
==>[b:[2]]


text:
Q: Titunium Studio Cannot find Android SDK I have a problem with Titanium Studio. It doesn't recognize my Android SDK installation.In the Platform->Android prefs panel, it says "No Android SDK found in the selected location"
When I first ran Titanium, it installed/updated a bunch of it's own and some Node plugins, so it's fulfilled all dependencies.
details:

*

*OS: Windows 7 (x64)

*Titanium Studio version is 3.3.1 (in %Appdata%\Roaming\Titanium Studio)

*JDK build 1.8.0_31 (%Program Files (x86)%\Java\JDK)

*Android SDK installation (in C:\Android-sdk)

*

*Android SDK tools 24.0.2

*Android SDK Platform Tools 21

*Android SDK Build Tools

*Android 4.2.2, API 17 (all children)

*Android 2.3.3, API 10 (all children)

*Android 2.2, API 8 (all children)

*also everything inside the Extras branch

According to Titanium Compatibility Matrix, I have at least one Android SDK (4.2.2) that falls within the accepted SDK bounds for my Titanium version.

A: have you checked those links?
1.link 1
2.link 2
and it's better to have same architecture of java and OS.
you can also type this in command line and check if there is any specific android issue
titanium info

A: I don't know exactly what contributed to the solution (note that titanium CLI alwayes detected everything correctly), but here's what I've done meanwhile.

*

*I had existing %ANDROID_SDK%, %JAVA_HOME% and the SDK's tools and platform-tools locations added to PATH from the beginning.

*I Uninstalled Titanium (Studio & SDK), JDK+JRE, Node and Git.Then reinstalled JDK and Titanium.

*Titanium installed node 10.13 and Git 14.sth to %programfiles(x86)%

*the problem still existed. Cue another series of uninstalls.

*Installed Jdk, Git, node and Titanium one-by-one.

*Interstingly, this time Titanium couldn't locate Git which was installed in C:\git (it was added to PATH). So I symlikned C:\Git into %programfiles(x86)% (also linked C:\nodejs for good measure :) )

*Now, I found the JDK installer only added C:\ProgramData\Oracle\Java\javapath to PATH which includes just java.exe, javaw.exe and javaws.exe. So I added %programfiles(x86)%\Java\jdk\bin to PATH.

*This time, Titanium Studio worked correctly!

So, perhaps, the problem lies in Titanium Studio needing dependencies in certain locations.
(btw, before this, even though path to git.exe was in PATH, the Studio's console "couldn't find a 'bash' shell." now it does.)
hope this helps others who face the same issue.


text:
Q: accessing array within multidimensional array - javascript here is the problem
multiDimensionalArray = [1, 2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, [13, 14, [15]]]]]];

I want to access number 15. I cant seem to figure it out.
p.s i am a newbee with js

A: multiDimensionalArray[3][3][3][3][2][0]
Each [n] is accessing an array value at index n.
So the above statement says:
1) take the 4th (index 3 is the 4th element due to indices starting at 0, not 1) element.
2) This happens to be an array. Take the 4th element again.
3) ...


text:
Q: Upgrade CakePHP 2.X to 4.X I'm trying to upgrade CakePHP2.x TO CakePHP4.x, I have WAMP 3.2.3 and Php 7.4. Downloaded CakePHP4.X but the entire directory structure is different between CakePHP2 and 4, if anyone share some idea how I can upgrade, that would be very helpful, share me the best way to achieve it.
Thank You!!


text:
Q: How to add text under images like shown in example below [Flutter] I would like to add the text "Appointments" like shown in the example below. I've tried using the Text widget under Image.asset but I don't think I'm using it right. I'm still new to Flutter so any help would be much appreciated.
Expected Output
This is the code I have so far:
            Container(
              height: 250,
              width: 320,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                boxShadow: kElevationToShadow[1],
                color: Color.fromARGB(255, 255, 255, 255),
              ),
              child: Align(
                alignment: Alignment(0, -0.5),
                child: Image.asset("assets/appointment.png", height: 150, width: 150),
              ),
            ),

A: Use below code :
 Container(
              height: 250,
              width: 320,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                boxShadow: kElevationToShadow[1],
                color: Color.fromARGB(255, 255, 255, 255),
              ),
              child: Column(
                children: [
                  Align(
                    alignment: Alignment(0, -0.5),
                    child: Image.asset("assets/appointment.png", height: 150, width: 150),
                  ),
                  SizedBox(height: 20,),
                  Text('Appointments',style: TextStyle(color: Colors.black,fontSize: 18),),
                ],
              ),
            ),

A: Used card and column widget for this type of UI.
Card(
  elevation: 10,
  shape: RoundedRectangleBorder(borderRadius:BorderRadius.circular(10)),
  child: Column(
    children: [
      // Your Image Widget
      // Your Text Widget
    ],
  ),
),


text:
Q: Difference between using and not using get; set; in data passed from backend What is the difference between using and not using get; set; in data passed from backend?
I saw examples like this in Apex:
using get; set;
public with sharing class MyBackendController {
    public class WrapperDataClass {
         @AuraEnabled
         List<Contact> contactsList {get; set;}
    }

    @AuraEnabled
    public static WrapperDataClass doesnotMatter() {
        WrapperDataClass res = new WrapperDataClass();
        //does not matter how res is filled
        return res;
    }
}

not using get; set;
public with sharing class MyBackendController {
    public class WrapperDataClass {
         @AuraEnabled
         List<Contact> contactsList;
    }

    @AuraEnabled
    public static WrapperDataClass doesnotMatter() {
        WrapperDataClass res = new WrapperDataClass();
        //does not matter how res is filled
        return res;
    }
}

Previously I thought that using get; set; is obligatory. But I forgot to include it a few times in my code and still everything worked the same way.
So, I am going not to use get; set; at all. Will I be fine or am I missing something?
Thank you.

A: On the one using the get; set; you can control if get; or set; is private or not by using private get; and private set; ...
Mostly you use properties for Visualforce pages.
So Apex properties are similar to variables but there are additional things you can do with them.
There are many particular things that are part of the Apex Properties that are not part of variables.

A: The { get; set; } code is only obligatory for Visualforce pages that bind to those variables. In all all other cases, { get; set; } is superfluous, and not required. This includes using those variables in JSON serialization/deserialization, objects used in Lightning, etc. However, @AuraEnabled is required in order to be visible to Lightning. There is no difference between specifying { get; set; } or not; it has the exact same behavior either way.


text:
Q: Show that $f=g$ almost everywhere on $\mathbb{R}^n$. Let $f$ and $g$ be complex-valued locally integrable functions on $\mathbb{R}^n$. Let $T_f$ and $T_g$ be the distributions associated with $f$ and $g$, respectively. Assume that $T_f$ and $T_g$ are identical as distributions, i.e., $\langle T_f,\phi\rangle=\langle T_g,\phi\rangle$ for all $\phi\in\mathscr{D}(\mathbb{R}^n)$. Then can we say that $f=g$ almost everywhere on $\mathbb{R}^n$ ?
My Intuition :
We should proceed via contradiction. Suppose that there exists a measurable set $E\subset\mathbb{R}^n$ such that $m(E)>0$ and $f-g\not=0$ on $E$. Now I don't know how to go further.

A: Let's prove that $f=g$ almost everywhere, i.e that $h:= f-g$ is equal to $0$ almost everywhere.
First, note that you have $\int_{\mathbb R^n}h\phi =0$ for all $\phi\in\mathcal C_0^\infty$ by hypothesis.
Next, let $\phi\in\mathcal C_0^\infty$ be supported on the unit ball centered at the origin, and such that $\int_{\mathbb R^n}\phi = 1 $. We can write for all $x\in\mathbb R^n$ and $r>0$ ($\mu$ is the Lebesgue measure) :
$$\begin{align}
h(x)&=h(x)\cdot\int_{\mathbb R^n} \phi({x-y})d\mu(y)\\
&=\int h(x)\phi({x-y})d\mu(y)\\
&=\frac{1}{r^n}\int h(x)\phi\left(\frac{x-y}r\right)d\mu(y)\\
&=\frac{1}{r^n}\int [h(x)-h(y)+h(y)]\phi\left(\frac{x-y}r\right)d\mu(y)\\
&=\frac{1}{r^n}\int [h(x)-h(y)]\phi\left(\frac{x-y}r\right)d\mu(y) \tag1\\
&+ \frac{1}{r^n}\int h(y)\phi\left(\frac{x-y}r\right)d\mu(y)\tag2\end{align} $$
Now, notice that because $\phi\in\mathcal C_0^\infty$, $\varphi :=\phi((x-\cdot)/r)$ is also in $C_0^\infty $ for all $r>0$. Hence the second integral $(2)$ is equal to $0$ for all $r>0$.
Finally, you have by Lebesgue's differentiation theorem that
$$\lim_{r\to0} \frac{1}{r^n}\int_{\|x-y\|\le r}|h(y)-h(x)|\ d\mu(y) = 0 $$
For almost all $x$ in $\mathbb R^n$, from which you can conclude that $(1)$ goes to $0$ as $r\to0$ (apply the triangle inequality and the boundedness of $\phi$).
By taking the limit as $r\to0$, the desired result follows.


text:
Q: SQL database experts: is this a bottleneck? I say no, partner says yes.  We are both stubborn. We will test but I need some ammunition from you to support my case that the below pseudocode is not that big a bottleneck.  What we are doing is running two queries.  The first is against a big table (100k records), called BigTable below.  Then, we take what we find (typically 30 or so records) and run these records (in a loop, see the second 'foreach' below) against a much smaller table, called SmallTable, typically having around 200 records.  My partner wants to combine the records found in SmallTable so they appear in the records of BigTable, but if you do this, you lose flexibility and the databases are no longer in normal form.  My partner says he does not care about Normal Form and claims the below is a bottleneck.  Help me win this battle!  Of course my fallback position will be "let's test it and see" but I could use some firepower now.  We expect between 10 requests a second (in which case probably the bottleneck, if any, is trivial) or up to 1500 a second (which probably will break our app somewhere else! LOL.  But we are optimists).
The platform: Microsoft SQL Server 2008, using web services written in C# and Linq-to-Entities (EF), running on a server remotely that we do not own, but owned by a server company like GoDaddy, on a 'Per Call' / stateless basis.  Everything set to default in SQL Server (e.g., Max Pooling = 100, Load Balance Timeout = 0, Pooling = True). I am not doing any caching, since I've read somewhere that caching does not work well with distributed databases, which I think this server company uses.
I appreciate it.  Here is the pseudocode:
Public  string MyWebMethod()
{

List<Record> myrecords = new List<Records>();

try  //try block 1
{
using (AEntityFramework context = new AEntityFramework())
{
var RecordsReturned =   (from x in context.BigTable
                            //some conditions deleted
            select x);

//do some stuff with these records, typically 30 records returned from BigTable, which has 10000 to 100000 records total

foreach (Record r in RecordsReturned)
{  myrecords.Add(r);} //add these records to the List myrecords, to be used later.

}

}
catch (Exception)
{
Try block 1 exceptions here
}
//end of try block 1
//////////////////  now move to the next SQL query, which loops--is this a bottleneck?

foreach (Record R in myrecords)
{
try  //try block 2
{
using (AEntityFramework context = new EntityFramework())
{

    var SmallQuery = (from y in context.SmallTable
                      //some conditions deleted
         select y);

//small table has 100 to 200 records, it is very small

//do a short operation with the Record R and anything collected by var SmallQuery, typically 2 to 3 entries.

}

}//end of try block 2

catch (Exception)
{
//try block 2 exceptions here
}

} //end of foreach

return "OK";
}

[EDIT] in response to the answers to do a JOIN.  Failing an answer here I will open a second thread.  Thanks!  Have pity on a newbie pls.
Well I was afraid of this.  Now this question morphs and perhaps I'll open a new thread.
Here is my query:

*

*Table ACustomers (contains customer IDs, and zip codes)

*Table CCategories (contains categories like "food", "shelter","clothing")
(linking) Table A_C (since Tables A and C are linked as many-to-many): contains "customer IDs" and categories, in combination as primary keys

I need to select all records in Table A that satisfy a condition, then filter these records depending on a list of parameters found in the linking Table A_C.  But I don't know what the length of the list of parameters is, ahead of time.  It varies method call by method call.
To give a concrete example
Table A has a list of "customer IDs" and "Zip Codes".  Table A_C has primary keys comprising "CustomerIDs" and "Categories".  Table C has "categories". I find the customers in Table A that live in a certain "Zip code".  Then, from this subset, I need to find which of these customers have selected certain products that fall in certain categories found in the linking table Table A_C: Food, Clothing, etc, but my web method does not know ahead of time what these categories are, rather, they are passed as a list: List myCategoryList (which could be 1 category or 100, varies method call by method call).
How do I write the projection using Linq-to-Entities?
   List<string> CategoryList = new List<string>() { "Food", "Shelter", "Housing" }; // in one call to the web service method

   List<string> CategoryList = new List<string>() { "Food", "Clothing" }; //in a second call--varies and I don't know ahead of time which is which.

So how can I do the projection using Linq-to-Entities?  I will open a second thread.

A: In general you're better off doing a join with all the records you are working on and dealing with them in one lot in your code. The DB server is probably quite stout and is optimized for doing combinations like this. It will be much faster than doing a 'pseudo-join' like it appears you're doing here (query, loop another query, etc).
Stick with the (possibly) 1st normal form. It will serve you better in the long run.


text:
Q: How to remove unwanted css and js from your django application? I'm making a Fullstack application which uses Django as a backend and javascript and jquery as a frontend.The app is finished now I want to remove unwanted css,images,js which just lie there in static files but are not used in templates is there a way to remove all of this unwanted code,files.I checked on the internet and there are solutions like purgecss but they use npm for running and I don't have npm
Is there any other way to it easily or if I have to do it by using purgecss.Can you guide me all the way in the answer section.
Thank you


text:
Q: Single click is not working in IOS for ionic app after updating cordova plugins to latest version Recently i updated all plugins to latest versions.But after that..single click is not working in IOS(only double tap is working).In android working fine.

A: Sry because initially i thought this problem because of plugins updates but the actual problem occurred as we added one script plugin, in that some reqEx is making the script as commented code in ios. By adding escape characters to the regEx we are able to resolve it.


text:
Q: Find date range in Prisma ORM I'm trying to filter vacations by date range, but I don't know how to do it. Please help.
Database: postgresql
Backend: nestjs + prisma orm (4.0.0)
Frontend: React
The data about vacations is stored in the database in this form:
id: Int
userId: Int
dateStart: DateTime
dateEnd: DateTime

In the frontend filter, I have the fields:
{
   dateStart: Date;
   dateEnd: Date;
}

I do not understand how to make a request to the database so that I would output the result of the contact of two ranges.
The following request works incorrectly:
where: {
   dateStart: { gte: dto.dateStart },
   dateEnd: { lte: dto.dateEnd }
}

If, for example, I am a user on vacation from January 25 to February 2, and I specify sorting from January 1 to January 31 in the filter, then the vacation will not appear. In this example, it will not work because of non-compliance with the dateEnd conditions.
The only thing I could guess was to turn the input dateStart and dateEnd into an array of dates, and then go through the loop inside the where query. It works, but slowly. For example, if you filter for a whole year, then the request to the database turns out to be too big fat, Please tell me.

A: This problem is solved using the OR operator.
Example:
OR: [
   { dateStart: { lte: dto?.dateEnd }, dateEnd: { gte: dto?.dateStart } },
   { dateStart: { gte: dto?.dateStart }, dateEnd: { lte: dto?.dateEnd } },
],

It's work for me.
Thank you for all!

A: I would start with writing down in plain words, what you want to search for.
To my understanding (but please correct me), you want to find all vacations that fall (partly) in the specified date range.
(It certainly helps to differentiate dateStart/dateEnd of the vacation and the filterStart/filterEnd of the filter.)
Then you translate that into an algorithm, e.g. by analyzing the different cases with respect to these dates. The algorithm should be:

*

*dateStart is before (or equal) filterEnd AND

*dateEnd is after (or equal) filterStart
As a last step (and I would leave that to you), you have to translate this algorithm into a prisma query.


text:
Q: Not getting Google Ad words Link Id from Test Client Account by using Test Manager account for Link third-party app analytics to Google Ads I am working with Google AdWords Manager account. I need to get all campaign deatails of client campaigns. For this process client is need to get Link Id from adwords panel by follow this process
Tools >> Linked accounts >> Third-party app analytics >> Details >> Create Link Id >> Fill Form with Following Details
App Analytics Provider : Other Provider
Provider Id: 4602942452
Platform: Android
Package Name: com.lionmobi.netmaster
Then Click on Create Link ID
But got following error : An error occurred. Please try again later.
View Snapshot
Please help me to get Link Id of google Ad words


text:
Q: Access report/atlas page from feature in layer (QGIS) In QGIS 3.22. I've created an atlas layout from a polygon shapefile layer. What I'd like to do is be able to access the atlas page for a given feature without having to open the layout manager. Some possibilities of what this could look like:

*

*create an automatic popup of the atlas page upon clicking a feature; this would be great, but I do not think the Identify Features tool settings allows this (it always opens a form) and I do not know if there is another similar tool that could be set to pop up like this.

*create a field with a link to the feature page in the atlas; in this way, I could open the Identify Features form, scroll down to the right field, and click the link to open the atlas page. Seeing as the atlas is already connected dynamically to the map layout on a feature-by-feature basis, I suspect it is possible to link to a specific feature page, though I am not sure how.

*create a layer action that opens the feature page. This would also require a link between each feature and its page in the atlas.

*create a Layout Manager sidebar or box where the feature pages are visualized as you click the features. As far as I can tell, this manner of viewing layouts/reports is not currently possible.
If none of these solutions are possible, I suppose a workaround would simply be saving images of each page and having a field link to the image. This is not a desirable solution because it is not dynamic and would need to be updated constantly (and would be much more work to implement).

A: The identify tool could do what you expect in possibility number 1. It could open the atlas page you click on.
Step by step :

*

*Select the layer used as coverage layer

*Click on the identify tool

*Right-click on the feature you want to use for atlas. A menu will show up, click on the layer used for atlas and then it let you choose between Identify and Set as atlas feature for Atlas (as I have only one atlas layout for this layer and the name is "Atlas").

*Click on Set as Atlas Feature for Atlas. It will open your atlas Layout on with the feature you selected as atlas feature. If the layout is already opened it will change the feature selected for atlas.


text:
Q: Using "the" with past participle but not with the present participle I am currently working on a book review of verb presentation in two texts. I am contemplating the nominal function of present participles. Of course, we know that a present participle is called a gerund or is functioning nominally. However, it is odd to say "The swimming is fun," but we can say "Swimming is fun." For the past participle counterpart, we find instances like "The dead." Consider the following sentences: "The damned are in hell." "Doctor Faustus is among the wretched." "They buried the dead." The past participle, affixed with "the" before it, functions nominally- in the place of the subject, direct object, and the object of the preposition.
So, why can we say "the dead" but not "the flying?"

A: The present and past participles are often written identically to related adjectives.
When we say "the damned", "the wretched", "the dead" or "the dying", those are adjectives with an implied noun of "people", so an article makes sense. "The flying" sounds weird because it's hard to imagine a context where "the flying (people)" makes sense.
Gerunds are not adjectives; they are nouns that (usually) do not take an article. In fact, this lack of article is a clue to distinguish them from the adjective.

*

*The dying (people) are in pain.

*Dying is painful.


text:
Q: Changing column order with Table Manager Plugin in QGIS 3 There was a Table Manager Plugin in earlier QGIS versions I can't see it for QGIS 3 anymore.
Is there a way to achieve this in QGIS 3.6?

A: See my answer here: QGIS changing the attribute input fields order
Open the attribute table. Right click the column headings in the attribute table. Select "Organize columns" in drop down menu. Then, just drag the heading to the position you want it to be in (See image of the "organize table columns" box below). Click OK. Headings should have rearranged the way you want it to be arranged in the attribute table.

A: Yes, you can use the "Refactor fields" tool from the Toolbox:


text:
Q: PostgreSQL: how to find id's with max money in a weekly table I have the following table holding virtual money for weekly tournaments:
# select * from pref_money limit 5;
       id       | money |   yw
----------------+-------+---------
 OK32378280203  |   -27 | 2010-44
 OK274037315447 |   -56 | 2010-44
 OK19644992852  |     8 | 2010-44
 OK21807961329  |   114 | 2010-44
 FB1845091917   |   774 | 2010-44
(5 rows)

In my PHP script listing users, I need to know who has been a weekly winner, so that I can show medals near their names. So I'm trying this SQL statement:
# find the weekly winners
$sth = $db->prepare('select id from pref_money
    where money in
    (select max(money) from pref_money group by yw)');

$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC))
        @$medals[$row['id']]++;

This mostly works, but sometimes I get false positives, when a user happens to have the same amount of money in some week (but not max there) as the winner in another week.
Does anybody have an idea how to change the SQL statement, so that really only winner ids are being selected?
When I try the following, I get an error:
# select id, max(money) from pref_money group by yw;
ERROR:  column "pref_money.id" must appear in the
  GROUP BY clause or be used in an aggregate function

Thank you!
Alex
UPDATE: PostgreSQL 8.4.5 / CentOS and there can be ties :-)

A: Which version PostgreSQL? This is easy with windowing functions introduced in 8.4:
select id, yw from (
    select id,
           yw,
           row_number() over(partition by yw order by money desc) as ranking
    from pref_money
) x
where x.ranking = 1

This will just about do in older versions:
select id, yw
from pref_money
     join (select yw, max(money) max_money
           from pref_money
           group by yw) max_money
          on pref_money.yw = max_money.yw and pref_money.money = max_money.max_money

But observe that weeks where two users tie for the maximum money will be shown twice in the output. If that's actually what you want, you can do with with the windowing functions too, using rank() instead of row_number()

A: Assuming PostgreSQL 8.4+, and no one ties for the winner position in a given week -- this will list the weekly winners:
WITH sample AS (
  SELECT t.id,
         t.yw,
         ROW_NUMBER() OVER(PARTITION BY t.yw
                               ORDER BY t.money DESC) AS rank
    FROM PREF_MONEY t)
SELECT s.id
  FROM sample s
 WHERE s.rank = 1

If there can be ties, use:
WITH sample AS (
  SELECT t.id,
         t.yw,
         DENSE_RANK() OVER(PARTITION BY t.yw
                               ORDER BY t.money DESC) AS rank
    FROM PREF_MONEY t)
SELECT s.id
  FROM sample s
 WHERE s.rank = 1

I included the yw column, in case you want/need to filter by the column.


text:
Q: DateTime Parse error for millisecond level How to parse the datetime in millisecond for "20160803T0509+0100". I cannot change the input datetime format as I am receiving by client data file.
Client is using as a system local server time in UTC iso 8601 with offset
I am useing the simple function
 Console.WriteLine(Convert.ToDateTime("20160803T0509+0100"));

Error:

String was not recognized as a valid DateTime.

A: I think the +0100 is for time zone offset not milliseconds
var dateTime= DateTime.ParseExact("20160803T0509+0100", "yyyyMMddTHHmmzzz", CultureInfo.CurrentCulture);

A: use DateTime.ParseExact instead
DateTime result = DateTime.ParseExact("20160803T0509+0100", "yyyyMMddTHHmm+ssff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);

A: Simply use this
DateTime dt = DateTime.ParseExact("20160803T0509+0100", "yyyyMMddTHHmmzzz", CultureInfo.InvariantCulture);


text:
Q: Get identical elements and index from 2 Arrays in Perl I am new in Perl and I am trying to solve the following comparison.
I have two arrays:
@A = ("Red", "Green", "Yellow");
@B = ("Yellow", "Black","Yellow","Red", "White", "Yellow");
In array A, each element occurs only once.
In array B, each element can occur zero, one or many times.
For every element in A, the code should lists the position at which it is present in B and give the output as following:
> Red at index 3.
> Green is missing.
> Yellow at index 0, 2 and 5.
> Elements from B were detected 4 times in A.
I tried the following but I cannot figure out how to list indexes of elements after comparing two arrays
foreach $x (@A){
    foreach $y (@B){
    if ($y eq $x){
    print "$y\n";
    }
    elsif ($x ne$y){
    print "$x";
    }
  }
}

Can someone please, help me? Thank you very much in advance!
Rebi

A: Here is an example:
my @A = ("Red", "Green", "Yellow");
my @B = ("Yellow", "Black","Yellow","Red", "White", "Yellow");
my %indices;
for my $i (0..$#B) {
    push @{ $indices{$B[$i]} }, $i;
}
my $count = 0;
for (@A) {
    if (exists $indices{$_} ) {
        my @temp = @{ $indices{$_} };
        $count += (scalar @temp);
        print "$_ is at index: ", @temp, "\n";
    }
    else {
        print "$_ is missing\n";
    }
}
print "Elements from B were detected ", $count, " times in A.\n";

A: Here's a somewhat simple way. A count and a switch variable keeps track of whether an item is found or missing:
my @a = ("Red", "Green", "Yellow");
my @b = ("Yellow", "Black","Yellow","Red", "White", "Yellow");
my $count = 0;
for my $ael (0 .. $#a) {
 my $switch = "off";
 for my $bel (00 .. $#b) {
  if ($a[$ael] eq $b[$bel]) {
  $count++;
  $switch = "on";
print "$b[$bel] found at index $bel\n";
                            }
                         }
print "$a[$ael] is missing\n" if $switch eq "off";
                        }
print "Elements from B found $count times in A";

Outputs:
Red found at index 3
Green is missing
Yellow found at index 0
Yellow found at index 2
Yellow found at index 5
Elements from B found 4 times in A


text:
Q: How to run Flink Job Manager and Task Manager on different nodes? I have a long-running Flink cluster on Yarn.  This is the command to start it sudo -E flink run -m yarn-cluster -ynm FlinkStreamBootstrap -yn 2 -s ${SAVEPOINT} -d -c flink.FlinkBootstrap ${FLINK_LIB}/flink_2.11-${JAR_VERSION}-assembly.jar --jobName "Flink Job"
Sometimes the task manager is running on the same node as the job manager.  Sometimes is different.  Is there a way to specify to run them on different nodes to start with?
Thanks

A: Flink currently does not support expressing placement constraints for Yarn containers. Flink has been developed to be location agnostic and it is the responsibility of the underlying cluster manager to decide where to allocate resources. This property has the benefit that it does not matter whether the Yarn cluster has only a single very beefy node where it can place multiple containers onto or multiple smaller nodes.


text:
Q: Eclipse luna mac osx package explorer tree view I have updated package explorer font size by as per the answer in the post
Mac os X Eclipse Package Explorer view , project folders in smaller size in mac theme CSS and it works well. But when I update a java or properties file, it font size is reset to the default(I am unable to find what is the default size). I enabled Maven and Git for my project, how to retain the same font size even after updating the files.

A: The configuration is present in eclipse>preferences>change colors and fonts > Git > Uncommitted Change Font.


text:
Q: iOS - How to refresh/update Core Data transient property? I'm using a core data, NSFetchedResultsController UITableView, with a transient NSDate attribute. The main reason I have this as a transient property is so my UITableView entries get put into sections based on NSDate, but can move between the sections when the date changes.
So far it seems to work great, but it only updates/refreshes (I'm really new to this, so I don't know if I'm using the correct terminology, sorry!) when I either close the app and kill it from multitasking, or re-run it through Xcode. If I don't do that, the items don't change and aren't put into their correct sections. Is there a way to manually get it to refresh so the user doesn't need to do that to get it to run right?
Thank you!

A: First, make sure that you transient property is only used for the sectionNameKeyPath when creating your fetched results controller. Best name it sectionIdentifier (as Apple does in their sample code.) The actual date should be a separate attribute of your entity. (I will call it dateAttribute.
Second, make sure that you specify the key path dependencies in your Entity.m file:
+ (NSSet *)keyPathsForValuesAffectingSectionIdentifier {
    // If the value of dateAttribute changes, the section identifier may change as well.
    return [NSSet setWithObject:@"dateAttribute"];
}

Third, make sure that in your controller, you react appropriately to changes in the managed object context through
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
   if (!self.tableView.editing) [self.tableView reloadData];
   // the quick and dirty method without animations;
   // see referenced code for a more pleasant approach
}

If anything is unclear, take a look at the Apple example DateSectionTitles.

A: Transient properties are refreshed when you send a refreshObject:mergeChanges: to your object.
The solution provided by Mundi to apply key value observing mechanism might work too and if it does, it is definitely much more convenient than refreshing explicitly.


text:
Q: Can I have tabs on the left stacked vertically? I found an extension tree style tab - it can move tabs to the left, but it stacks them horizontally - while I want the stacked vertically.
I would like the following layout in Firefox:

The screenshot is from Notepad++ with the "Vertical" "Tab Bar" setting enabled.
Edit:
Several verical rows are allowed but not required.


text:
Q: How to use Microsoft Azure Storage Emulator with Xamarin? How to use Microsoft Azure Storage Emulator with Xamarin.Android?
I have downloaded Microsoft Azure Storage Emulator and Microsoft Azure Storage Explorer. I tried to follow tutorials at Microsoft websites but still i have problems with authentication. When I was using real during free trial subscription everything worked.
I know that I have to use SAS keys. But when I create table storage in storage explorer and then generate there SAS it's still wrong. Maybe someone already did that and can paste his code or steps to reproduce connection with storage emulator.
const string connectionString = "SharedAccessSignature=sv=2015-04-05&sr=c&sig=91HcGtCMxWM6%2B13mRDH1kej5Wq1a8gRk4WCFd6CeLuk%3D&se=2016-08-01T12%3A16%3A55Z&sp=rwdl;TableEndpoint=http://127.0.0.1:10002/devstoreaccount1";

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("Test");
bool exists = await table.ExistsAsync();
if (exists)
    System.Console.WriteLine("Exists");
else
    System.Console.WriteLine("Doesnt exist");

Error Details:
<RequestResult>
  <HTTPStatusCode>0</HTTPStatusCode>
  <HttpStatusMessage />
  <TargetLocation>Primary</TargetLocation>
  <ServiceRequestID />
  <ContentMd5 />
  <Etag />
  <RequestDate />
  <StartTime>Sun, 31 Jul 2016 13:43:44 GMT</StartTime>
  <EndTime>Sun, 31 Jul 2016 13:43:44 GMT</EndTime>
  <Error></Error>
  <ExceptionInfo>
    <Type />
    <HResult>-2146233088</HResult>
    <Message>Error: ConnectFailure (Connection refused)</Message>
    <Source />
    <StackTrace />
    <InnerExceptionInfo>
      <ExceptionInfo>
        <Type />
        <HResult>-2146233079</HResult>
        <Message>Error: ConnectFailure (Connection refused)</Message>
        <Source>mscorlib</Source>
        <StackTrace>  at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x0005e] in /Users/builder/data/lanes/2923/52635947/source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:1005
  at System.Threading.Tasks.TaskFactory`1[TResult].FromAsyncCoreLogic (IAsyncResult iar, System.Func`2 endFunction, System.Action`1 endAction, System.Threading.Tasks.Task`1 promise, Boolean requiresSynchronization) [0x00014] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/threading/Tasks/FutureFactory.cs:550
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:535
  at System.Net.Http.HttpClientHandler+<SendAsync>c__async0.MoveNext () [0x003d6] in /Users/builder/data/lanes/2923/52635947/source/mono/mcs/class/System.Net.Http/System.Net.Http/HttpClientHandler.cs:372
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:535
  at System.Net.Http.HttpClient+<SendAsyncWorker>c__async0.MoveNext () [0x000a9] in /Users/builder/data/lanes/2923/52635947/source/mono/mcs/class/System.Net.Http/System.Net.Http/HttpClient.cs:276
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/2923/52635947/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
  at Microsoft.WindowsAzure.Storage.Core.Executor.Executor+<ExecuteAsyncInternal>d__6`1[T].MoveNext () [0x003cf] in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\WindowsRuntime\Core\Executor\Executor.cs:128 </StackTrace>
        <InnerExceptionInfo>
          <ExceptionInfo>
            <Type />
            <HResult>-2147467259</HResult>
            <Message>Connection refused</Message>
            <Source>System</Source>
            <StackTrace>  at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x000cb] in /Users/builder/data/lanes/2923/52635947/source/mono/mcs/class/System/System.Net.Sockets/Socket.cs:1313
  at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request) [0x0019b] in /Users/builder/data/lanes/2923/52635947/source/mono/mcs/class/System/System.Net/WebConnection.cs:195 </StackTrace>
          </ExceptionInfo>
        </InnerExceptionInfo>
      </ExceptionInfo>
    </InnerExceptionInfo>
  </ExceptionInfo>
</RequestResult>

Thank you for your time.

A: I believe you're getting this error is because you're running this code in an Emulator. Since the IP address of your emulator is 127.0.0.1, the requests are not actually hitting the storage emulator but your device emulator only. That's why you're getting this connection refused error. Please see this thread for more details: https://forums.xamarin.com/discussion/1199/how-to-make-our-remote-host-127-0-0-1-reachable-from-android-device-monoandroid-using-vs2010.
What I would recommend is that you use an actual cloud storage account instead of storage emulator to test your code. When you do use the actual storage account, please use the code below (obviously change the connection string appropriately). It should work:
        var connectionString = "http://127.0.0.1/devstoreaccount1/Testowa?st=2015-07-31T11%3A50%3A00Z&se=2017-08-01T11%3A50%3A00Z&sp=raud&sv=2015-04-05&tn=testowa&sig=UEbinBTgpEGwy1ts0hwmSfELM1lYCBItLHgWpWSgvE4%3D";
        CloudTable table = new CloudTable(new Uri(connectionString));
        bool exists = await table.ExistsAsync();
        if (exists)
            System.Console.WriteLine("Exists");
        else
            System.Console.WriteLine("Doesnt exist");


text:
Q: Eclipse-Pydev cannot find Lucene Library I have been developing a Python program using the Pydev(2.5.0) plugin in Eclipse Helios on Ubuntu OS 11.4.
The program uses lucene (core 3.6) library. Lucene was installed using jcc.
Previously I developed it with a text editor and ran on the command line using python xxx.py and there was no problem regarding lucene libraries.
Then, I imported the project to Eclipse IDE. The other source files still run as-is, but the program cannot locate the basic classes of lucene library.
import lucene # no error

but if I try to import StandardAnalyzer or any other class, I get an error:
from lucene import StandardAnalyzer  #error:  unresolved import

My configuration:

*

*Grammer Version: 2.7

*Python interpreters: usr/bin/python2.7
Libraries include:

I tried the add the lucene folder to the external libraries but it didn't help.
I have found this path by using command line python interpreter with these commands.
import lucene
print lucene.__path__

Though a similar path is already in the library (see image. 2nd library)
['/usr/local/lib/python2.7/dist-packages/lucene-3.6.0-py2.7-linux-i686.egg/lucene']
I would appreciate your comments about this problem. Thanks.

A: I think that the problem is that the PyDev code-analyzer can't really analyze PyLucene. You can try adding 'lucene' to window > preferences > pydev > interpreter - python > forced builtins (see: http://pydev.org/manual_101_interpreter.html for details).

A: Had the same problem running Helios Service Release 2 on Mac OSX 10.8.5. Fixed it as follows:

*

*Open Project >> Properties

*

*Select PyDev - Interpreter/Grammar

*Click "Click here to configure an interpreter not listed"

*Select your interpreter

*Select "Forced Builtins" and add all three directories (lucene, org and java) (see http://pydev.org/manual_101_interpreter.html for details).

*Select "Libraries" and add the path to each of those directories to System libs.


text:
Q: Springdoc specify security as being open I'm using Springdoc (1.4.8) to document our Rest API.  99% of the calls are secured using an OAuth2 Bearer Token so I'd like to add it by default like this:
new OpenAPI()
            .components(new Components()
            .addSecuritySchemes("bearerTokenScheme",
                            new SecurityScheme()
                                    .type(SecurityScheme.Type.HTTP)
                                    .name("bearerTokenScheme")
                                    .scheme("Bearer")
                                    .bearerFormat("JWT")
                    )
              )
            .addSecurityItem(new SecurityRequirement()
                    .addList("bearerTokenScheme")
            )

This works fine to have it specified by default, but my question is now, can I somehow overrule it by specifying a single call to be unsecured?
I do realize that omitting .addSecurityItem() will show calls as unsecured by default, but I'd like to have them secured by default and only having to override it when unsecured.

A: I had a similar issue and I have solved it using a plugin. The plugin overrides the security value of tagged controllers or methods and sets it to empty list. So the tagged endpoints remain unsecured.
@Component
public class NoSecurityPlugin implements OpenApiCustomiser {

    private static final List<Function<PathItem, Operation>> OPERATION_GETTERS = Arrays.asList(
            PathItem::getGet, PathItem::getPost, PathItem::getPut, PathItem::getDelete,
            PathItem::getHead, PathItem::getOptions, PathItem::getPatch);

    private static final List<String> tagsForNoSecurity = List.of(
            "public", "unsecured"
    );

    @Override
    public void customise(OpenAPI openApi) {
        openApi.getPaths().forEach((path, item) -> getOperations(item).forEach(api -> {
           List<String> tags = api.getTags();
           if(tags != null && tags.stream().anyMatch(tagsForNoSecurity::contains)) {
               api.setSecurity(Collections.emptyList());
           }
       }));
    }

    private static Stream<Operation> getOperations(PathItem pathItem) {
        return OPERATION_GETTERS.stream()
                .map(g -> g.apply(pathItem))
                .filter(Objects::nonNull);
    }
}

Tag your API methods (or Controller):
@Tag(name = "public", description = "Public APIs")


text:
Q: Azure Storage Calculation of Blob Container Size Below i have function with an external which calculate blob container size
function getBlobContainerSize(container, callback) {
    storageClient.listBlobsSegmented(container, null, null, function(error, result) {
        var length=0,counter=result.entries.length;
        for (var i = 0; i < result.entries.length; i++) {
            getBlobSize(container, result.entries[i].name, function(size){
                length+=size;
                if(--counter===0) callback(length);
            });
        };
    });
}
function getBlobSize(container, blob, callback){
    storageClient.getBlobProperties(container, blob, function(err, result, response) {
        if(result==null) callback(0);
        else callback(parseInt(result.contentLength));
    });
}

And the result is for an specific container 20907510, and in the Azure Storage Explorer i see 84.03M. Correct me if i am wrong but this two is different by 64mb, Azure Storage Explorer show much more mb in compare with my function.

A: Considering you're using standard storage, the method you're using to calculate the size of container, may not be the size which Azure Storage bills you for. For page and block blobs in standard storage, Azure storage bills for the data stored. More detailed information can be found here:
http://blogs.msdn.com/b/windowsazurestorage/archive/2010/07/09/understanding-windows-azure-storage-billing-bandwidth-transactions-and-capacity.aspx
Your method will give you the sum of content lengths of all the blobs in your container. Azure-Storage might still be billing you for less.


text:
Q: SQL Server: exclude column row number from distinct? How can I exclude a column row number from distinct?
The select statement looks like this:
SELECT *
FROM
    (SELECT DISTINCT TOP 100
         ROW_NUMBER() OVER (ORDER BY Cases.CreatedDate DESC) as row,
         Cases.status, Cases.CreatedDate, Cases.DWFCaseId,
         Resource.ResourceInfo AS ResourceFullName,
         actions.ActionDate, Action.ActionDuedate
     FROM
         Cases
     INNER JOIN
         ResourceInfo ON Cases.caseid = ResourceInfo.caseid
     LEFT OUTER JOIN
         actions ON actions.ActionId = ResourceInfo.ActionId
     WHERE
         (actions.ActionType = 2)
    )

A: Take it out from subquery:
select ROW_NUMBER() OVER (ORDER BY   x.CreatedDate desc ) as row, x.*
from (
    SELECT  DISTINCT top (100)
        Cases.status,
        Cases.CreatedDate,
        Cases.DWFCaseId,
        Resource.ResourceInfo AS ResourceFullName,
        actions.ActionDate,
        Action.ActionDuedate
    from Cases
            inner join ResourceInfo  on Cases .caseid = ResourceInfo .caseid
            left outer join actions on actions.ActionId = ResourceInfo .ActionId
    WHERE     (actions.ActionType = 2)
) x

A: Use the window function in the outer query instead of the subquery as
SELECT *,
       ROW_NUMBER() OVER (ORDER BY CreatedDate DESC) as row,
FROM
    (
     SELECT DISTINCT TOP 100
            Cases.status,
            Cases.CreatedDate,
            Cases.DWFCaseId,
            Resource.ResourceInfo AS ResourceFullName,
            actions.ActionDate,
            Action.ActionDuedate
     FROM
         Cases
     INNER JOIN
         ResourceInfo ON Cases.caseid = ResourceInfo.caseid
     LEFT OUTER JOIN
         actions ON actions.ActionId = ResourceInfo.ActionId
     WHERE actions.ActionType = 2
    ) T; --Don't forget to use an alias for the subquery


text:
Q: WPF bindings not correct when window opens I am writing a small WPF utility with a single window that so far has the code below. I'm using PostSharp to automatically handle the property change notifications and the bindings are updating as I select different organisations in the combobox. However when the window first opens and the line
organisationComboBox.SelectedIndex = 0;

executes, the bindings do not update. A breakpoint set in the organisationComboBox_SelectionChanged() method reveals that the _lightningLocationsEnabled variable is being set to true for the item selected, and that the properties depending on it are set correctly, yet the controls that the properties are bound initially display values they would if the variable was false.
The PostSharp documentation suggests that no manual forcing of property change notifications should be required so I presume I am doing something wrong. Can anyone help me find the problem?
Here is the code
using DynaMiX.Common.Groups.Constants;
using DynaMiX.Data.Operations;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using PostSharp.Patterns.Model;

namespace LightningMapLocationToolGUI
{
    [NotifyPropertyChanged]
    public partial class MainWindow : Window
    {
        private IOrganisationRepository _organisationRepository = new OrganisationRepository();
        private bool _lightningLocationsEnabled;

        public MainWindow()
        {
            InitializeComponent();
            BindOrganisations();
        }

        public string StatusText => $"Lightning Map Locations feature is { (_lightningLocationsEnabled ? "ENABLED" : "DISABLED") }";
        public Brush StatusColorBrush => new SolidColorBrush(_lightningLocationsEnabled ? Colors.Green : Colors.Red);
        public string EnableButtonText => _lightningLocationsEnabled ? "Disable" : "Enable";

        private void BindOrganisations()
        {
            var orgList = _organisationRepository
                .GetOrganisationSummaries()
                .Where(o => o.DatabaseState == DatabaseState.Active)
                .OrderBy(o => o.Name)
                .ToList();

            organisationComboBox.ItemsSource = orgList;
            organisationComboBox.DisplayMemberPath = "Name";
            organisationComboBox.SelectedValuePath = "OrganisationId";
            organisationComboBox.SelectedIndex = 0;
        }

        private void organisationComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _lightningLocationsEnabled = _organisationRepository.LightningLocationsEnabledFor((long)organisationComboBox.SelectedValue);
        }
    }
}

and here is the XAML of the bound controls
<Label x:Name="statusLabel" Content="{Binding StatusText}" TextBlock.Foreground="{Binding StatusColorBrush}" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="25,71,0,0"/>
<Button x:Name="enableButton" Content="{Binding EnableButtonText}" Visibility="{Binding ControlVisibility}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="309,74,0,0"/>

A: Put BindOrganisations in the Loaded event of the Window.
Don't forget that the Loaded event can be called multiple time, you can use a boolean flag.


text:
Q: Merge rows in Excel & VBA I want to merge rows in Excel: the content to merge can be in different columns, "C" or "D" in my example. Any way I can do this using VBA? The file has ~20k rows.
My File: http://i.imgur.com/yDPdaQC.png

Goal: http://i.imgur.com/SZ5t9oX.png

Edit with more details:
Some sentences from the C & D columns are divided in 2,3 and sometimes 4 rows. I would like to merge those strings at the "top" cell from their respective column, when "A" and "B" have a value.
Thanks for your help!

A: you can use this.
Sub Merge()
    Dim ws As worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
    Dim ws2 As worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2")

    Dim sheet2Rng As Range: Set sheet2Rng = ws2.UsedRange
    Dim startRow As Integer: startRow = LastRow(ws) + 1
    Dim ws2RowCount As Integer: sheet2Rng.Rows.Count

    ChangeEvents False
    ws.Range("A" & startRow).Resize(ws2RowCount, 4).value = sheet2Rng.value
    ChangeEvents True
End Sub

Public Function LastRow(worksheet As worksheet) As Integer
    LastRow = worksheet.Cells(Rows.Count, 1).End(xlUp).Row
End Function

Sub ChangeEvents(value As Boolean)
    Application.EnableEvents = value
End Sub

A: Can you clarify?  Are you trying to:

*

*Create merged cells: C1 with D1, C2 with D2, etc?  This will lose the contents of the D column.

*Take the texts in column D and append them to the end of the column C cells;

*Create a new column which contains the C + D appended texts

A: Something like this:
Sub SquishRows()
    Dim sh1 As Worksheet, sh2 As Worksheet
    Dim rng As Range, rr As Range
    Dim rowdata As Variant
    Dim i As Integer, idx As Integer, j as Integer

    Set sh1 = Worksheets("Sheet1")
    Set sh2 = Worksheets("Sheet2")
    sh1.Activate

    Set rng = Range("A2").Resize(sh1.UsedRange.rows.Count - 1, sh1.UsedRange.Columns.Count)

    ReDim rowdata(Application.CountA(rng.Columns(1)), rng.Columns.Count - 1)

    idx = 0
    For i = 1 To rng.rows.Count
        Set rr = rng.rows(i)
        If Len(rr.Cells(1).Text) And Len(rr.Cells(2).Text) Then
            idx = idx + 1
            For j = 1 To rng.Columns.Count
                rowdata(idx, j - 1) = rr.Cells(j).Text
            Next
        Else
            For j = 3 To rng.Columns.Count
                If Len(rr.Cells(j).Text) Then
                    rowdata(idx, j - 1) = rowdata(idx, j - 1) & " " & rr.Cells(j).Text
                End If
            Next
        End If
    Next

    'push data to Sheet2
    sh2.Range("A1").Resize(UBound(rowdata, 1) + 1, UBound(rowdata, 2) + 1).Value = rowdata

    'add in header row
    sh2.Range(sh1.UsedRange.rows(1).Address).Value = sh1.UsedRange.rows(1).Value

    sh2.Activate
End Sub


text:
Q: Number of elements of $p$ where $p^q+p^r=p^s$ $p,q,r$ and  $s$ are positive integers that satisfy the equation $p^q+p^r=p^s$. Is there an infinite number of values for $p$ ?

A: We have
$$
p^q + p^r = p^s
$$
as $p \ne 0$ we have $p^k \ne 0$ and we can try to reduce the powers by division.
If $s \le \min(q, r)$ we have
$$
1 = p^{q-s} + p^{r-s} = \underbrace{p^m}_{\ge 1} + \underbrace{p^n}_{\ge 1}
$$
with $p > 0$, $m \ge 0$, $n \ge 0$. This equation has no solution for positive integer $p$.
Else $s > \min(q,r)$ and we assume $q \le r$ (otherwise flip $q$ and $r$).
We then get
$$
1 + p^{r-q} = p^{s-q} \iff \\
1 = p^m - p^n
$$
with $m = s - q > 0$ and $n = r - q \ge 0$.
If $n = 0$ (or $r = q$) the equation turns into
$$
2 = p^m
$$
which has the solution $p = 2$, $m = 1$ (or $s = q + 1$).
If $n > 0$ (or $r > q$), we look if $p$ is even or not.
If $p$ is even, then $p^m$ and $p^n$ are even and their difference must be even, the equation has no solution for this case.
If $p$ is odd, then $p^m$ and $p^n$ are odd and their difference must be even too, so again no solution.
In summary we have found only
$$
2^q + 2^q = 2^{q + 1}
$$
thus one value $p = 2$, not infinite many ones.


text:
Q: Clearfix не работает Не могу понять, почему не работает clearfix. В данном макете футер должен очиститься от float, но почему-то не выходит.

header {
  border: 1px solid black;
  background-color: #336596;
}

nav {
  border: 1px solid black;
  float: left;
  width: 15%;
  background-color: #fd9800;
}

main {
  border: 1px solid black;
  float: left;
  margin: 0 auto;
  width: 60%;
}

aside {
  border: 1px solid black;
  float: left;
  width: 15%;
  background-color: #983264;
}

footer {
  border: 1px solid black;
  background-color: #669900;

}

.clearfix::after {
  content: "";
  clear: both;
  display: table;
}

Header

Navigation

Main

Related links

Footer

Должен получится вот такой макет

A: Не работало потому что вы не поставили = после класса  class="clearfix"


text:
Q: PHP - sorting a 3 level multidimensional array - sort base on 3rd level value but sort it in first level What is the normal procedure to sort a 3 level multidimensional array base on the 3rd level array value "count".    In this array, the count number may be 1,2,3,4,5 and so on.    how to carryout and have the larger count number array data set to be sorted into the beginning by the 1st level array index.
basically if an array record has a larger number in 'count'  let it be in the beginning of the array in a descending order.
(if 1 record contains count 1, 2, 3, let it use the largest count number as the decision variable for the sorting)
sample multidimensional array looks like
Array
(
     [174] => Array
    (
        [28] => Array
            (
                [index] => 28
                [draw] => 1
                [date] => 12-05-2036
                [value_a_key] => 7
                [value_b_key] => 2
                [value_c_key] => 4
                [value_a] => 1
                [value_b] => 5
                [value_c] => 12
                [count] => 1
            )

    )

[175] => Array
    (
        [19] => Array
            (
                [index] => 19
                [draw] => 10
                [date] => 12-05-2027
                [value_a_key] => 2
                [value_b_key] => 4
                [value_c_key] => 3
                [value_a] => 1
                [value_b] => 5
                [value_c] => 13
                [count] => 1
            )

        [26] => Array
            (
                [index] => 26
                [draw] => 3
                [date] => 12-05-2034
                [value_a_key] => 5
                [value_b_key] => 4
                [value_c_key] => 2
                [value_a] => 1
                [value_b] => 5
                [value_c] => 13
                [count] => 2
            )

        [28] => Array
            (
                [index] => 28
                [draw] => 1
                [date] => 12-05-2036
                [value_a_key] => 7
                [value_b_key] => 2
                [value_c_key] => 5
                [value_a] => 1
                [value_b] => 5
                [value_c] => 13
                [count] => 3
            )

    )

[178] => Array
    (
        [19] => Array
            (
                [index] => 19
                [draw] => 10
                [date] => 12-05-2027
                [value_a_key] => 2
                [value_b_key] => 4
                [value_c_key] => 7
                [value_a] => 1
                [value_b] => 5
                [value_c] => 16
                [count] => 1
            )

    )

A: This should work for sorting from low count to high count. Switch the last negative on the last statement if you want it the other way around.
usort($array, function ($x, $y) {

    // Set highest count to 0 for both arrays
    $highestCountForX = 0;
    $highestCountForY = 0;

    // Loop through first array to check
    foreach ($x as $secondLevelX) {
        if ($secondLevelX['count'] > $highestCountForX) {
            $highestCountForX = $secondLevelX['count'];
        }
    }

    // Loop through second array to check
    foreach ($y as $secondLevelY) {
        if ($secondLevelY['count'] > $highestCountForY) {
            $highestCountForY = $secondLevelY['count'];
        }
    }

    if ($highestCountForX === $highestCountForY) {
        return 0;
    }

    return ($highestCountForX < $highestCountForY) ? -1 : 1;

});

A: If I understood correctly, you want to sort according to the total count of each record, so in your example, record #175 has a total count of 6 and should be first in the list.
You can do this with usort, but it overwrites the array keys, so instead I used multisort and sorted both the keys and the values:
$counts = array();
$keys = array_keys($arr);
foreach ($arr as $key => $value){
    $total = 0;
    foreach ($value as $key2 => $value2){
        $total -= $value2['count'];
    }
    $counts[] = $total;//it's actually negative totals to sort in descending order
}
$counts_copy = $counts;//array_multisort will rearrange, so we need a copy
array_multisort($counts, $arr);
array_multisort($counts_copy, $keys);
$out = array_combine($keys, $arr);
print_r($out);


text:
Q: Question regarding an inequality How to prove that $$ \frac{x_1}{1+x_1^2}+\frac{x_2}{1+x_1^2+x_2^2}+\cdots+\frac{x_n}{1+x_1^2+\cdots+x_n^2}<\sqrt{n} $$ knowing that $(x_n)$ is a positive sequence ? I looked up all kinds of inequalities such AM-GM, Chebyshev, Cauchy-Schwarz, but I couldn't manage to obtain anything useful..
Can anyone help ?

A: First use Cauchy-Schwarz Inequality:
$\displaystyle \left(\frac{x_1}{1+x_1^2}+\frac{x_2}{1+x_1^2+x_2^2}+\cdots+\frac{x_n}{1+x_1^2+\cdots+x_n^2}\right)^2 \le n\left(\frac{x_1^2}{(1+x_1^2)^2}+\frac{x_2^2}{(1+x_1^2+x_2^2)^2}+\cdots+\frac{x_n^2}{(1+x_1^2+\cdots+x_n^2)^2}\right)$
So, it suffices to show that: $\displaystyle \frac{x_1^2}{(1+x_1^2)^2}+\frac{x_2^2}{(1+x_1^2+x_2^2)^2}+\cdots+\frac{x_n^2}{(1+x_1^2+\cdots+x_n^2)^2} < 1$
Since, $\displaystyle \frac{x_k^2}{(1+x_1^2+\cdots+x_k^2)^2} \le \frac{x_k^2}{(1+x_1^2+\cdots+x_k^2)(1+x_1^2+\cdots+x_{k-1}^2)} = \frac{1}{(1+x_1^2+\cdots+x_{k-1}^2)} - \frac{1}{(1+x_1^2+\cdots+x_{k}^2)}$
and, $\displaystyle \frac{x_1^2}{(1+x_1^2)^2} \le 1- \frac{1}{(1+x_1^2)}$
Adding the above inequality, the upper bounds telescope,
$\displaystyle \frac{x_1^2}{(1+x_1^2)^2}+\frac{x_2^2}{(1+x_1^2+x_2^2)^2}+\cdots+\frac{x_n^2}{(1+x_1^2+\cdots+x_n^2)^2} \le 1 - \frac{1}{1+x_1^2+\cdots+x_n^2} < 1$.

A: I think the proof can be divided to two parts: when all elements are equal, and then when they are not equal, try to prove that the sum would be less than sum of all equal elements (either max or min of the sequence).
First step: any x can be replaced by 1/x to increase the sum, if x > 1.
Second step: For x < y <= 1 and C >= 1, we have x / (C + x^2) < y / (C + y^2)
Third step: we replace all items with x(k) = max of sequence and have a more convenient formula to prove.
Fourth step: when all elements are equal, sum is less than 1/2 + 1/3 + 1/4 ... Which is the exact case when all elements are equal to 1, and this is a known sequence, as I remember


text:
Q: Horizontal scroll - syntaxhighlighter I was googling to find a solution for this forever, I was so close but still can't find the problem...
The closest solution I found was at this site But:
I want exactly the opposite of what this guy posted: Automatic line break in js SyntaxHighlighter
He wants instead of horizontal bar to break the code down, but what do I want is instead of breaking the code down, to display a horizontal bar.
I've used SH on multiple projects and never actually had this issue till now.
I've installed it in wordpress as a plugin in a custom theme, I modified the theme css file(s) and the syntax highlighter's file(s) (.css), but still nothing's going on.
Here's a screenshot
If you have any suggestion what the problem might be, please tell me - any help is appreciated.

A: I think what you are looking for is a combination of overflow and white-space css properties.
pre {overflow:scroll;}
.pre-wrap {white-space:pre-wrap;}

Please see the footle here


text:
Q: multiple slideshow on one page works bad a beginner here : )
I know it's been asked before but I couldn't find a solution yet. I have two automatic slideshows running one beneath the other on one page. they both work, but work awfully bad, the timing is not as set and it's not looping as it should be. but - if I keep only one slideshow in the page, it works perfectly fine. I'm struggling with it for hours already.
this is my html:

this is my css
#slides {
    position: relative;
    height: 100%;
    padding: 0;
    margin:0;
    list-style-type: none;
}

#slides2 {
    position: relative;
    height: 100%;
    padding: 0;
    margin:0;
    list-style-type: none;
}

.slide {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    opacity: 0;
    z-index: 1;

    -webkit-transition: opacity 1s;
    -moz-transition: opacity 1s;
    -o-transition: opacity 1s;
    transition: opacity 1s;
}

.slidetwo {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    opacity: 0;
    z-index: 1;

    -webkit-transition: opacity 1s;
    -moz-transition: opacity 1s;
    -o-transition: opacity 1s;
    transition: opacity 1s;
}

img {
    max-height: 95vh;
    max-width: calc(100vw - 80px);
}

.showing {
    opacity: 1;
    z-index: 2;
}

and this is my javascript:
var slides = document.querySelectorAll('#slides .slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,3000);

function nextSlide() {
    slides[currentSlide].className = 'slide';
    currentSlide = (currentSlide+1)%slides.length;
    slides[currentSlide].className = 'slide showing';
}

var slides2 = document.querySelectorAll('#slides2 .slidetwo');
var currentSlide = 0;
var slideInterval = setInterval(nextSlideTwo,1000);

function nextSlideTwo() {
    slides2[currentSlide].className = 'slidetwo';
    currentSlide = (currentSlide+1)%slides2.length;
    slides2[currentSlide].className = 'slidetwo showing';
}

thanks a lot !

A: So the first thing I see is that you're trying to reuse the same global variables for both slideshows. What's happening is that when both of those calls in the setInterval() are running, they're addressing the same variables, which would result in the images being displayed out of order, timing issues, and other similar things.
What I'd recommend trying would be trying to separate the variables out, so that nextSlide() and nextSlideTwo() are addressing and updating different things as they run. For example:
var slides = document.querySelectorAll('#slides .slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,3000);

function nextSlide() {
    slides[currentSlide].className = 'slide';
    currentSlide = (currentSlide+1)%slides.length;
    slides[currentSlide].className = 'slide showing';
}

var slides2 = document.querySelectorAll('#slides2 .slidetwo');
var currentSlide2 = 0;
var slideInterval2 = setInterval(nextSlideTwo,1000);

function nextSlideTwo() {
    slides2[currentSlide2].className = 'slidetwo';
    currentSlide2 = (currentSlide2+1)%slides2.length;
    slides2[currentSlide2].className = 'slidetwo showing';
}

Will throw this in a fiddle shortly to see how it runs and if any additional tweaks are needed.


text:
Q: How to pass dynamic url to infragistics tab I am using on demand for webtab how can I pass dynamic values in content URL? I am using the following in code behind and it's not working
WebTab.Tabs[0].ContentUrl = string.Format("{0}/AgreementTabContent/Summary.aspx?Id={1}&RegardingId={2}", ConfigurationManager.AppSettings["Path"], Request.QueryString["Id"], Request.QueryString["RegardingId"]);

My aspx page has
<ig:WebTab ID="WebTab" runat="server" Width="100%"  StyleSetName="Claymation" >
    <tabs>
    <ig:ContentTabItem  Key="Summary" runat="server" Text="Summary"
</ig:ContentTabItem>

A: this worked in web config pass nulls
      <add key="Path" value="" />
<add key="BetaDirectory" value="" />


text:
Q: How do you implement the "one step build" for a LAMP project? Having the "one push build" to take your changes from development environment to live server is one thing that is very nice to have and often advocated.
I came on board with a small team running in a LAMP stack and use SVN for version control, currently deployed on a single production server (another server for development and soon to be a separate mysql server).  I'm just now putting in place a lot of the organizational things that have been missing prior to me coming on board.
I am curious to see

*

*how people are doing this (one step build) currently

*see how i can implement it best for my situation (small team, LAMP environment with SVN)

Some particular challenges I'm interested in would be handling database changes (schema) and also if and what kind of "packages" are people using to keep things organized (e.g. RPMs, PEAR, etc.).

A: We used ant with Hudson. Worked like a charm.
Hudson would work with other build systems too, and not just java projects.  It lets you setup multiple build targets, and will run them automatically, or manually.  It also forces you to implement a way to run your build from a single command.
It doesn't solve the communication problems where the server will be unavailable during the time it takes to run the build for the deployed server.
For our schema updates and changes, we setup our ant script to do two things:

*

*Update run the schema only if there's a difference in SVN.

*Check in a schema dump after the schema changes were built.

*If there was no update to the schema, simply use the dump to load a database

It did take a few tries to get right, but suddenly we had solved the issue of multiple developers being on different schemas. It was so easy to import the dump to update your development schema, that you could do it daily.

A: We do.  We use a product called Anthill Pro to do all of our builds and deployments.  It has a workflow process which set up to check out the files, do the builds, run the unit tests and then deploy the code to the servers.  You can use it to deploy just about anything as the process can run command line programs etc.

A: I don't think there's a simple cookbook answer for this, because this depends very much on your environment. Whatever you come up with, I highly recommend a script-based approach, with the deployment scripts being in source control themselves. Those scripts will also allow better integration with build solutions (see below).
The simplest such script to run in your production environment would simply be the command to get latest (or get a specific version) from source control.
The next challenge is database deployment. The solution that I have come to like the most for small to medium-sized projects is to maintain a schema version table in each database and have all DDL and data update scripts in source control (including the data sources they use in compressed archives). The scripts are numbered consecutively (starting 000001 ..., 000002 ..., etc.) and the deployment script I run simply first backs up the existing database, then gets the last run database script from the schema version table, and then runs any new database scripts found in source control in correct order, updating the schema version table accordingly.
This approach allows me to rebuild database from scratch pretty quickly.
The two approaches taken together make it possible to quickly deploy your code base to several different staging machines, your QA environment, beta, etc.

For just a little bit more complex scenarios, you should run a continues integration build server, like Kieveli et. al. suggested, which essentially "rebuilds" your entire deployment regularly and therefore contains scripts to do exactly what you would run "manually" above.
Database deployment can also be made more sophisticated by creating a rollback script for each database script. You should then write a little controller app to handle those. There are several OSS solutions for this kind of stuff and one of them may fit your needs.
BUT, make sure you never auto-deploy your database to a production environment ;-)

A: Best build tool for a PHP project is probably Phing, which is quite similar to Ant, but is written in PHP. It contains all the necessary things you'd need for something such as this, like grabbing things from your svn repo.

A: "make" on UNIX (and Windows) is your friend. It's got a learning curve though, but it's worth it. You can have make update the source, compile, test, etc, etc.

A: Once you've got a one step build going, you can easily turn it into continuous builds.
We've got all of our completed builds, marked with the change number they were built from, on a central server. When something gets committed (we use Perforce, but this would work for SVN), a cronjob on one of our build boxes notices that there's a more recent change than is build, fires of an http request to download the source tree, and starts building (with GMake, mostly). Continuous builds in only a few easy steps :)
After that, it's a short step to having all of your test automation run automatically. Fully built and tested (possibly deployable!) code after each commit.

A: For scripting language, usual advices like using ant-variant or CruiseControl variant don't mean much because you don't need to compile anything.
Let's stick to database. Three important things when it comes to continuous integration is automate, automate, and automate. This means you have to have everything from building empty database, importing from external data, and upgrading to new version scripted and ready to run using some scripts. A good example of that may be something like MediaWiki, which let's you configure and install using php itself. I would recommend running build server to deploy fresh database during the day, run unit tests and send out emails if any fail.

A: The way I think of it is that you want one script to pull everything together, basically get all the files\resources from source control an the perform all the steps to create a final 'product'
Off the top of my head those step could include get latest, compile, get any other files need to complete the product, create installer (if needed), run unit tests, share output on server (whatever that might mean for a particular project), and inform users that a new version has been create (or tell them if one has not, and why).  And whatever else you might need to do.
In the past I've usually started with some sort of batch file, then created some sort customized builder exe.  But maintaining that always became a pain.  Eventually I move one to 3rd party applications...now I just use one of the two products below.
http://www.kinook.com/VBP/
http://www.finalbuilder.com/


text:
Q: Given a finite set of points and a finite coloring of the plane, is there a monochromatic set of points of the plane similar with the first one? Two sets of points of the plane $A$ and $B$ are said to be similar iff there is a bijection $f: A\rightarrow B$ and a constant $c_f\in\Bbb{R}^*_+$ such that $\forall X, Y\in A: \overline{XY} = c_f\cdot \overline{f(X)f(Y)}$, so, for example, every two regular $n$-agons are similar.
Let $n\in\Bbb{N}$ and $S$ be a finite set of points of the plane. Every point of the plane is colored with one of $n$ colors. Is there a monochromatic set $S'$ of points of the plane similar with $S$?
I know already that the statement is true for any $n$ if $|S|\le 3$ (if $|S| = 1$ or $2$ the statement is trivial; if $|S| = 3$, a small adaptation of the solution to this problem along with induction in $n$ will do the job).
I believe that the statement is true for any $n$ if $|S| = 4$, but I was not able to prove it.
What I'm interested in, in fact, is finding a counter example: For what finite coloring of the plane and what finite set of points of the plane is the statement false? How can we construct this set and this coloring?


text:
Q: Get users with respect to a specific Azure directory Graph Explorer I have two directories in a single login of Azure.
When I hit the Graph Explorer API to get the users, it automatically goes to the default AD.
https://graph.microsoft.com/v1.0/users

I want to switch the directory and then get the users.
I just found this documentation where an app needs to be registered and you provide directory name in the tenant.
Please help.

A: The document you found is for the registered app  to communicate with Azure AD. It's not for Graph Explorer.
As I known, it's not possible to switch Directory in Graph Explorer. I test both Microsoft Graph and Azure AD Graph. I can only get users from the Default Directory.
My suggestion is that you can login Graph Explorer with another account which has another default directory.
You can also feedback Microsoft Graph in this UserVoice Forum.
Hope this helps!

A: This information came from: https://stackoverflow.com/questions/60931681/how-to-query-another-azure-active-directory-tenant-from-graph-explorer
Today that's possible if you pass the tenant query string parameter like this:
https://developer.microsoft.com/en-us/graph/graph-explorer?tenant=mydomainname.onmicrosoft.com

Note that you need to logout before going to this URL with the tenant query string. It'll ask you to login again. After login you can issue queries against the other tenant you have access to (not your home tenant where your account was originally created on).


text:
Q: How to submit "Beta App Description" to iTunes Connect with fastlane deliver I upload my iOS app and most of the app metadata to iTunes Connect using fastlane deliver. Most of the data and screenshots can be put into files that I then have stored in git.
This includes for example the review notes that are stored in a file
fastlane/metadata/review_information/notes.txt

In iTunes Connect there is a bit of information in the TestFlight part under "Test Information" called "Beta App Description". I would like to also upload this text using fastlane.
In the fastlane deliver docs I have found the parameter called "beta_app_description" and as far as I can read, this is exactly that. This is a command parameter and as such muct be spefified directly in the Fastfile or Deliverfile.
I would like to have fastlane load this from a file just like all the other metadata.
Is this possible and how?

A: Besides deliver (or upload_ios_app) there is a testflight (or upload_to_testflight or pilot) action in fastlane:
https://docs.fastlane.tools/actions/testflight/
As the name suggests, it is used for everything Testflight, which includes the beta description:

beta_app_description | Provide the beta app description when uploading a new build

https://docs.fastlane.tools/actions/testflight/#parameters
pilot is also the name of a connected command line tool, that has additional options:
https://docs.fastlane.tools/actions/pilot/
Unfortunately, getting this data from a file is not part of any of those.

A: It can be easily provided as a parameter to testflight action.
And if you like to format your text or provide more than just a sentence, you can use groovy's multi-line strings, e.g.:
upload_to_testflight(
  beta_app_description: "Have fun testing the app!",
  changelog:
"""This is my multi-line changelog
with information for my testers.
* align left to avoid blanks at the beginning of a line
* this allows nice formatting...

* ...and blank lines in between

Hope, you find it useful."""
)


text:
Q: Valgrind reports a memory error when trying to free a malloc'ed struct Valgrind always nags that there is a memory error when a previously malloc'ed struct is free'd. The struct looks as follows:
typedef struct bullet
{
  int x, y;
  struct bullet * next;
} BULLET;

... and I allocate the memory by using
BULLET * b;
b = malloc(sizeof(BULLET)); // sizeof(BULLET) is 16

and later on, the struct is free'd by simply calling free(b);. Valgrind however doesn't seem to be satisfied by this, and so it tells me
==2619== Invalid read of size 8
==2619==    at 0x40249F: ctrl_bullets (player.c:89)
==2619==    by 0x405083: loop_game (game.c:305)
==2619==    by 0x406CCA: main (main.c:47)
==2619==  Address 0x5b8d818 is 8 bytes inside a block of size 16 free'd
==2619==    at 0x4C29A9E: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==2619==    by 0x402E04: rm_bullet (player.c:329)
==2619==    by 0x402485: ctrl_bullets (player.c:95)
==2619==    by 0x405083: loop_game (game.c:305)
==2619==    by 0x406CCA: main (main.c:47)

Of course I can't just allocate only 8 bytes, because that would be the size needed to store the pointer, and not the size of the struct - so why does Valgrind keep telling me that there is an error?
Edit: Some more code which could be relevant ...
void
ctrl_bullets(WINDOW * w_field, BULLETLIST * lb)
{
  if (lb->num > 0)
  {
    BULLET * b;

    for (b = lb->head; b != NULL; b = b->next) // player.c:89
    {
      if (b->x > CON_FIELDMAXX)
      {
        write_log(LOG_DEBUG, "Bullet %p is outside the playing field; x: %d; "
                  "y: %d\n", (void *) b, b->x, b->y);
        rm_bullet(w_field, lb, b);
      }
      else
      {
        mv_bullet(w_field, b);
      }
    }
  }
}

A: The problem is that you free b, but then try to access b->next
The error that valgrind tells you is that you are accessing an 8 byte block (the NEXT pointer) inside a 16 byte block that has been free'd.
If you free b, you can't access to b->next. Just store it in a tmp variable :P
(also, remember to set b to null after freeing it so you don't have a Dangling Pointer)

A: 8 bytes inside BULLET is most likely the field next. You probably have kept &next somewhere and reuse that in ctrl_bullets (player.c:89). But since you don't show us that code, we can't say much more.
Edit: or perhaps we can guess that your next pointer forms a linked list and that you haven't set the next pointer of another element to 0 when doing the free.