How to assign values to a combobox

Question: Ill post an image to explain it better.

So, imagine that I make a 1st search, then I make a 2nd, or 3rd, 4th..search and I want to back to my old searches.
I already have some code that saves old searches (working fine). My only problem is how to assign the values to a combobox in order to comboboxes return to an old state.
How could I start doing this?
edit:
<code>$('#combos').on('change', '.combo', function() {
        var selectedValue = $(this).val();

        if (selectedValue !== '' && $(this).find('option').size() > 2) {
            var newComboBox = $(this).clone();
            var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
            var newComboBoxIndex = thisComboBoxIndex + 1;
            $('.parentCombo' + thisComboBoxIndex).remove();
            newComboBox.attr('data-index', newComboBoxIndex);
            newComboBox.attr('id', 'combo' + newComboBoxIndex);
            newComboBox.addClass('parentCombo' + thisComboBoxIndex);
            newComboBox.find('option[value="' + selectedValue + '"]').remove();
            $('#combos').append(newComboBox);
        }
        });

var check_combo_box_values = $('#combos .combo').map(function ()
                {
                    return $('option:selected', this).map(function() {
                    return parseInt(this.value);
                    }).get();
                }).get();
</code>
Comment: We can't write code for something we don't know the sourcecode of.
Comment: What language are you using? Jquery invloved?
Comment: @CR41G14: Tags: JavaScript / jQuery.
Comment: Do you want to assign changed value to your combobox?
Comment: @Cerbrus, what sourcecode you mean ?
Comment: @polin, I have an array with some old combobox values, and I want to assign them to combobox and it should assume the old "state", like is in the pic.
Comment: @user1148875 I didn't get your pictures. Is it arrays or dropdown boxes?
Comment: It is dropdown, but im storing the values (after the submit) in an array
Comment: @polin, I will update question with combobox code.
Answer: I made a fiddle how to add options to a combobox
http://jsfiddle.net/hRQqp/2/
Since you stated you had no troubles with saving the old searches, you should be able to put the pieces together
<code>var dropdown = document.getElementById('dropdown');
var list = [
    "first",
    "second",
    "third"
];

// remove old options
while (dropdown.length> 0) {
    dropdown.remove(0);
}

// add new ones
for (var i=0;i<list.length; i++) {
    var option = document.createElement("option");
    option.textContent = list[i];
    option.value = i;
    dropdown.appendChild(option);
}
</code>
Comment: `.appendChild is not a function` what could it be ?
Comment: http://www.w3schools.com/dom/met_element_appendchild.asp  It really is a function, it works in my example (http://jsfiddle.net/hRQqp/1/)
maybe you should post your existing code in jsfiddle and then we can see what goes wrong (propably var dropdown will be empty in your case)
Comment: I updated my example a little bit, now you can also select the value you want in the dropdown http://jsfiddle.net/hRQqp/2/

How to assign values to a combobox


App keeps force closing each time I try to run. Help needed.

Question: When I try to run this code it force closes. And I apologize in advance because I am a noob at java.
package com.MrNom;

import android.app.Activity;
import android.os.Bundle;

public class NomActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

}

This was red in LogCat right before it force closed.
07-29 18:59:40.626: ERROR/AndroidRuntime(347): FATAL EXCEPTION: main
07-29 18:59:40.626: ERROR/AndroidRuntime(347): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.MrNom/com.MrNom.Mr.NomActivity}: java.lang.ClassNotFoundException: com.MrNom.Mr.NomActivity in loader dalvik.system.PathClassLoader[/data/app/com.MrNom-1.apk]
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at android.os.Looper.loop(Looper.java:123)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at android.app.ActivityThread.main(ActivityThread.java:4627)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at java.lang.reflect.Method.invokeNative(Native Method)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at java.lang.reflect.Method.invoke(Method.java:521)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at dalvik.system.NativeStart.main(Native Method)
07-29 18:59:40.626: ERROR/AndroidRuntime(347): Caused by: java.lang.ClassNotFoundException: com.MrNom.Mr.NomActivity in loader dalvik.system.PathClassLoader[/data/app/com.MrNom-1.apk]
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
07-29 18:59:40.626: ERROR/AndroidRuntime(347):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)

Answer: In your AndroidManifest.xml, find where you declare that activity and change it's name property from "com.MrNom.Mr.NomActivity" to "com.MrNom.NomActivity".
As you can see from your activity class, it's in package "com.MrNom", not "com.MrNom.Mr"
Answer: to me it seems that you somehow messed up the namespaces - in the exception it says that it tries to create com.MrNom.Mr.NomActivity which is not found... the correct class would be (just a guess) com.MrNom.NomActivity - somewhere you make the runtime beleive there must be Mr. in there - you don't show enough code to solve this...
Comment: not sure... perhaps you can just search the project for "Mr." and see what turns up ?
Comment: um is there like an actual search or just look around for it myself?


basic question on cauchy sequences in $\mathbb{R}$

Question: I am a little confused about the following concept from Real Analysis:
suppose $\{a_n\}$ is a sequence in $\mathbb{R}$ which is Cauchy. then it is convergent, and it is shown as follows:
first we show it is bounded (this I understand how to do). then, from the Bolzano-Weierstrass theorem(every bounded sequence of real numbers contains a convergent subsequence) we deduce that there exists a convergent subsequence $\{a_{n_k}\}$ with limit $a$ (say).
we now claim that $\lim_{n \to \infty} a_n = a$.
what we need to show then is that for any given $\varepsilon > 0$ we can find $N > 0$ such that
$$\tag{1}
n \geq N \Rightarrow |a_n - a| < \varepsilon\,.
$$
by the triangle inequality we know that the following inequality is true, for all $n, n_k \in \mathbb{N}$:
$$\tag{2}
|a_n - a| \leq |a_n - a_{n_k}| + |a_{n_k} - a| \,.
$$
i know that the usual argument is now to say we control the first term using the Cauchy property of $\{a_n\}$ and the second term using the convergence of $\{a_{n_k}\}$ to $a$.
and here is where I am struggeling: why are we allowed to constrain the $a_{n_k}$? this is not clear to me, given the statement ${(1)}$. it looks like we have to make a $second$ choice, namely for the right hand side of ${(2)}$ to be $< \varepsilon$, the $n_k$ must be large also.
in particular, this choice cannot (at least as far as i understand) be resolved in a straightforward way (such as simply taking the larger of two constants) because the subsequence is a sequecen indexed by the subscript $k$, not the subscript $n$ any more - so choosing $K$ so that $|a_{n_k} - a| < \varepsilon/2$ whenever $k \geq K$ cannot be combined with choosing $N$ so that $|a_n - a_{n_k}| < \varepsilon/2$ whenever $n \geq N$.
I added this last paragraph because I sense this is where my misunderstanding is coming from - what am I missing? Thanks a lot for your help!!
Answer: You can make the two choices consistently.
First choose $N$ large enough so that $|a_n - a_m|< \epsilon/2$ for all $n,m \ge N$. Then choose $k$ such that $n_k \ge N$ and $|a_{n_k} - a| < \epsilon/2$. This can be done because any sufficiently large $k$ has both of these properties.
Then letting $m = n_k$, the right hand side of your inequality (2) is $< \epsilon$.
Answer: The idea, if you want $|a_n - a| < \epsilon$, is to choose an $N_1$ such that for any $n_k > N_1$, $|a_{n_k} - a| < \frac{\epsilon}{2}$. This can be done by convergence.
Separately, you want to find an $N_2$ such that for any two $n, m > N_2$, $|a_n - a_m| < \frac{\epsilon}{2}$. This can be done by Cauchy. If you now choose $n_k, n > \max(N_1, N_2)$, then by the triangle inequality (letting $a_{n_k}$ take the place of $a_m$),
$$
|a_n - a| \leq |a_n - a_{n_k}| + |a_{n_k} - a| < |a_n - a_{n_k}| + \frac{\epsilon}{2} < 2\frac{\epsilon}{2} = \epsilon
$$
where the first strict inequality is valid since $n_k > N_1$, and the second one is valid since $n, n_k > N_2$.
Answer: The basic idea is that to pick an $N$ for which $|a_m - a| \leq \epsilon$ for all $m \geq N$, you

Use the convergence of a subsequnce to find a $k$ such that $|a_{n_m}-a| \leq \epsilon$ for all $m \geq k$
Use the cauchy sequence property to find an $l$ such that $|a_p - a_q| \leq \epsilon$ for all $p,q \geq l$
Pick $K$ such that $K \geq k$ and $n_K \geq l$, and let $N = n_K$.

You then have for an arbitrary $m \geq N$ $$
 |a - a_m| = |a + (a_N - a_m) - a_N| \leq |a - a_N| + |a_N - a_m| \leq \underbrace{|a - a_{n_K}|}_{\leq \epsilon\text{ by (1)}} + \underbrace{|a_N - a_m|}_{\leq \epsilon\text{ by (2)}} \leq 2\epsilon
$$
Now, for cleanliness, you might want to go back and replace $\epsilon$ with $\frac{\epsilon}{2}$ everywhere ;-)


spring cloud zuul server : very high latency value

Question: I have an edge zuul server service which route requests to downstream services.
I load test this architecture with 400 thread concurrently
in the downstream service the total latency is only one second.
using a pre and post zuul filters on edge server, I managed to calculate latency to be about  7.5 seconds on average which is approximately the same figure I get from hystrix.stream endpoint enabled on my edge zuul server

{
   "type":"HystrixCommand",
   "name":"authenticate",
   "group":"RibbonCommand",
   "currentTime":1492879164747,
   "isCircuitBreakerOpen":false,
   "errorPercentage":0,
   "errorCount":0,
   "requestCount":500,
   "rollingCountBadRequests":0,
   "rollingCountCollapsedRequests":0,
   "rollingCountEmit":0,
   "rollingCountExceptionsThrown":0,
   "rollingCountFailure":0,
   "rollingCountFallbackEmit":0,
   "rollingCountFallbackFailure":0,
   "rollingCountFallbackMissing":0,
   "rollingCountFallbackRejection":0,
   "rollingCountFallbackSuccess":0,
   "rollingCountResponsesFromCache":0,
   "rollingCountSemaphoreRejected":0,
   "rollingCountShortCircuited":0,
   "rollingCountSuccess":492,
   "rollingCountThreadPoolRejected":0,
   "rollingCountTimeout":0,
   "currentConcurrentExecutionCount":397,
   "rollingMaxConcurrentExecutionCount":399,
   "latencyExecute_mean":7552,
   "latencyExecute":{
      "0":1003,
      "25":8131,
      "50":8359,
      "75":8543,
      "90":9095,
      "95":10495,
      "99":12311,
      "99.5":12311,
      "100":19551
   },
   "latencyTotal_mean":7552,
   "latencyTotal":{
      "0":1003,
      "25":8131,
      "50":8359,
      "75":8543,
      "90":9095,
      "95":10495,
      "99":12311,
      "99.5":12311,
      "100":19551
   },
   "propertyValue_circuitBreakerRequestVolumeThreshold":20,
   "propertyValue_circuitBreakerSleepWindowInMilliseconds":5000,
   "propertyValue_circuitBreakerErrorThresholdPercentage":50,
   "propertyValue_circuitBreakerForceOpen":false,
   "propertyValue_circuitBreakerForceClosed":false,
   "propertyValue_circuitBreakerEnabled":true,
   "propertyValue_executionIsolationStrategy":"SEMAPHORE",
   "propertyValue_executionIsolationThreadTimeoutInMilliseconds":200000,
   "propertyValue_executionTimeoutInMilliseconds":200000,
   "propertyValue_executionIsolationThreadInterruptOnTimeout":true,
   "propertyValue_executionIsolationThreadPoolKeyOverride":null,
   "propertyValue_executionIsolationSemaphoreMaxConcurrentRequests":5000,
   "propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests":10,
   "propertyValue_metricsRollingStatisticalWindowInMilliseconds":10000,
   "propertyValue_requestCacheEnabled":true,
   "propertyValue_requestLogEnabled":true,
   "reportingHosts":1,
   "threadPool":"RibbonCommand"
}

given that both the edge server and the downstream service is on the same internal network and given those properties values

server.tomcat.max-threads=5000
zuul.host.max-per-route-connections=5000
zuul.host.max-total-connections=10000
downstream service name : authenticate
zuul.eureka.authenticate.semaphore.maxSemaphores=5000

I set the property server.tomcat.max-threads=5000 in both the edge server and the downstream service
Why the latency is so high like that in the edge server? how can eliminate it or how can I trace where the latency occurs?
I use spring boot version 1.4.0.RELEASE to build both the edge server and the downstream service
Comment: Which version of spring cloud are you using ?
Comment: Brixton.RELEASE
Answer: I guess that your problem could be caused by maxTotalConnection and maxPerRoutConnections. If you are using zuul with ribbonRoutingFilter, please try to define the below properties.
<code>authenticate:
  ribbon:
    MaxTotalHttpConnections: 5000
    MaxHttpConnectionsPerHost: 10000
    MaxTotalConnections: 5000  # just for using apache http client in camden
    MaxConnectionsPerHost: 10000 # just for using apache http client in camden
</code>
The current releases (brixton, camden, dalston) seem to have small bug about these properties. Unlike the documentation, zuul.host.max-per-route-connections, zuul.host.max-total-connections don't affect the actual configuration. Instead, we should define ribbon configuration directlt like above.
Comment: the property "propertyValue_executionIsolationSemaphoreMaxConcurrentRequests":5000 already has the right value according hystrix.stream output.
Comment: I find out that the issue is related to our network setup..and the netwok team is in charge now...thnx for your support.


How to get the Cache Event Key from Mule

Question: I am using Anypoint Studio 6.1 and Mule 3.8.1 and have a mule managed store Caching Strategy that uses the default Event Key generation.
How can I get the value of this key in a flow?  Where is it stored?
Thanks
Answer: By default the generator provides SHA 256 hash as a key if you don't provide a key generator expression in your cache.
ref:- https://github.com/mulesoft/mule/blob/mule-3.x/core/src/main/java/org/mule/keygenerator/SHA256MuleEventKeyGenerator.java
This generators computes a SHA 256 hash of the current message bytes payload.
You can use the following example to get the list of cache key of your flow:-
<ee:object-store-caching-strategy name="cachingStrategy" doc:name="cachingStrategy">
   <managed-store storeName="myNonPersistentManagedObjectStore" maxEntries="-1" entryTTL="20000" expirationInterval="5000"/>
</ee:object-store-caching-strategy>

<flow name="keylist" doc:name="keylist">
         <http:listener config-ref="HTTP_Listener_Configuration" path="/getkeyvalue" doc:name="HTTP"/>

            </scripting:script>
        </scripting:component>
       </flow>

Whenever you put some message in your cache, using the above flow you can get all the list of the default cache keys values which the cache scope provide as SHA 256 hash as default


Why is $w$ real if z is on the circle through $z_1,z_2,z_3$?

Question: Question on answer to this (*), a duplicate of this and related to this
(*) Exer 3.24 in A First Course in Complex Analysis by Matthias Beck, Gerald Marchesi, Dennis Pixton, and Lucas Sabalka
What I understand:

Based on Exer 2.14 or Exer 3.10, $T(z)$ refers to an arbitrary Möbius of the form $$\frac{az+b}{cz+d}, ad-bc \ne 0.$$

$\forall T$, Möbius, $$[z,z_1,z_2,z_3] = [T(z),T(z_1),T(z_2),T(z_3)]$$

Recall that the cross ratio itself is Möbius by Prop 3.12. Choose $T(z)$ to be $[z,z_1,z_2,z_3]$. Observe that $$T(z_1)=0, T(z_2)=1, T(z_3)=\infty,$$ which is pointed out in Prop 3.12.

Denote $w:=T(z)$. Observe that $$w = T(z) = [z,z_1,z_2,z_3] = [T(z),T(z_1),T(z_2),T(z_3)] = [w,0,1,\infty].$$

By (4), $$w \in \mathbb R \iff [z,z_1,z_2,z_3] \in \mathbb R$$

Recall that $\forall T$, Möbius, $T$ is bijective and maps clines to clines by Prop 3.1 and Thm 3.4.

By (6), $$w \in \mathbb R \iff z \in C(z_1,z_2,z_3)$$

By (5) and (7), $$\therefore, [z,z_1,z_2,z_3] \in \mathbb R \iff z \in C(z_1,z_2,z_3)$$ QED

Questions:

Which part of the paraphrasing is wrong, and why?

Why is (7) true please?

I believe this is the crux of my misunderstanding. I don't believe I understand the explanations in the answers in the linked questions.

Actually, it seems like we needed to have proved that $$[z,z_1,z_2,z_3] \in \mathbb R \cup \{\infty\} \iff z \in C(z_1,z_2,z_3).$$ Am I wrong? Was that done? If $[z,z_1,z_2,z_3] = \infty$, then $z=z_3 \in C(z_1,z_2,z_3)$. Not sure about converse. Oh actually, I think what may have been meant by 'real line' is $\mathbb R \cup \{\infty\}$? In which case, I think #4 in the answer should have been 'iff w is on the real line' rather than 'w is real' ?

Btw, can we get somewhere with using Cauchy-Riemann? I'm thinking if $f$ is real-valued then it is constant wherever it is holomorphic by Exer 2.19. Then the cross ratio $[z,z_1,z_2,z_3]$ equals some constant real number $c$. If we would solve for $z$ in terms of $c,z_1,z_2,z_3$, then could we do something with it? I mean, other than manually computing the equation of the circle and then plugging $z$ into it.
Comment: Functions of the form that $T$ has send the set of circles and lines to the set of circles and lines. Since $z$ is in the circle passing through $z_1,z_2,z_3$, and these three points are sent to the real line, to the points $0,1,\infty$, then the point $z$ would also be sent to that line.
Comment: @nextpuzzle thanks....soooo if the 3 points' image is in R then the circle between them has an image in R and so if z is on the circle, then the image of z is real valued? Why/why not? And what about the converse? If w is in R, then why is the preimage in the circle passing through the preimages of 0,1,infty?
Comment: @nextpuzzle I think I got it. Is my answer wrong please?
Answer: I think I got it: w is the image of z under T. Thus...
$\leftarrow$
If z is on the circle, then the image under T is on the real line. Why? T maps 3 distinct points to 2 finite points and $\infty$. Thus, T maps the points to a subset of the real line. I conclude this is the whole real line either because $\infty$ is there or because an empty or proper subset would not be a line. Now because T maps clines to clines bijectively, it maps the entire circle passing through the 3 points to entire real line. $\therefore$, if z is in the circle, its image is on the real line. But the image under T is the cross ratio.
$\rightarrow$
Now suppose the cross ratio, which is the image of z under T, is on the real line. We know the whole circle is mapped to the whole real line under T. Since T is bijective and maps clines to clines, the preimage of T(z), w/c is z, is on the circle.
QED


Vagrant behind NTLM proxy on windows - guest unable to connect to the host proxy

Question: I'm on a Windows machine behind a corporate NTLM proxy and I need to vagrant up a VM from the given Vagrantfile.
I've read a few things on this topic:

http://runefs.com/2014/11/28/setting-up-vagrant-behind-a-corporate-proxy/
VirtualBox: How to set up networking so both host and guest can access internet and talk to each other

What I've so far:
CNTLM on my Windows machine, listening to 192.168.33.1:5865. Here's a snippet from cntlm -v -f
section: global, Listen = '5865'
section: global, Listen = '192.168.33.1:5865'

Exported HTTP_PROXY and HTTPS_PROXY:
set HTTP_PROXY=http://192.168.33.1:5865
set HTTPS_PROXY=http://192.168.33.1:5865

Installed the vagrant-proxyconf plugin
Created the .vagrant.d\Vagrantfile:
Vagrant.configure("2") do |config|
  # configuration based on http://digitaldrummerj.me/vagrant-behind-proxy-server/
  if Vagrant.has_plugin?("vagrant-proxyconf")
    config.proxy.http     = "http://192.168.33.1:5865/"
    config.proxy.https    = "http://192.168.33.1:5865/"
    config.proxy.no_proxy = "localhost,127.0.0.1,10.43.125.137,10.43.125.137,10.43.124.177"
  end
end

Set up a Windows firewall rule to allow everything from 192.168.33.10 to 192.168.33.1, on any port, for all programs and profiles.
And I'm still getting:
==> default: Cannot add PPA: 'ppa:webupd8team/java'.
==> default: Please check that the PPA name or format is correct.
==> default: Err http://security.ubuntu.com trusty-security InRelease
==> default:
==> default: Err http://security.ubuntu.com trusty-security Release.gpg
==> default:   Unable to connect to 192.168.33.1:5865:
==> default: Err http://archive.ubuntu.com trusty InRelease
==> default:
==> default: Err http://archive.ubuntu.com trusty-updates InRelease
==> default:
==> default: Err http://archive.ubuntu.com trusty-backports InRelease
==> default:
==> default: Err http://archive.ubuntu.com trusty Release.gpg
==> default:   Unable to connect to 192.168.33.1:5865:
==> default: Err http://archive.ubuntu.com trusty-updates Release.gpg
==> default:   Unable to connect to 192.168.33.1:5865:
==> default: Err http://archive.ubuntu.com trusty-backports Release.gpg
==> default:   Unable to connect to 192.168.33.1:5865:
==> default: Reading package lists...
==> default: W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/trusty/InRelease
==> default:
==> default: W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/trusty-updates/InRelease
==> default:
==> default: W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/trusty-backports/InRelease
==> default:
==> default: W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/trusty-security/InRelease
==> default:
==> default: W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/trusty-security/Release.gpg  Unable to connect to 192.168.33.1:5865:
==> default:
==> default: W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/trusty/Release.gpg  Unable to connect to 192.168.33.1:5865:
==> default:
==> default: W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/trusty-updates/Release.gpg  Unable to connect to 192.168.33.1:5865:
==> default:
==> default: W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/trusty-backports/Release.gpg  Unable to connect to 192.168.33.1:5865:
==> default:
==> default: W: Some index files failed to download. They have been ignored, or old ones used instead.

Note all these Unable to connect to 192.168.33.1:5865.
Why can't my guest connect to the proxy on my host? How can I diagnose this?
I am quite sure CNTLM proxy works, Vagrant itself accesses it a couple of times to check if the box is still actual. But the provisioning scripts which are executed later on can't.
I'm trying this for several hours already, getting desperate. Does anyone have an idea?
Answer: I also tried the links you did with no luck, then I came across: Using vagrant with cntlm proxy. The mistake we both made was to use the HOST only network (e.g. 192.168.33.*)  We want to access the internet so we should have used the Internet connection network (Vagrant NAT adapter).
Install vagrant-proxyconf plugin and set your proxy variables to 10.0.2.2:5865.


Richardson method optimal parameter

Question: The question I am about to ask came to my mind when I was analyzing Richardson method with symmetric and positive definite matrices. But it is really about simple math I somehow can't defeat.
Given real numbers: $\lambda_1\ge \lambda_2 \ge ...\ge \lambda_n>0$ find parameter $\alpha$ such that $\max_k|1-\alpha\lambda_k|$ is minimal. The answer is that $\alpha=\frac{2}{\lambda_1+\lambda_n}$. Why?
Answer: This can be proved by induction on $n$. (Side note: This is a nice example of a time when the geometric median in a metric space has a nice formula!) I have to run, however, and so I only sketch an argument below.
First, prove that this holds when $n = 1$ and $n = 2$.
Inductive Hypothesis: Assume that for all $x_1\geq \ldots \geq x_n > 0$ the function $a\mapsto \max_k|1-ax_k|$ is minimized at $\frac{2}{x_1+x_n}$. Given $\lambda_1 \geq \ldots \geq \lambda_n \geq \lambda_{n+1} > 0$, break the argument into three cases:

If $\lambda_1 = \lambda_2 = \ldots = \lambda_{n+1}$, the result follows from the $n=1$ case.
Similarly, if $\lambda_1 = \lambda_2 = \ldots = \lambda_n > \lambda_{n+1}$, then the result follows from the $n=2$ case.
Now for the interesting case. Assume that at least one of the first $n-1$ inequalities is strict, i.e., that $\lambda_1 > \lambda_n \geq \lambda_{n+1}$. For $k = 1,\ldots,n$, define

$$
x_k = \begin{cases}
          \lambda_1 - \lambda_n &\text{if } k = 1\\
          \lambda_k             &\text{if } 2\leq k \leq n-1\\
          \lambda_n + \lambda_{n+1} &\text{if } k = n.
      \end{cases}
$$
By the inductive hypothesis
$$
a\mapsto \max_k|1-ax_k|
$$
is minimized at
$$
a = \frac{2}{x_1+x_n} = \frac{2}{\lambda_1+\lambda_{n+1}}.
$$
You can then do some algebra to infer from this that $\min_k|1-a\lambda_k|$ is also minimal at this $a$.
Answer: since $\lambda_1\geq \lambda_2\geq \ldots \geq \lambda_n$ and $\alpha$ is fixed there, so
$|1-\alpha \lambda_1|\leq |1-\alpha \lambda_2|\leq \ldots \leq |1-\alpha \lambda_n|. $
$|1-\alpha \lambda_n|$ is minimum when $|1-\alpha \lambda_1|=|1-\alpha \lambda_n|$ or $1-\alpha \lambda_1=\alpha \lambda_n-1$, that is, for $\alpha=\frac{2}{\lambda_1 +\lambda_n}$.
Comment: A bit elaboration: For the specified alpha we have $|1 - \alpha \lambda_1|$ =  $|1 - \alpha \lambda_n|$, indeed:  If you plug $\alpha = \frac{2}{\lambda_1 + \lambda_n}$ into $|1 - \alpha \lambda_1|$ you obtain $\left|\frac{\lambda_n - \lambda_1}{\lambda_n + \lambda_1}\right|$ if you plug same $\alpha$ into $|1 - \alpha \lambda_n|$ you obtain $\left|\frac{\lambda_1 - \lambda_n}{\lambda_n + \lambda_1}\right|$  observe that $\left|\frac{\lambda_n - \lambda_1}{\lambda_n + \lambda_1}\right| = \left|\frac{\lambda_1 - \lambda_n}{\lambda_n + \lambda_1}\right|$

Richardson method optimal parameter


Why is dx/dt = -(∂u/∂t) / (∂u/∂x)?

Question: I found that $\frac{dx}{dt} = -\cfrac{ \frac{\partial u}{\partial t} }{ \frac{\partial u}{\partial x}}$ on the internet. I can´t figure out if it is true and why.
Comment: it's the chain rule...
Answer: This expression does not mean anything. So first we must define the variables. I assume that you meant: let $u(\alpha,\beta)$ be a smooth function of two real variables and let $x$ be a smooth univariate function with real values such that $u(t,x(t))=0$.
Then, $x'(t)=-\frac{(\partial u)/(\partial \alpha)(t,x(t))}{(\partial u)/(\partial \beta)(t,x(t))}$.
This is straightforward when you differentiate wrt $t$ the equation $u(t,x(t))=0$.
Answer: This is a result of the implicit function theorem. In fact, in some presentations (i.e. Rudin) this is included in the theorem. Look there for definitions/proofs.

Why is dx/dt = -(∂u/∂t) / (∂u/∂x)?


Separar nome do ramal - em Python

Question: Tenho uma coluna na planilha em Excel com a seguinte coluna:
Atendido por
Ismael  (100)
JEFFERSON LUIZ ESTEVAO DE MOURA (111)
Felipe Braga Regis Souza (222)

Tenho que pegar apenas o nome e colocar em uma nova coluna e o ramal em outra, se o exemplo abaixo:
ANALISTA                                         RAMAL

Ismael                                           100
JEFFERSON LUIZ ESTEVAO DE MOURA                  111
Felipe Braga Regis Souza                         222

Meu código:
arquivoxlsx = pd.read_excel('C:/Users/Desktop/Python/Base/Atendidas.xlsx')

Atendidapor = arquivoxlsx["Atendida por"]
cont = 0
indice = 0

for c in Atendidapor:
    Analista = arquivoxlsx.at[cont,'Atendida por']
    tamanhomatriz = len(Analista.split())

    # print(registro)

    while True:
        registro = Atendidapor.get(indice)
        if indice < tamanhomatriz:
            arquivoxlsx.at[cont, 'Analista'] = registro + ""
        else:
            arquivoxlsx.at[cont, 'Analista'] = "" + registro
            indice = 0
            break
        indice  += 1
    #
    cont += 1

Answer: Consegues extrair os valores diretamente através dos métodos extract e replace das Series do Pandas.
import pandas as pd

data = ['Ismael  (100)', 'JEFFERSON LUIZ ESTEVAO DE MOURA (111)', 'Felipe Braga Regis Souza (222)']
df = pd.DataFrame(data, columns=['Atendido por'])
df['Analista'] = df['Atendido por'].str.replace(r"\((.*)\)", "")
df['Ramal'] = df['Atendido por'].str.extract(r"\((.*)\)")
df.drop(df.columns[[0]], axis=1, inplace=True)

Out[3]:
                           Analista Ramal
0                          Ismael     100
1  JEFFERSON LUIZ ESTEVAO DE MOURA    111
2         Felipe Braga Regis Souza    222

Answer: Você pode utilizar o split pelo parentese assim você vai ter uma lista onde o primeiro elemento será o nome e o segundo elemento o número com os parenteses depois é só você incluir cada valor na sua devida coluna.
   for x in Atendidapor.index:
        lista = Atendidapor[x].split("(")
        arquivoxlsx['ANALISTA'][x] = lista[0]
        arquivoxlsx['RAMAL'][x] = lista[1].replace("(", "").replace(")", "")

Separar nome do ramal - em Python


Linux RAID1 Software - grub resync after fail

Question: I've a linux server with 2 IDE HD & Raid (hda - hdb)
I've changed the "BAD" hdb with a new:
mdadm --fail /dev/md2 /dev/hdb3
mdadm --fail /dev/md0 /dev/hdb2
mdadm --fail /dev/md1 /dev/hdb1
mdadm --remove /dev/md1 /dev/hdb1
mdadm --remove /dev/md0 /dev/hdb2
mdadm --remove /dev/md2 /dev/hdb3
... change hdb
.... fdisk the new hdb
..... and:
mdadm --add /dev/md1 /dev/hdb1
mdadm --add /dev/md0 /dev/hdb2
mdadm --add /dev/md2 /dev/hdb3
Now I need to rebuild the grub/mbr for new hdb
Is it the correct way?
grub
root (hd0,0)  <-- ???
setup (hd0)   <-- ???
quit
Thanks!
Answer: When the RAID array has finished to resync, run:
grub
root (hd1,0)
setup (hd1)

Here there is a full howto.
Answer: Instead of using grub on each drive. You can just copy the mbr over.
To copy the MBR from sda into a file called /mbrbackup:
dd if=/dev/sda of=/mbrbackup bs=512 count=1

Now to restore the image to sdb
dd if=/mbrbackup of=/dev/sdb bs=446 count=1

MBR is divided into 3 sections

Bootstrap . 446 bytes
Partition table. 64 bytes
Signature. 2 bytes

See http://www.cyberciti.biz/faq/howto-copy-mbr/ for source.
Comment: It is trivial to use grub when you have two disks but it is a nuisance when you have 16 or more disks, and this copying approach is much quicker in those situations. The only thing to be careful of is not to copy the empty MBR over the good MBR. It can easily happen if you don't pay attention.
Answer: Will this work?
dd if=/dev/sda of=/dev/sdb bs=446 count=1


xamarin how to change the unique id of child in firebase

Question: I'm a beginner in firebase and i'm using nuget FirebaseDatabase.net.
I'm trying to replace the unique id of child with the users uid this is how it looks in the database

i tryed this code but it didnt work
private async void signupbutton_Clicked(object sender, EventArgs e)
{
    // the registration part
    FirebaseClient firebaseClient = new FirebaseClient("foo");
    try
    {
        var authProvider = new FirebaseAuthProvider(new FirebaseConfig(webApiKey));
        var auth =  await authProvider.CreateUserWithEmailAndPasswordAsync(UserNewEmail.Text, UserNewPassword.Text);
        string getToken = auth.FirebaseToken;

      //save user info in database

      await firebaseClient.Child("users").Child("some uid").PostAsync(new userinfo
        {

            firstName = UserFirstName.Text ,
            secondName = UsersecondName.Text
        }) ;

        await App.Current.MainPage.DisplayAlert("Alert", auth.User.LocalId, "Ok");
    }
    catch (Exception ex)
    {
        await App.Current.MainPage.DisplayAlert("Alert", "ala " + ex.Message, "OK");
    }
}

and this is the opject im trying to send
class userinfo
{
    public string firstName { get; set; }
    public string secondName { get; set; }
}

pleace let me know if my question needs  more Clarificatio thanks in advance.
Answer: When you Post to Firebase Realtime Database it always creates a new child node with a generated unique ID. If you want to specify your own ID, specify the entire path you want to write to (including that ID) and then use Put.
                                                     //
 await firebaseClient.Child("users").Child("some uid").child(getToken).PutAsync(new userinfo
{

    firstName = UserFirstName.Text ,
    secondName = UsersecondName.Text
}) ;


Which ukulele harmonic corresponds to which fret position?

Question: According to this page, ukulele natural harmonics can be played on the 12th (octave), 9th, 7th (octave+fifth), 5th (2octaves) and 3rd frets.
Which interval is obtained at the 9th and 3rd frets?
Comment: At least closely related, if not dupe - 'what are the actual notes of each natural harmonic?'.
Answer: The 3rd fret is two octaves plus a fifth.
(see https://liveukulele.com/lessons/techniques/harmonics/#natural)
The 9th fret is two octaves plus a major third.
(see https://fretsource-guitar.weebly.com/natural-harmonics-map.html. Although the source regards guitar, it will be the same for ukulele.)
As a supplement, the Wikipedia page regarding the harmonic series may be of interest.
Answer: Harmonics can be played at any position where overtones have a "node", which is all integral divisions of the string. The 12th fret is at 1/2 of the string, the 7th and the 19th fret correspond to 1/3 and 2/3, The 5th fret and the 24th fret correspond to 1/4 and 3/4, slightly below 4th freth, 9th fret, 16th fret correspond to 1/5, 2/5, 3/5.
3rd corresponds to 1/6. Between 2/3, slightly under 6, slightly under 10, 15, 22 is 1/7, 2/7, 3/7, 4/7, 5/7. Slightly above 2nd fret, 8th fret, 16th fret correspond to 1/8, 3/8, 5/8. And so it goes on, but the higher you get the harder it becomes to pinpoint a node and the less energy is there, so it gets harder to get a nice harmonic.
1/2 then produces multiple of the first overtone, which is an octave. 1/3, 2/3 produce the second overtone, which is a fifth plus one octave. 1/4, 3/4 produce multiples of the third overtone, which is two octaves. 1/5, 2/5, 3/5, 4/5 produce the fourth overtone which is a (pure) major 3rd plus two octaves. 1/6, 5/6 produce the fifth overtone, which is a fifth plus two octaves, 1/7 - 6/7 produce the sixth overtone, which is a natural seventh. 1/8, 3/8, 5/8, 7/8 produce the seventh overtone, which is three octaves. And so on.
Comment: "integral divisions" - do you mean integer?
Answer: The ukulele harmonic at the 12th fret corresponds to the same pitch as the open string, but one octave higher. The harmonic at the 7th fret corresponds to the same pitch as the 5th fret note, while the harmonic at the 5th fret corresponds to the same pitch as the 7th fret note.


Golang Gorm reverse hasMany relation

Question: We can Easy to get the child of hasMany relation in Golang Gorm with Preload.
But how to get reverse of relation.
type Owner struct {
    ID         int        `gorm:"column:id" json:"id"`
    Name       string     `gorm:"column:name" json:"name"`
    Projects   []Project  `gorm:"foreignkey:OwnerID" json:"projects"`
}

type Project struct {
    ID          int     `gorm:"column:id" json:"id"`
    Name        string  `gorm:"column:name" json:"name"`
    OwnerID     int     `gorm:"column:owner_id" json:"owner_id"`
    Gallery     []Gallery `gorm:"foreignkey:ProjectID" json:"gallery"`
}

type Gallery struct {
    ID             int    `gorm:"column:id" json:"id"`
    ProjectID      int    `gorm:"column:project_id" json:"project_id"`
    Url            string `gorm:"column:url" json:"url"`
    Title          string `gorm:"column:title" json:"title"`
    Description    string `gorm:"column:description" json:"description"`
}

we can populate Gallery inside Project with Preload, like this:
db.Preload("Gallery").Find(&project)

How to get reverse, we want load project from gallery or owner from project?
the result I want some thing like this, when get project in form of json:
{
   "id": 1,
   "name": "Name Of Project",
   "owner": {
      "id":1,
      "name": "Owner 1"
   },
   "gallery":[]
}

Comment: I am also looking for this. I am coming from NodeJS(express) which has ways to do this. Anyone ?
Answer: I am a bit late to the game with this answer, but you can define inverse relationships (belongs to) on the child models by doing this:
type ParentModel struct {
    Children []Child // This is a 'has many'
}

type Child struct {
    ParentModelID int // These behave as a 'belongs to'
    ParentModel ParentModel // You need both the model and the modelID
}

Full working example
This uses the models from your question. A note on performance, the preloading in gorm isn't done via joins. It's done via additional SQL queries, the more nesting the more queries. If you have commonly executed preloading, it could be worth writing a raw query and a custom scanner to use an optimised query.
package main

import (
    "fmt"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

type Owner struct {
    gorm.Model
    Projects []Project
}

type Project struct {
    gorm.Model
    OwnerID int
    Owner   Owner
    Gallery []Gallery
}

type Gallery struct {
    gorm.Model
    ProjectID int
    Project   Project
}

func main() {
    db, err := gorm.Open(sqlite.Open("many2many.db"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    err = db.AutoMigrate(&Owner{}, &Project{}, &Gallery{})
    if err != nil {
        return
    }

    ownerOne := Owner{}
    db.Create(&ownerOne)

    projectOne := Project{Owner: ownerOne}
    projectTwo := Project{Owner: ownerOne}
    db.Create(&projectOne)
    db.Create(&projectTwo)

    galleryOne := Gallery{Project: projectOne}
    galleryTwo := Gallery{Project: projectOne}

    galleryThree := Gallery{Project: projectTwo}
    galleryFour := Gallery{Project: projectTwo}

    db.Create(&galleryOne)
    db.Create(&galleryTwo)
    db.Create(&galleryThree)
    db.Create(&galleryFour)

    // Find by project and preload owners
    fetchedProject := Project{}
    db.Preload("Owner").Find(&fetchedProject, projectOne.ID)
    fmt.Println(fetchedProject.Owner)

    // Find by a gallery and preload project and owner
    fetchedGallery := Gallery{}
    db.Preload("Project.Owner").Find(&fetchedGallery, galleryOne.ID)
    fmt.Printf("Gallery.id = %d --> Project.id = %d --> Owner.id = %d\n", fetchedGallery.ID,
        fetchedGallery.Project.ID, fetchedGallery.Project.Owner.ID)
}

Comment: Your answer works for me. But I wonder where the constraints for `OnUpdate` and `OnDelete` should be defined. Parent or Child, is there some kind of precedence?

Golang Gorm reverse hasMany relation


Linux backup using tar

Question:
Im new to linux backup.
Im thinking of full system backup of my linux server using tar.
I came up with the following code:
tar -zcvpf /archive/fullbackup.tar.gz
--exclude=/archive
--exclude=/mnt
--exclude=/proc
--exclude=/lost+found
--exclude=/dev
--exclude=/sys
--exclude=/tmp
/

and if in need of any hardware problem, restore it with
cd /
tar -zxpvf fullbackup.tar.gz

But does my above code back up MBR and filesystem? Will the above code be enough to bring the same  server back?
Answer:
But does my above code back up MBR and filesystem?

No. It backs up the contents of the filesystem.
Not the MBR which is not a file but is contained in a sector outside the file systems.
And not the filesystem with it potentially tweaked settings and or errors, just the contents of the file system (granted, that is a minor difference).

and if in need of any hardware problem, restore it with

cd /
tar -zxpvf fullbackup.tar.gz

Will the above code be enough to bring the same server back?

Probably, as long as you use the same setup. The tarball will just contain the files, not the partition scheme used for the disks. So you will have to partition the disk in the same way. (Or copy the old partition scheme, e.g. with dd if=/dev/sda of=myMBRbackup bs=512 count=1).
Note that there are better ways to create backups, some of which already have been answered in other posts.   Personally I would just backup the configuration and the data. Everything else is merely a matter of reinstalling. Possibly even with the latest version.
Also not that tar will backup all files. The first time that is a good thing.
But if you run that weekly or daily you will get a lot of large backups. In that case look at rsync (which does incremental changes) or one of the many other options.
Comment: Could you paste the URL of other post for better ways to create backups?
I have been looking for it but couldn't get the just way of doing it.
Comment: It depends on how you want to make backups. If you have several servers, try using Amanda (http://www.amanda.org/), if you just have two servers use rsync (comes with the OS). If you have a build in tape drive use your tar command. If you want a once off backup with a nice graphical front consider Acronis True Image. Etc etc.
Comment: It's single Linux server (CentOS - shell access only) which I want to take a full system backup once. Once the backup is taken locally, I will transfer that backup to other PC to keep it safe.
Comment: In that case why create the backup on a server and then transfer it. You can do this instead:  One the host to store your backup run `nc -l 1234 > MyBackupOfComputerA.tgz`. And on the computer to archive run the tar command with as output filename `-` and append `| nc ComputerB 1234`.  That `-` will write to std out instead of to a file. The `|` pipes the std out text to netcat which forwards it to another computer.  The nc on the other computer listens for the information and writes it to a file. No intermediate copy is needed.
Comment: As you told me above that the tar command won't backup the MBR and filesystem.
I am looking for a way to have them in a backup in case of harddisk failure.
Comment: Aye. But it will have all your data. The OS is not that important. The data is. And it includes /etc/ with fstab and other files. For a true full disk backup you would want to mount the drive read-only, which means you usually end up booting from a liveCD and then making a copy. (e.g. using dd for the whole disk, output redirected to another drive or via the network). But that requires physical access to the server, or a DRAC/ILO or similar card.
Comment: So when restoring this tar backup, I will first need to install the same version of OS and then restore the backup. Is this restore step correct? But what about the filesystem and partition tables in this case of restore?
Comment: Depends on what you --exclude. If you just excluded /dev/ then you can just recreate the partitions (all the information on how you set them up is int he file called fstab which will be in your tar), untar the backup and restore the bootloader. All quite doable.
Comment: With this code will I be able to recreate the partitions?
`tar -zcvpf /archive/fullbackup.tar.gz
--exclude=/archive
--exclude=/mnt
--exclude=/proc
--exclude=/lost+found
--exclude=/dev
--exclude=/sys
--exclude=/tmp
/`
Answer: Using tar to backup/restore a system is pretty rudimentary, and by that I mean that there are probably more elegant ways out there to backup your system... If you really want to stick to tar, here's a very good guide I found (it includes instructions on backing up the MBR; grub specifically).=:
https://help.ubuntu.com/community/BackupYourSystem/TAR
While it's on the Ubuntu wiki website, there's no reason why it wouldn't work on any UNIX/Linux machine.
You may also wish to check out this:
https://help.ubuntu.com/community/BackupYourSystem
If you'd like something with a nice web GUI that's relatively straightforward to set up and use:
http://backuppc.sourceforge.net/
Hope this helps!
Comment: Let me second the pointer to backuppc. If you have several machines to backup, backuppc is a dream come true. Best thing of it is it's deduplication and compression.
Answer: Using remastersys :
http://www.geekconnection.org/remastersys/ubuntu.html
You can create live iso of your existing system. so install all the required packages on your ubuntu and then take a iso using remastersys. Then using startup disk, you can create bootable usb from this iso.
edit your /etc/apt/sources.list file. Add the following line in the end of the file.
deb http://www.remastersys.com/ubuntu precise main
Then run the following command:
sudo apt-get update
sudo apt-get install remastersys
sudo apt-get install remastersys-gui
sudo apt-get install remastersys-gtk
To run the remastersys in gui mode, type the following command:
sudo remastersys-gui
Comment: Any decent system would have all that in a startup script on the boot media. Nobody should have to search for instructions like that when trying to recover a system.
Comment: @JohnGardeniers : remastersys-gui is a decent tool for these purposes. I have provided detailed way to install and use it

Linux backup using tar


Rota no Google Maps utilizando coordenadas

Question: Tenho este código para criação de rotas utilizando Google Maps

var map;
var directionsDisplay; // Instanciaremos ele mais tarde, que será o nosso     google.maps.DirectionsRenderer
var directionsService = new google.maps.DirectionsService();

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer(); // Instanciando...
  var latlng = new google.maps.LatLng(-18.8800397, -47.05878999999999);

  var options = {
    zoom: 5,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById("mapa"), options);
  directionsDisplay.setMap(map); // Relacionamos o directionsDisplay com o mapa desejado
}

initialize();

$("form").submit(function(event) {
  event.preventDefault();

  var enderecoPartida = $("#txtEnderecoPartida").val();
  var enderecoChegada = $("#txtEnderecoChegada").val();

  var request = { // Novo objeto google.maps.DirectionsRequest, contendo:
    origin: enderecoPartida, // origem
    destination: enderecoChegada, // destino
    travelMode: google.maps.TravelMode.DRIVING // meio de transporte, nesse caso, de carro
  };

  directionsService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) { // Se deu tudo certo
      directionsDisplay.setDirections(result); // Renderizamos no mapa o resultado
    }
  });
});

Eu encontrei este código no link Blog PrinciWeb
Eu preciso usar a rota utilizando coordenadas diretamente, sem utilizar Geoprocessamento para converter as coordenadas em endereço.
Comment: Você pode passar a lat/lng para as propriedades `origin` e `destination`, não precisa ser necessariamente um endereço (String). Veja mais na documentação do [Google Maps API](https://developers.google.com/maps/documentation/javascript/3.exp/reference?hl=pt-br#DirectionsRequest).
Comment: Obrigado Douglas, estava procurando esta documentação.
Comment: Ok, vou deixar isso como resposta então. Só marcar como a correta fazendo favor.
Answer: Conforme eu havia comentado, não é necessário passar para as propriedades origin e destination um endereço (String), você pode passar latitude e longitude.
Para maiores esclarecimentos, favor verificar a Google Maps API.


Pegar primeira letra de cada palavra

Question: Estou usando o seguinte código para capturar a primeira letra de cada palavra. Como eu posso acrescentar mais uma regra no preg_split para ignorar palavras como: da, do, das, dos, de?
$nome = preg_split("/[\s,_-]+/", $loja->nome);
$iniciais = "";
foreach($nome as $n)
   $iniciais .= $n[0];

echo $iniciais;

Answer: <?php

$nome = preg_split("/((de|da|do|dos|das)?)[\s,_-]+/", "A C Loja do Supermercado");
$iniciais = "";
foreach($nome as $n)
{
    if (strlen($n) > 0)
    {
       $iniciais .= $n[0];
    }
}

echo $iniciais;

Verifique o exemplo ONLINE Ideone
Referencia: preg_split
Comment: Agora funcionou perfeitamente! Valeu!
Comment: Não funcionou. Não acho q seja esse o problema, já que o código sem remover essas palavras está funcionando, mas o código está dentro de um foreach, pq preciso pegar as iniciais de todas lojas do sistema.
Comment: @DiegoVieira Qual foi o problema de não funcionar? o que aconteceu, porque, eu gerei inclusive uma página de teste e funcionou! agora por exemplo fiz um ajuste para ficar sem o problema de campos vazios  verifique! e me avise e se tiver problemas relate o problema!

Pegar primeira letra de cada palavra


Inverse image of image of an ideal under quotient.

Question: Let $R$ be a ring and $I$ be an ideal of $R$.Then define $q:R\to R/I$ by $q(x)=x+I$.Let $J$ be an ideal of $R$,then our professor told us that $q^{-1} (q(J))=I+J$.I am not sure how this is true.Can someone help me understand this?
Answer: Just show a two sided inclusion. If $x=i+j\in I+J$ then we have:
$q(x)=i+j+I=j+I=q(j)\in q(J)$
And so $x\in q^{-1}(q(J))$.
Conversely, suppose $x\in q^{-1}(q(J))$, i.e $q(x)\in q(J)$. That means there is some $j\in J$ such that $q(x)=q(j)$, i.e $x+I=j+I$. By definition this means $x-j\in I$. Hence there is some $i\in I$ such that $x-j=i$. And then $x=i+j\in I+J$.
Answer: Just stare at it for long enough until it clicks.
The ideal $q(J)$ of $R/I$ is $\{j+I:j\in J\}$ since $q\colon R\to R/I$ is surjective.  Note that $q^{-1}(r+I)=r+I$ for all $r\in R$, and so
$$
q^{-1}(q(J))=q^{-1}(\{j+I:j\in J\})=\bigcup_{j\in J}(j+I)=J+I.
$$


In a 2-connected simple graph, is there always a simple cycle containing any given path P and disjoint edge e?

Question: For any finite simple graph $G$ which is 2-connected, given a path $P$ and a disjoint edge $e$, is it true that there is always a simple cycle containing $P$ and $e$?
If instead of an edge $e$, a vertex $v$ is specified with $v \notin V(P)$, then I believe the answer is yes by Menger's theorem.
Answer: No.

It is also not true of a path and a vertex. Pick the path specified above and one end of the edge specified above.
Answer: No. The path $P$ may contain enough edges to cut the remainder so much apart that its endpoints cannot connect to $e$ any more.
Comment: Thanks Hagen, that sounds reasonable but do you have a simple example please? I'm having trouble seeing how that would happen.


Geometrically interpreting quotient rings

Question: I would like some help with geometrically interpret quotient rings using algebraic geometry. To explain my current understanding using an example, take:
$$  R=\mathbb{C} \left[ x, y, z \right] / \left( xy, yz \right) $$
It seems to be that if you mod out $xy$ so $xy=0$, then $x=0$ or $y=0$. Thus the algebraic subset of $\mathbb{C}^3$ corresponding to the ideal $\left( xy \right)$ is the union of the $x$ and $y$ axes.
Similarly, when we mod out the other equation, we are left with the union of the $y$ and $z$ axes.
What, then, does the ideal $\left( xy, yz \right) $ correspond to? The $x$, $y$, $z$ axes? Is it only the $y$ axis?
Is there some way to geometrically interpret $R$ overall, using similar reasoning in algebraic geometry?
This is where things get a little fuzzy. Any help in finishing off/clarifying the geometric interpretation of $R$ here would be great. Any advice/comments on how to interpret things like this in general would be welcome too
Comment: To start with: $\mathbb{C}[x,y]$ is not a plane with axes. It's the ring of polynomials in two variables with complex coefficients. That means the rest of your attempt to understand the quotient makes little sense.
Comment: Have you taken a look at the coordinate ring of an algebraic affine variety?
Comment: Yes I understand that. I'm thinking more along the lines of using the Nullstellensatz (and related corollaries) to interpret the behavior of the quotient ring geometrically. Apologies, maybe I should have mentioned that more explicitly.
Comment: Maybe to help people understand my motivation: many algebraic geometers seem to use their geometric understanding of objects such as quotient rings to quickly and intuitively calculate things like maximal ideals in said quotient ring. This is my motivation for trying to 'visualise' rings like $R$ here using the Nullstellensatz.
Comment: There is no $z$ in $\mathbf{C}[x,y]$.
Comment: Whoops! Ok, fixed.
Answer: There is a bijection between coordinate rings and affine varieties. In our case, that variety is $V= V(xy, yz)$. A point $x \in \Bbb C^3$ is in $V$ iff either its $y$-coordinate is zero or both its $x$- and $z$-coordinates are zero.
We can write $V = V(x, z) \cup V(y)$. Therefore $V$ is the union of the $xz$-plane and the $y$-axis.
Comment: Which can also be seen with $(xy, yz) = (y)*(x,z) = (y) \cap (x,z)$, and then use that $V(I \cap J) = V(I) \cup V(J)$.


Building a ASP.NET & SQL Server Machine(s); need some help

Question: I currently have an asp.net web application running on an xp machine w/ iis 5.1 and sql server 2005 on our network.  This application processes large excel files (50MB+), handles 100's of 1000's of records of product information, and manipulates that data.  Right now not many people can access the app and do anything substantial with out the system freezing.
I would like to be able to have ~10 people using the system at any given time doing these large tasks.
Should I separate the web server and sql server on separate machines? XP, Vista, 7, Windows server? 32-bit, 64-bit? RAM? CPUs?
Obviously cost is somewhat of an issue...
Any recommendations, ideas, or links to articles would be greatly appreciated!
Answer: Your application requirements don't seem too onerous today.  With a well specified machine you shouldn't need to separate the functions into SQL box & web box.
If cost is a main factor then OS and SQL versions will depend on licensing costs, which in turn depend on whether your organization has partner agreements / special deals from MS.
However, it is definitely worth looking at the overall system design before you go throwing money at it.  Often 'freezes' can be fixed by changing locking / isolation schemes within the SQL database - if you have users trying to read from a table that is being updated with SQL's default locking, you will get blocked. (Look at READ UNCOMMITTED and NOLOCK hints but don't blindly rely on them)
Also look at PerfMon to see if disk I/O is causing your slowdowns (look up average disk queue length expected values) - and this will help to to see whether you need to concentrate on better disk arrays in your new machine (RAID 1, 5, 10 etc).
Answer: You know that IIS 5.1 on Windows XP has some serious limitations in terms of concurrent users? I belive the limit is 2 concurrent HTTP connections; it's not a server OS.
I think you can hack the registry to enable 10, but I think you get my point. Moving the SQL server to another server is a good idea regardless of the IIS platfor.
-Oisin
Answer: Actually the limit is 10.  You are thinking about the WinInet limitation of 2 connections to the same host from a client perspective.
Move this to a Server 2003 or Server 2008 instance and unless the code was written poorly from a concurrency perspective you should be fine.  If you are however accessing physical files, i.e. excel files, and not doing the proper locking, etc for concurrency management you still may be out of luck.
Answer: IIS 5.1 is actually your physical limitation. As others have said, Windows XP is not a server, so the built in webserver was not designed to handle more than 10 users connecting at one time.
Moving your application to a Windows Server 2003 or 2008 would give you a lot more potential for your application. If you're not looking for more than a few hundred connections in a day, then running both SQL server and the web server on the machine is okay. If you're looking for more, than a seperation of concerns would probably be a better way to go with this.
Good luck, and hope this helps some.


What type of Keyboard is best for use with DAWs for adding Bass Lines and Leads to my mixes?

Question: I produce original music using a Digital Audio Workstation similar to Logic Pro - and I want a hands on device to aid in adding nice sounding basslines and smooth ambient lead guitar solos (and other instruments as the song may dictate) to my compositions.  I am not looking to reproduce synth sounds of the analog moog variety, but rather to emulate various instruments that might be in a pop, rock or country or folk music band.
I am looking at purchasing some type of keyboard and would like to keep the price under $1,000. US.  I have seen advertisements for Keyboard Workstations, Keyboard Synths, Keyboard Arrangers, and Keyboard MIDI Controllers.
Which of these type keyboards are best suited for my specific application as stated above?
And what features should I look for that might be available within my budget?
I am not asking for recommendations for a specific brand, but rather want to narrow down my choices based on which option is best suited to help me accomplish my goals and know what features are most important for my intended use.
Comment: Yes I borrowed and improved upon a similar question by Donald  that was put on hold. It's a question I have often wondered about personally and really do want to gain more specific insight for my own purposes.   JC Pedroza attempted to resurrect the same question but his version has not attracted any answers so far.  This version narrows the scope and provides more parameters to contain the answers.  Hopefully we can attract some valuable content within the scope of this question.  I would not mind editing Donalds question and deleting this one if that is preferred by the community.
Comment: "...to emulate various instruments that might be in a pop, rock or country or folk music band." If those instruments aren't already keyboard instruments, my thought is that you'll never be fully satisfied by a keyboard. If they are keyboard instruments... I would go with a controller and software in your budget range. If you feel like the cost of the computer should be considered part of the budget in the case of software instruments, then I don't think you can get decent sounds for under $1000.
Comment: @ToddWilcox I have two computers capable of running DAW software.
Answer:
I am not looking to reproduce synth sounds of the analog moog variety, but rather to emulate various instruments that might be in a pop, rock or country or folk music band.

I suggest either a physical modeling synthesizer or multisample synthesizer designed to reproduce classic keyboard sounds. Something like a used Nord Electro 2 (around USD 1000 on e-Bay), which is actually a hybrid of the two types I recommend, is a perfect example.
As I mention in my comment, it's not so easy to find good non-keyboard sounds in a keyboard instrument. The best non-keyboard sounds tend to be orchestral ensemble sounds (a strings section or brass section), then maybe electric bass sounds, acoustic bass sounds, and drums and percussion. I've never heard a decent guitar, banjo, mandolin, ukelele, or other plucked instrument sound. I attribute this partly to difficulty in reproducing the raw sounds themselves, and also to the difficulty in re-creating the actual articulations of non-keyboard instruments using a keyboard.
Of course, re-creating keyboard articulations using a keyboard is dead easy. Acoustic piano is an instrument that is used for almost every purpose in literally every genre, so having one of those around is always a good plan. It's not so obvious how common it is to hear electric piano sounds in all kinds of rock, pop, country, R&B, etc. It's a subtle sound but it's also very versatile. The Hammond B3 organ is an excellent and versatile "pad" sound and also comprises most of the "bass" sounds for the band The Doors. So those are the sounds I would look for.
Physical modeling uses digital re-creations of the individual components of a device that are virtually connected exactly like they would be in the real device to create a very good re-creation of the sounds and response of the modeled device. This is a good technique for reproducing the sounds of a tonewheel organ like the Hammond B3 by using samples for the sounds of the individual tone wheels and then physically modeling the playback, mixing, and effects characteristics of the rest of the electronics of such an organ.
Multisampling uses multiple samples of each note of an instrument at several levels of playing intensity, and even uses multiple samples of the same note at the same intensity (that are then randomly selected from on playback). While it can be memory and computing intensive, multisampling is extremely effective at reproducing acoustic and electric piano sounds, since the entire sound of each note is determined by the stroke of the hammer, and the only "articulation" available after the hammer has struck is the dropping of the damper on the string or tine.
Note that if you are using a DAW, many of the best synthesizers are actually software plugins. For instance, currently the best acoustic piano synth I've heard is Apple's Steinway Grand sample for their ESX sampler, available in Logic and Mainstage. If you want to go with software synths, the choices are endless, and all you'll need otherwise is a good controller. I'd recommend finding one with USB bus power, and decide carefully what kind of action you want (fully weighted, semi-weighted, etc.) based on your comfort level and how you like to play. Many controllers also have knobs, faders, buttons, and pads that can be mapped to software controls to bring synth settings out to the hardware. That requires mapping of the controls and normally those controls aren't labelled the way the would be on a dedicated keyboard synth. The upside to this plan, if you already have the computer and the DAW, is you can get a decent controller for much less than $1000 and you can add on additional software instruments as needs arise and budget allows.


My JPEG files are not being rendered

Question: I have a hosting account on GoDaddy and I'm using cPanel on a Lenix server. My HTML file is in the same folder as the 2 images.
However, when I run the HTML the rendered image frames are blank. Can someone help?

Bedroom

Another shot of the bedroom.

Answer: Since this is hosted on GoDaddy, you're probably accessing the page via http:// or https://, not file://. You need to take out the file:// part of the URLs.
file:// is used on the local network. For example, if your computer's hostname is my-pc, then file://my-pc/Users might display the Users directory of your computer. Note that web pages that are accessed over HTTP or HTTPS are usually blocked from accessing resources through file://.
When you're on the Internet, you'll be using HTTP or HTTPS for linking to just about all resources on a webpage. Those protocols are not just for accessing the page itself.
Files that are part of the same website as the page itself don't need to include the protocol, so src="AnnBR2.jpg" and src="AnnBR1.jpg" should be good enough.

My JPEG files are not being rendered


assigned ips to my custom nameservers, however still the nameservers showing with "No IP"

Question: I went to  Main >> Server Configuration >> Basic cPanel & WHM Setup and correctly assigned the IPs to my 2 custom nameservers. After that (on same screen) I created A records also for the nameservers, and finally clicked on "Save Changes".
However when I go to Main >> Networking Setup >> Nameserver IPs, the 2 nameservers are shown, but under IP Address field, the value shown is "No IP".
What do I do to ensure that IPs are correctly assigned to my nameservers?
Comment: I wonder if it's looking for the "glue records" your domain registrar has for your nameservers.  Does `whois` list your nameservers' IP addresses for your domain?
Answer: You will need to register your name servers with the domain registrar. This creates so-called "glue records", which will then show up in your domain registration details. Some domain registrars will require a working DNS setup for the domain before they activate the glue records, so all your preparations so far are correct, you just need to make the final step.
Once the domain updates have propagated around the world, name resolution for your domain should work.
Comment: +1 for the most part, except that DNS doesn't propagate.
Comment: thanks, i created glue records and now it works perfectly :)
Answer: You should edit the following file:
<code>/etc/nameserverips
</code>
Once you have added the correct entries, which are in the format
<code>220.127.116.11=ns1.domain.com
126.96.36.199=ns2.domain.com
</code>
you should then load the Nameserver IPs option in WHM, these should then show up with IPs.


How to allow each company section to manage their own content on the Intranet?

Question: I have a simple problem of permissions. I work in a company which is divided into different sections. I have to make a Drupal intranet for them.
Each section must be able to manage their own content on the Intranet. The contents of the intranet are always the same, ie the same "content type" with the same "fields". It is necessary that a section could only edit the contents within its section. Thus, "computer" could only create / edit / delete content of "computer". The section of "press" could only create / edit / delete content of "press". All sections can view all content.
I tried different modules. "Field permissions", which lets you field level permissions, is interesting but does not help in this case. "Content Access" allows me to level management content type, but I can do what necesito.Con "Taxanomy Access Control" can define visibility rules, editing and deletion according to the presence or absence of one or more terms a taxonomy. It could be interesting, was not that "computer" should not be able to create content "press", for example.
You could create a content type for each section equal, and each give the required roles. The problem is that they are over 15 and does not seem the most optimal way to do this, because if I have to add a field so I have to do in the 15 (DRY).
I sense that Drupal has a more efficient way of doing this, but as I am new to this CMS I can not find it.
Comment: Taxonomy Access Control was good for me. What exactly you need that cannot be done with it?
Answer: The thing you are looking for is Organic groups. It does exactly what you need.
Further more you may be interested in some solutions already made on drupal. Like Open Atrium or Drupal Commons
Hope it helps.
Answer: The Group module allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.
For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. That's it.
For more details about the various types of roles used by the Group module, refer to my answer to "What are the various roles supported by the Group module?".
Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Serializing and deserializing data - JavaScript

Question: I need to perform a lot of serializing and de-serializing in an application.
The data is POST parameters and Cookie headers.

Post data example:

Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21

Set-Cookie data example:

ASP.NET_SessionId=esur3bqqgrmnci45um4xegye; path=/

Does anyone have any fast libraries to suggest or efficient ways to perform these operations?
Comment: http://stackoverflow.com/search?q=json.stringify
Comment: @David: can you explain please? :)
Answer: Consider using a JSON stringify method:
http://zumbrunn.com/mochazone/JSON.stringify+and+JSON.parse/
JSON is a fairly universal serialization format that you can parse in ASP.Net. Basically it converts a JS object into a string of text that represents the object itself (as if you were to type the object declaration out literally).


Como reutilizar uma conexão do Mongodb usando Golang?

Question: Boa noite a todos..
Tenho um pequeno projeto api em Go com Gin framework, estou usando o mongodb como banco de dados
com o driver "go.mongodb.org/mongo-driver/mongo"
Gostaria de abrir a conexão ao iniciar o app, e reusa-la posteriormente em outros packages do app, afim de que não seja criada uma nova a cada requisição. Fiz uma pesquisa e montei o seguinte código:
package config

import (
    "context"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "time"
)

var DB *mongo.Database

func init() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    db, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    DB = db.Database("bancoUnico")
}

Dessa forma, estou usando a variável DB no package de repositório para persistir os dados. Aparentemente, tudo funcionando... Ex:
    rep := repositorios.NovoRepUser(config.DB)
    usuario, err := rep.CadastrarUsuario(context.Background(), request)
    if err != nil {
        return nil, err
    }
    return usuario, err

Devido a pouca experiência, não sei se essa seria a abordagem correta. Se possível, gostaria de orientação para corrigir/melhorar a forma de reusar a conexão com o banco de dados.
Fico agradecido.
Comment: a gente usa aqui um padrão bem parecido com esse config seu, porém os repositórios ficavam como variável ali no config tb.. daí pra usar os repositorios era só fazer `config.UserDao.FindAll()` em qualquer lugar no código
Comment: Muito obrigado Eduardo!!!
Answer: Uma solução interessante para o seu problema é Dependency Injection.
Um exemplo prático:
package main

import (
    "database/sql"
    "log"
)

func OpenDB() (*sql.DB, error) {
    panic("not implemented")
}

type UserRepository struct {
    db *sql.DB
}

func NewUserRepository(db *sql.DB) *UserRepository {
    return &UserRepository{db: db}
}

func (r *UserRepository) Create(u *User) error {
    r.db.Exec("INSERT INTO users (name) values (?)", u.Name)
    panic("not implemented")
}

type User struct {
    ID   uint64
    Name string
}

func main() {
    db, err := OpenDB()
    if err != nil {
        log.Fatal("connect database error", err)
    }
    defer db.Close()

    userRepository := NewUserRepository(db)

    if err = userRepository.Create(&User{
        ID:   42,
        Name: "Don't Panic",
    }); err != nil {
        log.Fatal("create user", err)
    }
}

Com esse código é fácil acompanhar o fluxo de execução, pois evitamos o uso do init.
Seguindo a mesma lógica pode criar handlers/controllers:
package controller

func NewUserController(repository *UserRepository) *UserController {
    return &UserController{repository: repository}
}

func (c *UserController) Create(w http.ResponseWriter, r *http.Request) {
    c.repository.Create(...)
    panic("not implemented")
}

Answer: Creio que isso não seja uma questão da linguagem em específico e sim algo relacionado a arquitetura do seu projeto, existem vários tipos no mercado como clean, ddd, hexagonal etc, decidir qual usar vai variar de acordo com o escopo do projeto, porém se é algo simples você pode usar o SOLID por exemplo, crie uma implementação do seu banco de dados e o injete para seus controllers ou repositórios (ou seja la onde for usar) via injeção de dependência, recomendo estudar bem a orientação a composição do Go e como implementar as interfaces corretamente para aplicar o SOLID.
Esse artigo fala sobre a arquitetura hexagonal e o conceito de portas e adaptadores que você pode usar para implementar no seu projeto, e esse artigo fala de SOLID em Go, arquitetura não é algo que se aprende da noite pro dia mas a longo prazo vai lhe ajudar bastante.


Check not NULL in entityfieldquery propertyCondition

Question: I want to only return results in entityfieldquery that have a propertyCondition of 'field_entry_path' that is not empty.
<code>  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'example')
        ->propertyCondition('field_entry_path', '', 'NOT IN');
  $result = $query->execute();
</code>
Thanks.
Comment: According to the docs it _is_ possible. See http://drupal.stackexchange.com/questions/26128/when-using-entityfieldquery-is-there-a-way-to-exclude-entities-when-a-specific-f
Answer: Unfortunately, it is impossible at the moment. See the workaround described on http://drupal.org/node/1226622.
Answer: According to the docs it is possible. See Excluding empty(Null) fields when using EntityFieldQuery query condition
@Clive


How to get the latest data which is unique in angular

Question: I have original data like this in an array arr
[
{Id:1,
Date:20/06/2023,
ProdId:1
},
{Id:2,
Date:21/06/2023,
ProdId:1
},
{Id:3,
Date:21/06/2023,
ProdId:2
},
{Id:4,
Date:23/06/2023,
ProdId:2
},
{Id:5,
Date:20/06/2023,
ProdId:3
}
]

I want the items with unique prodIds and it should be latest. I should get the below data
[
{Id:2,
Date:21/06/2023,
ProdId:1
},
{Id:4,
Date:23/06/2023,
ProdId:2
},
{Id:5,
Date:20/06/2023,
ProdId:3
}
]

What do I need to do?
Comment: Added answer. please refer the below for the working code.
Answer: I'm sure there is probably an easier way, but this worked for me:
    this.customers.sort((a, b) =>
      new Date(b.Date) > new Date(a.Date) ? 1 : -1
    );
    var uniqueCustomers = this.customers.filter((value, index, array) =>
      array.findIndex((c) => c.ProdId === value.ProdId) === index
    );
    console.log(JSON.stringify(uniqueCustomers));

This code first sorts by the date. Then filters for unique values based on the ProdId.
Answer: This function gets any proid and returns an object of same proid from myArray with latest date
function filterByProId(ProId: number){

    const filtered = myArray.filter((e:any) => e.ProId==ProId); //filter array by ProId
    var latest = filtered[0]; // get first item
    filtered.forEach(function(item){
       //get item with date greater than previous
       latest = (new Date(item.Date) > new Date(latest.Date)) ? item : latest;
    })
}

Use Function filterByProId:
The function below parameter end and start defining the range of objects to return in the final array
function gettill(end: number, start: number = 0){
    finalArray: any[] = [];
    for (let i = start; i < end; i++) {
        // push latest item with ProId = i to the final array
        finalArray.push(filterByProId(i));
    }
    return finalArray; //the filtered array returned
}

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: const myArray = [
  {Id:1,
  Date:20/06/2023,
  ProdId:1
  },
  {Id:2,
  Date:21/06/2023,
  ProdId:1
  },
  {Id:3,
  Date:21/06/2023,
  ProdId:2
  },
  {Id:4,
  Date:23/06/2023,
  ProdId:2
  },
  {Id:5,
  Date:20/06/2023,
  ProdId:3
  }
];

Trick:
const modifiedArray = myArray.filter((item, idx, array) =>
          array.findLastIndex((c) => c.ProdId === item.ProdId) === idx
    );

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: This can be achieved via an array filter method along with array findLastIndex() method.
Refer below for the working sample code:

const myArray = [{Id:1,Date:20/06/2023,  ProdId:1 },{ Id:2,Date:21/06/2023,PodId:1,Id:3,Date:21/06/2023,ProdId:2},{Id:4,Date:23/06/2023,ProdId:2},{Id:5,Date:20/06/2023,ProdId:3}];

const modifiedArray = myArray.filter((item, idx, array) =>
     array.findLastIndex((c) => c.ProdId === item.ProdId) === idx);

console.log(modifiedArray)


Automatically insert new record into child table when new record is added to parent table?

Question: I have a one to many relationship between a IdeaLog table and a IdeaStatus table respectively. I am trying to create an application using lightswitch and C# to allow a user to enter new idea into the IdeaLog table. Once that record is created I want it to be created in the IdeaStatus table with a default status of submitted. So far I haven't been able to find any information online to help me do this. Any nudge in the right direction is greatly appreciated!
Comment: You should check out triggers in the database that you're using.
Comment: However please notice that if you're about to use ORM, it will get crazy not knowing what's going on when trigger fires and creates new record that is not tracked by EntityFramework proxy.
Answer: In your Lightswitch Server project:

Locate your Data Sources.
Locate the parent table (.lsml) and open it.
Up the top locate "Write Code" and click the drop down arrow on the right.
Select the appropriate event. e.g. IdeaLog_Inserted
Insert a record into the IdeaStatus table using EntityFramework (or SQL, etc)


Derive cell value of an Excel Table based on two parameters

Question: I have 2 columns in excel, A and B. In A I have percentages (rates) and in B integers numbers (years).
 rating PD  year
    0.39%   3
    0.88%   2
    1.32%   17
    0.88%   1
    0.26%   15
    0.17%   2
    0.17%   2
    0.59%   2
    0.59%   2

Then I have a Table in which in column F I have years and in row I have text.
Like this (the table is much bigger and years go up to 30):
    Rating
Year AAA     AA+      AA      AA-
1   0.003%  0.008%  0.018%  0.049%
2   0.016%  0.037%  0.074%  0.140%
3   0.041%  0.091%  0.172%  0.277%
4   0.085%  0.176%  0.318%  0.465%
5   0.150%  0.296%  0.514%  0.708%

And so on (the table is much bigger than this).
So I would need a function, or a shortcut, which, for a given rate in column A and a given year in column B, gives me, in column C, the corresponding rating (AAA,AA+,AA etc.).
In the table the rates are the maximum. So if I have A1=0.50% and B1=2, then I go to look at the table, year 2 and corresponding rate, which is 0.74% (and therefore AA), because AA+ is 0.37% and is too low.
In other words, AA+ and year 2 are all the rates between 0.16% and 0.37%. And AA with year 2 are all the rates between 0.37% and 0.74%.
Do you know how I could perform this task?
Thank you very much.
Comment: It's unclear from your question, how do the years (`column B`) come into equation here.
Comment: Column B is column "Year" in the table. So for example if I have in Column A1 0.50% and in column B1 "2" I want in column C1 "AA"
Comment: Sorry, maybe I'm just missing something, but how is it determined, that it's `AA ` from the provided information in Column A and B?
Comment: Because in the table the rates are the maximum. So if I have A1=0.50% and B1=2, then I go to look at the table, year 2 and corresponding rate, which is 0.74% here (and therefore AA), because AA+ is 0.37% and is too low.

In other words, AA+ and year 2 are all the rates between 0.16% and 0.37%. And AA with year 2 are all the rates between 0.37% and 0.74%.

Is it more clear?
Comment: @Severio Yup, I get it now. Perhaps this "fetch" algorithm should also be [edited](https://stackoverflow.com/posts/51782382/edit) into the original question to make it more clear. One last question though, what to do if the year is 17, but in the second table the years only go to 5? Should it grab the data from year 5?
Comment: The table is much bigger than this, this was just an example
Answer: For the sake of code readability, I've used two custom-made functions, alongside the main procedure shown here. Otherwise it would be a huge code-dump.
Before you begin, you have to change/check these data fields.

The (blue) data table needs to be named "scores" (or changed inside code to your own name)
Same goes for the (green) grades table - to be named "grades" and start in F1
Last but not least, the code presumes these two tables are in a sheet called "Sheet1"

So all of this needs to be changed within the code, if the names do
  not match!

Now to the procedure:
Option Explicit
Private Sub run_through_scores()

    Dim scores As ListObject ' table from A1
    Dim grades As ListObject ' table from F1
    Set scores = Sheets("Sheet1").ListObjects("scores")
    Set grades = Sheets("Sheet1").ListObjects("grades")

    Dim cell As Range ' for "for" loop
    Dim inrow As Long ' will store in which row the year is
    Dim resultColumn As Integer ' will store in which column the percentage is

    'for every cell in second column of scores table (except header)
    For Each cell In scores.ListColumns(2).DataBodyRange
        inrow = get_year(cell).Row - 1
        ' ^ returns Row where result was found, -1 to accoutn for header

        'using our get_interval() function, _
         determines in which column is the sought percentage
        resultColumn = get_interval(cell.Offset(0, -1), inrow).Column
        cell.Offset(0, 1) = Sheets("Sheet1").Cells(1, resultColumn)
        'write result in Column C   ^
    Next cell

End Sub

And to the functions:
get_year()

returns a Range Object from the "grades" table, in which we found
  the matching year from our "scores" table. If the desired year is not found, it returns the year closest to it (the last table row)

' Returns a Range (coordinates) for where to search in second table
Private Function get_year(ByVal year As Variant) As Range

    Dim grades As ListObject ' table from F1
    Set grades = Sheets("Sheet1").ListObjects("grades")

    Dim testcell As Range
    Set testcell = grades.ListColumns(1).DataBodyRange.Find(year, LookIn:=xlValues)

    'if found
    If Not testcell Is Nothing Then
        Set get_year = testcell
    Else
        Dim tbl_last_row As Long 'if year not found, return last row
        tbl_last_row = grades.ListColumns(1).DataBodyRange.Rows.Count
        Set get_year = grades.ListColumns(1).Range(tbl_last_row)
    End If

End Function

And the second function:
get_interval()

returns a Range Object from the "grades" table. It compares individual cell ranges and returns upon a) if the sought percent from "scores" is less or equal (<=) then current cell percent or b) if we went through all the cells, it returns the last cell
  (because it must be higher, than the maximum of specified interval)

Private Function get_interval(ByVal what As Variant, ByVal inyear As Long) As Range

    Dim grades As ListObject ' table from F1
    Set grades = Sheets("Sheet1").ListObjects("grades")

    Dim cell As Range
    For Each cell In grades.ListRows(inyear).Range

    'check for interval
        If what <= cell And cell.Column <> 6 Then 'we don't want to check year column
            Set get_interval = cell
            Exit Function
        End If
    Next cell

    ' if we arrived here, at this stage the result will always be the last cell
    Set get_interval = grades.ListRows(inyear).Range(, grades.ListColumns.Count)

End Function

Upon firing (invoking) the run_through_scores() procedure, we get the results as expected:

if you have any questions, please let me know :)
Comment: The code works perfectly, and it is perfectly suitable for a VBA file! Thanks a lot man. However, I managed to solve my problem with a simple function, simple inverting a two-way lookup:

`=INDEX($G$11:$Y$11,MATCH(A9,INDEX($G$12:$Y$41,MATCH(B9,$F$12:$F$41,0),0)))`

where $G$11:$Y$11 is the row with ratings
A9 is the cell value for the rate
$G$12:$Y$41 is the entire table (excluding row header and column header)
B9 is the cell value for the year
$F$12:$F$41 is the array of the years


Combinations and Permutations in ice cream cones... what is the difference?

Question: The first two I am certain I have correct however c and d... I am struggling to understand the difference. I have done research on this site and have seen similar questions with explanations but I just want to double check my thinking.
A certain store sells 31 different flavors of ice cream.  How many different 3-scoop cones are possible if:
a. each flavor must be different and the order of the flavors is unimportant? $31 nCr 3 = 4495$
b. each flavor must be different and the order of the flavors is important? $31 nPr 3 = 26970$
c. Flavors need not be different and the order of the flavors is unimportant? (This is a nontrivial question.)
I think I need to use this formula $$\binom{n+m-1}{m}$$
where $n$ in the total numbers in the set, and m is how many numbers you want to choose.
So,  $$\binom{31+3-1}{3}=\binom{32}{3}=\frac{32\times 31\times 30}{1\times 2\times 3}=4960$$  Is this correct?
d. Flavors need not be different and the order of the flavors is important?
I am thinking this is $31 \cdot 31 \cdot 31 = 29791$
Answer: I think your (c) is wrong. You can count it by considering $3$ different cases: 1) $3$ flavors $X_3$; 2) $2$ flavors $X_2$ and 3) $1$ flavor $X_1$.

The case of $3$ flavors is easy:
$$
X_3 = {31 \choose 3}
$$
The case of $2$ flavors. You first choose $2$ flavors, then choose one of them to be the $2$ cones and another as the remaining cone.
$$
X_2 = {31 \choose 2}\cdot 2
$$
The case of $1$ flavor.
$$
X_1 = {31 \choose 1}
$$
Answer: part d) is correct
part c) should be:
all different: $\binom{31}3$
two the same: $31\times30$
all the same 31
total $5456$
Answer: For c, you may use star-and-bar model, that is
$$\Large\star \star \star \normalsize \underbrace{||...||}_{30},$$
with $3$ stars and $30$ bars. The stars represent the $3$ scoops and the bars form $31$ slots, which represent the $31$ flavors. As the flavor can be the same and the order of the scoops is unimportant, there are
$${31+3-1 \choose 3}={33 \choose 3}$$ ways, which is the same as the sum of the $3$ cases which Echo presents. In addition, there seems to be a minor math error in your answer for c.
Answer: (d) is correct.
For (c), you had the correct idea and formula, but you made an arithmetic error. $31 + 3 - 1$ is $33$, not $32$. Using $\binom{33}{3}$ would give you $5456$, which is the correct answer.
Comment: Hi MathGod, welcome to the site.  Perhaps it is better to answer question that has not been answered before given that the post is $3$ years old.


Need a tool for PostgreSQL monitoring on Windows

Question: I have Postgres running on Windows and I'm trying to investigate the strange behaviour: There are 17 postgres processes, 8 out of those 17 consume ~300K memory each.

Does anybody know what such behavior is coused by?
Does anybody know about a tool to investigate the problem?
Answer:
8 out of those 17 consume ~300K memory
  each.

Are you 110% sure? Windows doesn't know how much memory is used from the shared buffers. Each proces could use just a few kb's and using the shared memory together with the other processes.
What problem do you have? Using memory is not a problem, memory is made to use. And 300KB each, that's just a few MB all together, if each proces is realy using 300KB.
And don't forget, PostgreSQL is a multi proces system. That's also why it scales so easy on multi core and multi processor systems.
Comment: - I've taken memory consuming numbers from the "Mem Usage" column of Windows Task Manager. Do you mean that it is not adequate for processes using shared memory?
- I understand that PostgreSQL is a multi-process system, but 17 processes!?
Comment: The "Mem Usage" column of Windows Task Manager doesn't know anything about shared memory, it's just an estimate. 17 processes isn't that much, sounds like a couple of basic processes (like the postmaster and auto_vacuum) and some connections from applications. When you have 50 connections, you will see more than 50 processes. Nothing to worry about, this is normal.
Answer: See pgAdmin: http://www.pgadmin.org/
Answer: A tool for analyzing output from postgresql can be found at http://pgfouine.projects.postgresql.org/

pgFouine is a PostgreSQL log analyzer used to generate detailed reports from a PostgreSQL log file. pgFouine can help you to determine which queries you should optimize to speed up your PostgreSQL based application.

I don't think you can find out why you have alot of processes running, but if you feel that it might be because of database usage, this tool might help you find a cause.


Postgre's and pyodbc's booleans are incompatible?

Question: I'm using pyodbc 3.0.10 and PostgreSQL 9.6, using the native Postgre odbc driver (Postgre Unicode (x64)). I've created a test table
create table test ( col boolean )

And I tried to insert a Python boolean. I can't see what parameter substitution was done, but doesn't seem like pyodbc works with all Postgre datatypes?
In [3]: cur = cxn.cursor()

In [4]: cur.execute('insert into test values (?)', (True,))
---------------------------------------------------------------------------
ProgrammingError                          Traceback (most recent call last)
<ipython-input-4-5a0edc50457d> in <module>()
----> 1 cur.execute('insert into test values (?)', (True,))

ProgrammingError: ('42804', '[42804] ERROR: column "col" is of type boolean but
expression is of type "char";\nError while preparing parameters (1) (SQLExecDirectW)')

Comment: Try adding `;BoolsAsChar=0` to the end of your ODBC connection string. That seems to have fixed the problem for me.
Comment: That worked, thanks!
Answer: As Gord Thompson pointed out above, all you have to do is add ;BoolsAsChar=0 to the connection string


Need guidance installing Drush

Question: I have successfully installed composer, but when i try to install drush and modify the .~/.bashrc file it returns Content-Type: text/html when i run any kinda of drush command.
Anyone seen anything like this? Sorry can't be more specific but can get you  any info you need to be helpful..
Comment: Here is a guide that may help you. [Drush Installation](http://docs.drush.org/en/master/install/)
Comment: That is the documentation I have followed. I should mention this is on a shared hosting box - Bluehost
Comment: if you are installing it on remote server then its best to download zip file from there and paste it in bin.
Answer: If you see Content-Type: text/html when running Drush commands, it means that you are running Drush with php-cgi instead of php-cli.
If you already have php-cli on your system, set the environment variable DRUSH_PHP to point to the full path of php-cli.  If you do not have it installed yet, try installing it and see if that clears up your trouble (sudo apt-get install php5-cli on Ubuntu).
Comment: The php5-cli may be already installed. To find out path to installed php versions run 'locate bin/php' (on linux).
Answer: There are various ways for doing this:

If you are linux/ubuntu user you can simply do it with
sudo apt-get install drush
if you are installing it on remote server just download the latest zip file from github and paste it in you bin directory on server home folder.

Hope this helps!
Comment: Both suggestions will only work with Version prior to 7. In Ubuntu / Debian you'll end up with a pretty old version. Drush is not supported by Linux package management systems since 7.

https://github.com/drush-ops/drush/issues/1628

Need guidance installing Drush


[cocos2dx android]Rendering CCSprite using raw data from Bitmap

Question: I am trying to fetch an image from a URL into a Bitmap and then using the raw data from the Bitmap am trying to create a CCSprite. The issue here is that the image is corrupted when I display the sprite. I created a standalone android only application(no cocos2dx) and used the same code to fetch and display the Bitmap and its displayed correctly. Any reason why the image is not being properly rendered in cocos2dx?
My code to fetch the image from the URL is:
String urlString = "http://www.mathewingram.com/work/wp-content/themes/thesis/rotator/335f69c5de_small.jpg";//http://graph.facebook.com/"+user.getId()+"/picture?type=large";
Bitmap pic = null;
pic = BitmapFactory.decodeStream((InputStream) new URL(urlString).getContent());
int[] pixels = new int[pic.getWidth() * pic.getHeight()];
pic.getPixels(pixels, 0, pic.getWidth(), 0, 0,pic.getWidth(),pic.getHeight());
int len = pic.getWidth()* pic.getHeight();
nativeFbUserName(pixels,len,pic.getWidth(), pic.getHeight());

The function "nativeFbUserName" is a call to a native c++ function which is :
void Java_com_WBS_Test0001_Test0001_nativeFbUserName(JNIEnv *env, jobject thiz,jintArray name, jint len, jint width, jint height) {
jint *jArr = env->GetIntArrayElements(name,NULL);
int username[len];
for (int i=0; i<len; i++){
    username[i] = (int)jArr[i];
}
HelloWorld::getShared()->picLen = (int)len;
HelloWorld::getShared()->picHeight = (int)height;
HelloWorld::getShared()->picWidth = (int)width;
HelloWorld::getShared()->saveArray(username);
HelloWorld::getShared()->schedule(SEL_SCHEDULE(&HelloWorld::addSprite),0.1);
}
void HelloWorld::saveArray(int *arrayToSave)
{
arr = new int[picLen];
for(int i = 0; i < picLen; i++){
    arr[i] = arrayToSave[i];
}
}
void HelloWorld::addSprite(float time)
{
this->unschedule(SEL_SCHEDULE(&HelloWorld::addSprite));
CCTexture2D *tex = new CCTexture2D();
bool val = tex->initWithData(arr,(cocos2d::CCTexture2DPixelFormat)0,picWidth,picHeight, CCSizeMake(picWidth,picHeight));
CCLog("flag is %d",val);
CCSprite *spriteToAdd = CCSprite::createWithTexture(tex);
spriteToAdd->setPosition(ccp(500, 300));
this->addChild(spriteToAdd);
}

Edit:
So I found this link Access to raw data in ARGB_8888 Android Bitmap that states that it might be a bug. Has anyone found a solution to this?
Answer: EDIT
So I just noticed a corruption of images on the lower right corner of the image.I am not sure why this is happening and how to fix it. Any ideas?
EDIT END
Answering my own question, I obtained a byte array from the bitmap using:
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pic.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();

And then passed this byte array to the native code.
Comment: I am using the same code to do this but the red and blue channels are reversed. Any idea why this may be happening?
Comment: Are you using the byte array or the getPixels() method?I dont know the problem with the getPixels() method but if you use the byte array, then the data is fine and the image is displayed as expected.
Comment: I have just been able to do it. Thanks for the help. The question is here http://stackoverflow.com/questions/15700714/inter-change-blue-and-red-channels-in-bitmap-in-android


How to create an array of strings in a linked list node

Question: I've been playing around with linked lists and I want to know if it's possible to have an array of strings in a linked list node. I've been trying to get it to work the same way as the string "name", so that I can insert more strings into the array as needed
class Test1 {
    public static void main(String[] args) {
        Node n = new Node("Ace");
    }
}

class Node {
    private Node next;
    private String name;
    private String[] data;

    public Node(String s1) {
        s1 = name;
        next = null;
    }

    public String[] getArray() {
        return array;
    }

    public void setData(String s1, int point) {
        name = s1;
        array
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node nextVal) {
        next = nextVal;
    }
}

Comment: What's the problem? What did you expect to see/happen and what did you see/happened instead?
Comment: You can't dynamically grow an array. Use a List for that (Vector, ArrayList, etc).
Comment: You may have a design problem here.  Do you intend each `Node` to hold one and only one name?  Or, can a given `Node` correspond to more than one name?
Comment: I'm trying to add array entries into the node the same way I do with the name entry and Node n= new Node("");
Ideally I'm looking for a solution that lets me enter more strings into the array once the node has been initialized
I only need one name for each node as well
Comment: @Jabba, "Ideally I'm looking for a solution that lets me enter more strings into the array once the node has been initialized I only need one name for each node as well". Does this mean the you want to dynamically add strings to the array contained within the node?
Comment: @Brady Sheehan, Yeah. I'm guessing that's possible?
Answer: You can have a String array in your linked list, but you cannot extend an array once it is allocated.
If you want to have something extensible, you should use an ArrayList.


Como bloquear a movimentação do cursor no masked input?

Question: Estou utilizando o plugin jQuery Masked Input.
<input name="dueDate" class="form-control input-mask-date" type="text" placeholder="Data de Vencimento" data-parsley-trigger="keyup" required="">

E faço a ativação do masked input através da classe em JavaScript.
$(".input-mask-date").mask("99/99/9999");

Entretanto, eu consigo ao clicar no canto, ficar com o cursor no último caractere da máscara.
Como eu posso bloquear isso? Ou como voltar o cursor sempre para o primeiro caractere quando clicar?
Answer: Encontrei uma solução utilizando jQuery bem interessante no SOen que não é uma propriedade do masked input plugin, mas resolve seu problema:
$.fn.selectRange = function(start, end) {
    if(end === undefined) {
        end = start;
    }
    return this.each(function() {
        if('selectionStart' in this) {
            this.selectionStart = start;
            this.selectionEnd = end;
        } else if(this.setSelectionRange) {
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};

Você pode utilizar da seguinte maneira:
$(".input-mask-date").click(function() {
  $(".input-mask-date").selectRange(0);
});

Sempre que o evento de click for acionado, o cursor é posicionado no início do input.
Criei um JSFiddle com um exemplo.
Comment: Até o momento foi que resolveu melhor o problema.