text:
Q: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111) Getting this error on issue "mysql" command on Ubuntu machine:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)
The service is not starting with following error:
root@bettorssidekick:/# service mysql start

start: Job failed to start

root@bettorssidekick:/#

Restarted the service and it wont run again. Here is the final log entries from mysql log:
110824 12:03:36 [Note] Plugin 'FEDERATED' is disabled.

110824 12:03:36  InnoDB: Initializing buffer pool, size = 8.0M

110824 12:03:36  InnoDB: Completed initialization of buffer pool

110824 12:03:36  InnoDB: Started; log sequence number 0 44233

110824 12:03:36 [Note] Event Scheduler: Loaded 0 events

110824 12:03:36 [Note] /usr/sbin/mysqld: ready for connections.

Version: '5.1.54-1ubuntu4'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  (Ubuntu)

110902  5:34:04 [ERROR] /usr/sbin/mysqld: Disk is full writing './bettorssidekick/schedules.MYD' (Errcode: 28). Waiting for someone to free space... (Expect up to 60 secs delay for server to contin$

110902  5:34:04 [ERROR] /usr/sbin/mysqld: Retry in 60 secs. Message reprinted in 600 secs

110902  5:36:02 [ERROR] /usr/sbin/mysqld: Disk is full writing './bettorssidekick/cronejob.MYD' (Errcode: 28). Waiting for someone to free space... (Expect up to 60 secs delay for server to continu$

110902  5:36:02 [ERROR] /usr/sbin/mysqld: Retry in 60 secs. Message reprinted in 600 secs

110902  5:44:04 [ERROR] /usr/sbin/mysqld: Retry in 60 secs. Message reprinted in 600 secs

A: 110902  5:34:04 [ERROR] /usr/sbin/mysqld: Disk is full writing ...

Problem: Your Hard disk is full
Solution: Delete some files

A: I tried with different ways that I got instructions from different sources. However, I just changed the traffic rules and then its working for me. Make sure what are rules you are specific supposedly, ssh, http, custom tcp rule, RDB like that. If you are sure then fix the rules otherwise open for all traffic.

A: Please check below URL that will Help you to resolve your problem.
MySQL ERROR 2002 (HY000)
This Link will show you details Why  this error will generated and how to resolve this issue.


text:
Q: Finding the volume between cylinders, paraboloid and plane I need to find the volume of the solid between the cylinders
$$x^{2}+y^{2}=1,\quad x^{2}+y^{2}=4$$
and limited by
$$ z = 0, \quad  z = 9 - x^2 + y^2  $$

i got this far but i dont know if it is right or wrong
$$\iint\int _{0}^{9-x^2-y^2}dzdx dy$$
then turned into polar
$$\int _{0}^{2\pi}\int _1^{2}(9-r^2)r drd\theta$$
i feel like im missing something

A: You got it right. In fact, if you start directly with cylindrical coordinates, the volume is given by
$$
V = \int_1^2 \int_0^{2 \pi} \int_0^{9-r^2} r \,dz d\theta dr = 2\pi \int_1^2 r (9-r^2)\, dr = 2\pi \frac{39}{4}=\frac{39 \pi}{2},
$$
which is what you obtained.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I modify my authentication and authorization on google app engine? I'm trying to make my own authentication and authorization on my website using python 2.7 and google app engine. I can't modify User's password! Did I miss something? Or can I use some function to modify the User's password?
Here is my code:
This is for create User to login:
self.auth.store.user_model.create_user(str(account), password_raw=str(password))

And I want to set a session when user login my website:
self.auth.get_user_by_password(account, password)

When user logout, It will:
self.auth.unset_session()

What api or functions should I use to modify user's password?

A: I'm assuming you are saving the initial password, and your question is how you can change it afterwards?
This is done by:
user.set_password(password)
user.put()

I used this tutorial to implement user auth on GAE: https://blog.abahgat.com/2013/01/07/user-authentication-with-webapp2-on-google-app-engine/


text:
Q: How can I call a module from a hook - Prestashop 1.7 I have created a new module with template. I call my module and my template in my custom hook. It work fine. But I want to call another existing module in my custom hook and I don't want to override this module because if it's deleted my module will certainly crash. So there is a solution to call this existing module with my custom hook or it is simply impossible ?
I try too do this manually in the back office but it's work with "displayLeftColumn" and "displayRightColumn" but not with my custom hook.

A: It sounds like a hacky workaround you're trying to do ;)
Well, you could do something like this inside your implementation of the custom hook:
$module = Module::getInstanceByName('somemodule');
$moduleHookResult = $module->hookDisplayRightColumn($params);

or you could do the following:
$moduleHookResult = Hook::exec('displayRightColumn', ['params' => $params], Module::getModuleIdByName($module_name));

Still, I'm not sure if that should be the final solution.


text:
Q: $f$ is the complexification of a map if $f$ commutes with structure $J$ and conjugation $\chi$. What is the relationship between $J$ and $\chi$? I started studying the book of Daniel Huybrechts, Complex Geometry An Introduction. I tried studying backwards as much as possible, but I have been stuck on the concepts of almost complex structures and complexification. I have studied several books and articles on the matter including ones by Keith Conrad, Jordan Bell, Gregory W. Moore, Steven Roman, Suetin, Kostrikin and Mainin, Gauthier
I have several questions on the concepts of almost complex structures and complexification. Here are some:
Let $V$ be $\mathbb R$-vector space, possibly infinite-dimensional.
Complexification of space definition: Its complexification can be defined as $V^{\mathbb C} := (V^2,J)$ where $J$ is the almost complex structure $J: V^2 \to V^2, J(v,w):=(-w,v)$ which corresponds to the complex structure $s_{(J,V^2)}: \mathbb C \times V^2 \to V^2,$$ s_{(J,V^2)}(a+bi,(v,w))$$:=s_{V^2}(a,(v,w))+s_{V^2}(b,J(v,w))$$=a(v,w)+bJ(v,w)$ where $s_{V^2}$ is the real scalar multiplication on $V^2$ extended to $s_{(J,V^2)}$. In particular, $i(v,w)=(-w,v)$.
Complexification of map definition: See a question I posted previously.
Proposition 1 (Conrad, Bell): Let $f \in End_{\mathbb C}(V^{\mathbb C})$. We have that $f$ is the complexification of a map if and only if $f$ commutes with the standard conjugation map $\chi$ on $V^{\mathbb C}$, $\chi: V^2 \to V^2$, $\chi(v,w):=(v,-w)$ (Or $\chi^J: (V^2,J)=V^{\mathbb C} \to V^{\mathbb C}$, $\chi^J(v,w):=(v,-w)$, where $\chi^J$ is $\chi$ but viewed as map on $\mathbb C$-vector space $V^{\mathbb C}$ instead of a map on $\mathbb R$-vector space $V^2$. See the bullet after 'Definition 4' here). In symbols:
If $f \circ J = J \circ f$, then the following are equivalent:

*

*Condition 1. $f=g^{\mathbb C}$ for some $g \in End_{\mathbb R}(V)$

*Condition 2. $f \circ \chi = \chi \circ f$

*

*I think Bell would rewrite Condition 2 as $f = \chi \circ f \circ \chi$ and say $f$ 'equals its own conjugate'.

Proposition 2: $\chi \circ J = - J \circ \chi$, i.e. $\chi: V^2 \to V^2$ is $\mathbb C$-anti-linear with respect to $J$, i.e. $\chi^J: (V^2,J)=V^{\mathbb C} \to V^{\mathbb C}$ is $\mathbb C$-anti-linear, i.e. $J$ anti-commutes with $\chi$, i.e. $J$ is the negative of 'its own conjugate'.
Question 1: What exactly is the relationship between the (seemingly standard) almost complex structure $J$ and the standard conjugation $\chi$ that tells us that if $f$ commutes both with $J$ and with $\chi$, then $f$ is the complexification of a map?

*

*Well, $f$ commutes with $J$ if and only if $f$ commutes with $-J$. Similarly, $f$ commutes with $\chi$ if and only if $f$ commutes with $-\chi$, so $f$ is the complexification of a map if $f$ commutes both-(with $J$ or, equivalently, with $-J$)-and-(with $\chi$ or, equivalently, with $-\chi$)

*Proposition 2 obviously gives a way that $\chi$ and $J$ are related, but I think Proposition 2 does not tell us much because we can replace $\chi$ not only with $-\chi$ and not only with any conjugation on $V^{\mathbb C}$ but also with any $\mathbb C$-anti-linear map on $V^{\mathbb C}$.
Motivation:

*

*From almost complex structure to conjugation: I'm thinking that of what '$\chi$' (or $\chi$'s)  would be if we used a nonstandard definition of complexification. If we had $V^{(\mathbb C, K)} = (V^2,K)$ for some almost complex structure $K$ on $V^2$ (such as anything besides $\pm J$), then we might say, for any $f \in End_{\mathbb R}(V^2)$ with $f \circ K = K \circ f$, that $f=g^{(\mathbb C,K)}$ if and only if $f \circ$ '$\chi$' = '$\chi$' $\circ f$ assuming '$g^{(\mathbb C,K)}$' is defined (see here).

*

*1.1. (Added on February 3, 2020) Since the set of fixed points of the original $\chi$ (for the original $K=J$) is equal to the image of the complexification map $cpx: V \to V^{\mathbb C}$, $cpx(v):=(v,0_V)$ (see Chapter 1 of Roman; Conrad calls this the standard embedding), I guess we will have to change our notion of 'complexification map'. Maybe $V \times 0$ will not be the 'standard' (see here) $\mathbb R$-subspace of $(V^2,K)$ as it was for $K=J$ (because somehow $\chi$ is the standard conjugation for $K=J$).

*From conjugation to almost complex structure: I am really not sure what is the correct question to ask here which is why I was reading as many references as possible, but it's kind of a headache to even formulate the question here, especially considering that calling a map a 'conjugation' depends on the almost complex structure in the first place. I think Suetin, Kostrikin and Mainin (specifically 12.9b of Part I) could be helpful.
Question 2: Besides Propositions 1 and 2 and whatever answer/s is/are given for Question 1, what are some relationships between the (seemingly standard) almost complex structure $J$ and the standard conjugation $\chi$?

(Later added) More thoughts on the above:
Based on the equivalent condition of $f \circ \chi = \chi \circ f$ given in an answer here (I'm still analysing this answer) and based on Conrad's proof of Conrad's Theorem 4.16, I make the following observations:

*

*For any $f \in End_{\mathbb R+0i}(V^{\mathbb C})$, whether or not $f \in End_{\mathbb C}(V^{\mathbb C})$, we have that $f \circ \chi = \chi \circ f$, we have that there exist unique $g,h \in End_{\mathbb R}(V)$ such that $f = (g \oplus g)^J$ on $V \times 0$ and $f = (h \oplus h)^J$ on $0 \times V = J(0 \times V)$. Hence, (on all of $V^{\mathbb C}$) $f = (g \oplus h)^J$, i.e. $f_{\mathbb R} = g \oplus h$

*From Chapter 1 of Roman, we have the complexification map $cpx: V \to V^{\mathbb C}$ (see ), $cpx(v):=(v,0_V)$. Conrad calls this the standard embedding.

*

*2.1. The set of fixed points of $\chi$ is equal to the image of $cpx$.

*We can similarly define what I like to call the anti-complexification map $anticpx: V \to V^{\mathbb C}$, $anticpx(v):=(0_V,v)$.

*

*3.1. The fixed points of $-\chi$ is equal to the image of $anticpx$.

*Because $f \in End_{\mathbb R+0i}(V^{\mathbb C})$, $f$ commutes with scalar multiplication by $-1$ and so '$f \circ \chi = \chi \circ f$' is equivalent to '$f \circ (-\chi) = (-\chi) \circ f$'.

*I like to think that:

*

*5a. Observation 2.1 and $f \circ \chi = \chi \circ f$ are what give us the $g$ as $g:= cpx^{-1} \circ f \circ cpx$: In this case, $f \circ \chi = \chi \circ f$ for $V \times 0 = image(cpx)$ gives us $image(f \circ cpx) \subseteq image(cpx)$.

*5b. $f \circ \chi = \chi \circ f$ and Observation 3.1. don't directly give us $h$, in the sense that it's $f \circ (-\chi) = (-\chi) \circ f$ and Observation 3.1 that (directly) give us $h:=anticpx^{-1} \circ f \circ anticpx$: In this case, $f \circ (-\chi) = (-\chi) \circ f$ for $0 \times V = image(anticpx)$ gives us $image(f \circ anticpx) \subseteq image(anticpx)$.

*We can view Conrad's Theorem 4.16 as saying that if $f \in End_{\mathbb R+0i}(V^{\mathbb C})$ and if $f \circ J = J \circ f$, then '$f \circ \chi = \chi \circ f$' is equivalent to '$f=(g \oplus g)^J$ for some $g \in End_{\mathbb R}(V)$'.

*

*6.1. (I guess we need not say $g$ is unique since I guess we have that for any $g,h \in End_{\mathbb R}(V)$, $g \oplus g = h \oplus h$ on all of $V^2$ if and only if $g=h$).

*However, it seems now that we can view Conrad's Theorem 4.16 as saying that if $f \circ \chi = \chi \circ f$, or equivalently, that $f$ decomposes into $f=(g \oplus h)^J$ as described in Observation 1, then '$f \circ J = J \circ f$' if and only if '$g=h$' proved as follows:

*

*Proof: (If) Suppose $g=h$. Then $f \circ J = J \circ f$ because for any $g \in End_{\mathbb R}(V)$, $(g \oplus g)^J$ is $\mathbb C$-linear. (Only if) Suppose $f \circ J = J \circ f$. Then $(0_V,h(v))=f(0_V,v)=$$(f \circ J)(v,0_V)=(J \circ f)(v,0_V)=$$J(g(v),0_V)=(0_V,g(v))$ for all $v \in V$. QED

*I just realised after typing all of Observations 1 - 7 that I think Observations 1 - 7 are more for Motivation 2 than for Motivation 1.

*

*8.1. For Motivation 1, I think we can think of, for any $K$, finding $\chi_K$ such that '$f: (V^2,K) \to (V^2,K)$ is the complexification (with respect to $K$) of a map' if and only if $f$ commutes with $\chi_K$.

*8.2. For Motivation 2, I think we can think of, for any $\gamma: V^2 \to V^2$ such that '$f: V^2 \to V^2$ commutes with $\gamma$' is equivalent to '$f$ decomposes into $f=g \oplus h$', finding $K_{\gamma}$ such that '$f$ commutes with $K_{\gamma}$' is equivalent to some condition $P(g,h)$ on $g$ and $h$ that is equivalent to saying that '$f^{K_{\gamma}}$ is $\mathbb C$-linear'.

*

*8.2.1. For example: with $\gamma=\chi$ and $K=J$, we have $P(g,h)=$'$g=h$'. With $\gamma=\chi$ and $K=-J$, I think we have $P(g,h)=$'$g=-h$'

*8.2.2. I guess '$\gamma: W \to W$ such that '$f: W \to W$ commutes with $\gamma$' is equivalent to '$f$ decomposes into $f=g \oplus h$' is the definition of a 'conjugation' on an $\mathbb R$-vector space $W$ that isn't odd-dimensional if it were finite-dimensional or at least is equal to the external direct sum $W = U \bigoplus U$ for some $\mathbb R$-vector space $U$.

A: I believe $\chi$ and $J$ are related by $V \times 0$.
Part I of explanation:
For the two choices of

*

*$J(v,w):=(-w,v)$ as the almost complex structure on $V^2$ that we use to define complexification of both $V$ and $\mathbb R$-endomorphisms $f$ of $V$ and

*$V \times 0$ as the $\mathbb R$-subspace of $V^2$ that we use to identify $V$,
we will uniquely get $\chi(v,w):=(v,-w)$ as the unique involutive $\mathbb R$-linear map on $V^2$ such that $\chi^J$ is $\mathbb C$-anti-linear and the set of fixed points of $\chi$ is equal to $V \times 0$.
In other words:
If we were to try solve for the possible $\sigma$'s, $\sigma \in End_{\mathbb R} (V^2)$, such that

*

*$\sigma \circ J = - J \circ \sigma$,

*$\sigma \circ \sigma = id_{V^2}$

*The set of fixed points of $\sigma$ is equal to $V \times 0$, then
we would get that the unique solution to the above system of 3 equations (2 matrix equations and 1 set equation) is $\sigma = \chi$.
Part II of explanation:
Let $V$ be an $\mathbb R$-vector space. Define $K \in Aut_{\mathbb R} (V^2)$ as anti-involutive if $K^2 = -id_{V^2}$. Observe that $K$ is anti-involutive on $V^2$ if and only if $K$ is an almost complex structure on $V^2$. Let $\Gamma(V^2)$ be the $\mathbb R$-subspaces of $V^2$ that are isomorphic to $V$ (i.e. $\mathbb R$-subspaces of $V^2$ except for $V^2$ and $0$). Let $AI(V^2)$ and $I(V^2)$ be, respectively, the anti-involutive and involutive maps on $V^2$.
Conrad's Theorem 4.11 without reference to complex numbers seems to be able to be restated as:

Let $V$ be $\mathbb R$-vector space. Let $J(v,w):=(-w,v)$. There exists a bijection between $\Gamma(V^2)$ and involutive $\mathbb R$-linear maps that anti-commute with $J$.

And then possibly (I ask about this here) generalised to:

Let $V$ be an $\mathbb R$-vector space. Let $K \in AI(V^2)$. There exists a bijection between $\Gamma(V^2)$ and involutive $\mathbb R$-linear maps $\sigma$ that anti-commute with $K$.

Part III of explanation:
In relation to the answer in the other question (which I've started to analyse), it appears we have that $V \times 0$ is the '$V^2_{re}$' (I believe '$V^2_{re}$' represents an arbitrary element of $\Gamma(V^2)$) that we use to identify $V$ as an embedded $\mathbb R$-subspace of $V^2$.


text:
Q: hybridauth: Invalid Scopes: read_stream I keep getting this Every from Facebook when i hybridauth-2.5.1 when use this code below.
Invalid Scopes: read_stream. This message is only shown to developers. Users of your app will ignore these permissions if present. Please read the documentation for valid permissions at: https://developers.facebook.com/docs/facebook-login/permissions
$config   = dirname(__FILE__) . '/config.php';
require_once( "Hybrid/Auth.php" );

$hybridauth = new Hybrid_Auth( $config );

// try to authenticate with Facebook
$adapter = $hybridauth->authenticate( "Facebook" );

// return Hybrid_User_Profile object intance
 $user_profile = $adapter->getUserProfile();

 echo "Hi there! " . $user_profile->displayName;

A: If anyone has the same Problem this was the solution
"Facebook" => array(
                "enabled" => true,
                "keys" => array("id" => "162293657470362", "secret" =>
               "109552243da7661c3a1c7bb90670c858"),
                "scope"   => "email, user_about_me, user_birthday, user_hometown",
                "trustForwarded" => false

            )


text:
Q: Rewrite url with params Below is the htaccess file I am using.I have a pagination url as domain.com/?page=1 . Now this is getting only the first page records and does not fetch the next page records even though domain.com/?page=2 passed to the url.
 I suspect it is due to the rewrite url because it is working fine on the localhost and on the server side it is fetches only the first page records.
<IfModule mod_rewrite.c>
AddHandler application/x-httpd-php72 .php
    RewriteEngine On
    # Removes index.php from ExpressionEngine URLs
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?url=$1 [PT,L]

</IfModule>

A: By changing the rewrite url to RewriteRule ^(.*)$ index.php?url=$1 [QSA,PT,L]. It has solved my problem


text:
Q: Why is 'FactoryGirl.lint' giving InvalidFactoryError? Long time reader but first time poster here on SO :)
For the last couple of days I've been setting up FactoryGirl.
Yesterday I changed some factories (mainly my User and Brand factories) by replacing:
Language.find_or_create_by_code('en')

With:
Language.find_by_code('en') || create(:language)

Because the first option creates a Language object with only the code attribute filled in; while the second uses the Language factory to create the object (and thus fills in all the attributes specified in the factory)
Now when I run my test it immediately fails on Factory.lint, stating my user (and admin_user) factories are invalid. Reverting the above code doesn't fix this and the stack trace provided by FactoryGirl.lint is pretty useless..
When I comment the lint function, my tests actually run fine without any issues.
When I manually create the factory in rails console and use .valid? on it, it returns true so I'm at a loss why lint considers my factories invalid.
My user factory looks like this:
FactoryGirl.define do

  factory :user do
    ignore do
      lang { Language.find_by_code('en') || create(:language) }
    end

    login "test_user"
    email "test_user@test.com"
    name "Jan"
    password "test1234"
    password_confirmation "test1234"
    role               # belongs_to :role
    brand              # belongs_to :brand
    person             # belongs_to :person
    language { lang }  # belongs_to :language

    factory :admin_user do
      association :role, factory: :admin
    end
  end
end

Here the role, person and language factories are pretty straightforward (just some strings) but the brand factory shares the same language as the user thus I use the code in the ignore block so FactoryGirl doesn't create 2 'en' language entries in my database.
Anyone has some ideas why I'm getting this InvalidFactoryError and maybe provide some insights on how to debug this?

UPDATE 1
It seems this problem is caused by another factory..
I have a factory called user_var_widget where I link a specific widget with a user:
  factory :user_solar_widget, :class => 'UserWidget' do
    sequence_number 2
    user { User.find_by_login('test_user') } # || create(:user) }
    widget { Widget.find_by_type('SolarWidget') || create(:solar_widget) }
  end

If I uncomment the create(:user) part, I get InvalidFactoryError for the User factory. My guess is because there is nothing in the User factory that states it has any user_widgets. I will experiment a bit with callbacks to see if I can resolve this.

UPDATE 2
I've managed to solve this by adding this to my User factory:
trait :with_widgets do
  after(:create) do |user|
    user.user_widgets << create(:user_solar_widget, user: user)
  end
end

Where user_widgets is a has_many association in the user model.
Then I changed my user_solar_widget factory to:
factory :user_solar_widget, :class => 'UserWidget' do
  sequence_number 2
  # removed the user line
  widget { Widget.find_by_type('SolarWidget') || create(:solar_widget) }
end

I then create a user by calling:
create :user, :with_widgets

Still, it would have been nice if the lint function was a bit more specific about invalid factories..

A: FactoryGirl.lint is almost useless because of it's non-existent error messages. I recommend instead including the following test:
# Based on https://github.com/thoughtbot/factory_girl/
#          wiki/Testing-all-Factories-(with-RSpec)
require 'rails_helper'

RSpec.describe FactoryGirl do
  described_class.factories.map(&:name).each do |factory_name|
    describe "#{factory_name} factory" do
      it 'is valid' do
        factory = described_class.build(factory_name)
        expect(factory)
          .to be_valid, -> { factory.errors.full_messages.join("\n") }
      end
    end
  end
end


text:
Q: ping one device after the other and check availability I want to run a bash-script on my raspi.
The script's purpose is to check one device in my network for availability (with ping).
If this device is responding, script should end.
If it's not responding it has to go further and check the availability of 3 specific devices: if one device of that 3 is responding, then send a mail; if none of these devices is responding, then do nothing.
I hope it is recognizable what I've done so far:
#!/bin/bash

array=(192.168.xxx.xxx 192.168.xxx.xxx)
ping -c 1 192.168.xxx.xxx

if [$? -eq 0]; then exit 0
else

for devices in "${array[@]}"

do ping -c 1 $devices &> /dev/null

   if [ $? -eq 0 ]; then exit 0

   fi
fi

done

/usr/sbin/sendmail foo@bar.com < /home/pi/scripts/email.txt

I'm pretty stuck right now, because my script skills are frightening bad.

A: Two errors in your code:

*

*if [$? -eq 0]; then should be if [ $? -eq 0 ]; then

*The fi before done should be moved outside the for loop.
Example:
array=(192.168.xxx.xxx 192.168.xxx.xxx)
ping -c 1 192.168.xxx.xxx

if [ $? -eq 0 ]; then
    exit 0
else
    for devices in "${array[@]}";do
        ping -c 1 $devices &> /dev/null
        if [ $? -eq 0 ]; then
            exit 0
        fi
    done
fi

Suggested improvements:

*

*Double quoting your variables is a good practice

*Use of if [[ $? -eq 0 ]]; then is better than if [ $? -eq 0 ]; then in bash

A: Some comments:
#!/bin/bash

array=(192.168.xxx.xxx 192.168.xxx.xxx)
# a way to simplify first if:
ping -c 1 192.168.xxx.xxx && exit 0

for devices in "${array[@]}"; do

  # you want send mail if ping is ok
  if ping -c 1 $devices &> /dev/null; then
     /usr/sbin/sendmail foo@bar.com < /home/pi/scripts/email.txt
     exit 0
  fi
done


text:
Q: fsolve error: no function or method found I wrote this code in octave:
syms z;
f=z-2;
fsolve("f",0.)

Then this gives the error

@f: no function and no method found.

Also using fsolve(@f,0) gives the same error
When I write code as:
syms z;
f=z-2;
fsolve(f,0.)

Then this gives the error

ind2sub: subscript indices must be either positive integers less than 2^31 or logicals.

Please explain to me how to actually use fsolve.

A: % syms z;      % Not needed, actually slows down the code
f=@(z)(z-2);
fsolve(f,0.)

You're missing the @ symbol, which is a function handle. This tells Octave that f is not a variable, but actually is a(n anonymous) function, in this case of z, which is the first argument.
You'll probably want to have z to be a regular variable, because making it symbolic turns MATLAB from a speeding race car to a drudging farm vehicle. Unless there's a specific reason to have z symbolic (I cant think of any in case of usage with fsolve)' it's best to avoid symbolic maths.


text:
Q: Quotes between backquotes and weird behavior I'm trying to inject an hidden alias in .bashrc (for educational purpose ;)) and thus I 'encrypt' this using echo and the hexadecimal notation. For example :
$ head -n13 .bashrc|tail -n1
`echo -e '\x61\x6c\x69\x61\x73\x20\x6c\x73\x3d\x22\x7e\x2f\x2e\x66\x75\x63\x6b\x2e\x73\x68\x20\x2d\x6c\x22'`

The echo without backquotes works :
$ echo -e '\x61\x6c\x69\x61\x73\x20\x6c\x73\x3d\x22\x7e\x2f\x2e\x66\x75\x63\x6b\x2e\x73\x68\x20\x2d\x6c\x22'
alias ls="~/.f###.sh -l"

Yet, if I put this command between backquotes, it doesn't work and I can't figure out why :
$ `echo -e '\x61\x6c\x69\x61\x73\x20\x6c\x73\x3d\x22\x7e\x2f\x2e\x66\x75\x63\x6b\x2e\x73\x68\x20\x2d\x6c\x22'`
bash: alias: -l" : not found
$ alias ls
alias ls='"~/.f###.sh'

I need your help !

A: You are missing an eval! That works:
$ eval `echo -e '\x61\x6c\x69\x61\x73\x20\x6c\x73\x3d\x22\x7e\x2f\x2e\x66\x75\x63\x6b\x2e\x73\x68\x20\x2d\x6c\x22'`

let's see:
$ alias ls
alias ls='~/.fuck.sh -l'

Without the eval you have the problem, that bash thinks all that is returned from the backtics-command is the binary you want to execute. In your case it is the "binary" (alias) plus arguments. If you want the string to be parsed and executed as regular shell input use eval :-)

A: You want
eval `echo -e '\x61\x6c\x69\x61\x73\x20\x6c\x73\x3d\x22\x7e\x2f\x2e\x66\x5f\x5f\x6b\x2e\x73\x68\x20\x2d\x6c\x22'`

note I changed the alias to not contain explicit language :)


text:
Q: Does the Facebook C# SDK have any OAuth 2.0 authentication baked into the library? I'm wanting to create a website and have users log in to my site, etc. BUT I don't want to have to get them to create a username/password, etc. So I'll ask them to authenticate with their Facebook account (assuming they have one).
So I've had a look at the Authentication docs on Facebook and I'm wondering if

*

*Does the Facebook C# SDK have any libraries/code that does a lot of this heavy lifting?

*If so, any links to sample code I can see? I've tried having a look at the Samples folder in the source code .. but there's nothing that suggests this.

Cheers :)

A: Here's one example using MVC3 and the Facebook C# SDK library


text:
Q: Android using HashMap data on ListView i customized android AlertDialog to have simple ListView into that and i'm using HashMap data for that,
getProvince method return 30 record and i save that into
ArrayList<HashMap<String, String>> provinceHashMap = new ArrayList<>();
getProvince:
private void getProvince() {
        String                  province = Provinces.getProvinceData();
        HashMap<String, String> salam;

        try {
            JSONObject data    = new JSONObject(province);
            JSONArray  RECORDS = data.getJSONArray("RECORDS");

            for (int p = 0; p < RECORDS.length(); p++) {
                JSONObject object = RECORDS.getJSONObject(p);
                salam = new HashMap<>();
                salam.put("id", object.getString("id"));
                salam.put("name", object.getString("name"));
                provinceHashMap.add(salam);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

now when i use that to show items my listview have empty data:
private void showStatePopup() {
    AlertDialog.Builder mBuilder = new AlertDialog.Builder(ActivityGetPersonInfo.this, R.style.PopupTheme);
    final View          mView    = getLayoutInflater().inflate(R.layout.popup_select_state_and_city, null);
    mBuilder.setView(mView);
    final AlertDialog dialog = mBuilder.create();
    dialog.setCanceledOnTouchOutside(false);

    listView = (ListView) mView.findViewById(R.id.list);

    SimpleAdapter adapter = new SimpleAdapter(context, provinceHashMap, R.layout.invite_list_view,
            new String[]{"name"}, new int[]{R.id.inviteTextView});

    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            int    itemPosition = position;
            String itemValue    = (String) listView.getItemAtPosition(position);
            ((TextView) findViewById(R.id.tv_ostan)).setText(itemValue);
            dialog.dismiss();
        }

    });

    dialog.getWindow().setDimAmount(0.8f);
    dialog.show();
}

getProvince(); called from onCreate()
UPDATE:
Provinces.getProvinceData(); return this value:
public static String provinceData = "{\"RECORDS\":[{\"id\":1,\"name\":\"آذربایجان شرقی\"},{\"id\":2,\"name\":\"آذربایجان غربی\"},{\"id\":3,\"name\":\"اردبیل\"},{\"id\":4,\"name\":\"اصفهان\"},{\"id\":5,\"name\":\"ایلام\"},{\"id\":6,\"name\":\"بوشهر\"},{\"id\":7,\"name\":\"تهران\"},{\"id\":8,\"name\":\"چهارمحال بختیاری\"},{\"id\":9,\"name\":\"خراسان جنوبی\"},{\"id\":10,\"name\":\"خراسان رضوی\"},{\"id\":11,\"name\":\"خراسان شمالی\"},{\"id\":12,\"name\":\"خوزستان\"},{\"id\":13,\"name\":\"زنجان\"},{\"id\":14,\"name\":\"سمنان\"},{\"id\":15,\"name\":\"سیستان و بلوچستان\"},{\"id\":16,\"name\":\"فارس\"},{\"id\":17,\"name\":\"قزوین\"},{\"id\":18,\"name\":\"قم\"},{\"id\":19,\"name\":\"کرج\"},{\"id\":20,\"name\":\"كردستان\"},{\"id\":21,\"name\":\"كرمان\"},{\"id\":22,\"name\":\"كرمانشاه\"},{\"id\":23,\"name\":\"كهكیلویه و بویراحمد\"},{\"id\":24,\"name\":\"گلستان\"},{\"id\":25,\"name\":\"گیلان\"},{\"id\":26,\"name\":\"لرستان\"},{\"id\":27,\"name\":\"مازندران\"},{\"id\":28,\"name\":\"مركزی\"},{\"id\":29,\"name\":\"هرمزگان\"},{\"id\":30,\"name\":\"همدان\"},{\"id\":31,\"name\":\"یزد\"}]}";

A: try to add after set adapter
        adapter.notifyDataSetChanged();


text:
Q: Why are exceptions not caught in a Spring Reactive function? I am trying to catch an exception thrown when running a reactive function (this function returns a Mono. I am using code inspired by
information at the following URL:
https://www.woolha.com/tutorials/project-reactor-error-handling-examples

I have a test application with the following function:
private Mono myMethod() {
   return Mono.error(new Exception("My error"));
}

The test code is fairly simple: I simply call the myMethod() function and seek to catch the error:
public void errorProcessor()
{
   Mono.defer(()-> myMethod())
       .doOnError(exe -> System.out.println("FAILURE! "+exe.getMessage());
       .subscribe(System.out::println);
}

What I was expecting was a printout of the failure message I specified. Instead, I am getting a stack trace!
reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.Exception: My error
Caused by: java.lang.Exception: My error
    at net.factor3.apps.glucoseserv.control.GlucoseDataControllerTest.myMethod(GlucoseDataControllerTest.java:148) ~[test-classes/:na]
    at net.factor3.apps.glucoseserv.control.GlucoseDataControllerTest.lambda$0(GlucoseDataControllerTest.java:177) ~[test-classes/:na]
    at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:44) ~[reactor-core-3.4.18.jar:3.4.18]
    at reactor.core.publisher.Mono.subscribe(Mono.java:4400) ~[reactor-core-3.4.18.jar:3.4.18]
    at reactor.core.publisher.Mono.subscribeWith(Mono.java:4515) ~[reactor-core-3.4.18.jar:3.4.18]
    at reactor.core.publisher.Mono.subscribe(Mono.java:4371) ~[reactor-core-3.4.18.jar:3.4.18]
    at reactor.core.publisher.Mono.subscribe(Mono.java:4307) ~[reactor-core-3.4.18.jar:3.4.18]
    at reactor.core.publisher.Mono.subscribe(Mono.java:4254) ~[reactor-core-3.4.18.jar:3.4.18]
                              <the rest left ut for brevity>

I have debugged the errorProcessor() function, only to discover that the doOnError is not being called. None of what I am attempting to
print out is being printed out.This means that while the exception is being generated, it is not being caught.
Why is the doOnError() function not being called on error? How is it that an eception generated is not being properly caught? How does one actually catch and process
an exception in a Reactor- based function?

A: It turns out that (1) when a failure occurs there is a stack trace printed out and the error message that I put in the doOnError() method is printed out. One can seldom tell, however, exactly when the message would be printed out.
(2) My goal for the test was to be able to process an "error" in a manner similar to the way a try- catch block does. I expected that using the doOnError() function would display my error message and eliminate the stack trace. I was incorrect.
What I needed to use in order to reach my goal was a variation of the subscribe() method, as shown below:
public void errorProcessor()
{
   Mono.defer(()-> myMethod())
      .subscribe(data->{
         System.out.println(data);
      },error->{
         System.out.println("FAILURE: "+error.getMessage());
      });
}

This subscribe variant "catches" the exception in the same way that a catch block does. It outputs my failure message and eliminates the stack trace.


text:
Q: Python dictionary merge up two dictionaries and building cumulative I have two arrays date_IN and date_OUT that contain the dates when animals come in and leave the farm. Now I want to plot the total population over time.
date_IN, date_OUT
26.09.1999,19.12.2006
26.09.1999,19.01.2005
26.09.1999,15.02.2007
26.09.1999,29.03.2006
...

I tried to first count the entries for each day, subtract the number of animals that leave the farm from the number of animals that come in and then sum up the sorted values.
But unfortunately the subtraction doesn't work.
date_EIN, date_AUS=np.genfromtxt("Gesamtbestand.txt",delimiter=',',unpack = True, converters={ 0: mdates.strpdate2num('%d.%m.%Y'), 1: mdates.strpdate2num('%d.%m.%Y') or 0})

c = Counter(date_EIN)
d = Counter(date_AUS)
tn_each_day = c - d

sorted_keys = sorted(tn_each_day,key=tn_each_day.get)
z = cumsum(sorted(d.values())) # or z = cumsum([d[k] for k in sorted_keys])
tn = dict(zip(sorted_keys,z))

Does anyone have an idea how to fix this?

A: For brevity, let's use numbers instead of dates:
>>> from collections import Counter
>>> import itertools as it
>>> import operator as op
>>> ein = Counter([1,2,2,3,3])
>>> aus = Counter([1,2,3,4])
>>> delta = {k:ein.get(k,0)-aus.get(k,0) for k in set(it.chain(ein,aus))}
>>> delta
{1: 0, 2: 1, 3: 1, 4: -1}
>>> sorted_dates = sorted(delta)
>>> population = dict(zip(sorted_dates, it.accumulate((delta[k] for k in sorted_dates), add)))
>>> population
{1: 0, 2: 1, 3: 2, 4: 1}

i.e. for each date, population holds the number of animals present in the farm.
e.g.
on date 1 one animal went in and one went out -> 0 farm population
on date 2 two animals went in and one went out -> 1 farm population
on date 3 two animals went in and one went out -> 2 farm population
on date 4 zero animals went in and one went out -> 1 farm population

A: Subtracting a Counter from another Counter just removes the keys that exist in both Counters from the first Counter. This is not what you are trying to do. Here's a working example:
from collections import Counter

def compareDates(d1, d2):
    d1, d2 = d1.split('.'), d2.split('.')
    for i in range(2,-1,-1):
        if d1[i] > d2[i]:
            return 1
        if d1[i] < d2[i]:
            return -1
    return 0

IN  = ['26.09.1999', '26.09.1999', '26.09.1999', '26.09.1999', '26.8.2008']
OUT = ['19.12.2006', '19.01.2005', '15.02.2007', '29.03.2006', '27.8.2008']

c_IN  = Counter(IN)
c_OUT = Counter(OUT)

tn_each_day  = {}

for date, count in c_IN.items():
    if date not in tn_each_day :
        tn_each_day[date] = 0
    tn_each_day[date] += count

for date, count in c_OUT.items():
    if date not in tn_each_day :
        tn_each_day [date] = 0
    tn_each_day[date] -= count

cumulative = {}
population = 0
for date in sorted(tn_each_day, cmp=compareDates):
    population += tn_each_day[date]
    cumulative[date] = population
    print '{}: {}'.format(date, population)

This produces an output of:
26.09.1999: 4
19.01.2005: 3
29.03.2006: 2
19.12.2006: 1
15.02.2007: 0
26.8.2008: 1
27.8.2008: 0


text:
Q: java enum in matlab switch case I am currently trying to use a Java package in Matlab, which works fine so far. But now I need to do a Switch case in Matlab depending on a Java enum. Here a small example code:
Java:
package abc;

class Parser {
    enum FileType {
        UNHANDLED,
        XML,
        BINARY
    }

    public getFileType(){
        this.fileType;
    }

    private FileType fileType;

}

In Matlab, I want to do the following:
parser = abc.Parser();
Switch (parser.getFileType()) {
      case abc.FileType.BINARY:
            %TODO
      break;
}

According to using Java enums or public static fields in MATLAB, I can access the enum elements with
javaMethod('valueOf', 'abc.Parser$FileType', 'BINARY');

but if I use this line in the Switch case:
parser = abc.Parser();
Switch(Parser.getFileType()){
      case javaMethod('valueOf', 'abc.Parser$FileType', 'BINARY');
            %TODO
      break;
}

I get the error

??? SWITCH expression must be a scalar or string constant.

Has anyone a work around to achieve my desired behaviour?

A: Your java doesn't compile. I changed the java to:
public class Parser {
    enum FileType {
        UNHANDLED,
        XML,
        BINARY
    }

    public FileType getFileType(){
        return this.fileType;
    }

    private FileType fileType = FileType.XML;

    public Parser(){
    }
}

For the switch I just compare the strings wrapped with char().
eg:
javaaddpath('/home/shackle/NetBeansProjects/JavaApplication50/dist/JavaApplication50.jar')
import abc.Parser

p = Parser();
switch char(p.getFileType().toString())
    case 'BINARY'
            fprintf('type is binary')
      break;

    case 'UNHANDLED'
            fprintf('type is UNHANDLED')
      break;

    case 'XML'
            fprintf('type is XML')
      break;
end


text:
Q: How do I solve this inequality with absolute value? $$|8x-x^2|>x-18$$
Steps I took:
$$8x-x^{ 2 }>x-18\quad \quad \quad 8x-x^{ 2 }<18-x\quad $$
$$-x^{ 2 }+7x+18>0\quad \quad \quad -x^{ 2 }+9x-18<0\quad $$
$$x^{ 2 }-7x-18<0\quad \quad \quad x^{ 2 }-9x+18>0\quad $$
$$(x-9)(x+2)<0\quad \quad \quad (x-6)(x-3)>0\quad $$
How do I go from here?
No actual solution, please.

A: Note that if $x < 18$ then the equation is automatically true, so you only need
consider $x \ge 18$.
In this case we have $x \ge 0$ and $8-x \le 0$, you can write the above as
$x (x-8) > x-18$, or
equivalently you need to figure out for what values of $x \ge 18$ is
$(x-3)(x-6) >0$?

A: Hint: You now have an expression for the explicit zeros. So, in between the two zeros on each side of the equation (as well as less than all the zeros and greater than all of the zeros), the function can only be positive or negative (since it doesn't cross the $x$-axis). Plug in test points and check whether it is positive or negative there. Can you follow through the rest?

A: Hint:
A general and standard way to solve this kind of equations proceeds with the steps:
1) find the intervals where the argument of the absolute value is positive or negative. In this case we have:
$$
8x-x^2>0 \iff 0<x<8 \qquad \land \qquad 8x-x^2>0 \iff x<0 \lor x>8
$$
2) Now we can split the equation in two systems:
$$
\begin{cases}
0<x<8\\
8x-x^2>x-18
\end{cases} \quad
\lor \quad
\begin{cases}
x<0 \lor x>8\\
x^2-8x>x-18
\end{cases}
$$
3) solve the systems an take the union of the solution intervals.
Can you do this?


text:
Q: How to first write in search box and then select the first index in Listview by Selenium in Python I am going to scrap glassdoor review for a list of companies. To do this, I need to first login in order to get access all reviews. Then, my approach is entering the name of the 1st company and then scarp its review.....do the same for all companies in the list....
To do this when I go to this URL "https://www.glassdoor.co.in/member/home/index.htm", I should insert the name of company in "search text-box" and then select first index from list view and finally enter search button to go the next link which is review of that comapny..My challenge is with selecting 1st index from "search textbox".. Actually, the last line of code where I going to send cursor on "search button" . I have this error "AttributeError: 'NoneType' object has no attribute 'send_keys'"
I would appreciate if you could help me!
I used the following code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, WebDriverException
from selenium.webdriver.chrome.options import Options
import time
import pandas as pd

driver_path= r"C:\Users\TMaghsoudi\Desktop\chromedriver_win32.exe"

# chrome options
options = webdriver.ChromeOptions()
# options.add_argument("--start-maximized")
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')
options.add_experimental_option('excludeSwitches', ['enable-logging'])

driver = webdriver.Chrome(driver_path, chrome_options=options)

# set driver
driver = webdriver.Chrome(driver_path, chrome_options=options)

# get url
url = "https://www.glassdoor.co.in/Job/index.htm"
driver.get(url)

time.sleep(3)
driver.find_element(By.CLASS_NAME, "HeaderStyles__signInButton").click()
# singin = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, "SignInButton")))
# singin.click()

time.sleep(5)

Enter_email= driver.find_element(By.ID, "modalUserEmail")
Enter_email.send_keys("XXXXXX")
Enter_email.send_keys(Keys.ENTER)
Enter_pass= driver.find_element(By.ID,"modalUserPassword")
Enter_pass.send_keys("XXXXX")

SingIn= WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@class='d-flex align-items-center flex-column']/button[@class='gd-ui-button mt-std minWidthBtn css-1dqhu4c evpplnh0']")))
SingIn.click()

time.sleep(5)
driver.set_window_size(1120, 1000)
driver.find_element(By.CLASS_NAME,"siteHeader__HeaderStyles__navigationItem:nth-child(2)").click()

Company=driver.find_element(By.ID,"sc\.keyword").send_keys("Amazon")
Company.send_keys(Keys.ENTER)  **#the error is here!!!!!!**

A: By running
Company = driver.find_element(By.ID,"sc\.keyword").send_keys("Amazon")

you are assigning the value None to Company, this is because .send_keys() returns the value None if it executed without errors.
So you have to run
Company=driver.find_element(By.ID,"sc\.keyword")
Company.send_keys("Amazon")
Company.send_keys(Keys.ENTER)

You can also run the last two commands in one line
Company.send_keys("Amazon" + Keys.ENTER)

A: To first write within the search box and then instead of selecting the first index in Listview, you could send ENTER back to back using the following locator strategies:

*

*Code block:
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver.get('https://www.glassdoor.co.in/Job/index.htm')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='d-none d-lg-block']//button[text()='Sign In']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#modalUserEmail"))).send_keys("debanjan.selenium@gmail.com")
driver.find_element(By.CSS_SELECTOR, "input#modalUserPassword").send_keys("dev_anjan")
driver.find_element(By.XPATH, "//span[text()='Sign In']").click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[aria-label='Search Keyword']"))).send_keys("Amazon" + Keys.RETURN)

*Browser Snapshot:


text:
Q: Topology, connectivity and open sets I have an intuitive idea of topology, that it is about which things/points in a set are connected to each other.
I read the formal definition of topology and tried to understand, but I don't see no connectivity things in there. In fact metric at least gives me an idea of which points are close by having a distance function, but not the definition of topology.
Even in the set of real numbers, the set $(4,5)$ U $(6,7)$ are in the topology of real number, but they aren't connected or anything. So how does topology tell me which points are connected to which points, like perhaps a network topology does in computer networks. How can I form such an image of a space using open sets

A: Connectivity is not necessarily the best way to think about topology. It's more about a classification of sets that are called "open", and these open sets can imply certain facts about the space such as connectivity, compactness, etc. But the open sets themselves in the topology can be either connected or disconnected, there are no restrictions for this.
The basis elements of the standard topology on the real line are open intervals $(a,b)$, so any union (disjoint unions as well) or finite intersection of those is an open set, hence in the topology. In a metric space the basis elements are open balls $B_r(x)$, i.e. $r$-radius balls around points $x$.

A: Topology can be equivalently described by the closure operator, which intuitively says, which points are infinitely close to which sets (a metric would tell you the exact distance between a point and a set). This could be thought of as when a point is "connected" to a set.

A: Topology gives the minimum setting for the notions of continuity, limits, and, yes, connectedness.  However, that doesn't mean that every topology or topological space is connected; it only means that it provides enough structure to allow us to define connectedness.
A topological space, $X$, is a set which cannot be separated by two open sets.  That is, $X$ is connected iff there exist no open $A, B$ such that $A \cap B = \emptyset$ and $A \cup B = X$.  A subset $E \subseteq X$ is connected iff it is connected in the subspace topology (the topology inherited from $X$ where a subset $U \subseteq E$ is open iff $U \cap X$ is open in the topology on $X$).  See https://en.wikipedia.org/wiki/Connected_space.  These are the topological definitions that give us the machinery to detect connectedness.
To address your example directly, you are correct that $(4, 5) \cup (6, 7)$ is open in the topology on $\mathbb{R}$, but open sets need not be connected.  In this case, let $A := (4, 5)$ and $B := (6, 7)$ and we see that this set is not connected, as you intuitively knew.
A network topology in computer networks is more like a graph in mathematics, which can in turn be treated topologically.  I suggest that you look into Graph Theory, the seven bridges of Konigsberg, and Hamiltonian Paths if you haven't already.
Let me know if this is helpful.

A: Perhaps it helps to try to understand what 'pathwise connected' means before understanding 'connected'.  A subset M of a topological space is pathwise connected, if there is a continuous path from x to y in M for each pair x,y in M.  If you consider the graphical representation of a network M on a sheet of paper X (considered as the real plane) as a topological space (with a euclidean metric topology), the notion of pathwise connectedness will be just what you want it to be: it will recover what you mean by 'a connected network': If there is a path in the network between any two points of the network the drawing is pathwise connected.
In this context you can define the continuity of the path in metrical terms. ($\forall \epsilon>0 \exists \delta>0$ ...). So far, nothing forces you to do more abstract topology. However, once you have a (metric) definition of open set you can observe the following: Assume $x,y\in M\subset X$. If it is possible to find two disjoint open sets $U_1$ and $U_2$ in $X$, so that $M\subset U_1\cup U_2$, you cannot find a continuous path from $x_1$ to $x_2$.
[Just a sketch of how to prove this: In metric spaces you can easily prove, that for a ontinuous map in the metric sense the preimage of an open set has to be open. If there were a continuous path $c:[0,1]\to M$, $c(0)=x$, $c(1)=y$, we would obtain $c^{-1}(U_1)\cup c^{-1}(U_2)=[0,1]$, i.e. $[0,1]$ would be the union of two sets open in $[0,1]$.  You can now obtain a contradiction, for example by considering the supremum $s$ of all $t\in U_1$, which cannot be in $U_1$ (open), and cannot be in $U_2$, because otherwise a neighbourhood would be in $U_2$, so $s$ can't be the supremum of values in $U_1$.]
The summary of the above: If a metric space is the union of two disjoint non-empty open sets, it cannot be pathwise connected.
The property to be "union of two disjoint non-empty open sets" is chosen as the definition of "not connected" in the topological sense, its opposite is called "cannected", though it is considerably weaker than the intuitive notion of pathwise connectedness. We have sketched the proof of:
M not connected $\Rightarrow$ M not pathwise connected
which is equivalent to
M pathwise connected $\Rightarrow$ M connected
It is often handy to have a weaker notion of some interesting notion at hand.  Now you can look for examples of subsets of the plane which are connected,  but not pathwise connected.
Happily, all this remains true, if we drop the necessity of X to be a metric space, but assume it has a topology only, and define continuity in topological terms.  In order to convince you that topology is really nice and useful I would have to come up with at least one example of an interesting topological space that does not have a metric structure. Ay, there's the rub. The interesting examples I think of are not so easy after all (weak topologies of duals of non-separable linear spaces, Zariski topology on varieties.) Maybe someone else comes up with a striking example.


text:
Q: Storing and Displaying TextArea user inputs How can i handle user inputs with textarea, i need to strip user entered html tags, store text somewhere and display it back in a webpage.
I also need to take care about line breaks
Any best practices without using <pre> tag ?

A: You can always do a find-replace of \n with <br /> to preserve line breaks.
However, stripping html is a bit trickier. The easiest thing to do is replace < and > with < and >. But that doesn't actually strip the html, it merely forces it to render as plain text instead of html.
You could use a regex replace to remove <anything> but that has many potential pitfalls.

A: if you're using PHP, you can always use the nl2br() function to display the text back on the page.

A: I created a function called SafeComment designed to eliminate the problem characters from the input for SQL, javascript, HTML and VB. Since our sites and code are almost all VB & VB script. It's function is to allow any freeform input field to be successfully received, processed, saved and displayed. We needed it to maintain PCI compliance.
It's not pretty, but it works.
Function SafeComment(ByVal strInput)
' Renders Any Comment Codes Harmless And Leaves Them HTML readable In An eMail Or Web Page
' Try: SafeComment("`~!@#$%^&*()_+=-{}][|\'"";:<>?/.,")
    SafeComment = ""
    If Len(strInput) = 0 Then Exit Function
    SafeComment =   Replace( _
                    Replace(Replace(Replace( _
                    Replace(Replace(Replace( _
                    Replace(Replace(Replace( _
                    Replace(Replace(Replace( _
                    Server.HtmlEncode(Trim(strInput)), _
                    ":", ":"), "-", "-"), "|", "|"), _
                    "`", "`"), "(", "("), ")", ")"), _
                    "%", "%"), "^", "^"), """", """), _
                    "/", "/"), "*", "*"), "\", "\"), _
                    "'", "'")
End Function


text:
Q: numbered list inside alphabetical list I'm using \begin{enumerate}[label={\alph*)}] to create alphabetical lists in LaTeX. However, any nested enumerate-environment will inherent that property. How can I use the standard numbered lists inside alphabetical lists? How to change label back to the default value?
Thanks in advance :)

A: Use \arabic instead of \alph.


text:
Q: ayuda graficos Columnas Google Chart Estimado, necesito de sus conocimientos, tengo el siguiente problema, necesito quitar el nombre de cada columna pero si mostrar el Q de cada una de ellas, actualmente tengo esto

como pueden ver sale el Q en cada columna y tambien sale el nombre de cada supervisor, pero al ser muchos registros esto se visualiza de manera erronea, el codigo lo genero de la siguiente forma
google.charts.load("current", {packages:['corechart']});
      google.charts.setOnLoadCallback(drawCharts);
      function drawCharts() {
        var data = google.visualization.arrayToDataTable([
          ["Supervisor", "Cantidad", { role: "style" } ],
          <?php
            $sql ="SELECT count(nota) as cantidad, supervisor, fecha_respuesta
                    FROM feedback_nps
                     where site ='$empresa' and supervisor is not null and month(fecha_respuesta)=month(SYSDATE())-1 group by supervisor  order by cantidad desc;";
            $stmt=$db->query($sql);
            while($row = $stmt->fetch()){
              if ($row['supervisor']==$nombre) {
                echo " ['".$row['supervisor']."',".$row['cantidad'].",'blue' ],";
              }else{
                echo " ['".$row['supervisor']."',".$row['cantidad'].",'color: #e5e4e2' ],";
              }

            }
          ?>
        ]);

        var view = new google.visualization.DataView(data);
        view.setColumns([0, 1,
                         { calc: "stringify",
                           sourceColumn: 1,
                           type: "string",
                           role: "annotation" },
                         2]);

        var options = {
          title: "Detractores por Supervisor",
          width: 900,
          bar: {groupWidth: "70%"},

        };
        var chart = new google.visualization.ColumnChart(document.getElementById("top_x_div"));
        chart.draw(view, options);
      };

Me podrian ayudar a quitar ese valor?, ahora tengo otro grafico que esta generado de una manera diferente, pero no me sirve porque no logro mostrar el Q de cada columna

el cual tiene el siguiente codigo
 google.charts.load('current', {'packages':['bar']});
      google.charts.setOnLoadCallback(drawStuff);

      function drawStuff() {
        var data = new google.visualization.arrayToDataTable([
          ['Empresa', 'Cantidad'],
          <?php
            $sql ="SELECT count(nota) as cantidad, site
                    FROM feedback_nps where supervisor is not null and month(fecha_respuesta)=month(SYSDATE())-1 group by site  order by cantidad desc;";
            $stmt=$db->query($sql);
            while($row = $stmt->fetch()){
              echo " ['".$row['site']."',".$row['cantidad']." ],";
            }
          ?>
        ]);

        var options = {
          width: 900,
          legend: { position: 'none' },
          chart: {
            title: 'Detractores por Site' },
          hAxis: {
            maxTextLines: 10,
            textStyle: {
              fontSize: 12,
            }
          },
          bar: { groupWidth: "70%" }
        };

        var chart = new google.charts.Bar(document.getElementById('top_x_div'));
        // Convert the Classic options to Material options.
        chart.draw(data, google.charts.Bar.convertOptions(options));
      };

Existe alguna forma de mostrar el Q de cada columna sin tener que mostrar el nombre, espero ser claro en mi duda y como siempre un agradecido de sus conocimientos,
Saludos,


text:
Q: Too many open files - how to find the culprit When running tail -f filename, I got the following message:
tail: inotify cannot be used, reverting to polling: Too many open files

Is that a potential problem?
How do I diagnose what's responsible for all the open files? I have a list of suspect processes, but if they don't turn out to be the culprits, instructions that don't rely on knowing which process to check would be useful.

A: You can use lsof to understand who's opening so many files. Usually it's a (web)server that opens so many files, but lsof will surely help you identify the cause.
Once you understand who's the bad guy you can

*

*kill the process/stop the program

*raise the ulimit

If output from lsof is quite huge try redirecting it to a file and then open the file
Example (you might have to Ctrl+C the first command)
lsof > ~/Desktop/lsof.log
cat ~/Desktop/lsof.log | awk '{ print $2 " " $1; }' | sort -rn | uniq -c | sort -rn | head -20
vim ~/Desktop/lsof.log

A: While ulimit can be used to determine how many files are allowed to be open per process you may want to find the culprit.
@itsadok @Tyler Collier @gaoithe in comments to other answers highlight that sorting and counting which process has the most files open is the best thing to do here:
sudo lsof | head -1 | awk '{ print "COUNT " $2 " " $1; }' && sudo lsof +c 0 | awk '{ print $2 " " $1; }' | sort -rn | uniq -c | sort -rn | head -20
Above command:

*

*Gives output a header

*lsof gives list of open files

*+c 0 option instructs lsof to print full command

*awk '{ print $2 " " $1; }' prints PID and COMMAND column in results

*sort -rn sorts results so identical entries are next to each other (needed for uniq -c to work properly)

*uniq -c counts files open by PID/command

*sort -rn sorts results by count

*head -20 shows top 20 files open by PID/command

Note: This will count includes "files" that don't count towards limits
You may want to investigate even further by looking at limits for a PID, # of files open for a specific PID, and limit lsof to only count files that count towards limit - see https://serverfault.com/a/964752/152562.

A: In case anyone else needs it...
ulimit -a

Will display all current limits.  Specifically ulimit -n 70000 will set the file descriptor limit.
Also...
cat /proc/sys/fs/file-max

Will display/set the kernel limit if edited.
sudo echo 200000 > /proc/sys/fs/file-max

A much more detailed explanation can be found at...
How do I increase the open files limit for a non-root user?


text:
Q: Which mobile browsers support "connectionless push" as described in the EventSource specification? In the EventSource specification:
  http://www.w3.org/TR/eventsource
There is a section titled:  Connectionless push and other features
Does anyone know if this is actively developed / supported on applicable browsers?  If so who is leveraging this feature of the spec?

A: I reached out to Ian Hickson (author of the eventsource rfc).  He's given me permission to repost his answer here:

"I haven't heard of any implementations. That section was added by
  request from some network-associated handset vendors a few years ago.
  Since then, the landscape has changed quite a bit and networks and
  handset vendors don't work as closely together."


text:
Q: select a value from model in a dropdown using angularJS I am aware of questions similar to mine in stack. But the difference is that I have hardcoded the options for my dropdown in my controller and then I want the dropdown to display the value in the model by default.
HTML :

                            Rating*

                                <select ng-model="talent.rating"  validator="required" required-error-message="Rating is required" name="talent.rating" ng-options="obj.value as obj.text for obj in array"></select>

Controller :
myApp.controller('editTalentController', ['$scope', '$rootScope', 'talentResolved', 'accountResolved', 'talentServices', '$location', 'ngDialog', '$window',
    function ($scope, $rootScope, talentResolved, accountResolved, talentServices, $location, ngDialog, $window) {

        $scope.talent = talentResolved.data;
            $scope.array = [{ value: '1', text: '1' }, { value: '2', text: '2' }, { value: '3', text: '3' }, { value: '4', text: '4' }, { value: '5', text: '5' }];

   }]);

Model :
$scope.talent: Object
createdOn:    "2017-02-03T00:58:20.0999066"
employee    :    Object
fromAccount    :    Object
id    :130
inDate    :    "2017-02-01T05:30:00"
movedOutOfBench    :    false
outTill    :    "2017-05-02T05:30:00"
rating    :    2
remark    :    "asd"
resumePath    :    ""

What am I doing wrong? please provide me the code for a fix.

A: Found a resolution.
HTML:
 <select ng-model="talent.rating" convert-to-number>
                                    <option value="1">1</option>
                                    <option value="2">2</option>
                                    <option value="3">3</option>
                                    <option value="4">4</option>
                                    <option value="5">5</option>
                                </select>

Controller :
myApp.directive('convertToNumber', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function (val) {
                return val != null ? parseInt(val, 10) : null;
            });
            ngModel.$formatters.push(function (val) {
                return val != null ? '' + val : null;
            });
        }
    };
});

Even though i tried giving the values as numbers in array like :
$scope.array = [{ value: 1, text: '1' }, { value: 2, text: '2' }, { value: 3, text: '3' }, { value: 4, text: '4' }, { value: 5, text: '5' }];, angular was considering it as string. Don't know why.
When inspecting from console,it was like - https://hastebin.com/ugatisazey.vbs

The directive helped me fix the issue.


text:
Q: Trying to set up a zapier webhook to pabau CRM error I'm trying to set up a webhook with zapier to take leads from facebook forms, and pass them to my CRM system Pabau. I have set it up as instructed in this link - https://intercom.help/pabau/en/articles/3847411-create-lead-api
It's not passing the leads through, although facebook is working and integrated properly with full admin access and set up correctly with the crm added to the bm.
It's showing a fault code as api key error but there are no other options with Pabau to change this and I tried different keys.
Fault error.
I have tried everything and both zapier and pabau support teams cannot advise on the issue. any help would be greatly appreciated,
Many Thanks

A: Get Api_key

*

*create api key

*then give it the right premissions

and make sure to add the new created api key to post data on zapier weebhooks

request failed because api key is required
pabau docs


text:
Q: Add extra btn-group onclick As you can see, I have a button group. I'm trying to extend this functionality in such a way that when i click on any of the three buttons (left, middle or right), corresponding buttons (left-sub, middle-sub or right-sub) appears respectively as and when clicked:

        Left
        Left-Sub
        Middle
        Middle-Sub
        Right
        Right-Sub
        Right-Sub-2

I'm new to angularJS and can't seem to figure out how to go about this. Even if i  get a sample code to work on, it would be really helpful.

A: First you need to change the names of your ng-model, as they aren't legal with - in the key names.
Then you can just use ngIf:
    Right

    Right-Sub

    Right-Sub-2


text:
Q: How to create instance of multiple inherited class? I have this code:
class Person:
    def __init__(self, name, last_name, age):
        self.name = name
        self.last_name = last_name
        self.age = age

class Student(Person):
    def __init__(self, name, last_name, age, indexNr, notes):
        super().__init__(name, last_name, age)
        self.indexNr = indexNr
        self.notes = notes

class Employee(Person):
    def __init__(self, name, last_name, age, salary, position):
        super().__init__(name, last_name, age)
        self.salary = salary
        self.position = position

class WorkingStudent(Student, Employee):
    def __init__(self, name, last_name, age, indexNr, notes, salary, position):
        Student.__init__(name, last_name, age, indexNr, notes)
        Employee.__init__(name, last_name, age, salary, position)

I want to create a WorkingStudent instance like this:
ws = WorkingStudent("john", "brown", 18, 1, [1,2,3], 1000, 'Programmer')

but it's not working, I get this error:
TypeError: __init__() missing 1 required positional argument: 'notes'

Or what I am doing wrong here? Also, I have already tried super() in WorkingStudent class but it calls only the constructor of the first passed class. i.e in this case Student
Note: I have already gone through multiple StackOverflow queries but I couldn't find anything that could answer this. (or maybe I have missed).

A: Instead of explicit classes, use super() to pass arguments along the mro:
class Person:
    def __init__(self, name, last_name, age):
        self.name = name
        self.last_name = last_name
        self.age = age

class Student(Person):
    def __init__(self, name, last_name, age, indexNr, notes, salary, position):
        # since Employee comes after Student in the mro, pass its arguments using super
        super().__init__(name, last_name, age, salary, position)
        self.indexNr = indexNr
        self.notes = notes

class Employee(Person):
    def __init__(self, name, last_name, age, salary, position):
        super().__init__(name, last_name, age)
        self.salary = salary
        self.position = position

class WorkingStudent(Student, Employee):
    def __init__(self, name, last_name, age, indexNr, notes, salary, position):
        # pass all arguments along the mro
        super().__init__(name, last_name, age, indexNr, notes, salary, position)

# uses positional arguments
ws = WorkingStudent("john", "brown", 18, 1, [1,2,3], 1000, 'Programmer')
# then you can print stuff like
print(f"My name is {ws.name} {ws.last_name}. I'm a {ws.position} and I'm {ws.age} years old.")
# My name is john brown. I'm a Programmer and I'm 18 years old.

Check mro:
WorkingStudent.__mro__
(__main__.WorkingStudent,
 __main__.Student,
 __main__.Employee,
 __main__.Person,
 object)

When you create an instance of WorkingStudent, it's better if you pass keyword arguments so that you don't have to worry about messing up the order of arguments.
Since WorkingStudent defers the definition of attributes to parent classes, immediately pass all arguments up the hierarchy using super().__init__(**kwargs) since a child class doesn't need to know about the parameters it doesn't handle. The first parent class is Student, so self.IndexNr etc are defined there. The next parent class in the mro is Employee, so from Student, pass the remaining keyword arguments to it, using super().__init__(**kwargs) yet again. From Employee, define the attributes defined there and pass the rest along the mro (to Person) via super().__init__(**kwargs) yet again.
class Person:
    def __init__(self, name, last_name, age):
        self.name = name
        self.last_name = last_name
        self.age = age

class Student(Person):
    def __init__(self, indexNr, notes, **kwargs):
        # since Employee comes after Student in the mro, pass its arguments using super
        super().__init__(**kwargs)
        self.indexNr = indexNr
        self.notes = notes

class Employee(Person):
    def __init__(self, salary, position, **kwargs):
        super().__init__(**kwargs)
        self.salary = salary
        self.position = position

class WorkingStudent(Student, Employee):
    def __init__(self, **kwargs):
        # pass all arguments along the mro
        super().__init__(**kwargs)

# keyword arguments (not positional arguments like the case above)
ws = WorkingStudent(name="john", last_name="brown", age=18, indexNr=1, notes=[1,2,3], salary=1000, position='Programmer')

A: Problem: we have a lot of arguments for our most derived class, that need to be used to initialize all the bases. However, in Python's multiple inheritance system with super(), the class that will be initialized next depends on an MRO (method resolution order) that may have been determined in another class. Therefore, when we use multiple inheritance, we don't know which class will have its __init__ called when we use super().
Solution: use consistent names for the parameters, and then take advantage of **kwargs, so that each class takes in the (explicitly named) parameters it cares about, and forwards the rest.
That looks like:
class Person:
    def __init__(self, name, last_name, age):
        self.name = name
        self.last_name = last_name
        self.age = age

class Student(Person):
    def __init__(self, indexNr, notes, **kwargs):
        super().__init__(**kwargs)
        self.indexNr = indexNr
        self.notes = notes

class Employee(Person):
    def __init__(self, salary, position, **kwargs):
        super().__init__(**kwargs)
        self.salary = salary
        self.position = position

class WorkingStudent(Student, Employee):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

Forcing the client code to use keyword arguments is more work for the clients, but it also helps guard against errors from mistaking the order of positional arguments.

A: This is the easiest way to reach your goal.
If your WorkingStudent class inherite Student and Employee class like this ,
class WorkingStudent(Student, Employee):
    def __init__(self, name, last_name, age, indexNr, notes, salary, position):
        Student.__init__(self, name, last_name, age, indexNr, notes)
        Employee.__init__(self, name, last_name, age, salary, position)

ws = WorkingStudent("john", "brown", 18, 1, [1, 2, 3], 1000, 'Programmer')
print(ws)
print(ws.name)
print(ws.age)

your output will be...
Output:

<main.WorkingStudent object at 0x7fc6c4d8ba10>
john
18
[1, 2, 3]


text:
Q: How do I create an HTML Email (Not Text) Verification Template in Parse I see where to edit the Email verification template in Parse, but if I add HTML to the field it is still sent as a text email (Not HTML as I would like) and therefore it is not displayed properly on the client end.  Does anyone know how/if I can create HTML emails for the verification template in Parse? The documentation states HTML can be used for Pro accounts, but there are no more pro accounts... So this doesn't make sense and I don't see how to do it.  Any help would be appreciated.

A: VERY uncool of Parse but - since 2012 - only the Paid accounts have access to customize the Email Verification templates... :(
Express Your Brand With Parse


text:
Q: Adding a css Button to php/HTML I was wondering if it is possible to use a button instead of a link in php?
Here is the code I have.
<?php echo "View and Download Spec Sheet .PDF ";?>

I was looking to simply add a button instead of having text.
Thank you!

A: How about:
<?php echo "<form target ='_blank' action='$prefix/$filename'><button>View and Download Spec Sheet .PDF </button></form>";?>

A: Try this:
<form>
<?php echo "<input type='button' value='your button text' onClick='window.location.href=(/"Your download location/",/"_blank/")'></input>"?>
</form>

Hope it helps!
You can add css to your button here.

A: Just put a button inside the  tags like this. This question should really be an HTML question though not a PHP question.
<?php echo "View and Download Spec Sheet .PDF "; ?>


text:
Q: Is UILabel the best way to display a simple vertical bar graph in iOS? I need to display several vertical bar graphs, side by side, on an iPhone.
The graphs may be different, simple colors (red, green, yellow).
The length of each graph may vary.
I'll be updating no more often than once a second.
I'm planning to use UILabel for each bar graph, because that's the way I did it as an iOS newbie several years ago.  It was simple and looked great.
Is there a faster/better way in iOS?
Perhaps using animation tools?

A: Personally, I don't see what a bar graph has to do with UILabel at all. I'd use rectangular layers or views (either of which could easily be animated as the graph changes), or even just draw the bar graph in code.


text:
Q: Как дождаться выполнения условия promise? Есть promise и мне нужно дождаться, когда выполниться условие: элемент a существует, но когда его нет в консоль выводиться Promise {pending}, но он так и не дожидается, когда кнопка станет зелёной, почему? Как сделать так чтобы Promise ждал когда элемент a будет существовать?
    'use strict';
    const a =  document.querySelector('[data-style="JoinToBattleComponentStyle-buttonJoinA JoinToBattleComponentStyle-buttonJoin"]'); //експорт 1 кнопки
    const join = document.querySelector('[data-style="DialogContainerComponentStyle-enterButton"]')//кнопка которая нажимаеться когда нажались какиет-то из двух
    const b = document.querySelector('[data-style="JoinToBattleComponentStyle-buttonJoinB JoinToBattleComponentStyle-buttonJoin"]')//експорт 2 кнопки
    const req1 = new Promise(function(resolve){//проверя существует ли кнопка А аж тогда я виполню resolve так же и b
    if(a){
        resolve()
    }
    })
    const req2 = new Promise(function(resolve){
        if(b){
            resolve()
        }
        })
    const req3 = new Promise(function(resolve){
        if(join){
            resolve()//здесь когда нажата или кнока а или б тогда здесь нажимеиться
        }
    })

    req1.then(()=>{
            a.click()
    })
    req2.then(()=>{
        b.click()
    });
    req3.then(()=>{
        join.click(
        )
    });
[![введите сюда описание изображения][1]][1]

A: Промисы нужны для асинхронных вызовов.
Попробуй написать функцию, в которой будут условия проверки твоих классов.
И запусти ее через setInterval.(не ставь слишком маленький интервал)
Функция будет раз в интервал проверять существуют твои классы на элементах или нет.
Если я не прав- поправьте
П.С. читать тяжело твое сообщение
у тебя же промис создается, сразу отрабатывает if, реджектится с ошибкой и дальше не идет

A: Вам нужно проверять наличие элемента постоянно с каким-то интервалом. И нужно каждый раз заново вызывать querySelector(), потому что переменная a не будет обновляться автоматически при появлении элемента.
const selectorA = '[data-style="JoinToBattleComponentStyle-buttonJoinA JoinToBattleComponentStyle-buttonJoin"]';

const req1 = new Promise(function(resolve){
  const interval = setInterval(() => {
    if(document.querySelector(selectorA)){
      clearInterval(interval);
      resolve();
    }
  }, 1000);
});

req1.then(()=>{
  document.querySelector(selectorA).click();
});


text:
Q: How to check an Android device is HDPI or MDPI without extending Activity in class? I have one class which does not extends any Activity. i want to find out that user uses LDPI,MDPI,HDPI or XHDPI screen using code. any idea? I have used DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics); but it needs an Activity to extend. i want that without extending activity.

A: The problem with window manager is that it needs the activity context, read the name again window manager it manages stuff on the scree, ergo, the activity.
There're some different tricks you can try:
You will need the context for this solution, but it doesn't have to be the activity context, it can be the application context. Actually, to be honest you'll need the resources, which can be accessed through the application context.
on your res folder create a value.xml for the all the parameters you want to find out:
  // res
      |- values-hdpi
             |- values.xml
      |- values-ldpi
              |- values.xml
      |- values-mdpi
              |- values.xml
      |- values-xhdpi
              |- values.xml

now on each one of those xml you put the following code:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <item name="is_ldpi" format="boolean" type="bool">true</item>
    <item name="is_hdpi" format="boolean" type="bool">false</item>
    <item name="is_mdpi" format="boolean" type="bool">false</item>
    <item name="is_xhdpi" format="boolean" type="bool">false</item>

</resources>

only changing the true or false as appropriate.
now it's just as simple as calling:
  boolean is_hdpi = context.getResources().getBoolean(R.bool.is_hdpi);


text:
Q: Separar elementos de uma array para consulta com sequelize Esse id_mensagem eu envio por parametro por minha requisiçao, um console.log nisso me retorna o valor da imagem.
const id_mensagem = [...new Set(response.data.map(mensagens => mensagens.id_mensagem))]

no meu back eu recebo essa info dessa forma:
const {id_mensagem}  = req.params

um console.log me retorna 423,421,422.
Porém preciso passar esse valor entre colchetes para uma consulta no banco de dados, código da consulta:
const mensagens = await Mensagens.findAll({
    where:{
        id_mensagem:{
            [Op.in]:[id_mensagem]
        }
    },
    order: [['created_at','DESC']],

})

e ai vem o problema, estou usando sequelize nesse caso e quando ele faz a query e ele busca somente os primeiros números antes da virgula, um console.log([id_mensagem]) me retorna dessa forma:

entendo que por estar envolto em aspas o codigo esta ignorando o que vem depois da primeira virgula, enfim como transformar isso ['423,421,422'] em números separados para consulta!
ex: [423,421,422].

A: Provavelmente você está recebendo como uma string "423,421,422". Então seria necessário fazer um split nela pra poder separar os valores num array:
const array = id_mensagem.split(',')

A: Na sua consulta, tente enviar a mensagem de resposta como um JSON, por exemplo:
res.send({id_mensagem: id_mensagem});

Que dessa forma ele enviará cada id_mensagem como um objeto e aí vc pode acessar o conteúdo de cada um pelo front assim:
response.data.id_mensagem

Acessando cada item separadamente e depois poder fazer o map.
Espero ter ajudado!


text:
Q: Need help fixing a permission error when launching another Activity in a differnt app Okay Both apps are mine so I can change code in either app.  Currently App B hasn't been modified in any way and is just a regular stand alone app.
App A goes to call App B using this code:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("net.pawworks.NurseTorando","net.pawworks.NurseTorando.lung"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
I do got it in a catch block for ActivityNotFoundException and deal with that one.
but when that exception doesn't happen I get a this permission denied error
there is an activity in the net.pawworks.NurseTorando app that is named lung it's not the one that first comes up if you launch it stand alone. but it's the one i want it to start with when called from app A.
this is the error I get:
07-07 08:47:47.624: ERROR/AndroidRuntime(11129): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.MAIN flg=0x10000000 cmp=net.pawworks.NurseTorando/.lung } from ProcessRecord{484bc180 11129:net.pawworks.emergency/10123} (pid=11129, uid=10123) requires null
I can modify the 2nd app, but I still want it to start on a different screen then this when launched by itself.  how can I fix this?

A: Add the following intent filter in the manifest file under the Activity tag (which one you are starting) in AndroidManifest.xml:
OR check if you are having two entries for that activity in your manifest file.
You can refer same posts over here:
Android: java.lang.SecurityException: Permission Denial: start Intent
HelloWebView Sample: java.lang.SecurityException: Permission Denial

A: I'm not sure I fully understand what the problem is, but have you tried editing the AndroidManifest.xml file to give your applications the proper permissions it needs to run? There are a large variety of things you need permission to do on Android and that is the place to make that happen.


text:
Q: Restarting Parallel Stages in Jenkins I am currently trying to build a Jenkins pipeline that uses multiple parallel steps. The entire execution is as intended, but I am not able to restart a particular stage once I branch into parallel stages.
For example in the below pipeline I want to restart only Stage D2 after the build is complete. But I am getting an option to restart the entire "stage Parallel", but no option to restart the individual stages inside 'stage Parallel'.
Is there any way to restart from an intermediate stage within a parallel stage?
Jenkins pipeline image
pipeline
{
    agent any
    stages {
        stage('Stage A') {
            agent any
            steps {
                sh """#!/bin/csh
                echo "Currently running A"
                """
                }
        }
        stage('Stage B') {
            agent any
            steps {
                sh """#!/bin/csh
                echo "Currently running B"
                """
                }
            }
        stage('Stage parallel') {
            parallel {
                stage('Stage C') {
                stages {
                    stage('Stage C_1') {
                        steps {
                        sh """#!/bin/csh
                        echo "Currently running C1"
                        """
                        }
                    }
                    stage('Stage C_2') {
                        steps {
                        sh """#!/bin/csh
                        echo "Currently running C2"
                        """
                        }
                    }
                }
                }
                stage ('Stage D') {
                    stages {
                        stage ('Stage D_1') {
                        steps {
                        sh """#!/bin/csh
                        echo "Currently running D1"
                        """
                        }
                    }
                        stage ('Stage D_2') {
                        steps {
                        sh """#!/bin/csh
                        echo "Currently running D2"
                        """
                            }
                    }
                        stage ('Stage D_3') {
                        steps {
                        sh """#!/bin/csh
                        echo "Currently running D3"
                        exit 1
                        """
                            }
                        }
                    }
                }
            }
        }
    }
}


text:
Q: Use of Pagination and MySQL queries We have using the pagination 123 buttons, here if we click next button also means it should go to the next page. But here it doesnt go to the next page because here im passing the _POST variable in sql query to the where conditions so if click the next page it doesnt show the relevant page.
we think the POST variable value doesn't updated after when we click other pages. here is my Code. Thanks in advance.
if(isset($_POST['submit']))
 {
  $bool = true;
  $gender=$_POST['gender'];
 }

 if(($bool == true)
 {

   $bool1=true;
   $connection = mysql_connect("localhost","root","Sakthi");
  if (!$connection)
  {
   die('Could not connect: ' . mysql_error());
  }
  mysql_select_db("nursingcarein",$connection);

  if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; };
  $start_from = ($page-1) * 3;

  $gender1=$gender;
  $profession1=$profession;
  $state1=$state;

  /**** Here gender value doesnt update when click the next page i think we have a error in this query ****/
  $sql = "SELECT id,description,name FROM nursereg WHERE gender='$gender1' LIMIT     $start_from, 3";

  $rs_result = mysql_query ($sql,$connection);
  echo "

Image	Description
";
   while($row=mysql_fetch_array($rs_result)) {
    echo"
";
        echo""; echo ""; echo"	";
        echo""; echo  $row['name']; echo"	";
        echo""; echo  $row['description']; echo"	";
        echo"
";
     };
  echo"
";
  $sql = "SELECT COUNT(Name) FROM nursereg";
 $rs_result = mysql_query($sql,$connection);
  $row = mysql_fetch_row($rs_result);
  $total_records = $row[0];
  $total_pages = ceil($total_records / 5);
 for ($i=1; $i<=$total_pages; $i++) {
   $pageno = $i;
       echo "".$i." ";
     };
 };

 ?>

A: You pagination uses a href, this does not invoke a POST as your code suggests
$gender1=$_POST['gender'];

Try to add the gender to the pagination and fetch via GET
echo "".$i." ";

And then in your code
$gender1 = isset($_POST['gender']) ? $_POST['gender'] : $_GET['gender'];


text:
Q: Does sessionAffinity over ClientIP works with UDP protocol on Kubernetes setup? lets say, we have two independent Kubernetes clusters Cluster 1 & Cluster 2 , Each of them has two replicas of same application Pod. Like
Cluster 1 : Pod A & Pod B
Cluster 2 : Pod C & Pod D
Application code in Pod A(client) wants to connect to any Pod running in cluster 2 via NodePort/Loadbalancer service over UDP protocol to send messages. The only requirement is, to maintain affinity so that all messages from Pod A should go to any one pod only (either Pod C or Pod D). Since, UDP is a connectionless protocol, my concern is around the session Affinity based on ClientIP. Should setting the sessionAffinity as client IP solve my issue ?

A:
Since, UDP is a connectionless protocol, my concern is around the session Affinity based on ClientIP. Should setting the sessionAffinity as client IP solve my issue ?

sessionAffinity keeps each session based on sourceIP regardless of the protocols at the same cluster. But it does not mean your real session is kept as you expected on your env across your whole access path journey.
In other words, just only using sessionAffinity does not ensure keeping whole session on your access paths.
For example, Pod A outbound IP is translated as running node IP(SNAT) if you does not use egress IP solutions for the Pod A.
It also depends your NodePort and LoadBalancer Service config about source IP in cluster 2. Refer Using Source IP for more details.
So you should consider how to keep session safely while accessing each other between other clusters. Personally I think you had better consider application layer(7Layer) sticky session for keeping the session, not sessionAffinity of the service.


text:
Q: div sidebar error correction in php paging Wrapper
center div
sidebar div
when click "sidste" button that are the last page in php paging.
Sidebar div content moves under center div.

The webpage is responsive but navigation is giving this error problem.
Where can the problem be?
css:

.wrapper
     margin-right: auto;
     margin-left:  auto;
     width: 100%;
     max-width: 1280px;
     padding-right: 10px;
     padding-left:  10px;
     overflow: hidden;

   .divcenter
    float: left;
    width: 70%;
    margin-bottom:3px;
    padding: 1.25em;
    word-wrap: break-word;
    margin: 0 auto;
    clear:both;
    border:3px solid  #ccc;
    margin-left:110px;

   .divrightsidebar
    float:right;
    width: 30%;
    margin:0px;
    margin-bottom:3px;
    padding: 1.25em;
    word-wrap: break-word
    margin: 0 auto;


text:
Q: If row doesn't exist in datareader The data reader named eventreader can be empty and i'm trying to work out an appropriate statement to detect if the datareader contains rows and if the require record exists.
oledbexecute("SELECT [Unit No] FROM UnitOpenAtEvent WHERE [Event ID]='" + strDate + "'");
            eventReader = dbcommand.ExecuteReader();
            for (int i = 0; i < checkboxEvent.Items.Count; i++)
            {
                if (checkboxEvent.GetItemCheckState(i) == CheckState.Checked)
                {
                    if (eventReader["Unit No"] != DBNull.Value)
                    {
                        while (eventReader.Read())
                        {
                            if (eventReader["Unit No"].ToString() == checkboxEvent.Items[i].ToString())
                            {
                                oledbexecute("INSERT INTO UnitOpenAtEvent ([Event ID],[Unit No]) VALUES ('" + strDate + checkboxEvent.Items[i].ToString() + "'");
                                intReader = dbcommand.ExecuteNonQuery();
                            }
                        }
                    }
                    else
                    {
                        oledbexecute("INSERT INTO UnitOpenAtEvent ([Event ID],[Unit No]) VALUES ('" + strDate + checkboxEvent.Items[i].ToString() + "'");
                        intReader = dbcommand.ExecuteNonQuery();
                    }
                }
                else if (checkboxEvent.GetItemCheckState(i) == CheckState.Unchecked)
                {

                   // this is effectively a copy of above
                 }
            }

A: You can check if the DataReader has any rows using e.g.
if (eventReader.HasRows)

Update:
Following from comment below re: IDataReader...
You could do something like this (shortened to include the most relevant bits for conciseness)
eventReader = dbcommand.ExecuteReader();
bool hasRow = eventReader.Read();
if (hasRow)
{
    for (int i = 0; i < checkboxEvent.Items.Count; i++)
    {
        ...
            ...
            while (hasRow)
            {
                // Code in here to deal with each row
                hasRow = eventReader.Read();
            }
    }
}

A: You may be misunderstanding how IDataReader.Read() works.
From that help page:
Return Value
Type: System.Boolean
true if there are more rows; otherwise, false.

and

The default position of the IDataReader is prior to the first record.
  Therefore you must call Read to begin accessing any data.

So when you first get a datareader it won't be pointing to any data. If you call .Read() it will return true if there is a row to move to and move to it and if there are no rows it will return false.


text:
Q: SQL select default parameter I have a table with columns like name, age, email etc. For some columns I also have parameters to control the behaviour of queries. I want to show the column's value if the corresponding parameter has the value 0. If that parameter has value 1 I don't want to show that column.
For example, if I have data
name  age  show_email  email
abc,  22   1           abc@gmail.com  -- parameter = 1 do not show this value
def,  33   0           def@gmail.com  -- parameter = 0 => show this value

Then output of select name, age, email from MyTable1 will be
name  age  email
abc,  22   NULL          -- NULL because of parameter value.
def,  33   def@gmail.com

A: Use the case statement
select name, age,
 case show_email when 0 then email else null end
from my_table;

A: select name, age,
       IF(show_email, email, NULL) AS email
    from my_table;


text:
Q: ReactJS BootstrapTable with pagination does not work with ExportCSV I am using ReactJS BootstrapTable with pagination.  Works great, but my users want the ability to export the data on the table to Excel spreadsheet.  I integrated the Bootstrap ExportCSV ToolkitProvider. It only works if I don't have pagination.
<ToolkitProvider
              keyField="id"
              data={ products}
              columns={ columns }
              exportCSV
            >
              {
                props => (

                    <ExportCSVButton { ...props.csvProps }>Export CSV!!</ExportCSVButton>

                    <BootstrapTable { ...props.baseProps } noDataIndication={ noDataFunction } />

                )
              }
            </ToolkitProvider>

When I added pagination, I get this error:
csv.js:120 Uncaught TypeError: Cannot read property 'get' of null
    at u.handleExportCSV (csv.js:120)
    at onClick (button.js:57)
    at Object.<anonymous> (react-dom.production.min.js:49)
    at p (react-dom.production.min.js:69)
    at react-dom.production.min.js:73
    at C (react-dom.production.min.js:140)
    at P (react-dom.production.min.js:169)
    at T (react-dom.production.min.js:158)
    at N (react-dom.production.min.js:232)
    at On (react-dom.production.min.js:1718)

Here is my code with pagination:
<ToolkitProvider
              keyField="id"
              data={ products}
              columns={ columns }
              exportCSV
            >
              {
                props => (

                    <ExportCSVButton { ...props.csvProps }>Export CSV!!</ExportCSVButton>

                    <PaginationProvider pagination={ paginationFactory(paginationOption) }>
                    {
                      ({
                        paginationProps,
                        paginationTableProps
                      }) => (

                                <BootstrapTable headerClass={ headerClass }
                                  noDataIndication={ noDataFunction }

                                  striped
                                  hover
                                  keyField='id'
                                  data={ products}
                                  columns={ columns }
                                  filter={ filterFactory() }
                                { ...paginationTableProps }
                                />

                                {paginationProps.dataSize > 0 &&
                                    <PaginationListStandalone { ...paginationProps  } />
                                }
                                {paginationProps.dataSize > 0 &&
                                    <SizePerPageDropdownStandalone { ...paginationProps } />
                                }

                                { paginationProps.dataSize > 0 &&
                                    <PaginationTotalStandalone { ...paginationProps } />
                                }

                      )
                    }
                </PaginationProvider>

                )
              }
            </ToolkitProvider>

A: Please check your imports.These are the necessary imports
import ToolkitProvider, {  CSVExport } from 'react-bootstrap-table2-toolkit';

import paginationFactory from 'react-bootstrap-table2-paginator';

const { ExportCSVButton } = CSVExport;

Also instead of PaginationProvider
you can also put props to
<BootstrapTable pagination={paginationFactory()} >


text:
Q: dynamically create classes with sass Can I use sass and a loop to create the following:
.m-t-0 {
    margin-top: 0px !important;
}

.m-t-1 {
    margin-top: 1px !important;
}

.m-t-2 {
    margin-top: 2px !important;
}

.m-t-3 {
    margin-top: 3px !important;
}

.m-t-4 {
    margin-top: 4px !important;
}

.m-t-5 {
    margin-top: 5px !important;
}

.m-t-6 {
    margin-top: 6px !important;
}

A: This is this first result you get when you search for 'sass loop' on Google. Here's what we have for the @for section of the referenced page:
@for $i from 1 through 4
  .#{$class-slug}-#{$i}
    width: 60px + $i

Once adapted to the example you provided, you get this:
@for $i from 0 through 6
  .m-t-#{$i}
    margin-top: 1px * $i !important


text:
Q: How to use QXmpp server_example? I've compiled Qxmpp server_example successfully, but yet dunno
how to connect a client to that server - Example from Qxmpp library. Can anybody suggest smth, I'll be grateful for that stuff.

A: Do you have an XMPP server that you can connect to? You can setup one locally by using one of these servers: http://xmpp.org/xmpp-software/servers/
Ideally, you'd want to have two instances of the client software on two different physical machines/virtual machines so you can test that the messaging works between two users.


text:
Q: How do I export the point cloud test data on the validation set? I am using the point nets code for my own dataset and they do have an output but it's only ever for 8 random data pieces. How do I take this code and export all of the datasets after the validation set goes through the model? (I do not need the images of the point cloud itself) an example of output would be just like an excel file with the prediction label versus the actual label but of the whole validation set not just the 8.
This is the code:
history = model.fit(train_dataset, epochs=num_epocs, validation_data=test_dataset)

#################################################
########## Visualizing the predictions ##########
#################################################
data = test_dataset.take(1)

points, labels = list(data)[0]
points = points[:8, ...]
labels = labels[:8, ...]

# run test data through model
preds = model.predict(points)
preds = tf.math.argmax(preds, -1)
points = points.numpy()

### plot points with predicted class and label
fig = plt.figure(figsize=(10, 15))
for i in range(8):
    ax = fig.add_subplot(2, 4, i + 1, projection="3d")
    ax.scatter(points[i, :, 0], points[i, :, 1], points[i, :, 2])
    ax.set_title(
        "pred: {:}, label: {:}".format(
            CLASS_MAP[preds[i].numpy()], CLASS_MAP[labels.numpy()[i]]
        )
    )
    ax.set_axis_off()
plt.show()


text:
Q: How to use and display PagedResultDto Using ASPNet Boilerplate, and returning a pagedResultSetDto with the below code, how do I display the page links?
 public PagedResultDto<ArticleDto> GetAll()
    {
        var articleCount = articleRepository.Count();

        var t = articleRepository.GetAllIncluding(x => x.articleImage).Include(x => x.Category).Where(
                x => x.PublishFrom <= DateTime.Now &&
                x.PublishTo >= DateTime.Now &&
                 x.Status == PostStatus.Published &&
                 x.IsDeleted == false
                ).OrderByDescending(x=> x.PublishFrom).ToList();

        return new PagedResultDto<ArticleDto>
        {
            TotalCount = articleCount,
            Items = t.MapTo<List<ArticleDto>>()
        };
    }

A: First, take in IPagedResultRequest as input:
// using Abp.Linq.Extensions;

public PagedResultDto<ArticleDto> GetAll(PagedResultRequestDto input)
{
    var articleCount = articleRepository.Count();

    var t = articleRepository
            .GetAllIncluding(x => x.articleImage)
            .Include(x => x.Category)
            .Where(x =>
                x.PublishFrom <= DateTime.Now &&
                x.PublishTo >= DateTime.Now &&
                x.Status == PostStatus.Published &&
                x.IsDeleted == false
            )
            .OrderByDescending(x => x.PublishFrom)
            .PageBy(input) // Page by SkipCount and MaxResultCount
            .ToList();

    return new PagedResultDto<ArticleDto>
    {
        TotalCount = articleCount,
        Items = t.MapTo<List<ArticleDto>>()
    };
}

Then create your own links to pass in SkipCount, e.g. GetAll?SkipCount=10 for page 2.
MaxResultCount has a default value of 10.

A: You can calculate it according to the result of GetAll().
You request how many records you want. Let's say 10 (default value).
It returns TotalCount and Items (=records). Let's say TotalCount = 95. Divide 95/10 = 9.5 ~=> 10 pages. Show 10 links. While 9 pages will show 10 records, last page will have 5 records. That