Attribute Error: 'str' object has no attribute 'str'

Question: I have a dataframe column which contains URLs. I want to extract a specific string  out of this URL by using a regex pattern for each row. Here is an example of the URL string:
'www.abcdef.com/sports-bra-sports-bra-black-abcde1f02-c11.html',
As a column is a series and I need to iterate through, I've tried the following codes:
1.
for i in df['landing_screen_name']:
    regex = i.str.extract(r'.{0,13}.html')
    print(regex)
    break

2.
for idx, row in df.iterrows():
    a = row['landing_screen_name'].str.contains(r'.{0,13}.html')
    print(a)
    break

however for both I got the following error:
AttributeError: 'str' object has no attribute 'str'
I've tried everything but couldn't find the issue yet, could you please help me with this?
Comment: There is nothing hateful about what I said. I am pointing out to you how to solve problems for yourself, which is an expected skill for programmers. I didn't say anything about your level of experience, either; what I said is that if you have a string, you should expect to work with the string in the ordinary string-like ways, and Pandas is no longer relevant.
Comment: @KarlKnechtel The reason why I used the loop methods above is I wanted to try on the first value and see if it works, since not every row has the URL and I have to create a condition for it on the next step.

And yes, I haven't heard pandas (nor python) until 3-4 months ago and still struggle. You can just ignore simple questions like this if you are annoyed by them, instead of throwing hate on them
Comment: try your code without `.str`
Comment: Then I have the following error:AttributeError: 'str' object has no attribute 'extract'
or same error with 'contains'
Comment: The purpose of methods like `.str`, `.extract` etc. is that they *work on entire columns of the DataFrame* and *handle the iteration for you*. If you are writing your own loop (which you shouldn't normally do when working in Pandas), then you end up with e.g. `row['landing_screen_name']` being **a string**, which you work with *the same way that you would work with any other string*, as if you had never heard of Pandas.
Comment: That's why the error message tells you `'str' object has no attribute` etc. In general, you should learn how to read and understand error messages, and draw conclusions about what they are telling you about the code.
Answer: Try this:
df['landing_screen_name'] = df['landing_screen_name'].str.extract(r'(.{0,13}\.html)')

Answer: You should operate at the column level, e.g. use:
print(df['landing_screen_name'].str.extract(r'.{0,13}.html').to_string(index=False))


Are numerically keyed choices no longer possible in Django 1.7?

Question: I tried to implement this as a choices variable for a model:
>>> choices = (
...         (1, 'Primary'), (2, 'Secondary'), (3, 'Tertiary')
...         )

But it failed with this quasi-cryptic error:
characters.CharacterArcanumLink.priority: (fields.E005) 'choices' must
be an iterable containing (actual value, human readable name) tuples.

Lets see,

choices is an iterable? Check.
containing (actual value, human readable name) tuples? Check: The Actual value is an integer, and the 'human readable name' is a string.

Looks ok.
Digging into the code, it looks like new checks are done for Django 1.7:
def _check_choices(self):
        if self.choices:
            if (isinstance(self.choices, six.string_types) or
                    not is_iterable(self.choices)):
                return [
                    checks.Error(
                        "'choices' must be an iterable (e.g., a list or tuple).",
                        hint=None,
                        obj=self,
                        id='fields.E004',
                    )
                ]
            elif any(isinstance(choice, six.string_types) or
                     not is_iterable(choice) or len(choice) != 2
                     for choice in self.choices):
                return [
                    checks.Error(
                        ("'choices' must be an iterable containing "
                         "(actual value, human readable name) tuples."),
                        hint=None,
                        obj=self,
                        id='fields.E005',
                    )
                ]
            else:
                return []
        else:
            return []

Its the second check, after the elif that looks fishy. Lets try that isinstance on my choices tuple above:
>>> any(isinstance(choice, six.string_types) for choice in choices)
False

No good! How about with some modification?
>>> any(isinstance(choice[1], six.string_types) for choice in choices)
True
>>>

Excellent.
My question is, have I missed something? I'm sure this used to be possible. Why is it no longer possible? Am I implementing this wrongly?
I've also opened a ticket on code.djangoproject, if that helps?

The code that trigger it comes in two parts:
class Trait(models.Model):
    PRIORITY_CHOICES = (
        (None, '')
        )
    MIN = 0
    MAX = 5
    current_value = IntegerRangeField(min_value=MIN, max_value=MAX)
    maximum_value = IntegerRangeField(min_value=MIN, max_value=MAX)
    priority = models.PositiveSmallIntegerField(choices=PRIORITY_CHOICES, default=None)
    class Meta:
        abstract = True

And:
class CharacterSkillLink(CharacterLink, SkillLink, Trait):
    PRIORITY_CHOICES = (
        (1, 'Primary'), (2, 'Secondary'), (3, 'Tertiary')
        )
    speciality = models.CharField(max_length=200)

Comment: @Pureferret This isn't the actual `choices`, is it? I can't reproduce the bug, and if you ask me, the check is doing exactly what it's supposed to do.
Comment: @knbk I've added the code that actually triggers this. I might be a subtler bug.
Answer: The issue is when you have a single choice - the outer brackets don't construct a tuple, just provide grouping. The creation of a tuple is provided by the comma, not the brackets.
((None, '')) == (None, '')

You should leave a trailing comma to signify that you want a single-item tuple (or use a list):
PRIORITY_CHOICES = ((None, ''), )

Comment: @Pureferret It probably is still checked by the check framework, as it can't guarantee that all subclasses will override the value. It won't produce any bugs in production, though, if it _is_ always overridden.
Comment: Python class variables don't override like that - they are literally just variables on the class object. When you create a subclass and assign `PRIORITY_CHOICES`, it doesn't change the value of `priority`.
Comment: This however should never be evaluated, it's from an abstract class. That seems to fix it though. Bizzare.
Comment: @knbk but why do my errors point to each subclass? The check must happen after subclassing but before PRIORITY_CHOICES is overridden.
Comment: @Pureferret Scratch that, it _will_ lead to bugs. The field is constructed during the creation of the abstract base class by the metaclass. Subclasses don't create a new field, they copy the field from their parent class. You can't override the choices like that. It might be possible using a callback or property, but I'm not too sure.
Comment: @knbk I've seen it 'advertised' elsewhere on SO so long as the superclass is abstract... I'm not sure how else to do this....
Comment: @Pureferret It will work if you define the field itself on the subclass. Then, you can provide a default value in an (abstract) base class, and override the choices if necessary. I don't know how it's supposed to work if you define the field on the base class, though. Could you post a link to that SO answer?
Comment: @knbk Found it: http://stackoverflow.com/q/5911155/1075247 Ok so it doesn't advocate it, but I 'tried it' and and it worked.


can't get values from url

Question: i sent values with url http://localhost/mysite/pagename?f1=1&f2[value][year]=2009&f2[value][month]=1  (i'm sending filters values)
in the directed page i'm trying to get this value by $_GET[] but when i print it nothing show up(i thinks it's null).
here is my code:
<?php
$f1= $_GET['f1'];
$year = $_GET['f2']['value']['year'];
$month = $_GET['f2']['value']['month'];
drupal_set_message($f1,true);
drupal_set_message($month,true);
drupal_set_message($month,true);
$view = views_get_view('emp1')
$view->set_exposed_input(array('f1' => $f1,'f2' => array('year' => $year, 'month' =>   $month)),);
$display_id = 'default';
$view->set_display($display_id);
$view->render();
print($view->preview());
?>

Comment: Have you tried printing all of $_GET to see what's in it? drupal_set_message(print_r($_GET, true));
Comment: How can i print it to show all values inside it?
Comment: Array ( [q] => node/194)
Comment: why it's return that value? the $f1 return it's value correctly !!! :|
Answer: You should be able to get your values like this:
$year = $_GET['f2']['value']['year'];
$month = $_GET['f2']['value']['month'];

Comment: not work i will edit my post with the php code.
the error massage is:
Parse error: syntax error, unexpected T_VARIABLE in C:\xampp\htdocs\mysite\modules\php\php.module(74) : eval()'d code on line 9
Comment: That's a different problem, you've got a comma at the end of `$view->set_exposed_input(array('f1' => $f1,'f2' => array('year' => $year, 'month' =>   $month)),);` that shouldn't be there, try removing that
Comment: i tried
$year = $_GET['f2']['value']['year'];
$month = $_GET['f2']['value']['month'];
but it's not work
Comment: If your code is being run when the URL is `http://localhost/mysite/pagename?f1=1&f2[value][year]=2009&f2[value][month]=1` then that should definitely work. I've just tried it on a local installation and I get the expected values
Comment: i will tell you what i'm doing in my site,i have a views with table dispaly, in views template i created a button which it's link send the filters values (http://localhost/mysite/pagename?f1=1&f2[value][year]=2009&f2[value][month]=1) to a page.--------------- in the directed page in body filed i wrote the code above which i want to display the table views for print it by print module,this is my site Adventure :D.

can't get values from url


jQuery / Javascript Element height alway returns 0

Question: I'm trying to split some paragraphs into their respective line at each line break. My code seems to break when trying to recover the height of the element, it always returns '0'.
My function:
function getLines(element){
    words = element.text().split('');
    width = element.width();
    lines = [];
    hiddenElement = jQuery('

');
    hiddenElement.text('i'); //add character to get height
    height = hiddenElement.height();
    alert(height);
    hiddenElement.empty();
    jQuery.each(words, function(i, val) {
      lineText = hiddenElement.text();
      hiddenElement.text(lineText + this);
        if(hiddenElement.height() > height) {
            lines.push(lineText);
            hiddenElement.text(this);
        }
   });
    alert(hiddenElement.height());
    alert(lines);
    jQuery('body').append(hiddenElement); // to see results
}

http://jsfiddle.net/zQUhV/2/ - function called via up arrow key
Why does this return 0 rather than the height of the element?
Answer: Elements have no dimension if they are not inserted into the document. Also, you are creating your
 incorrectly.
Comment: @ethorn10 Well, that and the fact that neither `width` nor `visible` are valid attribute names...
Comment: Does this look like valid HTML to you? ``
Comment: Once you straighten that out, if you `.append` the `hiddenElement` to `element` prior to the `.height()` call, you should be fine.
Comment: He's suggesting you remove the comma between the width and visible
Comment: Ah yes, got mixed up between style attributes and html attributes.


Prime Ideals examples

Question: I've to solve the following problem.

$R=\mathbb Q [x]$ and for $S \subset \mathbb C$ define $I(S):=\{f \in \mathbb Q [x]: f(x)=0 \forall x \in S \}$.

I have already shown, that this is an ideal in $\mathbb Q [x]$.
The question is now:

For which $S_i$ is $I(S_i)$ a prime ideal ?
$S_1 := \{3,7\}$, $S_2 := \{7+3i,7-3i\}$, $S_3 := \{\sqrt[3]2,-\sqrt[3]2\}$,$ S_4 := \{\sqrt2,-\sqrt2\}$

For $S_1$: it is a prime ideal.
$I(S_1) \neq R$, because of the polynomial $f=x$ with $f(3)=3 \neq 0$ and $f(7)=7 \neq 0$.
Let $a,b \in R$ such that $ab \in I(S_1)$, so $(ab)(x)=0 \forall x \in S_1$.
Now I know that $0=(ab)(x)=a(x)b(x) \forall x \in S_1$. This leads to $a(x)=0$ or $b(x)=0$ , because there are no zero divisors in $\mathbb Q[x]$. So $a \in I(S_1)$ or $b \in I(S_1)$, which is the definition of prime ideal.
So now I need the other $S_i$. I hope someone of you can help me.
Edit: This "proof" is wrong, because of the polynomials $a(x)=x-3$ and $b(x)=x-7$.
Comment: @Myrkuls JayKay: Your argument for $S_1$ is flawed. Consider $a,b$ given by
$a(x) = x-3$ and $b(x) = x-7$.
Comment: It might help to note that non-zero prime ideal = maximal ideal in $\mathbb{Q}[x]$.
Answer: Hints: Argue that
\begin{align*}
I(S_1)&=((x-3)(x-7))\\[4pt]
I(S_2)&=(x^2-14x+58)\\[4pt]
I(S_3)&=((x^3-2)(x^3+2))\\[4pt]
I(S_4)&=(x^2-2)\\[4pt]
\end{align*}
and recall that an ideal $(f)$ of $\mathbb{Q}[x]$ is a prime ideal if and only if $\deg(f) \ge 1$ and $f$ is irreducible in $\mathbb{Q}[x]$.
Comment: One direction is immediate: Let $f \in \mathbb{Q}[x]$ with $\deg(f)>1$, and suppose $f=gh$ for some $g,h \in \mathbb{Q}[x]$ with $\deg(g) < \deg(f)$ and $\deg(g)<\deg(f)$. Then $gh \in (f)$ but $g,h \notin (f)$ (since all elements of $(f)$ have degree at least that of $f$). Thus, if $f$ is reducible in $\mathbb{Q}[x]$, the ideal $(f)$ is not a prime ideal of $\mathbb{Q}[x]$.
Comment: For the other direction, let $f \in \mathbb{Q}[x]$ with $\deg(f)>1$ be irreducible in $Q[x]$, and suppose $gh \in (f)$ for some nonzero $g,h \in \mathbb{Q}[x]$. Then $gh=af$ for some $a \in \mathbb{Q}[x]$. Since $\mathbb{Q}[x]$ is a UFD, $gh$ factors uniquely (apart from order and unit [nonzero constant] factors) into irreducible factors. Since $f$ is irreducible, it must be one of the irreducible factors of $gh$, hence (by uniqueness) must be one of the irreducible factors of $g$ or $h$. It follows that at least one of $g,h$ is in $(f)$. Therefore $(f)$ is a prime ideal of $\mathbb{Q}[x]$.
Comment: Thank you, but I dont know that fact. Is it easy to proof ?

Prime Ideals examples


How can i get cilium to pass the failing connectivity test

Question: I am trying to deploy cilium to my eks cluster, for context, this cluster is a private cluster running behind a private subnet, and routed to the internet through a NAT gateway and then an internet gateway. I have been able to follow the cilium installation guid here. my nodes are tainted and i have patched the daemonset as the documentation asked.
When i run cilium status, i can see it is ok
    /¯¯\
 /¯¯\__/¯¯\    Cilium:             OK
 \__/¯¯\__/    Operator:           OK
 /¯¯\__/¯¯\    Envoy DaemonSet:    disabled (using embedded mode)
 \__/¯¯\__/    Hubble Relay:       disabled
    \__/       ClusterMesh:        disabled

Deployment        cilium-operator    Desired: 2, Ready: 2/2, Available: 2/2
DaemonSet         cilium             Desired: 3, Ready: 3/3, Available: 3/3
Containers:       cilium             Running: 3
                  cilium-operator    Running: 2
Cluster Pods:     2/2 managed by Cilium
Image versions    cilium             quay.io/cilium/cilium:v1.15.0@sha256:9cfd6a0a3a964780e73a11159f93cc363e616f7d9783608f62af6cfdf3759619: 3
                  cilium-operator    quay.io/cilium/operator-aws:v1.15.0@sha256:cf45167a8bb336c763046553c6a97c0d7f12f7e2a498dfb2340fa27832a81b3a: 2

However when i run cilium connectivity test, not all the test passes. the error is as shown below.
❌ 4/42 tests failed (30/321 actions), 13 tests skipped, 1 scenarios skipped:
Test [no-policies]:
  ❌ no-policies/pod-to-host/ping-ipv4-1: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> <NODE_IP> (<NODE_IP>:0)
  ❌ no-policies/pod-to-host/ping-ipv4-3: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> <NODE_IP> (<NODE_IP>:0)
  ❌ no-policies/pod-to-host/ping-ipv4-5: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> <NODE_IP> (<NODE_IP>:0)
  ❌ no-policies/pod-to-host/ping-ipv4-7: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> <NODE_IP> (<NODE_IP>:0)
  ❌ no-policies/pod-to-host/ping-ipv4-9: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> <NODE_IP> (<NODE_IP>:0)
  ❌ no-policies/pod-to-host/ping-ipv4-11: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> <NODE_IP> (<NODE_IP>:0)
Test [no-policies-extra]:
  ❌ no-policies-extra/pod-to-remote-nodeport/curl-0: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> cilium-test/echo-other-node (echo-other-node:8080)
  ❌ no-policies-extra/pod-to-remote-nodeport/curl-1: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> cilium-test/echo-other-node (echo-other-node:8080)
  ❌ no-policies-extra/pod-to-remote-nodeport/curl-2: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> cilium-test/echo-same-node (echo-same-node:8080)
  ❌ no-policies-extra/pod-to-remote-nodeport/curl-3: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> cilium-test/echo-same-node (echo-same-node:8080)
  ❌ no-policies-extra/pod-to-remote-nodeport/curl-4: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> cilium-test/echo-other-node (echo-other-node:8080)
  ❌ no-policies-extra/pod-to-remote-nodeport/curl-5: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> cilium-test/echo-other-node (echo-other-node:8080)
  ❌ no-policies-extra/pod-to-remote-nodeport/curl-6: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> cilium-test/echo-same-node (echo-same-node:8080)
  ❌ no-policies-extra/pod-to-remote-nodeport/curl-7: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> cilium-test/echo-same-node (echo-same-node:8080)
  ❌ no-policies-extra/pod-to-local-nodeport/curl-0: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> cilium-test/echo-other-node (echo-other-node:8080)
  ❌ no-policies-extra/pod-to-local-nodeport/curl-1: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> cilium-test/echo-same-node (echo-same-node:8080)
  ❌ no-policies-extra/pod-to-local-nodeport/curl-2: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> cilium-test/echo-other-node (echo-other-node:8080)
  ❌ no-policies-extra/pod-to-local-nodeport/curl-3: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> cilium-test/echo-same-node (echo-same-node:8080)
Test [allow-all-except-world]:
  ❌ allow-all-except-world/pod-to-host/ping-ipv4-1: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> 18.104.22.168 (<NODE_IP>:0)
  ❌ allow-all-except-world/pod-to-host/ping-ipv4-3: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> 126.96.36.199 (<NODE_IP>:0)
  ❌ allow-all-except-world/pod-to-host/ping-ipv4-5: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> 188.8.131.52 (<NODE_IP>:0)
  ❌ allow-all-except-world/pod-to-host/ping-ipv4-7: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> 188.8.131.52 (<NODE_IP>:0)
  ❌ allow-all-except-world/pod-to-host/ping-ipv4-9: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> 220.127.116.11 (<NODE_IP>:0)
  ❌ allow-all-except-world/pod-to-host/ping-ipv4-11: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> 188.8.131.52 (<NODE_IP>:0)
Test [host-entity]:
  ❌ host-entity/pod-to-host/ping-ipv4-1: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> <NODE_IP> (<NODE_IP>:0)
  ❌ host-entity/pod-to-host/ping-ipv4-3: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> <NODE_IP> (<NODE_IP>:0)
  ❌ host-entity/pod-to-host/ping-ipv4-5: cilium-test/client-846d67868c-mpfrc (10.0.1.217) -> <NODE_IP> (<NODE_IP>:0)
  ❌ host-entity/pod-to-host/ping-ipv4-7: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> <NODE_IP> (<NODE_IP>:0)
  ❌ host-entity/pod-to-host/ping-ipv4-9: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> <NODE_IP> (<NODE_IP>:0)
  ❌ host-entity/pod-to-host/ping-ipv4-11: cilium-test/client2-865b7d7b6f-469vq (10.0.1.178) -> <NODE_IP> (<NODE_IP>:0)
connectivity test failed: 4 tests failed

Question
How can i resolve this and get cilium running.
PS
I just swapped out the node ip addresses for the variable <NODE_IP> for the purpose of posting this question.
Answer: The solution is disable assigning public IP addresses to EKS nodes.
You can configure that in the Network Interfaces in the Launch Template that the EC2 instances are using. Set the "Auto-assign public IP" to Disable.


IntelliJ: Cannot open SBT Project: jansi 1.11 error

Question: Having very recently started working with Big Data, I'm looking to learn more about Spark and Scala to learn to work with many files and hdfs. While experimenting with IntelliJ (which was recommended to me), I installed the most recent update of IntelliJ along with an installation of SBT as well as the Scala plugin.
However, I seem to have encountered a problem, when I open an idea project in Scala, it works without any issues, however, if I try to open an sbt project, I encounter the following error:
TL;DR Something called Jansi 1.11 is not with the file.
<code>Error while importing sbt project:

Getting org.fusesource.jansi jansi 1.11  (this may take some time)...

:: problems summary ::
:::: WARNINGS
module not found: org.fusesource.jansi#jansi;1.11

==== local: tried

C:\Users\user_name\.ivy2\local\org.fusesource.jansi\jansi\1.11\ivys\ivy.xml

-- artifact org.fusesource.jansi#jansi;1.11!jansi.jar:

C:\Users\user_name\.ivy2\local\org.fusesource.jansi\jansi\1.11\jars\jansi.jar

==== local-preloaded-ivy: tried

file:/C:/Users/user_name/.sbt/preloaded/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml

==== local-preloaded: tried

file:/C:/Users/user_name/.sbt/preloaded/org/fusesource/jansi/jansi/1.11/jansi-1.11.pom

-- artifact org.fusesource.jansi#jansi;1.11!jansi.jar:

file:/C:/Users/user_name/.sbt/preloaded/org/fusesource/jansi/jansi/1.11/jansi-1.11.jar

==== Maven Central: tried

https://repo1.maven.org/maven2/org/fusesource/jansi/jansi/1.11/jansi-1.11.pom

-- artifact org.fusesource.jansi#jansi;1.11!jansi.jar:

https://repo1.maven.org/maven2/org/fusesource/jansi/jansi/1.11/jansi-1.11.jar

==== sbt-maven-releases: tried

https://repo.scala-sbt.org/scalasbt/maven-    releases/org/fusesource/jansi/jansi/1.11/jansi-1.11.pom

-- artifact org.fusesource.jansi#jansi;1.11!jansi.jar:

https://repo.scala-sbt.org/scalasbt/maven-    releases/org/fusesource/jansi/jansi/1.11/jansi-1.11.jar

==== sbt-maven-snapshots: tried

https://repo.scala-sbt.org/scalasbt/maven-snapshots/org/fusesource/jansi/jansi/1.11/jansi-1.11.pom

-- artifact org.fusesource.jansi#jansi;1.11!jansi.jar:

https://repo.scala-sbt.org/scalasbt/maven-snapshots/org/fusesource/jansi/jansi/1.11/jansi-1.11.jar

==== typesafe-ivy-releases: tried

https://repo.typesafe.com/typesafe/ivy-releases/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml

==== sbt-ivy-snapshots: tried

https://repo.scala-sbt.org/scalasbt/ivy-snapshots/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml

::::::::::::::::::::::::::::::::::::::::::::::

::          UNRESOLVED DEPENDENCIES         ::

::::::::::::::::::::::::::::::::::::::::::::::

:: org.fusesource.jansi#jansi;1.11: not found

::::::::::::::::::::::::::::::::::::::::::::::

:::: ERRORS

Server access Error: sun.security.validator.ValidatorException: PKIX path     building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target url=https://repo1.maven.org/maven2/org/fusesource/jansi/jansi/1.11/jansi-1.11.pom

Server access Error: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target url=https://repo1.maven.org/maven2/org/fusesource/jansi/jansi/1.11/jansi-1.11.jar

Server access Error: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target url=https://repo.scala-sbt.org/scalasbt/maven-releases/org/fusesource/jansi/jansi/1.11/jansi-1.11.pom

Server access Error: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target url=https://repo.scala-sbt.org/scalasbt/maven-releases/org/fusesource/jansi/jansi/1.11/jansi-1.11.jar

Server access Error: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target url=https://repo.scala-sbt.org/scalasbt/maven-snapshots/org/fusesource/jansi/jansi/1.11/jansi-1.11.pom

Server access Error: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target url=https://repo.scala-sbt.org/scalasbt/maven-snapshots/org/fusesource/jansi/jansi/1.11/jansi-1.11.jar

Server access Error: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target url=https://repo.typesafe.com/typesafe/ivy-releases/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml

Server access Error: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target url=https://repo.scala-sbt.org/scalasbt/ivy-snapshots/org.fusesource.jansi/jansi/1.11/ivys/ivy.xml

:: USE VERBOSE OR DEBUG MESSAGE LEVEL FOR MORE DETAILS
Error during sbt execution: Error retrieving required libraries
unresolved dependency: org.fusesource.jansi#jansi;1.11: not found
(see C:\Users\user_name\.sbt\boot\update.log for complete log)
Error: Could not retrieve jansi 1.11`
</code>
Is there a way to fix this? I've already tried reinstalling multiple times.
Comment: Are you behind a corporate proxy? If so, check this question out: https://stackoverflow.com/questions/41981320/scala-sbt-and-corporate-proxy-suncertpathbuilderexception
Answer: I landed here after facing the same issue (behind corporate proxy and getting this same error message). I tried all the suggestions mentioned in multiple (related) threads but was able to finally resolve it by setting up the HTTP Proxy directly in IntelliJ. Here's what my settings look like (Note: specify your network username and password in the corresponding boxes):-


Why can't my jQuery.Widgets namespace be accessed?

Question: I've been reading alot about the advantages of using the jQuery.Widget Factory for my plugins. One of the capabilities touted is how the jQuery.widget creates a namespeace for your widget.  This is attractive, as I can maintain my current namespacing (naturally) within the jQuery context.
THE PROBLEM:
I keep getting "$(".myWidget").namespace.newWay is not a function" error.
For the following element...

THIS EXAMPLES CODE WORKS:
While nice...this is NOT what I am trying to achieve...as I still want my namespace to be honored.
var workingVersion = {
            _init: function () { /* Do Something*/ }
        };
$.widget("ui.workingVersion", workingVersion);

$(document).ready(function () {
     $('.myWidget').workingVersion();
});

HOWEVER, MY CODE FAILS:
var namespace = namespace || { };
;namespace.newWay = (function ($, window, document, undefined) {

     return function (options) {

          var self = this;

          this._create = function () {
               // Do something
          },
          this._init = function() {
               // Do something
          },
          this.publicFunction = function () {
               // Do something
          };
     };
})(jQuery, window, document);

$(document).ready(function () {
     $.widget("ui.namespace.newWay", namespace.newWay); //<-- Namespace does get appended
     $('.myWidget').namespace.newWay({ type: 'testing' }); //<-- But still fails here
});

MY QUESTION IS:
Why does it fail?
RELATED READING:

Understanding jQuery UI widgets: A tutorial
Tips for Developing jQuery UI 1.8 Widgets
Comment: And your question is, "Why does it fail?"?  To answer that question, I need to understand why you decided to take a different approach and what you're trying to gain from this new approach.
Comment: `$('.myWidget').newWay();` would be how you call it. You don't need to use your namespace from the `$()` instance.
Comment: Thanks for replying: (a) Using the namespace IS the goal! (b) Why append the namespace if you cannot access it? (c) The sample articles imply it is possible.
Answer: This answer comes a bit late, maybe, but I was struggling with the same thing and had to do some reading.
$() in General
The $() instance is a no-namespace shortcut list to different functions spread out over different namespaces. You can add more functions to this shortcut list by writing:
$.fn.myFunction = function() {
    ...
};

Which then will be accessed by calling
$("...").myFunction();

If you add two functions by the same name the latter one will overwrite the first one.
Widgets
When you create a widget with a namespace it's created with it's namespace, as you would expect, but to $() it's added without it's namespace, as a simplified shortcut to your real widget-with-shortcut. This is done using $.widget.bridge(). You can therefore create your own namespaced link to $() by writing like this:
$.widget.bridge("namespace_myFunction", $.namespace.myFunction );

And then access your widget like this:
$("#myDiv").namespace_myFunction();

To use a widget directly with it's original namespace you can instead invoke it like this:
$.namespace.myWidget(
  {
    option1: "",
    option2: ""
  },
  $("#div")
);

Hope this will clarify a little...
Comment: Great explanation to a question I had long forgotten I asked...+1 atop of the check mark!
Comment: Glad you liked the explanation :)


Problema de linkagem em projeto com mais de um arquivo fonte

Question: Esta é à minha função. Dá me erro quando chamo na função main.
Este é o cabeçalho da minha função, no arquivo função1.h
int eleminar_numeros_repetidos(int *vec, int n, int *vec1);

Arquivo função1.c:
void organizar_vetor(int *vec, int n){

   int i,j;

   for(i=0 ; i <n-1; i=i+1)
   {
       for(j=i+1 ; j<n ; j=j+1)
       {
           if (*(vec +i) >*(vec+j))
           {
            int aux =*(vec+i);
            *(vec+i)=*(vec+j);
            *(vec+j)=aux;
           }

       }

   }
}

int eleminar_numeros_repetidos(int *vec, int n, int *vec1){

 organizar_vetor(vec,n);

 int i,j;

   for(i=0 ; i <n-1; i++)
   {
       for(j=i+1 ; j<n ; j++)
       {
           vec[i]=vec1[i];

            if (vec1[i] == vec1[j])
           {

            int k;
              for (k = j; k <n-1 ; k++)
              {
                  vec1[k]=vec1[k+1];
                  j--;n--;
              }

           }

       }

   }
   return n;

}

Erro:
gcc ex09.c
/tmp/ccYQaeVL.o: In function `main':
ex09.c:(.text+0x112): undefined reference to `eleminar_numeros_repetidos'
collect2: error: ld returned 1 exit status
make: *** [ex09.o] Error 1

Comment: Seu problema não é no código da função em sim. Este problema acontece quando você chama uma função que está definida em um arquivo fonte a partir de outro, mas por algum motivo o linker não está conseguindo vincular a chamada com a função em si. Seria mais útil para podermos ajudá-lo se você publicasse como você declarou a funcão: nome, parâmetros. Você está utilizando um arquivo de cabeçalho, certo? Verifique se a declaração da função nele bate com a declaração no arquivo fonte.
Comment: int eleminar_numeros_repetidos(int *vec, int n, int *vec1); está é a minha função1.h (onde está o cabeçalho) ;  -    @  C. E. Gesser
Comment: E no arquivo `funcao1.c`, como está? É preciso também garantir que no arquivo que contém a função `main` esteja sendo dado `#include "função1.h"`
Comment: Atualizei a minha publicação, coloquei mais códigos do meu programa. E no meu main chamo à função #include "funcao1.h" @ C. E. Gesser
Answer: Seu comando de compilação está errado:
gcc ex09.c      ### BAD!!!

Deve ser assim:
gcc -o ex09 ex09.c funcao1.c   ### GOOD :)

Comment: Obrigado pela vossa ajuda, já consegui resolver o problema. Mas não consigo eliminar os números repetidos @ José X.
Answer: Observe a linha de comando que foi utilizada para compilar:
gcc ex09.c

Você está instruindo o compilador para gerar um executável a partir de um arquivo fonte apenas, mas seu projeto é composto por mais de um. Por isso o compilador reclama que, no momento de gerar o executável, ele não acha a implementação de uma função.
Você tem duas opções
Compilar e linkar todos os fontes ao mesmo tempo:
gcc ex09.c funcao1.c

Ou compilar os fontes individualmente e linkar em separado:
gcc -c ex09.c
gcc -c funcao1.c
gcc ex09.o funcao1.o

Lembando que o parâmetro -c instrui o gcc a apenas compilar os arquivos fonte, sem linkar o executável final.
Comment: @Programador: Eu achei melhor alterar o título desta questão para ficar mais de acordo com o problema tratado aqui, que era o de linkagem. Eu dei uma olhada rápida no seu algoritmo, e achei curiosa a linha com o comando `vec[i]=vec1[i];`. Parece que você está descartando o conteúdo de `vec`, que você organizou umas linhas acima. Não está exatamente claro qual array é o de entrada e qual o de saída da função. Agora que já passamos dos problemas de compilação, você pode fazer mais testes. Se não conseguir resolver sugiro criar mais uma questão, agora sim sobre o algoritmo em si.
Comment: Obrigado pela vossa ajuda, já consegui resolver o problema. Mas não consigo eliminar os números repetidos @ C. E. Gesser


Do simple paths have unique endpoints?

Question: Let $Y \subset \mathbb{R}^n$ be a simple path.
That is there exists a continuous injective function $f : [0, 1] \rightarrow \mathbb{R}^n$ such that the image of $f$ is $Y$.
Note, by this definition $f(0)$ cannot equal $f(1)$.
Now assume there exists another continuous injective function $g : [0, 1] \rightarrow \mathbb{R}^n$ whose image is also $Y$.
Can $\{f(0), f(1)\} \neq \{g(0), g(1)\}$?
Comment: Is $g^{-1}$ automatically continuous under these hypotheses? If so the problem reduces to the continuous bijection $g^{-1}\circ f$ from $[0,1]$ to $[0,1]$, where it should be easy to establish that the image of $\{0,1\}$ is $\{0,1\}$.
Comment: @GregMartin The [Closed Graph Theorem](https://en.wikipedia.org/wiki/Closed_graph_theorem#Closed_graph_theorem_in_point-set_topology) guarantees that $g$ has closed graph, and that $g^{-1}$ is therefore continuous.
Comment: Note also, @c.abate, that this proof works in any Hausdorff topological space, as any such path $Y$ is the continuous image of the compact interval $[0, 1]$, hence making $Y$ compact (and Hausdorff).
Comment: In the same spirit as the answer given; you can argue that $f(0), f(1)$ are the only two points that, when removed, don't break the connectedness of $Y$.
Comment: Thank you guys, I will need to do a little more research in order to fully understand your answers.
Answer: Let's take ourselves through Greg's suggestion. If $g : [0, 1] \to Y \subseteq \Bbb{R}$ is injective, then it is bijective due to restricting the range. This implies $g^{-1}$ exists. We wish to show it is continuous.
Suppose $(x_n) \in Y$ is a sequence converging to $x \in Y$. Let $t_n = g^{-1}(x_n)$ for all $n$, and $t = g^{-1}(x)$. We wish to show that $t_n \to t$.
Suppose, for the sake of contradiction, that $t_n \not\to t$. Then, for some $\varepsilon > 0$, there must exist a subsequence $t_{n_k}$ such that $|t_{n_k} - t| \ge \varepsilon$. By taking further subsequences as necessary, since $[0, 1]$ is compact, we may assume that $t_{n_k} \to t'$ for some $t' \in [0, 1]$. Note that $|t' - t| \ge \varepsilon$, and so $t \neq t'$.
Since $g$ is continuous, $g(t_{n_k}) = x_{n_k} \to g(t')$. But, $x_{n_k}$ is a subsequence of the convergent sequence $x_n \to x$, and so $x_{n_k} \to x$. This implies that $x = g(t') \implies t' = g^{-1}(x) = t$. This contradicts $t' \neq t$. Thus, $g$ is continuous.
From here we see, as Greg suggests, that $h:= g^{-1} \circ f$ is a continuous, bijective map from $[0, 1]$ to $[0, 1]$.
Consider $t_0 := h^{-1}(0)$. If $t_0 \in (0, 1)$, then $t_1:= t_0 / 2 \in (0, t_0)$ and $t_2 := (1 - t_0) / 2 \in (t_0, 1)$. By injectivity, $h(t_1), h(t_2) > 0$. Pick some $s \in (0, \min\{h(t_1), h(t_2)\})$. Then $0 < s < h(t_1)$ and $0 < s < h(t_2)$. By applying intermediate value theorem twice, we can find $t_3 \in (t_1, t_0) \subseteq (0, t_0)$ and $t_4 \in (t_0, t_2) \subseteq (t_0, 1)$ such that
$$h(t_3) = h(t_4) = s,$$
despite $t_3 < t_0 < t_4$. This contradicts the intermediate value theorem. Thus, $h^{-1}(0) \in \{0, 1\}$. A similar proof shows that $h^{-1}(1) \in \{0, 1\}$ too. Injectivity of $h^{-1}$ implies that these points are different, so
$$\{h^{-1}(0), h^{-1}(1)\} = \{0, 1\}.$$
Applying the bijection $g \circ h = f$ to both sets, we get
$$\{g(0), g(1)\} = \{f(0), f(1)\}.$$
Comment: How about using $f^{-1}$? I am just a freshmen, less educated  so I cannot make a proof. But I know $f$ is simple, so it is also injective. The proof cannot be made using that?
Comment: @Nightflight I am not sure what you're thinking of here. In a way, I am indeed using the inverse curve, just using the inverse of $g$ instead of $f$. I think this is as simple as the proof will get (unless we simply remove the first four paragraphs and refer to the closed graph theorem). The structure of these simple paths are derived from the structure of $[0, 1]$, and so it is natural to expect there to be a function from $[0, 1]$ to $[0, 1]$ involved.

Do simple paths have unique endpoints?


Is it possible to install my own verison of Windows in AWS EC2 or lightsail

Question: I want to install my own version of Windows in AWS EC2 or Lightsail. Is this possible?
If yes, how do I install it? Thanks
Answer: Lightsail: no.
EC2: maybe, depending on what you mean by installing your own version of Windows. You can import a Windows image, as long as it's one of the supported Windows variants. You can't import your favorite Windows XP VM, for example.
You can also potentially bring your own license (BYOL), if that's you're looking for.
Comment: Thanks. I just feel windows instance in AWS is more expensive and I have windows server licenses. So, I feel it should be cheaper to create a linux instance first and then install a windows server myself. Is this feasible?
Comment: If I bring my own license, do I pay the same price as if I use a AWS windows license?
Comment: I think your first question is asking if you can install Windows in a VM on a Linux EC2 instance. If so, no you can't run virtualization within virtualization on EC2. If you BYOL then the EC2 cost does not include the license cost (see https://aws.amazon.com/windows/faq/). But ... licensing is a complex area so be sure to read and fully understand the rules.
Comment: Thanks. I mean if I buy a linux instance, could I replace the linux with windows by installing windows myself? I don't mean running windows on top of linux. I just want to replace linux with windows.
Comment: You don't buy an instance. You rent it. When you launch an EC2 instance, you choose from a library of machine images (called AMIs). Each comes with an Operating System. If you want to switch from Linux to Windows, you terminate your Linux instance and you launch a new Windows instance.


Android Studio can not import module

Question: Error message:
Element: class org.jetbrains.plugins.groovy.lang.psi.impl.GroovyFileImpl
because: different providers:
SingleRootFileViewProvider{
myVirtualFile=file:///Users/renrenliwangluokeji/Desktop/SDDAndroid/StepDemo2/settings.gradle,
content=VirtualFileContent{size=15}}(69e7355d);
SingleRootFileViewProvider{ myVirtualFile=file:///Users/renrenliwangluokeji/Desktop/SDDAndroid/StepDemo2/settings.gradle,
content=VirtualFileContent{size=15}}(1efd863f)

Comment: add your `gradle` files to the question
Comment: As @WIZARD has told you add the `gradle` file and also explain how or when exactly do you get that error.
Answer: Seems like IDE issue, try manually adding
include ':app', ':your_module_name'

in settings.gradle and sync gradle, hope it helps.
Reference: https://issuetracker.google.com/issues/77939622

Android Studio can not import module


Git is not working properly when installing with chef

Question: I'm provisioning my servers with Chef. For git I'm using the community cookbook and is installing version 184.108.40.206 in Amazon Linux. However after it gets installed I don't get any output while running git commands as git ls-remote or git clone (also it won't clone projects). I Googled with no luck.
Comment: Is there any specific error when doing a `git clone`?
Comment: No output whatsoever,

`git clone https://github.com/sstephenson/rbenv`

`Cloning into 'rbenv'...`

but the repo is not cloned, also git ls-remote doesn't returns anything. @mtak
Comment: Can you run `dpkg-query -S \`which git\`` to determine if the git binary came from the git package?
Comment: This is not a debian based linux distro. Amazon Linux is RHEL based so dpkg-query is not available.
Comment: I do get this in dmesg: `[1278397.007329] traps: git-remote-http[1296] trap invalid opcode ip:7ffe0de9b460 sp:7fffeabfe758 error:0 in libfreebl3.so[7ffe0de4a000+70000]`
Answer: 2014-04-16 @LuisDUrraca provided more information:
The invalid opcode in dmesg is a product of AWS' Xen hypervisor. It can mean that the action is not supported by the hypervisor in I/O requests or that you are running out of memory. Check your RAM and Steal Time.

I recently heard someone complaining of the same with puppet. I'd wager that the problem is more likely with other operating system components, not with Chef itself.

Did you try running git clone with --verbose? You should also check to see that you are able to connect to the remote host otherwise (ping, curl, ssh)?
Did you verify that git was or was not installed before? A very old git installation shouldn't, but could distrub the community cookbook code logic. Have you checked the output of git --version to see that you've 126.96.36.199 now.   You can also verify the Chef Entreprise logs or package manager logs for the installation.
Are all of this group of servers affected? Did you try reproducing the problem in a virtual machine or development environment? In a VM, you could try manually removing and reinstalling git to see if that resolves the problem. If it does, and it likely should, then you could just replicate a cookbook to do that across your servers.
If you determine that yum is the point of failure, yum clean && yum check-update may be a starting point (i.e. via cluster SSH).
Comment: 3.   yeah, all my others amazon linux are affected. I tried reinstalling manually different versions of git, same issue.

2.   I don't know if git was installed before I don't think it was. git --version returns 18.104.22.168.

1. git clone --verbose doesn't returns any additional output however in the dmesg I found: `[1278397.007329] traps: git-remote-http[1296] trap invalid opcode ip:7ffe0de9b460 sp:7fffeabfe758 error:0 in libfreebl3.so[7ffe0de4a000+70000]`
Comment: yum can cause issues like this?
Comment: Supposing an installation was corrupted, yes. Low RAM or [high Steal Time](http://stackoverflow.com/questions/11703320/aws-ec2-high-cpu-alarms-going-off) are likely culprits though, if you're running a t1.mirco instance for example.


How to strip html from Elasticsearch and search API index?

Question: I'm also using the search API autocomplete module. When I start typing, the autocomplete shows fields with html code.
What settings do I need to set to get the index to store correctly?
Answer: i had the same problem.
The solution for me came from unchecking the 'Elasticsearch direct link' checkbox in the edit form of the autocomplete tab in the search api index.
Comment: Thanks! that fixed it! Is this a drupal setting issue or should i be making further filters on my elastic indexing to strip all html?


Shift from single gpu to multiple gpu.Throws an error TypeError: '<' not supported between instances of 'list' and 'int'

Question: I had shifted from using single gpu to multiple gpu. The Code throws an error
    epoch       main/loss   validation/main/loss  elapsed_time
   Exception in main training loop: '<' not supported between instances of
    'list' and 'int'
       Traceback (most recent call last):
   File "/home/ubuntu/anaconda3/envs/chainer_p36/lib/python3.6/site-
       packages/chainer/training/trainer.py", line 318, in run
       entry.extension(self)
   File "/home/ubuntu/anaconda3/envs/chainer_p36/lib/python3.6/site-
        packages/chainer/training/extensions/evaluator.py", line 157, in
        __call__
         result = self.evaluate()
    File "/home/ubuntu/anaconda3/envs/chainer_p36/lib/python3.6/site-
         packages/chainer/training/extensions/evaluator.py", line 206, in evaluate
       in_arrays = self.converter(batch, self.device)
    File "/home/ubuntu/anaconda3/envs/chainer_p36/lib/python3.6/site-
       packages/chainer/dataset/convert.py", line 150, in concat_examples
       return to_device(device, _concat_arrays(batch, padding))
    File "/home/ubuntu/anaconda3/envs/chainer_p36/lib/python3.6/site-
       packages/chainer/dataset/convert.py", line 35, in to_device
          elif device < 0:

Will finalize trainer extensions and updater before reraising the exception.
I have tried without using gpu it worked fine. But when using single gpu ,got an error of out of memory.so, shifted p28xlarge instance and now it throws the above error.where is the problem and how to solve it ?
change's done using 8 gpu's
     num_gpus = 8
     chainer.cuda.get_device_from_id(0).use()

3.# updater
     if num_gpus > 0:

        updater = training.updater.ParallelUpdater(
        train_iter,
        optimizer,
        devices={('main' if device == 0 else str(device)): device for
                 device in range(num_gpus)},
    )
    else:
        updater = training.updater.StandardUpdater(train_iter, optimizer,
                    device=args.gpus)

4.and son on..
5.Training :
       trainer.run()

output --
epoch       main/loss   validation/main/loss  elapsed_time
Exception in main training loop: '<' not supported between instances of 'list' and 'int'
I expected the output as
          epoch       main/loss   validation/main/loss  elapsed_time
           1.
           2.
           3. and so on till it converge's.

Answer: It seems like an error caused by the Evaluator extension when it's transferring data to the specified device. How are you specifying the device to Evalutor.__init__ ? Note that it should be a single device. Maybe this example could be a reference https://github.com/chainer/chainer/blob/master/examples/mnist/train_mnist_data_parallel.py
Comment: I have assigned single device.It worked. @hvy. Hey,Can you look into my second  [Question](https://stackoverflow.com/questions/56593549/chainer-typeerror-zip-argument-2-must-support-iteration?noredirect=1#comment99775181_56593549)
Comment: Your second question seems to be commented already. Did you try it? Also, could you vote up the answer in case it worked?
Comment: Yes,I Tried .Regarding vote mine reputation is less than 15.Sorry for that.But it worked.


Perform the operation or operations when possible.

Question: $\begin{bmatrix}-5& -9\\ 9 & 3 \end{bmatrix} + \begin{bmatrix}8& 5\\ -4 & -1\end{bmatrix} -\begin{bmatrix} 4& -7\\ -9 & -6 \end{bmatrix}    $
Also, I was trying to add -5+8-4 but I am not show how matrices work.
Comment: @HowDoIMath  My answer is \begin{bmatrix}-1& 3\\ 14 & 8 \end{bmatrix}  Is this correct?
Comment: When you add matrices, that is how they work. You add them entry by entry.
Comment: For further explanations: [Matrix addition](https://en.wikipedia.org/wiki/Matrix_addition).
Answer: We have $\begin{bmatrix}-5& -9\\ 9 & 3 \end{bmatrix} + \begin{bmatrix}8& 5\\ -4 & -1\end{bmatrix} -\begin{bmatrix} 4& -7\\ -9 & -6 \end{bmatrix} =\begin{bmatrix} (-5+8-4)& (-9+5+7)\\ (9-4+9) & (3-1+6) \end{bmatrix}
=\begin{bmatrix} -1& 3\\ 14 & 8 \end{bmatrix}.$


L'Hospital rule for product

Question: I consider the function $$ h_t:\mathbb{R}\to \mathbb{R},x\mapsto t\cdot x\cdot (1-t)^x $$ with $ t\in [0,1] $. I want to confirm  $ \lim h_t(x)=0 $ by L'Hospital rule like this: It is with $ t\in]0,1[ $
$$ \begin{align}\lim\limits_{x\to \infty}h_t(x)&=\lim\limits_{x\to \infty}t\cdot x\cdot (1-t)^x=t\cdot \lim\limits_{x\to \infty}x\cdot (1-t)^x=t\cdot \lim\limits_{x\to \infty}\frac{x}{\frac{1}{(1-t)^x}}\\&=t\cdot \lim\limits_{x\to \infty}\frac{x}{(1-t)^{-x}}=t\cdot \lim\limits_{x\to \infty}\frac{x}{e^{-x\cdot \ln(1-t)}}\stackrel{L'H}{=}t\cdot \lim\limits_{x\to \infty}\frac{1}{e^{-x\cdot \ln(1-t)}\cdot (-\ln(1-t))}\\&=-\frac{t}{\ln(1-t)}\cdot \lim\limits_{x\to \infty}\frac{1}{e^{-x\cdot \ln(1-t)}}\stackrel{L'H}{=}-\frac{t}{\ln(1-t)}\cdot \lim\limits_{x\to \infty}\frac{0}{e^{-x\cdot \ln(1-t)}\cdot (-\ln(1-t))}=0.\end{align}$$
Are my calculations correct?
Comment: While it doesn't affect the final result, your application of L'Hopital the first time is missing a negative sign on the denominator. Also, your application of L'Hopital the second time is incorrect since the expression is not of indeterminate form (you can directly argue that the limit evaluates to zero).
Comment: I corrected the signs.
Answer: For $t=0$ and $t=1$ the answer is zero, so we consider the case when $t\in (0,1)$. Your calculation is correct except for the last step.
$\frac{1}{e^{-xln(1-t)}}=(1-t)^x$. Now there is no need to use L'Hospital again. This is because $0<1-t<1$ so $(1-t)^x$ goes to zero when x goes to infinity.

L'Hospital rule for product


Checkboxlist checked based on url $_GET

Question: I'm trying to make my checkboxlist checked based on the current page url in Yii 1.1.15
in my view:
   $arr0 = array('1'=> 'store 1', '2'=> 'store 2', '3'=>'store 3' .......);
    echo $form->checkBoxList($model,'store', $arr0,
                                                array(
                                                      'name'=>'store',
                                                      'separator'=>'',
                                                      'template'=>'{input} {label}',
                                                      'uncheckValue'=>0
                                                )
                                    );

and my URL looks like this
url/?store=1,4,5,6

any idea how to do this? Thanks
Answer: Simply set your array to your model before rendering checkBoxList like below:
$arr0 = array('1','2');
$model->store=$arr0;

Now, 1,2 will be marked as selected.

Checkboxlist checked based on url $_GET


Prior Gamma distribution: Select appropriate alpha given beta and median

Question: I am trying to programatically select a prior distribution from the Gamma family of distributions. The primary criteria that I need to satisfy is that the median of the distribution should be a given value $X$ (i.e. such that it's equally probable to have a parameter value above $X$ or below $X$)
Additionally, because I'm using the distribution as a conjugate prior for a Poisson distribution's lambda, and I know how much relative weight I want to give to the prior relative to the subsequent observations, I think I know what an appropriate $\beta$ parameter is (though I could be wrong on this point, feel free to make comments if I'm thinking about that incorrectly).
So essentially my problem becomes how to select an appropriate $\alpha$ such that the median is $X$. The way I've considered this seems to work well to get a good prior distribution when constraining the mean (or even mode), but technically, I should be constraining the median. Is this possible formulaicly, or would I need to resort to some kind of computational search to find the right value?
Comment: Which form of the gamma are you discussing (is $\beta$ the scale or the rate?)
Comment: Just for reference... I believe rate. The one mentioned in "$\alpha$ total occurrences in $\beta$ intervals" as interpretation of hyperparameters for the Poisson distribution
Comment: I may be misunderstanding the phrasing but that looks like scale to me. What's the mean - $\alpha\beta$ or $\alpha/\beta$? (alternatively see the explicit functional forms below)
Comment: In the parameterization I'm using, the mean of the gamma distribution would be $\alpha$/$\beta$
Comment: Okay, that's definitely the rate-form. Sorry to be dense.
Answer: Much about your question is unclear, but I can talk about the median in the gamma distribution and you may be able to resolve the problem from that.
The gamma distribution is typically written either in the rate form or the scale form (I'll avoid using $\beta$ here, since your intention isn't clear):
Rate form:
$$f(x;\alpha,\phi) = \frac{\phi^\alpha}{\Gamma(\alpha)} x^{\alpha-1}e^{-\phi x} \quad \text{ for } x > 0 \text{ and } \alpha, \phi > 0$$
Scale form:
$$f(x;\alpha,\theta) =  \frac{x^{\alpha-1}e^{-\frac{x}{\theta}}}{\theta^\alpha\Gamma(\alpha)} \quad \text{ for } x > 0 \text{ and } \alpha, \theta > 0$$
It's sometimes also written in the mean form (especially for GLMs):
$$f(x;\alpha,\mu) = \frac{\alpha^\alpha}{\mu^\alpha\Gamma(\alpha)}x^{\alpha-1}e^{-\frac{x\alpha}{\mu}} \quad \text{ for } x > 0 \text{ and } \alpha, \mu > 0$$
--
The mean is $\alpha\theta = \alpha/\phi=\mu$.
The median doesn't have a simple closed form, but for larger $\alpha$, it can be approximated.
For $\beta=1$, for large $\alpha$, the median is approximately the mean $-\frac{1}{3}$. This works well for $\alpha$ around 10 and higher.

More accurately, the median is approximately $\frac{3 \alpha - 0.8}{3 \alpha + 0.2}$ times the mean (as long as $\alpha$ is not too small, say no less than somewhere around 1-2, it works okay):

Another way to approach the median is via the Wilson-Hilferty transformation; since the cube root of a gamma is approximately normal, one can approximate the relationship between the mean and the median via that relationship (the median directly transforms both directions, but the mean is more complicated - one can use Taylor expansions to approximate the mean). (Examination of this approximation suggests it's actually pretty poor. The Wikipedia page uses it to approximate the median for the chi-square distribution, but frankly it looks like it's not nearly as good as even the "$-\frac{1}{3}$" rule I mentioned earlier, let alone the other one.)
For more accuracy, if one specifies the median and one specifies the scale or rate parameter, one can use the gamma cdf or the inverse gamma cdf (the gamma quantile function) to iteratively solve for the required alpha.
If $F$ is the gamma cdf and $F^{-1}$ is its inverse, you use root finding to solve $F_{\alpha,\beta}(m) - \frac{1}{2}=0$ for $\alpha$, or to solve $m - F^{-1}_{\alpha,\beta}(\frac{1}{2})=0$
A good starting point would be from one of the previously mentioned approximations.

I think I know what an appropriate β parameter is (though I could be wrong on this point, feel free to make comments if I'm thinking about that incorrectly)

It's a bit hard to comment about whether you have a misconception here if you aren't explicit about what you actually think and why.
Comment: To hopefully clarify my intentions... My logic was based on the Gamma distribution being a conjugate prior for the Poisson distribution. In that context, I read that the hyperparameters should be interpreted as "$\alpha$ total occurrences in $\beta$ intervals". So if I want my prior to have the "weight"/"effect" of half an observation on my posterior, I know a good value for $\beta$... 0.5 . And, I want my prior to have 50% probability on either side of an initial hypothesis, in other words specifying the median. Hence, I wanted to find a suitable $\alpha$ given the median and "this" $\beta$
Answer: Based on testing a large number of possible medians $X$, and the formula I was using to select beta as $\beta = 1/X$, it seems that alpha is constant: $\alpha \approx 1.314250$ . I still don't know the formula for this result, but for my programmatic needs, it's sufficient.


npx thirdweb@latest create --contract is giving error

Question: When I try to run the comand it gives me error
EINVAL: invalid argument, mkdir 'C:\Users\fahim\AppData\Local\Temp\fahim\if-you-need-to-delete-this-open-an-issue-sync-disk-cache\thirdweb:cli'
details:
{
  errno: -4071,
  syscall: 'mkdir',
  code: 'EINVAL',
  path: 'C:\\Users\\fahim\\AppData\\Local\\Temp\\fahim\\if-you-need-to-delete-this-open-an-issue-sync-disk-cache\\thirdweb:cli'
}

I don't know what is causing the error.
Answer: Seems like we have an issue with the latest version of the CLI.
Thanks for letting us know - we'll work on a fix!
In the meantime, the previous patch version should work:
npx firstname.lastname@example.com


Inconsistent Right Hand Technique - Mixing economy and double picking

Question: I am coming back to the guitar after almost 10 years away. I have been around the instrument as a jazz player for almost 25 years.
The biggest challenge coming back is what, I believe, drove me away the first time. That inconsistentnt right hand technique that stems from trying to convert to double picking from a problem free economy picking life.  Thanks a bunch John Petrucci.
At what point in time do you bite the bullet with time and effort to reprogram yourself to focus on a style of picking? To truly commit to economy picking would mean a great deal of work to focus on odd/even string patterns etc etc. But enough is enough, right?
Anyone else have experience with this?
Answer: It's really up to you. I don't know enough about any individual players technique to know which they're using. In theory, economy picking should be faster but I'm sure there are many alternaters out there that can keep up with the best of them. For example, I'm pretty sure Paul Gilbert uses alternate picking and he's definately no slouch.
The great thing about alternate picking is that its consistent. You're always doing the same thing with your right hand and therefore should lead to an overall better technique? At least it makes sense to me that it should. Like you've already said economy picking involves a lot of thinking and if this do this except when this happens then do this instead unless this then do that. If up then down else up.
But things like sweeping and stuff obviously you can't do by alternate picking but that sort of stuff is easy to mix in.
If you have a good right hand technique I see no need to spend countless hours trying to change it to a different one unless you want to. If your right hand technique was inconsistent or poor then I see no reason not to try to improve it. By changing the technique completely and learning correctly this time around will be easier than trying to change your current technique to be more proper.
Answer: Both styles are equally valuable to have in your repertoire - for the majority of the time you can happily use alternate picking for rhythm and even many lead parts, while pulling out some sweeps as required can be a nice flourish.
You don't need to commit to either exclusively, and in fact I would recommend not abandoning one in favour of the other.
Just make sure you build in practice plans for the types of things you want to be able to accomplish. Are you wanting to go all out like Petrucci? Or is your need more restrained? If you have one song out of five that requires economy picking, then when you practice all your songs, you will be practising the moves you need.


Entity framework update entity?

Question: Controller
[HttpPost]
public ActionResult EditUserProfile(UserProfiles _postedUserProfile)
{
    UserProfiles orjinalUserProfile = entity.UserProfiles.Where(x => x.UserId == _postedUserProfile.UserId).Single();
    orjinalUserProfile.AboutMe = _postedUserProfile.AboutMe;
    orjinalUserProfile.Birthday = _postedUserProfile.Birthday;
    orjinalUserProfile.Comments = _postedUserProfile.Comments;
    ...... // there are lines more
    entity.SaveChanges();
    return View();
}

I updated entity like above. But I think this way is not good. Is There any solutoin to update entity in a line, for example insert operation like entity.AddToUserProfiles .
Thanks.
Answer: You can use the ApplyCurrentValues method.
Here is an example: ApplyCurrentValues in EF 4
Basically:
[HttpPost]
public ActionResult EditUserProfile(UserProfiles _postedUserProfile)
{
    UserProfiles orjinalUserProfile = entity.UserProfiles.Where(x => x.UserId == _postedUserProfile.UserId).Single();
    entity.UserProfiles.ApplyCurrentValues(_postedUserProfile);
    entity.SaveChanges();
    return View();
}

Comment: I try this. But there is no change on database. I cant understand How do orjinal and modified entity matches between them in above code?
Comment: i noticed a mistake with my original post.  I was passing orjinalUserProfile to the ApplyCurrentValues method, instead of _postedUserProfile. I've edited to reflect the change. Try using this object instead.
Comment: It still does not work. Should we ensure relationship between orjinal and posted entity?
Comment: Yes, i assumed they had the same primary key value.

Entity framework update entity?


Find the coefficient of $x^{10}$ in $(x + (\frac{1}{x}))^{100}$

Question: Find the coefficient of $x^{10}$ in $(x + (\frac{1}{x}))^{100}$

My solution:
We can calculate the coefficient using the Binomial Theorem:
$$(x+y)^n = \sum_{k=0}^n\binom{n}{k}x^{n-k}y^k$$
We know that:

$n = 100$
$k = 90$, since $100-90 = 10$ and we want $x^{10}$

thus
$$\binom{100}{90}x^{100-90}+(\frac{1}{x})^{90} = \binom{100}{90}x^{10}(\frac{1}{x})^{90}$$
So the coefficient of $x^{10}$ is $\binom{100}{90}$
Is this correct?
Answer: We have
$$(a+b)^n=\sum_{k=0}^n{n\choose k} a^{n-k}b^k$$
so with $a=x$ and $b=\frac1x$ we get the coefficient of $x^{10}$ on $100-2k=10$ so $k=45$ and then the coefficient is  ${100\choose 45}$.
Comment: $$\left(\frac1x\right)^k=x^{-k}$$
Comment: Why 2k? Why 100-2k?
Comment: Oh wow yes, missed that!


React Hook "useState" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function

Question: I'm new in React Frontend developing. I'm trying to add a temporary drawer to my Material-UI NavBar. I've add a drawer in my code:
class Navbar extends Component {
    render() {
        const { authenticated } = this.props;
        const [open, setOpen] = useState(false);
        const handleDrawer = () =>{
           setOpen(true)
        }
        return (
            <AppBar position="fixed">
                <Toolbar className="nav-container">
                    {authenticated ? (
                        <Fragment>
                            <IconButton edge="start" onClick={handleDrawer} >
                                <Menu/>
                            </IconButton>
                            <Drawer
                                anchor='left'
                                open={open}
                                onClose={()=> setOpen(false)}
                                >

 Drawer

                            </Drawer>
                            <NewPost/>
                            <Link to="/">
                                <MyButton tip="Home">
                                    <HomeIcon color = "disabled"/>
                                </MyButton>
                            </Link>
                            <Link to="/chats">
                                <MyButton tip="Chats">
                                    <ChatIcon color = "disabled"/>
                                </MyButton>
                            </Link>
                            <Notifications />
                        </Fragment>

                    ):(
                        <Fragment>
                            <Button color="inherit" component={Link} to="/login">Login</Button>
                            <Button color="inherit" component={Link} to="/signup">Singup</Button>
                            <Button color="inherit" component={Link} to="/">Home</Button>
                            {/* <Button color="inherit" component={Link} to="/user">Profile</Button>*/}
                        </Fragment>
                    )}
                </Toolbar>
            </AppBar>

        )
    }
}

Navbar.propTypes = {
    authenticated:  PropTypes.bool.isRequired
}

const mapStateToProps = state =>({
    authenticated: state.user.authenticated
})

export default connect(mapStateToProps)(Navbar)

But this error appeared:
React Hook "useState" cannot be called in a class component. React Hooks must be called in a React function component or a custom React Hook function

So, I've create a constructor to handle this (before render):
constructor(props) {
    super(props);
    this.state = {
      open: false
    };
  }

And when I want to change the state, I've use:
this.setState({ open: true })

But, when I triggered the Drawer (clicking the button),It does not open. What can I do?
Comment: Try  `open={this.state.open}` instead of `open={open}`.
Comment: Or `const { open } = this.state;` at the top of the render method so `open={open}` works.
Answer: The state hook (useState) is available with functional React Components, but in your case you are using a Class component. Functional React components normally don't have states out of the box, but useState is a new feature that will let you work around that
You can either change this to functional component, or keep it as a class component and use the state differently
E.g :

!this.state.open instead of !open
and
this.setState({open: false}) instead of setOpen(false)

https://reactjs.org/docs/hooks-state.html
Answer: Change this line const [open, setOpen] = useState(false); to this.state = { open: false };
and when setting to true just call  this.setState({ open: this.state.open: true })
Answer: You have to use a functional component. Currently your component is a class component, so instead you should have something like:
const Navbar = (props) => {
  const { authenticated } = props;
  const [open, setOpen] = useState(false);
  const handleDrawer = () =>{
    setOpen(true)
  }

  return (
    <AppBar position="fixed">...</AppBar>
  );
};

I also noticed that your class component has the state parts defined in the render method. When using class components, state should be defined in the constructor instead, otherwise your state will be overwritten every render.
Answer: What about functional component instead of class component?
Functional component is recommended as you know.
I think it's easy to code and it improves performance.
const Navbar = () => {
     //useState, define functions here
     return (//the same as render method of your class component)
}

Answer: use function Navbar(props) in place of class Navbar extends Component
Its because, There is a rule that : React Hook "useState" cannot be called in a class component e.g. class Navbar extends Component . React Hooks must be called in a React function component e.g. function Navbar(props) or a custom React Hook function


extract value from JSON object using SQLite and the json_tree function

Question: I have a table (named, patrons) that contains a column (named, json_patron_varfields) of JSON data--an array of objects that looks something like this:
[
    {
    "display_order": 1,
    "field_content": "example 1",
    "name": "Note",
    "occ_num": 0,
    "varfield_type_code": "x"
    },
    {
    "display_order": 2,
    "field_content": "example 2",
    "name": "Note",
    "occ_num": 1,
    "varfield_type_code": "x"
    },
    {
    "display_order": 3,
    "field_content": "some field we do not want",
    "occ_num": 0,
    "varfield_type_code": "z"
    }
]

What I'm trying to do is to target the objects that contain the key named varfield_type_code and the value of x which I've been able to do with the following query:
SELECT
patrons.patron_record_id,
json_extract(patrons.json_patron_varfields, json_tree.path)
FROM
patrons,
json_tree(patrons.json_patron_varfields)
WHERE
json_tree.key = 'varfield_type_code'
AND json_tree.value = 'x'

My Question is... how do I extract (or even possibly filter on) the values of the field_content keys from the objects I'm extracting?
I'm struggling with the syntax of how to do that... I was thinking it could be as simple as using json_extract(patrons.json_patron_varfields, json_tree.path."field_content") but that doesn't appear to be correct..
Answer: You can concat to build the string
json_tree.path || '.field_content'

With the structure you've given - you can also use json_each() instead of json_tree() which may simplify things.
extract:
SELECT
patrons.patron_record_id,
json_extract(value, '$.field_content')
FROM
patrons,
json_each(patrons.json_patron_varfields)
WHERE json_extract(value, '$.varfield_type_code') = 'x'

filter:
SELECT
patrons.patron_record_id,
value
FROM
patrons,
json_each(patrons.json_patron_varfields)
WHERE json_extract(value, '$.varfield_type_code') = 'x'
AND   json_extract(value, '$.field_content') = 'example 2'

Comment: Thank you so much for that! That's interesting about being able to build the path with string concatenation

And thank you for the suggestions on how the syntax for this works. That's much more clear!


Second hand piano

Question: I've just bought a second hand piano and one of the Ds of the left part sounds totally disaccorded.  It hasn't been tuned yet but I feel very worried. Is it okay for one of the keys to sound like that before tuning?
My brother thinks the left side of the piano sounds slightly out of tune altogether
Comment: Related/possible dupe? [Do pianos really need to rest before tuning, after being moved?](https://music.stackexchange.com/q/28977/2576)
Answer: Even if it was perfectly in tune at the time and place you bought it, by the time it's been moved somewhere else - different temperature differential, different humidity, and the fact that physically it's been moved, it's bound to be out. If you'd noticed the D out before you paid for it, that could have been a bargaining point. Too late now!
Wait a few weeks for it to settle in, then get it tuned professionally. The guy will sort out the problem, which is likely to be just those two strings. A 'sound cloud' may give us more clues.
Answer: If you play one key and hear two separate pitches that's a red flag for a loose tuning pin on one of the "unison" strings. It could mean that string isn't "tune-able" but that's not the end of the world, as there are often things your tuner can do to restore friction in to the tuning pin.
Answer: You don't expect a piano (new or second-hand) to be in tune when delivered.  Let it settle down, then have it tuned.  If some notes WON'T hold in tune, then start worrying.
This is why it is sensible to send a tuner to look at a piano BEFORE you buy it.  He can tell you if it just needs tuning or if there are problems, and how much it will cost to fix them.

Second hand piano


How to vertically align div?

Question: I have a section where I have floated content on the left and right. The left content is gonna be bigger that the right (on height) so I want the right content to be vertically centered/aligned to the left content. How can I make that ?
Example image:

The blue content is gonna be mostly h1 and p and the red one just one small image and 1-2 words below it.
Code:

.inner {
  background: none repeat scroll 0 0 #FFFFFF;
  max-width: 576px;
  width: 100%;
  padding: 37px 34px 37px 34px;
}
.leftSide {
  width: 80%;
  float: left;
  border-right: 1px solid #f2f2f2;
}
.leftSide a h1 {
  font-size: 20px;
  color: #3c3c3c;
  text-transform: none;
  font-family: 'Open Sans light';
}
.leftSide span p {
  font-size: 12px;
  padding-top: 2px;
}
.leftSide .description {
  font-size: 13px;
  padding: 15px 0 25px 0;
  color: #6a6868;
  line-height: 1.4;
  font-family: 'Open Sans';
}
.leftSide .button {
  background-color: #8D1313;
  border-radius: 3px;
  color: #FFFFFF;
  font-family: 'Open Sans light';
  font-size: 13px;
  margin-top: 20px;
  padding: 7px 10px;
}
.rightSide {
  float: right;
  width: 15%;
  height: 100%;
  text-align: center;
}
.rightSide p {
  text-align: center;
  color: #565656;
  font-size: 14px;
  font-family: 'Open Sans';
}

Jsut a simple Headline

 15 April / 4 Comments / 434Views

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    learn more...

J.Smith

Comment: JSfiddle: http://jsfiddle.net/GC8F8/
Comment: Similar solution exist at http://stackoverflow.com/questions/1022795/vertically-align-floating-divs
Comment: With CSS 3 you can use [flex boxes](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes) . It has many features, one of them is the ability to vertically align nodes. Here's the [playground](http://demo.agektmr.com/flexbox/)
Comment: Flex-boxes don't support IE10 or older.
Comment: @AdamZuckerman This is tagged with CSS3, that's why I'm asking the OP if it's OK... [Here's a working link](http://jsfiddle.net/GC8F8/2/) For IE, I'd fall back to using tables... I think it's much better than misusing floats or other techniques that aren't meant for vertical centering...
Answer: I found a method that works. You will have to tweak it based on your code.  JsFiddle here.
HTML:

Content
alpha

Right Side

CSS:
body {
    font-family: sans-serif;
    font-size: 20pt;
    box-sizing: border-box;
}
#myrow {
    vertical-align: middle;
    width: 100%;
    border: solid 1px black;
    position: relative;
}
#myrow:after {
    content: "";
    display: table;
    clear: both;
}
#content, #rightside {
    display: inline-block;
    float: left;
    margin: 0 auto;
    height: 3em;
    text-align: center;
    vertical-align: middle;
    color: white;
}
#content {
    width: 55%;
    background-color: #307FFF;
    line-height: 1.5em;
}
#rightside {
    width 45%;
    min-width: 45%;
    background-color: #F56362;
    line-height: 3em;
}

The line-height is what centers the text or image. You may need to adjust your line-heights to accommodate your content.

How to vertically align div?


Executar um JavaScript no Webbrowser com Delphi

Question: Criei um robô em Delphi para abrir um site e incluir os dados automaticamente.
Estou com problema para chamar uma rotina JavaScript que tem neste site, conforme abaixo:

E para acessar o registro tem a rotina que chama o script :
Comment: Qual o problema?
Comment: Cara, eu não sei se você consegue disparar esses métodos em Javascript. Mas pelo que me parece, são 2 objetos que vão incluir e excluir alguma coisa. Sendo assim ,você poderia disparar pelo Delphi, a ação desse determinado objeto (supondo que seja um botão)
Answer: Existe Esta Forma: WebBrowser1.EvaluateJavaScript('NomeDaFunction');
Answer: Usei o comando:
WebBrowser1.EvaluateJavaScript(vvScript);

Funcionou!


injective map between set of subfields and set of endomorphisms

Question: In Theorem 8.4 of Basic Algebra by Jacobson we have the following map $$\psi:\Sigma\rightarrow \Gamma: F\mapsto \text{End}_FE$$ where $\Sigma$ is the set of all subfields of  a field $E$ and $\Gamma$ the set of subrings of the ring of endomorphisms of the additive group of E.
How do we show that it is an injective map?
Answer: An element $x\in E$ is fixed by $End_FE$ if and only if $x\in F$. To see this, remark that $x\in F$, by definition the result is true, thus $F\subset Fix(End_F(E))$.
On the other hand, lrt $x\in Fix(End_F)$, suppose that $x$ is not in $F$, you can find a basis $(x,(y_i)_{i\in I})$ of the $F$-vector space $E$. Let $c\in F\neq 1$, you can define $f(x)=cx, f(y_i)=y_i$, it is an $F$-endomorphism of $E$ such that $f(x)\neq x$. Contradiction.
We deduce that $End_FE=End_{F'}E$ implies that $F=Fix(End_FE)=Fix(End_{F'}E)=F'$.
Comment: What do you mean by "fixed by $\text{End}_FE$"? I don't see why your first affirmation is correct. If I take $\phi\in\text{End}_FE, x\in F$ then $\phi(x) = \phi(x\cdot 1) = x\phi(1)$ and there is no reason $\phi(1)$ should be 1 that I can see.


Field collection with Entity reference strange behaviour

Question: I have an interesting setup That uses a field collection as a host for line items. These line items contain two entity references to different nodes.
One entity reference is for a node that is considered a parent or a trunk item. When a user is ready as part of an external workflow, they view this field collection line item and create a 'child item' which is intended to populate the second entity reference. And the 'child item' is also linked to its parent.
Generally this has been working well, and there is a custom module that handles the child item generation (which is essentially a clone of the parent item).
The problem is, suddenly a situation has developed where in certain cases When the user initiates the copy from the field collection level, it can attach the 'child item' to more than one item. (if there is three in a list, it may attach to the first and last item in the field collection, if there is four, first and last, if it's 8, it could be first and 5th, for example.
This is the code that decides if it should make a copy. (below) the strange thing is I pass into the function ONLY that field collection item, the story id, and the node that contains the field collection. No other line items are loaded, so it shouldn't even be able to do what it is doing.
/**
 * Implements hook_menu().
 */
function click_printflow_menu() {

  $items['print-create/%/%/%'] = array(
    'title' => 'Generating Story from Wire',
    'page callback' => '_click_print_create',
    'page arguments' => array(1, 2, 3),
    'access arguments' => array('stories curate'),
    'type' => MENU_LOCAL_TASK,
  );
  $items['generate-shell/%'] = array(
    'title' => 'Generating Story from Wire',
    'page callback' => '_generate_empty_node',
    'page arguments' => array(1),
    'access arguments' => array('stories curate'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

/**
 * Function to check for and hand off creation of print child.
 *
 * @param int $rnid
 *   Node ID of run list.
 * @param int $snid
 *   Node Id of story we want print child from.
 * @param int $fcitem
 *   Field collection item ID that is host to this story.
 */
function _click_print_create($rnid, $snid, $fcitem) {
  $host_line_item = entity_metadata_wrapper('field_collection_item', $fcitem);

  $story = $host_line_item->field_story->value();
  $child = $host_line_item->field_print_child->value();

  // First, let's check for held flag. If set, Prevent movement.
  if (isset($story->field_hold_for_approval[LANGUAGE_NONE])) {
    $held = $story->field_hold_for_approval[LANGUAGE_NONE][0]['value'];

    if ($held == "held") {
      drupal_set_message(
        'This story has been held for approval. It will need to be approved to continue.',
        'error'
      );
      drupal_goto('node/' . $story->nid);
    }
  }

  if (isset($story)) {
    if (isset($child)) {
      drupal_set_message('A Print child already exists. It has been loaded below.', 'status');
      drupal_goto('node/' . $child->nid);
      return FALSE;
    }
    else {
      $new_print_child = _generate_print_entity($rnid, $snid, $fcitem);

      // Go to print child edit screen.
      drupal_goto('node/' . $new_print_child . '/edit');
    }
  }
  else {
    // drupal_set_message('Invalidly set run list item detected, skipping', 'warning');
  }
}

For fun, here's the function that actually writes the child node: (_generate_print_entity($rnid, $snid, $fcitem))
/**
 * Function to generate new print entity and return nid.
 *
 * @param int $rnid
 *   Node ID of run list.
 * @param int $snid
 *   Node ID to clone from.
 * @param int $fcitem
 *   Field collection item ID that is host to this story.
 *
 * @return int
 *   Return nid of new child node.
 *
 * @throws Exception
 */
function _generate_print_entity($rnid, $snid, $fcitem) {

  $node = node_load($snid);

  global $user;

  $values = array(
    'type' => 'print_child_story',
    'uid' => $user->uid,
    // Do not publish story.
    'status' => 0,
  );

  $print_version = entity_create('node', $values);

  // Set entity wrapper for new node.
  $entity_data = entity_metadata_wrapper('node', $print_version);

  $entity_data->language(LANGUAGE_NONE);

  // Set up data for new node inside wrapper.
  if (isset($node->title)) {
    $entity_data->title->set($node->title);
  }

  if (!empty($node->body)) {
    $body = array(
      'value' => $node->body[LANGUAGE_NONE][0]['value'],
      'format' => 'filtered_html',
    );
  }

  if (isset($body)) {
    $entity_data->body->set($body);
  }

  if (isset($node->field_related_photos[LANGUAGE_NONE])) {
    foreach($node->field_related_photos[LANGUAGE_NONE] as $files) {
      $fid = $files['fid'];
      $files_array[] = array('fid' => $fid, 'display' => 1);
    }
    $entity_data->field_related_photos->set($files_array);
  }

  if (isset($node->field_name_story[LANGUAGE_NONE])) {
    $entity_data->field_name_story->set($node->field_name_story[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_byline_final[LANGUAGE_NONE])) {
    $entity_data->field_byline_final->set($node->field_byline_final[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_owner[LANGUAGE_NONE])) {
    $entity_data->field_owner->set(intval($node->field_owner[LANGUAGE_NONE][0]['target_id']));
  }

  if (isset($node->field_publication_of_origin[LANGUAGE_NONE])) {
    $entity_data->field_publication_of_origin->set(intval($node->field_publication_of_origin[LANGUAGE_NONE][0]['tid']));
  }

  if (isset($node->field_category[LANGUAGE_NONE])) {
    $entity_data->field_category[0]->set(intval($node->field_category[LANGUAGE_NONE][0]['target_id']));
  }

  if (isset($node->field_factbox_headline[LANGUAGE_NONE])) {
    $entity_data->field_factbox_headline->set($node->field_factbox_headline[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_factbox_text_area[LANGUAGE_NONE])) {
    $entity_data->field_factbox_text_area->set($node->field_factbox_text_area[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_jump_headline[LANGUAGE_NONE])) {
    $entity_data->field_jump_headline->set($node->field_jump_headline[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_field_pull_quote[LANGUAGE_NONE])) {
    $entity_data->field_pull_quote->set($node->field_field_pull_quote[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_field_pull_quote[LANGUAGE_NONE])) {
    $entity_data->field_pull_quote->set($node->field_field_pull_quote[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_subheadline[LANGUAGE_NONE])) {
    $entity_data->field_subheadline->set($node->field_subheadline[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_notes[LANGUAGE_NONE])) {
    $entity_data->field_notes->set($node->field_notes[LANGUAGE_NONE][0]['value']);
  }

  if (isset($node->field_slug[LANGUAGE_NONE])) {
    $entity_data->field_slug_text->set($node->field_slug[LANGUAGE_NONE][0]['value_token_filtered']);
  }

  // Set parent story link.
  if (isset($node->nid)) {
    $entity_data->field_parent_story->set($node->nid);
  }

  // Set Run list link.
  if (isset($rnid)) {
    $entity_data->field_run_list->set($rnid);
  }

  // Entity API cannot set dates. Old Method:
  $print_version->field_story_date[LANGUAGE_NONE][0] = array(
    'value' => date_format(date_create($node->field_story_date[LANGUAGE_NONE][0]['value']), 'Y-m-d 00:00:00'),
    'timezone' => 'America/Moncton',
    'timezone_db' => 'America/Moncton',
  );

  if (isset($node->field_embargo[LANGUAGE_NONE])) {
    $print_version->field_embargo[LANGUAGE_NONE][0] = array(
      'value' => date_format(date_create($node->field_embargo[LANGUAGE_NONE][0]['value']), 'Y-m-d 00:00:00'),
      'timezone' => 'America/Moncton',
      'timezone_db' => 'America/Moncton',
    );
  }

  $entity_data->revision->set(TRUE);
  $entity_data->log->set('Print Story Created.');

  $entity_data->save();

  $the_node = $entity_data->getIdentifier();

  // Load and Add to run list item
  $rli_row = entity_metadata_wrapper('field_collection_item', $fcitem);
  $rli_row->field_print_child->set(intval($the_node));
  $rli_row->save(TRUE);

  return $the_node;
}

At the end of this function, it loads the field collection item, and sets the entity referennce for the child item and saves that field collection row only (not the entire run list node). could it have something to do with this?
Answer: Turns out there was a module that was interfering called Corresponding Entity References (CER) that was not needed anymore. Disabling it solved the issue.


How to deserialize a list as a single objects instead of a list object?

Question: I have the following Address and AddressList classes
public class Address {
  private String street;
  private String city;
  private String state;
  // ...
}

public class AddressList {
  private List<Address> addresses;
  // ...
}

and then a Person class
public class Person {
  private String name;
  @JsonDeserialize(contentUsing = ListDeserializer.class)
  private Map<String, AddressList> addresses;
  // ..
}

Then I have the Yaml file like this
---
name: 'abc'
addresses:
  offices:
    - street: 123 main st
      city: san francisco
      state: ca
    - street: 234 post st
      city: san francisco
      state: ca

My List deserializer class is as follows:
public class ListDeserializer extends JsonDeserializer<AddressList> {

@Override
public AddressList deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    return jsonParser.readValueAs(new TypeReference<Map<String, List<Address>>>() {
    });
}

}
my parsing code is as follows:
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
return objectMapper.readValue(inputYamlFile, Person.class);

when I read the list of addresses: it prints as
{offices=null}

Can anyone help with resolving this?
Answer: If it was serialized as a list you have to deserialize it the same way. But you then have the list and and can iterate it yourself.
Answer: I found a way to resolve this issue using deserializing addresses map using Converter.
The modifications I made are
public class Person {
  private String name;
  @JsonDeserialize(converter = AddressListConverter.class)
  private Map<String, AddressList> addresses;
  // ..
 }

I, then, wrote a new converter class for the AddressList.
public class AddressListConverter implements Converter<Map<String, List<LinkedHashMap>>, Map<String, AddressList>> {
@Override
  public Map<String, AddressList> convert(Map<String, List<LinkedHashMap>> stringListMap) {
      Map<String, AddressList> addressListMap = new HashMap<>();
      ObjectMapper mapper = new ObjectMapper();
      for (Map.Entry<String, List<LinkedHashMap>> entry : stringListMap.entrySet()) {
         AddressList addressList = new AddressList();
         for(LinkedHashMap map: entry.getValue()) {
          Address address = mapper.convert(map, Address.class);
          addressList.getAddresses().add(address);
         }
          addressListMap.put(entry.getKey(), addressList);
      }
     return addressListMap;
  }

  @Override
  public JavaType getInputType(TypeFactory typeFactory) {
    return typeFactory.constructMapType(Map.class, String.class, List.class);
  }

  @Override
  public JavaType getOutputType(TypeFactory typeFactory) {
      return typeFactory.constructMapType(Map.class, String.class, AddressList.class);
  }
}

This should do the trick


SQL server in networks

Question: a network consists of a lot of servers like web server, DNS server, FTP server , ... but i confused about SQL server. SQL server is used to store data.

my first question: is SQL server a separate server in network and a
host is dedicated to run SQL server and other servers like DNS
server, Web server, ... query to it to store and fetch their data?
or not there is not any dedicated host to SQL server but other
servers in network like DNS server, Web server, ... also run SQL
server and store their own data locally in SQL server?
my second question: some part of internet traffic is because of SQL
server (queries to SQL server and responses from SQL server). who
query to SQL server? is clients query to SQL server? or is web
servers, FTP server, ... query to SQL server? i think if SQL server
is hosted in servers of network (Web server, DNS server, ...) so any
traffic should not generate because of SQL server because queries is
done locally

thanks in advance for your help
Comment: why negative score???!!! I ask question. I have problem but you give me negative score instead of helping me. sorry for you
Answer:
Technically a SQL server maybe a dedicates server or just a service running on a host concurrent with other services, so both are possible, but if there is SQL traffic it seems the first case is more plausible for your network.
Usally another service queries or stores data on an SQL Server, user interaction is seldom. An example would be a database containing users running on the SQL server queried by the webserver to see if the client(user) authentificating to the webserver is allowed to do so.
Comment: thanks for your help. in the second case, how that service communicate with SQL server? via port? for example imagine a web server that running SQL server and saves its data on that. how this web server communicate with SQL server? are them communicate via port?
Answer: I hope these quick points help clarify things:

Microsoft SQL Server (MSSQL) is Microsoft's longstanding, flagship Relational Database Management Systems (RDBMS) product.
MSSQL is an engine that can run on a dedicate Microsoft Windows Server deployment, on a system hosting other roles (not recommended), or in the cloud (Microsoft Azure SQL).
MSSQL's implementation of ANSI standardized SQL is called Transact-SQL (T-SQL).
While most servers and applications store their data in a RDBMS, there are many options besides MSSQL and options outside of RDBMS altogether, such as NoSQL.
MSSQL communicates via standard TCP/IP port traffic, must commonly being TCP port 1433.
MSSQL offers various other services to extend the RDBMS, such as SQL Server Reporting Services (SSRS), which typically communicate via their own TCP/IP ports.
You asked about Domain Name System (DNS); this typically runs on a flat file database, such as NoSQL.
Other well known systems, such as Active Directory and/or Microsoft Exchange Server, run on proprietary databases, such as Microsoft's Joint Engine Technology (JET) Blue and Red databases.

SQL server in networks


Serialization Versus Encoding

Question: What is the different between Serialization and Encoding.
As i understood
"Serialization defines how the .NET object maps to XML, while Encoding defines how the XML is written out to a stream of bytes. "
is this correct ?
Answer: Yes. Serialization used for transmission of messages in between client and server we need to convert CLR types to standards-based XML.
WCF defines serialization as the process of converting an object graph into an XML Information Set (XML Infoset)
1. The XML Infoset is the data model WCF uses internally to represent a message.
2. The XML Infoset is the data model for representing an XML document.

Encoding used to describe the process of converting a WCF message into an array of bytes. This is done so that the message can be sent across a transport protocol.
Here is the good explanation with example http://msdn.microsoft.com/en-us/magazine/cc163569.aspx#S1
Comment: I realise you posted this a long time ago, but if you're still around, it would be great if you could expand the acronyms the first time you use them.
Answer: Serialization is the conversion of the in-memory .NET object to another format such as XML, JSON, etc. so that they can be stored or transmitted. This format is usually text i.e. a string of characters.
Encoding is the conversion of these characters to a byte stream to transmit them over the wire or store them to disk. Some common encodings are ASCII, UTF-8, etc.
From Wikipedia,
Serialization: Serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and reconstructed later in the same or another computer environment.
Character Encoding: A character encoding system consists of a code that pairs each character from a given repertoire with something else — such as a bit pattern ... to facilitate the transmission of data (generally numbers or text) through telecommunication networks or for data storage.

Serialization Versus Encoding