SocketTimeout Exception When calling a webservice

Question: I am using a webservice in my application using android v4.0.3, but when i reached at
HttpTransportse Shows SocketTimeoutException and not getting response.The same code working perfectly in android.v.2.2
I got the following Exception  in logcat
05-10 11:18:38.245: W/System.err(849): java.net.SocketTimeoutException
05-10 11:18:38.255: W/System.err(849):  at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:130)

KSoap jar
---------
KSoap2 library android:2.5.2.jar

here is the code
public class busTravellDetailslistActivity extends Activity {
/** Called when the activity is first created. */
Button b;
EditText rteid,trvname,bustyp,deptm,arvtm;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    b=(Button) findViewById(R.id.button1);
    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            SoapObject request = new SoapObject("http://***********/WS2","TestRouteDataMobile");
                //System.out.println("req count:"+request.getPropertyCount());
            SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);

              envelope.setOutputSoapObject(request);

              HttpTransportSE transport = new HttpTransportSE("http://**********/RouteSearchService.asmx");//namespace
                try {

                    transport.call("http://***********/TestRouteDataMobile",envelope);
                    System.out.println("aftr call");
                } catch (SocketTimeoutException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                    SoapObject response;
                    try {
                        response = (SoapObject)(envelope.getResponse());

                        Log.i("Response",response.toString());

                    } catch (SoapFault e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

            // TODO Auto-generated method stub

                }
    });
    }
}

Comment: ok got it , I had same problem, Just you need to clean the variables after response.
Comment: I got answer  when i run from the project and there itself asking in which emulutor have to run.But when i made change the emulator from properties and androidmanifest,the same exception showing..why it is happening like this??or is any problem what i had done??
Comment: did you build and clean after changes ?
Comment: I did the same,but still have..
Comment: need a solution frm anybody else..
Comment: can you please upload the code , after the changes you made
Answer: I spent almost 2-3 hours to fix this problem and the solution was very easy. This problem comes when either you are accessing web service at wrong IP or Service has some problems. But except these two there is one thing you need to be caution which is if web service is hosted at Http then you should use HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); and if your web service is at https, then use HttpsTransportSE aht = new KeepAliveHttpsTransportSE(IP, 443,SERVICEPATH, 25000);. I hope would help you.


Counterexamples to the Grothendieck group of a commutative monoid respecting tensor products

Question: $\newcommand{\Q}{\mathbb{Q}}\newcommand{\N}{\mathbb{N}}\newcommand{\Z}{\mathbb{Z}}$Recall the definitions of the tensor product $\otimes_{\mathbb{N}}$ of commutative monoids (see also this note by Harold Simmons) and of the Grothendieck group $K_0$ of a commutative monoid (see also wikipedia). Given commutative monoids $A$ and $B$, we can apply the universal property of $K_0$ to the diagram

to get a morphism of abelian groups
$$K^{\otimes}_{0|A,B}\colon K_{0}(A\otimes_{\mathbb{N}}B)\to K_{0}(A)\otimes_{\mathbb{Z}}K_{0}(B).$$
Since we also have an isomorphism $K^{\otimes,1}_{0}\colon K_{0}(\mathbb{N})\overset{\sim}{\dashrightarrow}\mathbb{Z}$, these morphisms endow $K_{0}$ with the structure of an oplax monoidal functor
$$
                (K_{0},K^{\otimes}_{0},K^{\otimes,1}_{0})
                \colon
                (\mathsf{CMon},\otimes_{\mathbb{N}},\mathbb{N})
                \longrightarrow
                (\mathsf{Ab},\otimes_{\mathbb{Z}},\mathbb{Z}).
$$
(I think―I haven't actually checked the coherence conditions.)
Now, I'm quite confident that the map $K^\otimes_{0|A,B}$ is not always an isomorphism, so I'm trying to come up with a counterexample. Am I correct in thinking that $A=B=(\mathbb{Z},\cdot,1)$ is such an example?
On one side, we have $\mathbb{Z}\otimes_{\mathbb{N}}\mathbb{Z}\overset{\text{i think?}}{\cong}\Z\oplus\Z_{2}$, so
\begin{align*}
K_0(\Z\otimes_{\N}\Z) &\cong K_0(\Z\oplus\Z_2)\\
                      &\cong K_0(\Z)\oplus K_{0}(\Z_2)\\
                      &\cong \Q\oplus\Z_2,
\end{align*}
(where we've used the strong monoidality of $K_0$ with respect to direct sum), while on the other we have
\begin{align*}
K_0(\Z)\otimes_{\Z}K_0(\Z) &\cong \Q\otimes_{\Z}\Q\\
                           &\cong \Q
\end{align*}
(via here). Thus
$$K_0(\Z\otimes_{\N}\Z)\cong\Q\oplus\Z_2\neq\Q\cong K_0(\Z)\otimes_{\Z}K_0(\Z).$$

Question
Are the above calculations correct? Moreover, what are some other examples (assuming this is indeed one >_<) of commutative monoids $A$ and $B$ such that the map $K_{0}(A\otimes_{\mathbb{N}}B)\to K_{0}(A)\otimes_{\mathbb{Z}}K_{0}(B)$ is not an isomorphism?
Comment: (Note that [this question](https://math.stackexchange.com/questions/3084985) is quite similar to mine, but different)
Comment: I don't know where you're getting $\mathbb{Z}\otimes_\mathbb{N}\mathbb{Z}\cong\mathbb{Z}\oplus\mathbb{Z}_2$ from.  In any case, all the Grothendieck groups in your example are going to be trivial since you are inverting *every* element, including $0$, and inverting $0$ kills everything.
Answer: In fact, the canonical map $K_{0}(A\otimes_{\mathbb{N}}B)\to K_{0}(A)\otimes_{\mathbb{Z}}K_{0}(B)$ is always an isomorphism.  One way to see this is by observing that if $M$ is a commutative monoid then $K_0(M)$ is naturally isomorphic to $\mathbb{Z}\otimes_{\mathbb{N}} M$ (where here $\mathbb{Z}$ is the additive monoid).  You can prove this, for instance, by verifying that bilinear maps $\mu:\mathbb{Z}\times M\to N$ are in natural bijection with homomorphisms $f:M\to N$ that send each element of $M$ to an invertible element (by defining $\mu(a,m)=af(m)$ in one direction and defining $f(m)=\mu(1,m)$ in the other direction).
So, $$K_0(A\otimes_\mathbb{N} B)\cong \mathbb{Z}\otimes_\mathbb{N} A\otimes_{\mathbb{N}} B\cong (\mathbb{Z}\otimes_\mathbb{N}\mathbb{Z})\otimes_\mathbb{N} A\otimes_{\mathbb{N}} B\cong (\mathbb{Z}\otimes_\mathbb{N} A)\otimes_\mathbb{N}(\mathbb{Z}\otimes_\mathbb{N} B)\cong K_0(A)\otimes_\mathbb{N} K_0(B).$$  Since $\otimes_\mathbb{N}$ is the same as $\otimes_\mathbb{Z}$ when applied to commutative monoids that are actually already groups, this gives an isomorphism $K_{0}(A\otimes_{\mathbb{N}}B)\to K_{0}(A)\otimes_{\mathbb{Z}}K_{0}(B)$.  It is then a matter of definition-chasing to confirm that this isomorphism is the same as the map you are considering (for instance, by verifying that they both send elements of the form $[a\otimes b]$ (which generate the group $K_{0}(A\otimes_{\mathbb{N}}B)$) to $[a]\otimes [b]$)).
There are several errors in your proposed example.  I'm not sure how you got that $\mathbb{Z}\otimes_\mathbb{N}\mathbb{Z}\cong\mathbb{Z}\oplus\mathbb{Z}_2$; this does not seem correct since (for instance) the elements $p\otimes -1$ should be distinct invertible elements of $\mathbb{Z}\otimes_\mathbb{N}\mathbb{Z}$ for each prime $p$ whereas $\mathbb{Z}\oplus\mathbb{Z}_2$ has only finitely many invertible elements (assuming you mean the $\mathbb{Z}$ there to still be the multiplicative monoid).  Also, $K_0(\mathbb{Z})=0$, not $\mathbb{Q}$, since adjoining an inverse to $0$ kills everything ($0\cdot x=0$ implies $x=1$ if $0$ becomes invertible).
Comment: 1) Eh, $p$ probably doesn't need to be prime.  I was just thinking about primes specifically since they're the free generators of $\mathbb{Z}\setminus\{0\}$. 2) Yes, that's correct.
Comment: 3) I don't know the exact description.  If you removed $0$ from both copies of $\mathbb{Z}$ then they would each be isomorphic to a direct sum of countably many copies of $\mathbb{N}$ and one copy of $\mathbb{Z}_2$.  When you tensor these together you get countably many copies of each of $\mathbb{N}$ and $\mathbb{Z}_2$ since tensor products distribute over direct sums.  But then to actually get $\mathbb{Z}\otimes_\mathbb{N}\mathbb{Z}$, you have to add back in all the elements and relations you get by including $0$.  I don't know a clean description of the result of that.
Comment: I believe that the natural map $(\mathbb{Z}\setminus\{0\})\otimes(\mathbb{Z}\setminus\{0\})\to\mathbb{Z}\otimes\mathbb{Z}$ should be injective, so adding in $0$ doesn't give any new relations among the elements you already had.  But I haven't worked out a complete proof of that.
Comment: I think of tensor products of commutative monoids very similarly to how I think of tensor products of abelian groups (or of modules over a ring).  My core intution for how to think about $A\otimes B$ (if $A$ and $B$ are abelian groups, say) is that you describe how to "build" $A$ out of $\mathbb{Z}$ (more formally, by "building" I mean taking colimits), and then do the same thing but starting with $B$ instead of $\mathbb{Z}$.  One way to make this precise is the Eilenberg-Watts theorem, which says $-\otimes B$ is the unique colimit-preserving functor $Ab\to Ab$ that sends $\mathbb{Z}$ to $B$.
Comment: For commutative monoids, you do the same thing, except the role of $\mathbb{Z}$ is played by $\mathbb{N}$ instead.  So for instance, what is $\mathbb{Z}\otimes M$ (where here $\mathbb{Z}$ is additive)?  Well, $\mathbb{Z}$ is obtained from $\mathbb{N}$ by adjoining an inverse to its generator, so $\mathbb{Z}\otimes M$ should be obtained by adjoining inverses to the generators of $M$, which just gives the Grothendieck group.
Comment: Oh, this is excellent! Thank you! Would it be okay to ask a few more questions? 1) Why does $p$ need to be prime for $p\otimes_{\mathbb{N}}-1$ to be invertible in $\mathbb{Z}\otimes_{\mathbb{N}}\mathbb{Z}$? 2) On $K_0$'s and inverses of $0$, do we still have $K_0(\mathbb{Z}\setminus\{0\})\cong\mathbb{Q}^\times$? 3) Lastly, how does one describe $\mathbb{Z}\otimes_{\mathbb{N}}\mathbb{Z}$ explicitly (with $\mathbb{Z}$ again the multiplicative monoid)? (I think I'm still a bit confused about how to think about tensor products of commutative monoids :/)
Comment: Thank you so much! Your way of thinking about tensor products of commutative monoids/abelian groups is really nice! I'll go learn about the Eilenberg–Watts theorem to try to understand your point of view better :)
Comment: (By the way, I've opened another question about explicitly describing $\mathbb{Z}\otimes_{\mathbb{N}}\mathbb{Z}$ [here](https://math.stackexchange.com/questions/4217003), pointing to this discussion. This sounds like something with a very good chance of having been worked out before, so I think there's some value in asking it as a separate question―maybe someone already knows the answer. Also, I really like the description of $(\mathbb{Z}\setminus\{0\})\otimes_{\mathbb{N}}(\mathbb{Z}\setminus\{0\})$ you mentioned. Again, thank you so much!)


Updating htaccess file with new contents gives errors

Question: I need to make a certain configuration to my apache in order to utilize a certain npm package https://github.com/tlaverdure/laravel-echo-server over cpanel. So I was wondering if it is possible to safely add the follow code to an existing .htacess file.
RewriteEngine On
RewriteCond %{REQUEST_URI}  ^/socket.io            [NC]
RewriteCond %{QUERY_STRING} transport=websocket    [NC]
RewriteRule /(.*)           ws://localhost:6001/$1 [P,L]

ProxyPass        /socket.io http://localhost:6001/socket.io
ProxyPassReverse /socket.io http://localhost:6001/socket.io

Here are the contents of the .htaccess file:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

# php -- BEGIN cPanel-generated handler, do not edit
# Set the "ea-php74" package as the default "PHP" programming language.
<IfModule mime_module>
  AddHandler application/x-httpd-ea-php74 .php .php7 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit

EDIT:
I do not have root access to place it within my /etc/httpd/conf/httpd.conf as a virtualhost.
Comment: Distributed configuration files are only offered as a last means for those without access to the actual host configuration. They add complexity, are notoriously error prone, hard to debug and most important: the really slow down the http server...
Comment: I thought I did, but no. I have SSH access but not not root access.
Comment: If you have access to the actual host configuration, then why would you want to use a distributed configuration file (".htaccess")? Those have clear disadvantages...
Comment: Thank you for responding. Can you please explain the disadvantages to me @arkascha
Comment: Okay thank you @arkascha I'm running on a shared hosting and after consulting my host. They can't help me make such changes. As that's the case is there still a way I can go about this safely?
Comment: I am confused... Now do you have access to the actual host configuration as claimed in the question or do you _not_ have control over that?
Comment: @arkascha I have edited the question. And also resolved my problem. Thank you.
Answer: I was able to resolve my problem by placing this within my .htaccess
RewriteEngine On

RewriteCond %{HTTP_HOST} ^(www\.)?sub.domain\.com
RewriteRule ^socket.io/? http://localhost:6001/socket.io [R=301,L]

Comment: Very good that you have shared with us what solve your problem, keep it up(learning and sharing). Just an additional note you could change(optional and could help you in future) `(www\.)?sub.domain\.com` to `^(?:www\.)sub.domain\.com` too where `?:` refers a non capturing group.


PyUSB trouble with windows

Question: Pyusb works incorrectly with my PC. There isn't any topic about my problem on this forum. Details below.
I'm trying to run a simple script that should show USB devices info:
import usb.core
import usb.util
for device in usb.core.find(find_all=True):
    print(device)

And after that i get 2 errors: usb.core.USBError: [Errno 2] Entity not found and NotImplementedError: Operation not supported or unimplemented on this platform
log
 DEVICE ID 8087:8008 on Bus 001 Address 003 =================
 bLength                :   0x12 (18 bytes)
 bDescriptorType        :    0x1 Device
 bcdUSB                 :  0x200 USB 2.0
 bDeviceClass           :    0x9 Hub
 bDeviceSubClass        :    0x0
 bDeviceProtocol        :    0x1
 bMaxPacketSize0        :   0x40 (64 bytes)
 idVendor               : 0x8087
 idProduct              : 0x8008
 bcdDevice              :    0x5 Device 0.05
 iManufacturer          :    0x0
 iProduct               :    0x0
 iSerialNumber          :    0x0
 bNumConfigurations     :    0x1
  CONFIGURATION 1: 0 mA ====================================
   bLength              :    0x9 (9 bytes)
   bDescriptorType      :    0x2 Configuration
   wTotalLength         :   0x19 (25 bytes)
   bNumInterfaces       :    0x1
   bConfigurationValue  :    0x1
   iConfiguration       :    0x0
   bmAttributes         :   0xe0 Self Powered, Remote Wakeup
   bMaxPower            :    0x0 (0 mA)
    INTERFACE 0: Hub =======================================
     bLength            :    0x9 (9 bytes)
     bDescriptorType    :    0x4 Interface
     bInterfaceNumber   :    0x0
     bAlternateSetting  :    0x0
     bNumEndpoints      :    0x1
     bInterfaceClass    :    0x9 Hub
     bInterfaceSubClass :    0x0
     bInterfaceProtocol :    0x0
     iInterface         :    0x0
      ENDPOINT 0x81: Interrupt IN ==========================
       bLength          :    0x7 (7 bytes)
       bDescriptorType  :    0x5 Endpoint
       bEndpointAddress :   0x81 IN
       bmAttributes     :    0x3 Interrupt
       wMaxPacketSize   :    0x1 (1 bytes)
       bInterval        :    0xc
DEVICE ID 1c4f:0026 on Bus 003 Address 001 =================
 bLength                :   0x12 (18 bytes)
 bDescriptorType        :    0x1 Device
 bcdUSB                 :  0x110 USB 1.1
 bDeviceClass           :    0x0 Specified at interface
 bDeviceSubClass        :    0x0
 bDeviceProtocol        :    0x0
 bMaxPacketSize0        :    0x8 (8 bytes)
 idVendor               : 0x1c4f
 idProduct              : 0x0026
 bcdDevice              :  0x110 Device 1.1
 iManufacturer          :    0x1 Error Accessing String
 iProduct               :    0x2 Error Accessing String
 iSerialNumber          :    0x0
 bNumConfigurations     :    0x1
  CONFIGURATION 1: 98 mA ===================================
   bLength              :    0x9 (9 bytes)
   bDescriptorType      :    0x2 Configuration
   wTotalLength         :   0x3b (59 bytes)
   bNumInterfaces       :    0x2
   bConfigurationValue  :    0x1
   iConfiguration       :    0x0
   bmAttributes         :   0xa0 Bus Powered, Remote Wakeup
   bMaxPower            :   0x31 (98 mA)
    INTERFACE 0: Human Interface Device ====================
     bLength            :    0x9 (9 bytes)
     bDescriptorType    :    0x4 Interface
     bInterfaceNumber   :    0x0
     bAlternateSetting  :    0x0
     bNumEndpoints      :    0x1
     bInterfaceClass    :    0x3 Human Interface Device
     bInterfaceSubClass :    0x1
     bInterfaceProtocol :    0x1
     iInterface         :    0x0
      ENDPOINT 0x81: Interrupt IN ==========================
       bLength          :    0x7 (7 bytes)
       bDescriptorType  :    0x5 Endpoint
       bEndpointAddress :   0x81 IN
       bmAttributes     :    0x3 Interrupt
       wMaxPacketSize   :    0x8 (8 bytes)
       bInterval        :    0xa
    INTERFACE 1: Human Interface Device ====================
     bLength            :    0x9 (9 bytes)
     bDescriptorType    :    0x4 Interface
     bInterfaceNumber   :    0x1
     bAlternateSetting  :    0x0
     bNumEndpoints      :    0x1
     bInterfaceClass    :    0x3 Human Interface Device
     bInterfaceSubClass :    0x0
     bInterfaceProtocol :    0x0
     iInterface         :    0x0
      ENDPOINT 0x82: Interrupt IN ==========================
       bLength          :    0x7 (7 bytes)
       bDescriptorType  :    0x5 Endpoint
       bEndpointAddress :   0x82 IN
       bmAttributes     :    0x3 Interrupt
       wMaxPacketSize   :    0x3 (3 bytes)
       bInterval        :    0xa
Traceback (most recent call last):
  File "f:\newpy\venv\lib\site-packages\usb\core.py", line 746, in __str__
    for configuration in self:
  File "f:\newpy\venv\lib\site-packages\usb\core.py", line 1128, in __iter__
    yield Configuration(self, i)
  File "f:\newpy\venv\lib\site-packages\usb\core.py", line 603, in __init__
    desc = backend.get_configuration_descriptor(
  File "f:\newpy\venv\lib\site-packages\usb\backend\libusb1.py", line 773, in get_configuration_descriptor
    _check(self.lib.libusb_get_config_descriptor(
  File "f:\newpy\venv\lib\site-packages\usb\backend\libusb1.py", line 604, in _check
    raise USBError(_strerror(ret), ret, _libusb_errno[ret])
usb.core.USBError: [Errno 2] Entity not found
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "usbtesta.py", line 31, in <module>
    print(device)
  File "f:\newpy\venv\lib\site-packages\usb\core.py", line 750, in __str__
    configuration = self.get_active_configuration()
  File "f:\newpy\venv\lib\site-packages\usb\core.py", line 909, in get_active_configuration
    return self._ctx.get_active_configuration(self)
  File "f:\newpy\venv\lib\site-packages\usb\core.py", line 113, in wrapper
    return f(self, *args, **kwargs)
  File "f:\newpy\venv\lib\site-packages\usb\core.py", line 247, in get_active_configuration
    self.managed_open()
  File "f:\newpy\venv\lib\site-packages\usb\core.py", line 113, in wrapper
    return f(self, *args, **kwargs)
  File "f:\newpy\venv\lib\site-packages\usb\core.py", line 131, in managed_open
    self.handle = self.backend.open_device(self.dev)
  File "f:\newpy\venv\lib\site-packages\usb\backend\libusb1.py", line 804, in open_device
    return _DeviceHandle(dev)
  File "f:\newpy\venv\lib\site-packages\usb\backend\libusb1.py", line 652, in __init__
    _check(_lib.libusb_open(self.devid, byref(self.handle)))
  File "f:\newpy\venv\lib\site-packages\usb\backend\libusb1.py", line 600, in _check
    raise NotImplementedError(_strerror(ret))
NotImplementedError: Operation not supported or unimplemented on this platform

I saw a similar problem on the internet but there was a trouble about working with a specific USB device and it solved by installing Zadig and choosing the right driver. That way doesn't help me because I work not with some USB device but only with code trying to see a list of devices. The problem is not in PATH.
I've tried to run my script with the next configuration: win10, python 3.8.5, and also 3.7.9, pyusb 1.1.0, libusb 1.0.23b1 / libusb-win32.
If I run the script with libusb-win32 (libusb0.dll) nothing happens, python just returns an empty line and waits for the new command. If I run a script with libusb, python shows those errors above in this post. The first error disappears when I add to script line set_configuration()
for device in usb.core.find(find_all=True):
    print(device)
    device.set_configuration()

But how to fix the second error?
In the same configuration on mac os (pyusb, libusb 1.0, python 3.7.9) this script running successfully

Strangely, but this script running successfully:
for device in usb.core.find(find_all=True):
    print(device.bDeviceClass) # running only if i indicate parameter of variable "device" like here

Also strangely that pyusb finds some USB devices (as u can see in log) but in the end, appears errors. On another PC my script not running at all, errors appear right after start.
So how can I see a list of connected devices? I'm glad to get any help
Answer:
    import sys
    import ctypes as ct
    import libusb as usb

    def print_devs(devs):

        path = (ct.c_uint8 * 8)()

        i = 0
        while devs[i]:
            dev = devs[i]

            desc = usb.device_descriptor()
            r = usb.get_device_descriptor(dev, ct.byref(desc))
            if r < 0:
                print("failed to get device descriptor", file=sys.stderr)
                return

            print("{:04x}:{:04x} (bus {:d}, device {:d})".format(
                  desc.idVendor, desc.idProduct,
                  usb.get_bus_number(dev), usb.get_device_address(dev)), end="")

            r = usb.get_port_numbers(dev, path, ct.sizeof(path))
            if r > 0:
                print(" path: {:d}".format(path[0]), end="")
                for j in range(1, r):
                    print(".{:d}".format(path[j]), end="")

            print()
            i += 1

    def main():

        r = usb.init(None)
        if r < 0:
            return r

        try:
            devs = ct.POINTER(ct.POINTER(usb.device))()
            cnt = usb.get_device_list(None, ct.byref(devs))
            if cnt < 0:
                return cnt

            print_devs(devs)

            usb.free_device_list(devs, 1)
        finally:
            usb.exit(None)

        return 0

    sys.exit(main() or 0)

Comment: Thank you, ur script runs. I'm a beginner in working with USB devices so I also wanna ask, can u give me any advices about what i should to know to work with USB? For example I know what is vendor/product ID, but i don't know another parameters of device so i can't get it by code. Futhermore your code contains 'ctypes' library which is unavailable for me yet. Where can I see all parameters of device like manufacturer, name?

PyUSB trouble with windows


The sum of an Arithmetico-Geometric Series implementing permutations

Question: I have become stuck on an interesting series which I cannot seem to derive a closed form for, despite its seemingly simple nature.
As a precursor to the actual question, if I were given the series
$(3)(1)+(9)(5)+(27)(9)+(81)(13)$, I would recognize that the series as composed of an arithmetic series $a(n)=1+5+9+13$ with $d=4$, and a geometric series $g(n)=3+9+27+81$ with $r=3$.  Simple enough.
However, what if the geometric series was actually a permutation?  If I were given the expression $S(n)=(6*5*4*3)(1)+(6*5*4)(2)+(6*5)(3)+(6)(4)$ (assuming that in this case $n=6$), I would recognize it as an arithmetico-geometric series.  In this case, the permutations ($6P4, 6P3, 6P2, 6P1$) would be considered as the geometric series, and the $1+2+3+4$ terms as an arithmetic series.
However, with this all said and done, how would I actually go about deriving a closed form for the sum of this series, assuming that in this case $n=6$.  Is it even possible?!
Note: to avoid any confusion as to what different S(n) series would be, I have included a handy-dandy list below.
$S(7)=(7*6*5*4*3)(1)+(7*6*5*4)(2)+(7*6*5)(3)+(7*6)(4)+(7)(5)$
$S(8)=(8*7*6*5*4*3)(1)+(8*7*6*5*4)(2)+(8*7*6*5)(3)+(8*7*6)(4)+(8*7)(5)+(8)(6)$
Cheers!
Comment: What is the operation between the terms that are enclosed in parentheses? I initially assumed that it is multiplication, but then I see you use the * symbol for multiplication. What is the result of S(6)?
Comment: Try looking at $\frac{S(n)}{n!}$
Comment: @Thanassis The operations between sets of parentheses is multiplication, so your gut was correct.
Comment: @Thanassis S(6) should be $(6*5*4*3)(1)+(6*5*4)(2)+(6*5)(3)+(6)(4)$.
Answer: $$
\frac{S_n}{n!}=\frac{1}{1.2}+\frac{2}{1.2.3}+\frac{3}{22.214.171.124}+...+\frac{n-2}{(n-1)!}=\sum_{m=1}^{n-2}\frac{m}{(m+1)!}=\sum_{m=1}^{n-2}\frac{m\color{red}{+1-1}}{(m+1)!}\\
\quad =\sum_{m=1}^{n-2}\frac{1}{(m)!}-\sum_{m=1}^{n-2}\frac{1}{(m+1)!}=1-\frac{1}{(n-1)!}=1-\frac{n}{n!}\Rightarrow\color{red}{S_n=n!-n}
$$


Core Foundation and ARC

Question: I have a property like this in a UIView subclass
@property(nonatomic, assign) CTTypesetterRef typesetter;

I initiate the TypeSetter in the view constructor:
- (id)initWithFrame:(CGRect)frame andAttributedString:(NSMutableAttributedString * )   pageAttributedString
{
    self = [super initWithFrame:frame];
    if (self) {
            self.attributedString = pageAttributedString;
            self.typesetter = CTTypesetterCreateWithAttributedString((CFAttributedStringRef)CFBridgingRetain(self.attributedString));
}

The question is where to release the TypeSetter using CFRelease?
I am using ARC, IOS 7 and Xcode 5
Answer: in your -dealloc like you would do with MRR.
just remember that unlike MRR, in ARC you don't have to call [super dealloc] neither do you need to explicitely call -release on your ARC managed ivars.
Comment: Well you DO need to implement dealloc for releasing CF type properties. This is not highly visible but a requirement for ARC as ARC does not manage memory for non Objective-C objects.
Comment: I think it's what I just said ;) CF type properties are one kind of non ARC managed ivars, and you have to deal with their lifetime yourself.

Oh and when I wrote "you don't need to call `-release`" I meant for real, you don't have to set your ARC managed ivars to nil yourself, ARC will do that. you actually can't call `-release` on your ivars ;)
Comment: You are correct JTAS, I fixed the problem, I referenced a parent view in its sub layer using a strong property, so that dealloc was never called

    @property(nonatomic, strong) CoreTextView * coreTextView;
The correct is
    @property(nonatomic, weak) CoreTextView * coreTextView;

So the right place to release is dealloc. Thank you

Core Foundation and ARC


how can I dig my variable out of this pit?

Question: I asked a fairly poor question yesterday, but I still have the same general problem. I wanted to add a variable property to an object, and the solution I attempted was to do an ajax request to receive the variable, and then set the property to the response. I think I have tried this at least 100 different ways:
Ext.onReady(go);

function go() {

  var x;

  function getRating(id, callback) {
      Ext.Ajax.request({
          url: '/index.php/ajax/do_rate',
          method: 'POST',
          success: function(result)
          {
              jsonData = Ext.util.JSON.decode(result.responseText);
              x = jsonData.result;
          }
      });
  }
  r2 = new Ext.ux.form.Rater({
      displayValue: x,
      maxValue: 10
  });

  var simple = new Ext.FormPanel({
    items: [r2]
  });
  simple.render(document.body);
}

If it try it as above, x is undefined. If I try to create r2 prior to the ajax request, and set its displayValue within the request, the correct displayValue is shown for the object in the console, but it does not render with the correct displayValue. I don't think it makes it in time. Thanks for the help, I'm thinking I might need a 'callback', but cannot figure out the proper method.
The working code is below:
Ext.onReady(go);

function go() {
    Ext.Ajax.request({
        url: '/index.php/ajax/do_rate',
        method: 'POST',
        success: function(result)
            {
            jsonData = Ext.util.JSON.decode(result.responseText);
            var r2 = new Ext.ux.form.Rater({
                displayValue: jsonData.result,
                maxValue: 10
            });
            var simple = new Ext.FormPanel({
                items: [r2]
            });
            simple.render(document.body);
        }
    });
}

Answer: Just do everything you need to do with the data inside the "success" callback.
function go() {

  function getRating(id, callback) {
      Ext.Ajax.request({
          url: '/index.php/ajax/do_rate',
          method: 'POST',
          success: function(result)
          {
              jsonData = Ext.util.JSON.decode(result.responseText);

              var x = jsonData.result;

              var r2 = new Ext.ux.form.Rater({
                  displayValue: x,
                  maxValue: 10
              });

              var simple = new Ext.FormPanel({
                items: [r2]
              });
              simple.render(document.body);
          }
      });
  }
}

Comment: solved, thanks. modified code added above, in case this can help someone else.
Comment: ah, i see you had that on the way. thanks again. Spent way to many hours of my life working this out. Just out of curiosity (possibly need), is there any way to pop a response out (perhaps a wait until request is complete option)?
Comment: I'm not sure I get what you mean. You can't really "wait" in Javascript (in a browser). It's an event-driven model, so all you can do is tell the system that you want to do something when an event happens. That's what the "success" function is: a callback that's invoked when the HTTP request completes. That completion is an event, just like a mouse click is an event, as far as the browser is concerned.
Comment: Thanks pointy. So I guess the problem is everything below the request fires off very rapidly, and the request takes a few ms to complete. I see why the value was undefined. I guess my problem is that this bit is just a tiny component on the page. I don't know what the lead dev would think if I put the entire page contents and loader inside this tiny request. I really have to update or refresh the component somehow inside the success handler, but I'm not sure how to do this either.
Comment: Well you can spread the code out however you want; you can always put stuff in a *separate* function,, or dozens of separate functions, and just make sure that you call that code from the handler. The call to the Ajax request will return *immediately* after initiating the HTTP transaction, so you really don't have much choice other than to defer other processing. But all the code doesn't have to be inside the "success" handler. It's the control flow that matters.
Answer: you need to put this code:
r2 = new Ext.ux.form.Rater({
    displayValue: x,
    maxValue: 10
});

var simple = new Ext.FormPanel({
    items: [r2]
});

inside your AJAX POST CALLBACK like this:
success: function(result)
        {
            jsonData = Ext.util.JSON.decode(result.responseText);
            x = jsonData.result;
            r2 = new Ext.ux.form.Rater({
                displayValue: x,
                maxValue: 10
            });

            var simple = new Ext.FormPanel({
                items: [r2]
            });
        }


stdClass Object

Question: O que significa oasterisco em [*data], quando converto um objeto para array? O que tem de diferente nisso comparado ao array[data] ?
Array
(
    [0] => Source\Models\User Object
        (
            [entity:CoffeeCode\DataLayer\DataLayer:private] => users
            [primary:CoffeeCode\DataLayer\DataLayer:private] => id
            [required:CoffeeCode\DataLayer\DataLayer:private] => Array
                (
                )

            [timestamps:CoffeeCode\DataLayer\DataLayer:private] => 1
            [statement:protected] =>
            [params:protected] =>
            [group:protected] =>
            [order:protected] =>
            [limit:protected] =>
            [offset:protected] =>
            [fail:protected] =>
            [data:protected] => stdClass Object
                (
                    [id] => 30
                    [name] => Elvis
                    [passwd] => $2y$12$xNPOIrCoCS3uWqhudFvjRvkoRkzW
                    [email] => firstname.lastname@example.com
                    [franquia] => 90
                    [created_at] => 2020-02-22 21:33:52
                    [updated_at] => 2020-03-10 18:17:37
                )

        )

)

Convertendo para array:
$array = $array[0];

print_r((array)$session);

// e obtive

            Array
(
    [CoffeeCode\DataLayer\DataLayerentity] => users
    [CoffeeCode\DataLayer\DataLayerprimary] => id
    [CoffeeCode\DataLayer\DataLayerrequired] => Array
        (
        )

    [CoffeeCode\DataLayer\DataLayertimestamps] => 1
    [*statement] =>
    [*params] =>
    [*group] =>
    [*order] =>
    [*limit] =>
    [*offset] =>
    [*fail] =>
    [*data] => stdClass Object
        (
            [id] => 30
            [name] => Eliseu
            [passwd] => $2y$12$x.2SDn17RMxce0EV3xaoDet/NPOIrC.oCS3uWqhudFvjRv.koRkzW
            [email] => email@example.com
            [franquia] => 94
            [created_at] => 2021-02-22 21:33:52
            [updated_at] => 2021-03-10 18:17:37
        )

)

Answer: Significa que o atributo de onde foi extraído não tem acesso público.
no caso "[group:protected]" deve estar declarado dessa forma:
class User {
    protected $group;
    [...]
}

Comment: Criei uma estendida para extrair do protected para public somente não sensível e deu certo, obrigado.
Comment: Voltei para comentar, hoje aprendi a lidar com objetos, tinha uma limitação pois fiz uso somente de array's até então, obrigado pelo esclarecimento.

stdClass Object


Using jQuery to fill out a form element but value not passing to form action

Question: All
I have the following form input element:
<input name="payment_amount" type="text" id="payment_amount" value="" disabled>

I then manipulate the value of this form element by using jQuery:
jQuery(document).on('click','#remaining_balance',function(){
    jQuery("#payment_amount").attr('disabled', 'disabled');
    send_amount = jQuery("#value_to_transfer").val();
    jQuery("#payment_amount").val(send_amount);
});

When I click on that radio button it populates the value into my payment_amount field but when I submit the form the value doesn't get passed to my receiving page. Any idea why that it?
Thanks in advance.
Answer: Disabled elements are not sent to the server. Enable it, send the data, then disable it again.
Comment: Alternatively, you could pass a hidden input instead and leave `#payment_amount` disabled.
Comment: @pete That's a good idea too. I actually went with a different approach and just gave that input the readonly="readonly" tag and then it sends it correctly. I updated my jquery to say readonly instead of disabled.
Answer: From this site:
http://webdesign.about.com/od/forms/a/aa071805.htm
I can see that "the disabled element will not be successful when submitting the form"
So, disabled form-fields aren't sent
Your jquery code isn't *un*setting the disabled field, so you're setting the value, sure. But you're not sending it.
SOLUTION:
// To enable
$('#payment_amount').removeAttr('disabled');

// OR you can set attr to ""
$('#payment_amount').attr('disabled', '');

(i got that code snippet from
http://jquery-howto.blogspot.com/2008/12/how-to-disableenable-element-with.html)
ADDED BONUS:
your jquery hurt my eyes. Why not use
$('#remaining_balance').click( function(){
    ...
}

Actually, why aren't you using the $ operator at all? Um, you use it instead of the "jquery" keyword.
So, that said, the solution you'd want is (if you want to keep on not using the $ operator):
jQuery("#payment_amount").removeAttr('disabled');

Comment: it's because I'm using Wordpress and for the non-conflict it's making me use the jQuery instead of just using $. I only did the .on because I thought the .click function was causing my problem but I know now that I can change it back to that and it shouldn't be an issue.


How to Get data of Content type in a custom view

Question: I have a content type "tasks", I created a custom view.i want to show all data of content type "tasks" in that custom view.
Answer: I believe you are looking for this module:
https://www.drupal.org/project/viewsnodefield
Answer: Just to be clear do you want to the data in View using some custom code, if not u can just go to Structure and then click Views. Then click add a new View. Add a name and select your custom content. In Display format under create a Page,, select Unformatted list of type Field from the the 2nd selection and then press Continue & Edit   at Bottom. Here In Fields section click Add and add all the field relevant to your Content type.
Thanks hope that helps you. Click it if the answer is relevant to you.
Comment: Yes, i want the data in view using custom code.
Answer: This question seems to be answered already at How do I programmatically create a view?. In case you need the reference here is another link http://www.packtpub.com/article/creating-views-3-programmatically
Hope this helps you.
Comment: This link helps me to create a custom view programmatically.


How do I update a node's file field from within a module?

Question: I have a file: /tmp/new.zip and I have a node, $node, that has a file field, field_ios_file. Currently, old.zip is the file saved in to the field_ios_file field. I'd like to put /tmp/new.zip there.
What I have now:
$file = file_uri_to_object('/tmp/new.zip');
print_r($node->field_ios_file);
$node->field_ios_file['und'][0] = $file ;
print_r($node->field_ios_file);
node_save($node);

the node_save() fails here because $node->field_ios_file['und'][0] should be an array, not an object. I would imagine there is a function that looks something like field_update($node, $my_field, $data), but I can't find anything like that.
Answer: The file field type has a fid column (file ID); you just need to save the file so an ID is populated, and add it to the node like this:
$file = file_uri_to_object('/tmp/new.zip');
$file->status = FILE_STATUS_PERMANENT;
file_save($file);

$node->field_ios_file[LANGUAGE_NONE][0]['fid'] = $file->fid;
node_save($node);

Comment: Thanks for your help. Is that true regardless of private / public types of file fields?


PHP: Txt para Array relacionando as linhas.

Question: seguinte, eu tenho um arquivo de texto (.txt) com a seguinte estrutura:
|100|Nome do Cliente|
|200|Produto 1|R$100|
|200|Produto 2|R$200|
|200|Produto 3|R$300|

Resumindo, sempre que a linha começa com |100|, todos os |200| que seguem abaixo estão relacionados ao |100| acima.
Usando EXPLODE no PHP, tenho o seguinte Array:
Array(
     [0] =>
     [1] => 100
     [2] => Nome do Cliente
)
...

Ou seja, um array pra cada linha.
Gostaria de relacionar, no próprio array, os produtos ao cliente, numa estrutura em que os produtos fiquem no mesmo array que o Cliente, algo como:
Array(
     [0] =>
     [1] => 100
     [2] => Nome do Cliente
     Array(
          [0] =>
          [1] => Produto 1
          [2]=>R$100
     )
     Array(
          [0] =>
          [1] => Produto 2
          [2] => R$200
     )
     ... etc
)

Alguém pode me dar uma luz de como relacionar isso?
Comment: Todos clientes começam com 100 e todos produtos com 200?
Answer: Então não da para fazer exatamente desse seu jeito porque um grupo de matriz deve estar dentro de outro, sendo assim o mais fácil é associar uma nova posição e agrupar essa sub-matriz dentro. Não sei se ficou claro aqui vai o código de exemplo.
<?php
// Massa de dados de exemplo
$txt = "|100|Nome do Cliente|
|200|Produto 1|R$100|
|200|Produto 2|R$200|
|200|Produto 3|R$300|
|100|Nome do Cliente 2|
|200|Produto 1|R$100|
|200|Produto 2|R$200|
|200|Produto 3|R$300|";

$array_final = array(); // Inicia uma Matriz vazia
$temp_cliente = 0; // Variável de controle de posição dos clientes

// Quebra as linhas da sua fonte (no caso minha variável simples)
// No seu vem a leitura do TXT aqui nessa parte
$divide_linhas = explode("\n", $txt);

// Percorre todas as linhas
for ($l = 0; $l < count($divide_linhas); $l++) {
 list($a0, $a1, $a2, $a3) = explode("|", $divide_linhas[$l]);

 if ($a1 == "100") {
  if ($l > 0) { $temp_cliente++; } // Ajuste para primeira linha apenas

  // Monta a primeira estrutura da Matriz do cliente
  $array_final[$temp_cliente] = array($a1, $a2, array());
 } else {
  // Monta a sub-matriz dentro da primeira
  $array_final[$temp_cliente][2][] = array($a1, $a2, $a3);
 }
}

// Imprime o resultado
print_r($array_final);
?>

O resultado final sairá algo como isso (abaixo), ai bastará você chamar o cliente e depois percorre a posição 2 e nessa estará todos os produtos daquele cliente em especial.
Array
(
    [0] => Array
        (
            [0] => 100
            [1] => Nome do Cliente
            [2] => Array
                (
                    [0] => Array
                        (
                            [0] => 200
                            [1] => Produto 1
                            [2] => R$100
                        )

                    [1] => Array
                        (
                            [0] => 200
                            [1] => Produto 2
                            [2] => R$200
                        )

                    [2] => Array
                        (
                            [0] => 200
                            [1] => Produto 3
                            [2] => R$300
                        )

                )

        )

)

Comment: Nossa valeu, ambos funcionaram de forma magnífica.
Answer: Eu faria desta maneira, com o fopen e feof pra ajudar a poupar memória e com trim pra limpar quebras de linha:
<?php
function tratarDados($linha) {
    //Remove espaços do começo e fim nos nomes, valores e etc
    return array_map('trim', explode('|', $linha));
}

$handle = fopen('arquivo.txt', "r");

$vetor = array();
$i = -1;

while (feof($handle) === false) {
    $line = fgets($handle);
    $line = trim($line); //Remove espaços e \r
    $line = trim($line, '|'); //Remove | do começo e do fim

    //Quando encontra o 100 adiciona um novo elemento
    if (strpos ($line, '100|') === 0) {
         $vetor[] = tratarDados($line);
         ++$i;
    } elseif ($i > -1) {
         //Se já existe um cliente no vetor adiciona os produtos pra ele
         $vetor[$i][] = tratarDados($line);
    }
}

fclose($handle);

print_r($vetor);

O arquivo.txt ficou assim:
|100|João|
|200|Produto 1|R$100|
|200|Produto 2|R$200|
|200|Produto 3|R$300|
|100|Jose|
|200|Produto 1|R$100|
|200|Produto 2|R$200|
|200|Produto 3|R$300|
|100|Marcos|
|200|Produto 1|R$100|
|200|Produto 2|R$200|
|200|Produto 3|R$300|
|100|Paulo|
|200|Produto 1|R$100|
|200|Produto 2|R$200|
|200|Produto 3|R$300|

Resultado:
Array
(
    [0] => Array
        (
            [0] => 100
            [1] => João
            [2] => Array
                (
                    [0] => 200
                    [1] => Produto 1
                    [2] => R$100
                )

            [3] => Array
                (
                    [0] => 200
                    [1] => Produto 2
                    [2] => R$200
                )

            [4] => Array
                (
                    [0] => 200
                    [1] => Produto 3
                    [2] => R$300
                )

        )

    [1] => Array
        (
            [0] => 100
            [1] => Jose
            [2] => Array
                (
                    [0] => 200
                    [1] => Produto 1
                    [2] => R$100
                )

            [3] => Array
                (
                    [0] => 200
                    [1] => Produto 2
                    [2] => R$200
                )

            [4] => Array
                (
                    [0] => 200
                    [1] => Produto 3
                    [2] => R$300
                )

        )

    [2] => Array
        (
            [0] => 100
            [1] => Marcos
            [2] => Array
                (
                    [0] => 200
                    [1] => Produto 1
                    [2] => R$100
                )

            [3] => Array
                (
                    [0] => 200
                    [1] => Produto 2
                    [2] => R$200
                )

            [4] => Array
                (
                    [0] => 200
                    [1] => Produto 3
                    [2] => R$300
                )

        )

    [3] => Array
        (
            [0] => 100
            [1] => Paulo
            [2] => Array
                (
                    [0] => 200
                    [1] => Produto 1
                    [2] => R$100
                )

            [3] => Array
                (
                    [0] => 200
                    [1] => Produto 2
                    [2] => R$200
                )

            [4] => Array
                (
                    [0] => 200
                    [1] => Produto 3
                    [2] => R$300
                )
        )
)

Comment: Assim como o acima, ambos funcionaram de forma magnífica. Porém o seu, pra mim, teve um uso melhor devido ao loop de arquivos incontáveis que tenho numa pasta, pra tratar tudo um a um, o seu é mais usual.
Obrigado a todos
Comment: @Marcio o script estava gerando uma dimensão a mais, eu corrigi ele
Comment: @GuilhermeNasdcimento, eu meio que fiz uma certa confusão ontem quando vi outros arquivos que preciso transferir para banco de dados, onde há vários níveis de relacionamento. Eu tentei editar a pergunta aqui mas aparecia mensagem de que eu não podia editar. Acima do Cliente e produtos, há também a empresa responsável pela venda. Se puder, por favor, veja [aqui](http://pt.stackoverflow.com/questions/117590/php-txt-para-array-com-v%C3%A1rios-n%C3%ADveis) . Super obrigado pela ajuda.


Objeto aparece em determinado lugar da página

Question: Minha dúvida é a seguinte: eu quero/preciso de um código para meu site, que funcione da maneira deste site. Nele, quando o usuário usa o scroll do mouse para descer um pouco na página, uma setinha (que quando é clicada, volta para o topo - a parte de cima do site) aparece no canto direito.
Já pesquisei no Google, e acho que não soube usar as palavras corretas, pois não achei nenhum resultado que me atendesse.
Obs.: O código para voltar para cima eu já tenho.
Answer: Utilize jquery + css.
Coloque a seta dentro de uma div e aplique o css para que fique a flutuar sempre do lado direito, por exemplo:

O seu css ficaria da seguinte forma, partindo do princípio que seta tem 30x30:
.seta {position:fixed; display:none; right:0px; top:300px; width:30px; height:30px; z-index:999;}

Agora utilize jquery para esconder ou mostrar a div quando o scroll atingir uma certa posição. Para isso vamos utilizar o evento "scroll" do jquery:
$( window ).scroll(function() {
    nScrollPosition = $( window ).scrollTop();
    if(nScrollPosition>=100){
         $( ".seta" ).css( "display", "block" );
    }else{
         $( ".seta" ).css( "display", "none" );
    }
});

No exemplo acima, quando o scroll atingir 100px do topo, a seta irá aparecer, caso contrário esconde a seta.
Comment: +1. Acrescentando: para obter o mesmo efeito da página de exemplo, basta animar a exibição/ocultação da seta (usando por exemplo `fadeIn`/`fadeOut`) em vez de somente atribuir a propriedade CSS.
Comment: Eu quase que concordo totalmente contigo. O ponto é que para isso se usa `position: fixed` e não `absolute`
Comment: @mgibsonbr é verdade, me esqueci do efeito.
Comment: De qualquer forma, a questão principal foi respondida.
Comment: Cara Mutio Obrigado, muito Obrigado Mesmo!! +1 , e se eu podesse +1000
Comment: @AndréFigueiredo tens toda razão, mas penso que ele já possuía o css feito, só necessitava do javascript.
Comment: ok! +1 de qualquer maneira! :)


How to use the Regular Express of the end pattern in the next pattern not the entire string?

Question: I am trying to find the categories in a website by using Regular Expression.
I typed (?<=class="category-section" data-id=")(.*)(?=" id="nav)
but it return the whole string to me, and what I see it start from the first pattern after data-id=" until the end pattern has " id="nav
For Example:

I expected to get Motors and Fashion in the matches but it wil return
 Motors" id="nav-1"> <div class="category-section" data-id="Fashion

I dont get it....
Comment: `data-id=(['"]?)(.*?)\1` - the second capture group contains what you want, although you really should be using an XML parser for this.
Comment: Obligatory: **Do Not Use Regex To Parse HTML! **
Comment: If you're doing something in Notepad++ or something, you should use this `(?<=data-id=")(.*)(?=")`
Comment: @TomLord Please explain to OP *why* parsing HTML with regexes is a road to sorrow. Just saying "don't do that" isn't much help.
Comment: Which language are you trying to implement this in?
Comment: @andylester This is explained EVERY time a question like this gets asked, i.e. Hundreds of times per day. There's even a link to the famous response right above my comment.
Comment: I know it does, but OP doesn't know that.  Also, the famous response is not helpful.
Comment: @JackyCheung Please note that parsing HTML with regexes is error-prone and difficult.  The HTML can be in a zillion different formats.  Here are some examples: http://htmlparsing.com/regexes.html
Comment: @Jan I usually do C# programming but this time my VP wants me to provide a pure RE instead of a application in C# -_-" my VP is trying to train me to become a expert in RE
Comment: @JackyCheung I would explain to the VP that this is not good challenge; there are many better ways to test yourself with complex regex tasks. HTML *cannot* be fully parsed via regex. HTML is a context-free grammar, which by its very definition is *irregular*.
Comment: Given a *restricted* input like this, yes it's certainly doable with a regex. But this is not the "right" way to do it; and with arbitrarily complex HTML your pattern *will* fail in some way.
Answer: Try this:
data-id=".*?"
It will return two matches, then correspond to data-id="Motors" and data-id="Fashion".
So, you can replace the data-id= and " sings to get your desire value, inside attributes.
Edit 1:
By using simple js functions, you can retrieve this value:

Content1

Content2

Output:
Motors
Fashion

Comment: it works @Abe but my VP wants me to use pure RE to get the target instead of using function to cut it off >_<" I am die-ing now.....even my team leader doesn't know much in RE. How come they focus a volunteer, me, to become a RE expert...........
Comment: What language or resource you're using? It's pure JS? we can build a simple function to make this.
Comment: I do C#, but this time just do pure RE


Referenciar objeto não estático em um método estático

Question: Boa noite, preciso referenciar um componente PlaceHolder Asp.Net em um método estático no code-behind C#, esse método é chamado via AJAX pelo front-end vejam o código:
Chamada do método pelo front-end Form aspx:

O Método no Code-Behind C#:
[System.Web.Services.WebMethod]
public static string AtuarNoProcesso(int AndamentoID)
{
    PlaceHolder1.Controls.Add(new Literal
    {
          Text =  Andamento.Make_Table_Html(Convert.ToInt32(AndamentoID)) });
    }
}

Mas recebe a mensagem "An object reference is required for the non-static field, method, or property" no componente PlaceHolder1.
Como faço o método enxergar o componente PlaceHolder1?
Comment: Se o método precisa acessar um membro de instância ele não deveria ser estático.
Comment: @Evandro retorna um `JSON` e trabalhe a informação no seu front, já que está utilizando `Ajax`! diretamente isso não é possivel, ou até, retorna o html mudando o retorno `dataType:'html'` no seu `ajax`! tem duas opções ai.
Comment: @Evandro um exemplo: https://cbsa.com.br/post/web-service---retornar-json-com-aspnetc.aspx
Comment: @VirgilioNovic assim vai funcionar no retorno  `$('.resultado').text(data.d);` eu monto o html, vou testar e posto aqui
Comment: Não dá !!!! ..... vai ter que usar outra forma! o que pretende fazer?
Comment: @DiegoRafaelSouza Andamento é uma classe com uma função que retorna um string "Make_Table_Html" que monta o html uma tabela com nomes de pessoas
Comment: @VirgilioNovic vou tentar modelar retornando um JSON, vc teria um exemplo em código para orientar-me.
Answer: Conforme dica do pessoal montei a tabela html com as informações no retorno JSON da chamada Ajax, vejam como ficou:

//tabela


Como manter o Look And Feel selecionado no JComboBox após a janela ser fechada?

Question: Acabei de criar um simples JFrame no NeatBeans com alguns Look And Feel's(LAF) disponíveis, utilizando um JComboBox para que o usuário escolha o LAF que desejar, e botei também o botão "Salvar" para Ação.
Consigo mudar o "Tema" perfeitamente. O problema é que o LAF escolhido só é aplicado naquele exato momento da execução, quando fecho e executo o JFrame novamente, o LAF escolhido não permanece salvo.
Gostaria de saber como criar algum Método para que o LAF selecionado permanecesse aplicado ao reabrir o JFrame.
Aqui está o Exemplo:

Aqui está o Código de Botão Salvar:
private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {
        // Acao de Botao Salvar
       String t = (String)jComboBoxLAF.getSelectedItem();

        JOptionPane.showMessageDialog(null, t);

        try {

            if ("Metal".equals(t)){

                UIManager.setLookAndFeel(new MetalLookAndFeel());
                this.setVisible(false);
                new TelaJtable().setVisible(true);

            }else if("Nimbus".equals(t)){
                UIManager.setLookAndFeel(new NimbusLookAndFeel());
                this.setVisible(false);
                new TelaJtable().setVisible(true);

            }else if("CDE/Motif".equals(t)){
                UIManager.setLookAndFeel(new MotifLookAndFeel());
                this.setVisible(false);
                new TelaJtable().setVisible(true);

            }else if("Windows".equals(t)){
                UIManager.setLookAndFeel(new WindowsLookAndFeel());
                this.setVisible(false);
                new TelaJtable().setVisible(true);
            }
            else if("Windows Classic".equals(t)){
                UIManager.setLookAndFeel(new WindowsClassicLookAndFeel());
                this.setVisible(false);
                new TelaJtable().setVisible(true);
            }

        } catch (Exception e) {

        }
    }

Comment: Foi o que eu disse, não tem jeito de fazer isso sem salvar num arquivo externo. Após encerrar o programa, ele é despejado da memória, nada é salvo(caso você não tenha programado nenhum tipo de persistencia de dados). Tem como definir um tema padrão que sempre será usado ao abrir(como o netbeans já faz com o nimbus), só isso. Qualquer mudança disso, precisa de arquivo externo.
Comment: Você está salvando num arquivo externo? Esta é a unica forma de fazer isso. usando o construtor de GUI do netbeans, o tema inicial sempre será Nimbus, a não ser que você crie um mecanismo para salvar a opção escolhida num arquivo externo, e verifique-a antes da tela ser aberta.
Comment: Ola diegofm obrigado pela sua resposta, me desculpe talvez seja a minha explicação mal explicada, Não no arquivo externo, eu quero salvar a opção do LAF/Tema selecionado do tipo quando executar o JFrame novamente mudar pra outro LAF escolhido anteriormente, para não ter que sempre  selecionar o LAF todas as vezes que executar o JFrame! uma vez que a ação de botão "salvar" que eu criei só apenas Altera o LAF para outro, mas a opção não fica salvo, tenho que selecionar todas as vezes.
Comment: Obrigado mais uma vez diegofm, Opa não tenho ideia como fazer isso, podes me dar uma orientação para poder salvar num arquivo externo?
Answer: Você pode fazer isso com um simples arquivo de texto, salvando o nome do LAF¹(ou o nome da classe inteira) quando alterar o LAF¹ dentro da aplicação, e carregando este arquivo ao abrir a aplicação para checar qual tema foi salvo.
Uma das formas que eu sempre uso quando preciso desse tipo de recurso é usar a classe Properties, onde posso salvar vários itens de configuração e recuperá-los mais facilmente do que fazendo isso fazendo a leitura tradicional de um arquivo de texto.
Para o seu caso, eu fiz um exemplo de classe chamada Propriedade, cuja função  é ler e salvar o LookAndFeel da sua aplicação de um arquivo config.properties. Este último você pode trocar por qualquer nome(ex. config.txt).
public static class Propriedade {

    private static Properties prop;
    //aqui você pode mudar o nome e a extensão do arquivo
    private static String path = "config.properties";

    private static void LoadPropertiesFile() throws IOException {
        prop = new Properties();
        File f = new File(path);

        if (f.isFile()) {
            FileInputStream file = new FileInputStream(f);
            prop.load(file);
        } else {
            //se o arquivo não existir, cria um novo
            f.createNewFile();
            FileInputStream file = new FileInputStream(f);
            prop.load(file);
            //seta um valor inicial em branco pro parametro do LAF
            // isso é para evitar NullPointerException ao chamar
            // getLookAndFeel() logo após criar o arquivo
            setLookAndFeel("");
        }
    }

    public static String getLookAndFeel() throws IOException {
        LoadPropertiesFile();
        return prop.getProperty("lookandfeel.name");
    }

    public static void setLookAndFeel(String name) throws IOException {
        LoadPropertiesFile();
        prop.setProperty("lookandfeel.name", name);
        prop.store(new FileOutputStream(path), "");
    }
}

Para usar, você só precisa invocar um dos dois métodos públicos(a classe já está criando o arquivo se ele não existir).
Apenas lembrando que se você chamar o getLookAndFeel() antes de abrir sua tela, é importante verificar se o valor retornado é nulo ou em branco, pois se a classe acabou de criar o arquivo, o valor retornado será em branco(como pode ser viso no métodoLoadPropertiesFile()), ou se alguém mudar os valores diretamente no arquivo, pode retornar nulo também.

Obs.: conforme dito nos comentários, este método só ira funcionar corretamente com os look and feel's que estiverem instalados, se estiver usando algum externo ao java, você precisa instalar eles através do método UIManagerr.installLookAndFeel(String name, String className), onde name é um nome "amigável" do LAF¹, e className é o nome da classe, ficaria algo assim: installLookAndFeel(String "Custom LAF¹", String "com.example.mycustomlaf").

Para exemplificar, veja um exemplo executável do funcionamento desta classe:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.util.Properties;

/**
 *
 * @author diego.felipe
 */
public class SaveLAFTest {

    private void start() {
        final JFrame frame = new JFrame();
        frame.setTitle("Frame principal");
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JComboBox comboLAF = new JComboBox();

        for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            comboLAF.addItem(info.getName());
        }

        comboLAF.addItemListener(e -> {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                String LAFSelected = (String) e.getItem();
                changeLookAndFeel(LAFSelected);
                SwingUtilities.updateComponentTreeUI(frame);
            }

        });

        frame.setLayout(new FlowLayout());
        frame.add(comboLAF);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
    }

    private void changeLookAndFeel(String name) {
        for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if (info.getName().equalsIgnoreCase(name)) {
                try {
                    UIManager.setLookAndFeel(info.getClassName());
                    Propriedade.setLookAndFeel(name);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {

        try {
            String myLAF = Propriedade.getLookAndFeel();
            if (myLAF == null || myLAF.isEmpty()) {
                Propriedade.setLookAndFeel(UIManager.getLookAndFeel().getName());
            } else {

                for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                    if (myLAF.equalsIgnoreCase(info.getName())) {
                        UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        EventQueue.invokeLater(() -> new SaveLAFTest().start());
    }

    public static class Propriedade {

        private static Properties prop;
        private static String path = "config.properties";

        private static void LoadPropertiesFile() throws IOException {
            prop = new Properties();
            File f = new File(path);

            if (f.isFile()) {
                FileInputStream file = new FileInputStream(f);
                prop.load(file);
            } else {
                f.createNewFile();
                FileInputStream file = new FileInputStream(f);
                prop.load(file);
                setLookAndFeel("");
            }
        }

        public static String getLookAndFeel() throws IOException {
            LoadPropertiesFile();
            //lookandfeel.name é o nome que será salvo do parâmetro
            //você pode mudar pra outro, mas lembre de alterar também
            // no método setLookAndFeel()
            return prop.getProperty("lookandfeel.name");
        }

        public static void setLookAndFeel(String name) throws IOException {
            LoadPropertiesFile();
            prop.setProperty("lookandfeel.name", name);
            prop.store(new FileOutputStream(path), "");
        }
    }
}

Veja funcionando no gif abaixo:

1 - LAF = look and feel
Comment: @AméricoJorge Creio que você precise instalar os LAFS, utilizando o comando `installLookAndFeel(String name, String className)`, passando o nome 'amigável que você quer que seja chamada o LAF, e o endereço de sua classe(esse que você está tentando passar no código). Isso precisa ser feito com todos os LAFs customs ali no começo do `try`, depois, todos serão listados normalmente no combobox.
Comment: você é um profissional pra valer aqui, deu tudo certo! um forte abraço , ate mais..
Comment: Olá diegofm me ajudaste bastante, deu tudo certo, porem não pude expressar nenhum sentimento de gratidão conforme a regra que não nos permite se não me engano. mas aceitei a sua resposta como útil.
Porém tenho mais um probleminha aqui, gostaria de mais uma ajuda sua, tenho uma biblioteca extra de LAFs, como posso fazer para adicionar os LAFs extra junto aos LAFs disponíveis no código que criaste para mim?
Comment: Nome da Biblioteca: JTattoo-1.6.11.jar

Aqui estão os nomes de pacotes e Classes:
UIManager.setLookAndFeel("com.jtatoo.plaf.noire.NoireLookAndFeel");
UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel");
UIManager.setLookAndFeel("com.jtattoo.plaf.texture.TextureLookAndFeel");
UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");
Comment: Eu tentei adicionar da seguinte forma no teu código lá no initComponents();
 for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
           comboLAF.addItem(info.getName());
         }
//assim    comboLAF.addItem(new NoireLookAndFeel());
//asimm    comboLAF.addItem(new info("NoireLookAndFeel", NoireLookAndFeel.class.getName()));

Tentei de outras formas também,porem não adiantou em nada parece que não se faz assim, alguma dica?


How can I pass props to children of React Router?

Question: I have checked this link
So far, I'm not able to understand the handler part. So I was hoping for a more simple example perhaps?
Here is my main parent component:
class appTemplate extends React.Component {
    render() {
        return (

                {this.props.children}

        );
    }
}

What I want to do is pass down the prop this.props.route.path to my child components which is this.props.children.
I'm not really fully familiar with all the terms even though I've been touching React already for the last few months.
An example with a proper explanation would be greatly appreciated. Thanks.
Comment: that example is pretty old, checkout the latest docs.... if you use redux than just use connect wrapper,  this will give you access to location and route anywhere in the app
Answer: The proper way to achieve that is using React.Children.map()
class appTemplate extends React.Component {
    render() {
        return (

                {React.Children.map(
                       this.props.children,
                       child => React.cloneElement(child,
                                   {
                                      customProp: "Here is your prop",
                                      path: this.props.route.path
                                   })
                )}

        );
    }
}

Answer: React has a cloneElement function. The idea is to clone the children object, passing on path as a part of the props:
class appTemplate extends React.Component {
    render() {
        let children = null;
        if (this.props.children) {
          children = React.cloneElement(this.props.children, {
            path: this.props.route.path
          })
        }
        return (

                {children}

        );
    }
}

You should then be able to access the path using this.props.path within a child element, but (from what I remember) not from within elements nested within the child.
You can read more about cloning and passing values here:
https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement


Getting RGB color from image in Android

Question: I'm making a game and in the game I load the map using an image.
I check each pixel RGB and depends on that I add objects.
This is my code:
        private void loadLevel() {
    Bitmap image = Assets.loadLevel(LEVEL);
    int w = image.getWidth();
    int h = image.getHeight();
    for (int xx = 0; xx < h; xx++) {
        for (int yy = 0; yy < w; yy++) {
            int pixel = image.getPixel(xx, yy);
            int red = (pixel >> 16) & 0xff;
            int green = (pixel >> 8) & 0xff;
            int blue = (pixel) & 0xff;

            if (red == 100 && green == 60 && blue == 0) { // / block
                Log.d("PlayState","Creating blockss!!!");
                addObject(new Block(xx * 32, yy * 32, 0, ObjectId.Block));

            }
            if (red == 100 && green == 50 && blue == 0) { // /block 1
                addObject(new Block(xx * 32, yy * 32, 1, ObjectId.Block));
            }
            if (red == 100 && green == 40 && blue == 0) { // /block 2
                addObject(new Block(xx * 32, yy * 32, 2, ObjectId.Block));
            }
            if (red == 100 && green == 30 && blue == 0) { // /block 3
                addObject(new Block(xx * 32, yy * 32, 3, ObjectId.Block));
            }
            if (red == 255 && green == 255 && blue == 255) { // /block 4
                addObject(new Block(xx * 32, yy * 32, 4, ObjectId.Block));
            }
            if (red == 255 && green == 255 && blue == 245) { // /block 5
                addObject(new Block(xx * 32, yy * 32, 7, ObjectId.Block));
            }
            if (red == 0 && green == 255 && blue == 33) { // /block up
                addObject(new Block(xx * 32, yy * 32, 5, ObjectId.Block));
            }
            if (red == 0 && green == 245 && blue == 33) { // /block up1
                addObject(new Block(xx * 32, yy * 32, 6, ObjectId.Block));
            }
            if (red == 0 && green == 0 && blue == 255) { // / player
                Log.d("PlayState","Creating Playerrr!!!");
                addObject(new Player(xx * 32, yy * 32, ObjectId.Player));

            }
        }
    }

}

The problem is that for some reason it only adds the Player object,it might be becuase it is the only object that both red & green are 0. When I used exactly the same code to program to windows it worked great.
Btw, I have also tried
            int red = Color.red(pixel);
            int green = Color.green(pixel);
            int blue = Color.blue(pixel);

same result...
EDIT:
If someone else has this problem thanks to @JASONGPETERSON I found the solution.
Instead of looking for the exact value check if it a bit lower or higher, for example
if ((red > 90 && red < 110) && (green > 50 && green < 70) && blue == 0) { // / block
                Log.d("PlayState","Creating blockss!!!");
                addObject(new Block(xx * 32, yy * 32, 0, ObjectId.Block));

            }

Comment: Please, look at this http://stackoverflow.com/questions/5669501/how-to-get-rgb-values-of-bitmap-in-android
Comment: Perhaps your conditions need to test for a narrow range instead of an exact integer. There may be some rounding due to the `getPixel()` method, image compression, etc.
Comment: @JpCrow I had a look there but it didnt help my problem..
Comment: @JASONGPETERSON yey you there right!!! when I checked if the the color is lower or higher by 10 it worked.Thanks alot :))
Answer: Did you try to Log.d the red, green and blue values to see whether it's really the situation as observed?
Answer: Perhaps your conditions need to test for a narrow range instead of an exact integer. There may be some rounding due to the getPixel() method, image compression, etc. (And, in fact, this turned out to work.)
Answer: Maybe not fixing your problem but :
int pixel = image.getPixel(xx, yy);

suggest you're using "xx" as "x coordinate" (width) but you're itering on the height of your image with :
int h = image.getHeight();
for (int xx = 0; xx < h; xx++)

Comment: I didnt notice that, but that doesnt matter becuase in the end it will check all the pixels so it will give the same result.

Getting RGB color from image in Android


How do I show that the two methods of permutation test are both valid?

Question: My main objective is to show the methods described below are really the same. However, I am having difficult both formulating the idea clearly and proving my assertion. Below is my attempt.
Suppose we are give a categorical dataset characterized by the following:

Treatment Group(T): Buy DVD(B), 40; Not Buy(N), 20.
Control Group(C): Buy DVD(B), 60; Not Buy(N), 20.

Now, we wish to derive the distribution of the permutation resample. Note this will be a discrete distribution with four possible outcomes, namely $(T, B), (C, B), (T, N), (C, N)$. Now, I present two ways of deriving the permutation resample.
The Standard Approach
Let a deck of $140$ cards be given. Label 100 of them as $B$ and the rest 40 as $N$. Then shuffle the cards carefully but randomly, then distribute the first 60 of them to the $T$ pile and the rest 80 to the $C$ pile. Now, we investigate the probabilistic distribution of the resulting resample.

$\mathbb{P}((T,B))=\mathbb{P}(B)\cdot\mathbb{P}(T\mid B)=\frac{100}{140}\cdot\frac{60}{140}=\frac{6000}{140^2}$ since the probability any card, regardless of $B$ or $N$, being in the top 60 cards in the shuffled deck  is 60 out of 140 (So the conditional probability is really the same as the unconditioned as since being $B$ or $N$ is independent from going to $T$ pile or $C$ pile). Similarly, we derive the following.
$\mathbb{P}((T,N))=\mathbb{P}(N)\cdot\mathbb{P}(T\mid N)=\frac{40}{140}\cdot\frac{60}{140}=\frac{2400}{140^2}$
$\mathbb{P}((C,B))=\mathbb{P}(B)\cdot\mathbb{P}(C\mid B)=\frac{40}{140}\cdot\frac{80}{140}=\frac{3200}{140^2}$
$\mathbb{P}((C,N))=\mathbb{P}(N)\cdot\mathbb{P}(C\mid B)=\frac{100}{140}\cdot\frac{80}{140}=\frac{8000}{140^2}$

An easy check is to add up all the probability values, this gives us 1, a successful check. Now, if we can show the probability of each possible outcome using the below approach is the same as the standard approach, we are done.
An Alternative Approach
Let a deck of $140$ cards be given. Label 60 of them as $T$ and the rest 80 as $C$. Then shuffle the cards carefully but randomly, then distribute the first 100 of them to the $B$ pile and the rest 40 to the $N$ pile. Again, picking a random card from the resulting resample, the probability it is a $T$ is trivially $\frac{60}{140}$. Furthermore, the chance a random card is $B$ is simply $\frac{100}{140}$ since the chance any card is placed in the top 100 cards is $\frac{100}{140}$. Note that the $\mathbb{P}(B\mid T)=\mathbb{P}(B)$ since the regardless a card is $T$ or $N$, they are have the same probability of being in the top 100 of the shuffled pule. Therefore, we have that
$$\mathbb{P}((T,B))=\mathbb{P}(T)\cdot\mathbb{P}(B\mid T)=\frac{60}{140}\cdot\frac{100}{140}=\frac{6000}{140^2}.$$ Note that this is exactly what we had in the standard method. The probabilities of other outcomes then follows from the same logic and should each be equal to their corresponding ones in the previous approach.
To sum up, hopefully I showed the probabilistic distribution of the two resampling methods are identical by showing each outcome has the same probability in both of the methods.
Answer: Some terminology will help here.  Basically you have a 2x2 contingency table, and your methods are trying to produce a series of independent replications when the "row" (T or C) and "column" (B or N) are independent.  I would think about setting up a joint distribution for the counts in each cell of the table, under each distribution.  To help start you off, I'll do the alternative method.  When you take a deck of cards and label then as T and C, then the distribution of the number of units that are "buy" and "treatment", $n_{TB} $, is a hypergeometric distribution:
$$p(n_{TB})=\frac{\binom {100}{n_{TB}}\binom {40}{60-n_{TB}}}{\binom{140}{60}}$$
To reason this out, note that there are $\binom {140}{60} $ ways to label the data $T $ and $C $.  Then we have $\binom {100}{n_{TB}} $ ways to pick how many of the $B $ assignments also get assigned to $T $, and for each way we also have $\binom {40}{60-n_{TB }} $ ways to assign the remaining $60-n_{TB} $ units as "TN".  Note this implies that $60\geq n_{TB}\geq 20$.
Also, once we have $n_{TB} $ the rest follows from what is known about the table.  We have $n_{TN}=60-n_{TB} $ and $n_{CB}=100-n_{TB} $ and finally $n_{CN}=n_{TB}-20$.  Note that these reproduce the constraints provided $60\geq n_{TB}\geq 20$.
Now you need to show that you get the same hypergeometric distribution for $n_{TB} $ if you apply the standard method.
hope this helps!


Simple line equation question (find median through origin)

Question: I am trying to teach myself A-level maths but have become a little stuck on the following quesion:
"The line $4x-5y+20 = 0$ cuts the x-axis at A and y-axis at B. Find the equation of the median through $O$ of triangle$OAB$."
I approached this by finding point A (-5,0) and B(0,4) and making a triangle using the origin (I assumed $O = $origin). I think the median of O is the same as the line which is perpendicular to $4x - 5y + 20 = 0$ and passes through the midpoint of $AB$. Doing this I got $10x + 8y - 41 = 0$ which I checked against an online calculator as correct.
However the answer in my book is $4x + 5y = 0$, so I feel I have misunderstood something pretty fundamental in the $Q$, but after looking around for a while I am no closer to understanding what.
Thanks for your help,
Joe
Answer: "the median of O is the same as the line which is perpendicular to $4x - 5y + 20 = 0$" is incorrect and need not be considered.
The equation of the median will be thestraight line joining the midpoint of $AB$ and $O(0,0)$
Comment: Oh I see! I made a bad assumption there. Thanks a lot for your help!


Testing with Mocha in Node.js

Question: I'm getting really inconsistent behavior in my terminal when console.logging inside of a test I wrote using mocha. We are running a node.js server and running socket.io. Does the console.log not go to the terminal only some of the time for some reason? I'm really confused about this behavior.
➜  tests git:(master) ✗ mocha test-chat-server.js
hello world

echo
✓ echos message (68ms)

On Connect Things Should Happen
✓ initial connection events
  disconnected
  i'm here

    2 passing (93ms)

➜  tests git:(master) ✗ mocha test-chat-server.js
  hello world

    echo
      ✓ echos message (61ms)

    On Connect Things Should Happen
      ✓ initial connection events

    2 passing (77ms)

The difference between these two times I ran the mocha test are the console.log statements that appears in the first test run (disconnected, i'm here). They do not appear in the second test that I ran.
Edit: posting my test code in response to the comment (thank you!)
var should = require('should');
var socket = require('socket.io-client')('http://localhost:3000');

describe("echo", function () {
    var server,
        options ={
            transports: ['websocket'],
            'force new connection': true
        };

    it("echos message", function (done) {
        var client = socket.connect("http://localhost:3000", options);

        client.once("connect", function () {
            client.once("echo", function (message) {
                message.should.equal("Hello World");

                client.disconnect();
                done();
            });

            client.emit("echo", "Hello World");
        });
        done();
    });
});

describe("On Connect Things Should Happen", function() {

    it('initial connection events', function() {

        should.exist(socket);
        socket.open();
        socket.compress(false).emit('an event', { some: 'data' });

        socket.on('error', function() {
            console.log('error');
        });

        socket.connect();
        socket.on('disconnect', function(connection) {
            console.log('disconnected');
            console.log("i'm here");
        });

        socket.on('connect', function(connection) {
            console.log('connected');
        });
    });
});

Comment: Post your test code please.
Comment: Sorry! I have posted it
Answer: You are falling into the classic node async trap. Your "things should happen" test sometimes returns before the disconnect event happens and sometimes not.
You need to handle the done function the same way you do in the "echoes message" test.  Punctually, it should like this:
socket.on('disconnect', function(connection) {
console.log('disconnected');
console.log("i'm here");
done()});

In general, I'm not sure how much that test makes handling all those different callbacks.

Testing with Mocha in Node.js


Como faço Log out em angular 4?

Question: boa tarde,
Gostaria de saber como faço para fazer Log out em angular 4, pois estou desenvolvendo um dashboard e só falta esse requisito
Desde já agradeço.
<code> import { Component, Input, OnInit } from '@angular/core';

import { NbMenuService, NbSidebarService } from '@nebular/theme';
import { UserService } from '../../../@core/data/users.service';
import { AnalyticsService } from '../../../@core/utils/analytics.service';

@Component({
  selector: 'ngx-header',
  styleUrls: ['./header.component.scss'],
  templateUrl: './header.component.html',
})
export class HeaderComponent implements OnInit {

  @Input() position = 'normal';

  user: any;

  userMenu = [{ title: 'Profile' }, { title: 'Log out' }];

  constructor(private sidebarService: NbSidebarService,
              private menuService: NbMenuService,
              private userService: UserService,
              private analyticsService: AnalyticsService) {
  }

  ngOnInit() {
    this.userService.getUsers()
      .subscribe((users: any) => this.user = users.nick);
  }

  toggleSidebar(): boolean {
    this.sidebarService.toggle(true, 'menu-sidebar');
    return false;
  }

  toggleSettings(): boolean {
    this.sidebarService.toggle(false, 'settings-sidebar');
    return false;
  }

  goToHome() {
    this.menuService.navigateHome();
  }

  startSearch() {
    this.analyticsService.trackEvent('startSearch');
  }
}
</code>
Comment: Isso depende da sua API
Answer: Deveria ter uma rota na sua api para realizar esta ação man. Você pode zerar o usuário e senha no Angular, ou deletar o token de verificação, isso resolveria seu problema, mas uma rota seria o mais indicado.
Answer: Bom dia, isso vai depender de como você está realizando o login ... se for com cookie ou localstorage, pode ser criado um componente, onde você poderia apenas usar o método de limpar pelo TypeScript e redirecionar, caso esteja fazendo isso via servidor, teria que fazer um método na sua aplicação e chamar um httprequest ... explique como está sua aplicação.

Como faço Log out em angular 4?


How fast the solution of $\frac{e^x}{e^x-1}-\frac{1}{x}=\frac{1}{n}$ goes to $-\infty$ as $n\to\infty$?

Question: I have an equation, for each $n\in\mathbb{N}$, $n\geq 3$:
$$
f(x):=\frac{e^x}{e^x-1}-\frac{1}{x} = \frac{1}{n}.
$$
which has a unique solution which tends to $-\infty$ as $n\to\infty$, since the left-hand side is continuous and monotone increasing with the limit $\lim_{x\to\pm\infty} f(x)= 1$ and $0$.
Since the solution cannot be written in a closed form, I would like to know how fast the solution goes to $-\infty$ comparing to $n$. In other words, how can I expressed the solution in terms of $n$, say $\phi(n)$, so that $f(\phi(n))\sim\frac{1}{n}$ as $n\to\infty$?
Answer: For large $n$ if we take $\phi(n) = -n$ then $$\left|f(-n) - \frac{1}{n}\right| =\left|\frac{1}{1-e^n}\right|<2e^{-n}.$$
Answer: Since the solution cannot be written in a closed form...
$$\frac{e^x}{e^x-1}-\frac{1}{x} = \frac{1}{n}\quad \implies \quad e^{-x}=\frac {n+(1-n)x}{x+n}$$ has an explicit solution in terms  of the generalized Lambert function (have a look at equation $(4)$).
If you consider the reciprocal for of the equation, that is to say
$$\frac{\left(e^x-1\right) x}{e^x (x-1)+1}=n$$ the solution is close to $x_0=-n$
The first iterate of Newton method is
$$x_1=-n+\frac{\left(e^n-1\right) n^2}{1+e^{2 n}-e^n \left(n^2+2\right)}$$ which seems to be decent.
For illustration purposes, let $n=2^k$ and compare
$$\left(
\begin{array}{ccc}
 n & x_1 & \text{solution} \\
 4 & -3.5710413473964268697 &  -3.5935119694474260822 \\
 8 & -7.9780516483210477777 &  -7.9781077369770703258 \\
 16 & -15.999971190162046898 &  -15.999971190213911766 \\
 32 & -31.999999999987031894 &  -31.999999999987031894 \\
\end{array}
\right)$$
Neglecting the "small" numbers
$$x_1 \sim -n + n^2\,e^{-n}$$


nginx load balancer - how to preserve full original url in upstream?

Question: nginx 1.7.9 on linux
Issue:
When using nginx, the Web servers see all requests as coming over http, even when they come in via https.
Using IIS request tracing, we see the request coming in like this, even when the outside (from browser) request is https://myapp.com:443/appdir/:
RequestURL="http://myapp.com:80/appdir/"

But on our hardware load balancer (which we are trying to phase out), it comes correctly as:
RequestURL="https://myapp.com:443/appdir/"

The app needs to see the https, it depends on it. (It tries to force connections to secure.)
We know about using X-Forwarded-Proto and the like to tell the app that the request came in via ssl, however part of the app is build around the request itself, and we may not be able to modify it.
The hardware load balancer can "do it all" -- terminate ssl, and send "pretend" requests back to the app (over port 80) that appear to be requests to https.
How do I get nginx to pass the full, unchanged, request url back to the servers?
Config:
http {

upstream sandbox_site {
    least_conn;
    # we pipe to back end on port 80 only, so that nginx handles all ssl
    server 192.168.2.16:80 max_fails=1 fail_timeout=60s;  # sbox3-site is .2.16
}

server {
    # This is sandbox.myapp.com block **************************************
    listen 192.168.2.27:80;
    server_name sandbox.myapp.com;

    location / {
    proxy_pass http://sandbox_site;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

server {
    # This is SSL version of sandbox.myapp.com block **************************************
    listen 192.168.2.27:443 ssl;
    server_name sandbox.myapp.com;

    ssl_certificate      new-sandbox-myapp-com.cer;
    ssl_certificate_key  new-sandbox-myapp-com.key;

    ssl_protocols SSLv3 TLSv1;
    ssl_ciphers HIGH:!aNULL:!MD5;

    location / {
        proxy_pass http://sandbox_site;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

}
Comment: `The hardware load balancer can "do it all" -- terminate ssl, and send "pretend" requests back to the app (over port 80)` - perhaps look at the actual request sent over the wire to determine how it's doing that. Either there's a header it's setting (such as `ORIGINAL_URI`) or it's doing something different than you think.
Answer: Basically you have two choices:

either you are offloading SSL, like you are doing it now, then you may tell your backends that the request actually was received with SSL (if it was):
proxy_set_header X-Forwarded-Proto $scheme;

but this surely means you have to adjust the code, so it handles that header.
or, if no code modification is allowed, you can stop offloading SSL, and actually proxy pages from backends via it.
So this is how the SSL sandbox block would look like:
location / {
    proxy_pass https://sandbox_site;
    proxy_redirect     off;
    proxy_set_header   Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

However, this second way is way redundant: you see, you actually do still offload SSL, but then assemble the SSL request again, even when it comes through your trusted network. All it does - just adding unnecessary conversion.
Comment: I don't think so, nginx it better as load balancer when it comes to HTTP. Furthermore I am not sure how IIS handles it. To my knowledge, passing https request to port 80 should either rise an error, or should mean that port 80 is SSL-enabled. However, IIS/Windows is not really my area of expertise. Finally I should say that I don't see a way to archieve your goal on haproxy (though it does provide similar possibilities to the mentioned above ones).
Comment: Ohhhhhh, not a nice choice at all.  I am familiar with the "X-Forwarded-Proto" as part of our app (the old part) uses it to detect secure channel. But the new part depends on the request (possibly due to js/backend division of responsibility, not sure, I do the network, not the app). The hardware load balancer can "do it all" (terminate ssl, and pass full requests back over port 80). Is it time to drop nginx and look at haproxy?
Comment: You are correct. On closer inspection, the hardware lb is not doing what we thought. Code mods... here we come...


FTP user permission issues

Question: I have created 1 ftp share under /var/ftp/xyz, now i want to set permission in such a way that user can upload and download files from that share but cannot edit and delete files from that share.
Answer: You'll need to do two things:

Set the file permission on the folder(s) folks are uploading to to allow them read/write permission.
You'll also need to set the umask in /etc/vsftpd.conf so new files are created read-only.  Change the local_umask for logged-in users, anon_umask for anonymous users.  A umask of local_umask=0222 will remove write access on all files uploaded.

EDIT:  You're correct - you'll need another step.  Add this to your /etc/vsftpd.conf:
"cmds_denied=DELE"

Comment: Permission on my xyz folder is 3770. After making local_umask=0222 files are created r--r--r-- but still user is able to delete file which he has uploaded. I want is like once its uploaded cannot be deleted by anyone not even the owner of the file who has uploaded.

FTP user permission issues


Como descobrir se um número é subnúmero

Question: Gostaria de um código,com explicação (se possível é claro), para saber se um número é sub número de outro.
Exemplo:

P=101
  Q=100001010057

Logo P é sub número de Q. Grato desde já.
Answer: Uma forma simples de fazer isso:
>>> str(101) in str(100001010057)
True

>>> str(18) in str(100001010057)
False

Você converte seus 2 números para string e utiliza o operador in nativo de Python, que procura uma substring dentro de uma string. Mais genérico:
str(P) in str(Q)

Comment: Nossa,havia feito um código com mais de 20 linhas,bem mais complicado.
Comment: Muito obrigado,é de grande ajuda.
Answer: Com o método find você pode verificar se a ocorrências na string alvo, veja o exemplo abaixo:
if '101'.find(str(011001101)):
    print('101 eh sub numero de 011001101')

Converti para string o numero 011001101 e em seguida pesquisei pelo numero 101 através do método find passando como parâmetro a sequencia de numero que é a string alvo que converti.
Implementação com variáveis:
P = '101'
Q = '100001010057'

if P.find(Q):
    print("P eh sub numero de Q")

Lebre-se que o método find é um método do módulo string.py ou seja, ele só funciona com strings, se tiver um inteiro sera necessário converte-lo para string como foi feito no exemplo acima.
Fonte: https://docs.python.org/2/library/string.html
Comment: Se não entender algo, deixe um comentário que eu acrescento mais informações.

Como descobrir se um número é subnúmero


Calculate the Variance of $\min(N_k,p)$

Question: I am trying to compute the variance of a random variable $\min(N_k,p)$, where $N_k$ is a random variable and $p$ is a fixed number. I have computed the expectation using the conditional expectation, which is as given below $$\mathbb{E}[\min(N_k, p)] = \mathbb{E}[N_k \mid N_k \leq p] *\mathbb{P}(N_k \leq p)+ \mathbb{E}[\min(N_k, p)\mid N_k > p] * \mathbb{P}(N_k > p).$$ Now, to compute the variance, we need to compute $\mathbb{E}[(\min(N_k,p))^2]$. I don't have any idea how I should proceed to compute this because I don't have access to $\mathbb{P}(\min(N_k,p)=i)$.
Comment: If you don't have any information about the distribution of $N_k$, there is no way you can compute this.
Comment: Use the same formula that you used for  the expectation.
Comment: @user6247850 here, $N_k$'s are discrete random variables. Let's say it is a binomial distribution.
Answer: You can still apply conditional probability, as
$$
\begin{align*}
\text{Var}(\min(N_k, p)) &= E[(\min(N_k, p))^2] - E[\min(N_k, p)]^2 \\
&= E(N_k^2 | N_k \leq p)P(N_k \leq p) + p^2 P(N_k > p) - \left[ E(N_k | N_k \leq p) P(N_k \leq p) + p P(N_k > p) \right]^2
\end{align*}
$$
Comment: how do we go for this $E(N_k^2 | N_k \leq p)$?
Comment: I'm assuming you know the distribution of $N_k | N_k \leq p$. So then you just use the variance of $N_k | N_k \leq p$.
$$
Var(N_k | N_k \leq p) = E(N_k^2 | N_k \leq p) - E(N_k | N_k \leq p)^2 \implies E(N_k^2 | N_k \leq p) = Var(N_k | N_k \leq p) + E(N_k | N_k \leq p)^2
$$
Comment: Actually, I have access to the distribution of $N_k$ only. I can't compute the variance you mentioned. I have found a way to calculate the expectation, can you verify that is it correct or not?
Comment: \begin{align*}
    E(N_k^2\mid N_k\leq p) &= \sum_{i=1}^n i^2\, P(N_k = i \mid N_k\leq p)\\
    &= \sum_{i=0}^n i^2 \;\dfrac{P(N_k = i \cap N_k\leq p)}{P(N_k\leq p)}\\
    &= \sum_{i=0}^p i^2 \;\dfrac{P(N_k = i \cap N_k\leq p)}{P(N_k\leq p)}\quad\quad [\text{as $P(N_k = i \cap N_k\leq p)= 0$ for $i>p$.} ]\\&= \sum_{i=0}^p i^2 \;\dfrac{P(N_k = i)}{P(N_k\leq p)}\\&= \dfrac{\sum_{i=0}^p i^2 \,P(N_k = i)}{P(N_k\leq p)}\\
\end{align*}
Comment: Thus we have $$E(N_k^2 \mid N_k\leq p) * P(N_k\leq p) = \sum_{i=0}^p i^2 \,P(N_k = i) $$ Can I do that? I am a little bit confused.

Calculate the Variance of $\min(N_k,p)$


QSettings how to read ini without value of keys

Question: I have config:
[Users]
joe
bill
dona
serg

I need QStringList with all usernames.
QSettings ini("/tmp/users.ini", QSettings::NativeFormat);
ini.beginGroup("Users");
QStringList keys = ini.allKeys();
qDebug() << keys;
ini.endGroup();

This not work :(
Comment: Where such ini file comes from? Qt docs say: "Each setting consists of a QString that specifies the setting's name (the key) and a QVariant that stores the data associated with the key.". I think `QSettings` does not support such format.
Comment: What exactly doesn't work? Show your output.
Answer: I change the config to
[Users]
joe=1
bill=1
dona=1
serg=1

And it work now.
Comment: in the future you should be able to verify format issues with `QSettings::status()`


How to find optimal border that defines, who is "friend"

Question: I have the data about usage of several services in the population and the data about interactions among users.
The idea is to determine, who is user's friend and who has interacted just "accidentally".
The basic idea is that friends affect users behavior. So if a friend or a number of friends adopted the service, there is a bigger chance that you will adopt is as well.
Tho probability of service adoption is represented as Bayes Network:
P(FA,GA,UA) = P(FA)P(GA)P(UA|FA,GA)
where FA = friend adoption = {Service A, B, C, D}
GA = global adoption = {A, B, C, D}
UA = observed user adoption = {A, B, C, D}

Besides the data of service adoption I have the data of users interactions:
UserA, UserB, sum(interactions duration), number of interactions
What I would like to do here is determine the optimal values for parameters c, d for logistic regression
P(neighbor = friend|number of interactions, duration) = 1/(1+exp(-c*number of interactions - d*duration)) that fits the best the given data of service adoption and Bayes Network.
Does anyone know what would be the best approach for solving the given problem?
Thank you!
Answer: If you are trying to fit your data to the logistic function, the usual method is Maximum Likelihood Estimation of the parameters (in your case c and d).
Since a closed-form expression for the ML estimator of the logistic function does not exist, you have to use a numerical method (e.g. Newton).
http://en.wikipedia.org/wiki/Logistic_regression#Maximum_likelihood_estimation