问:
How does Facebook folly::AccessSpreader work?
Here is the code for AccessSpreader from the Facebook Folly library:
https://github.com/facebook/folly/blob/master/folly/concurrency/CacheLocality.h#L212

```<code>/// AccessSpreader arranges access to a striped data structure in such a
/// way that concurrently executing threads are likely to be accessing
/// different stripes.  It does NOT guarantee uncontended access.
/// Your underlying algorithm must be thread-safe without spreading, this
/// is merely an optimization.  AccessSpreader::current(n) is typically
/// much faster than a cache miss (12 nanos on my dev box, tested fast
/// in both 2.6 and 3.2 kernels).
///
/// If available (and not using the deterministic testing implementation)
/// AccessSpreader uses the getcpu system call via VDSO and the
/// precise locality information retrieved from sysfs by CacheLocality.
/// This provides optimal anti-sharing at a fraction of the cost of a
/// cache miss.
///
/// When there are not as many stripes as processors, we try to optimally
/// place the cache sharing boundaries.  This means that if you have 2
/// stripes and run on a dual-socket system, your 2 stripes will each get
/// all of the cores from a single socket.  If you have 16 stripes on a
/// 16 core system plus hyperthreading (32 cpus), each core will get its
/// own stripe and there will be no cache sharing at all.
///
/// AccessSpreader has a fallback mechanism for when __vdso_getcpu can't be
/// loaded, or for use during deterministic testing.  Using sched_getcpu
/// or the getcpu syscall would negate the performance advantages of
/// access spreading, so we use a thread-local value and a shared atomic
/// counter to spread access out.  On systems lacking both a fast getcpu()
/// and TLS, we hash the thread id to spread accesses.
///
/// AccessSpreader is templated on the template type that is used
/// to implement atomics, as a way to instantiate the underlying
/// heuristics differently for production use and deterministic unit
/// testing.  See DeterministicScheduler for more.  If you aren't using
/// DeterministicScheduler, you can just use the default template parameter
/// all of the time.
template <template <typename> class Atom = std::atomic>
struct AccessSpreader {
  /// Returns the stripe associated with the current CPU.  The returned
  /// value will be < numStripes.
  static size_t current(size_t numStripes) {
    // widthAndCpuToStripe[0] will actually work okay (all zeros), but
    // something's wrong with the caller
    assert(numStripes > 0);

    unsigned cpu;
    getcpuFunc(&cpu, nullptr, nullptr);
    return widthAndCpuToStripe[std::min(size_t(kMaxCpus), numStripes)]
                              [cpu % kMaxCpus];
  }

 private:
  /// If there are more cpus than this nothing will crash, but there
  /// might be unnecessary sharing
  enum { kMaxCpus = 128 };

  typedef uint8_t CompactStripe;

  static_assert(
      (kMaxCpus & (kMaxCpus - 1)) == 0,
      "kMaxCpus should be a power of two so modulo is fast");
  static_assert(
      kMaxCpus - 1 <= std::numeric_limits<CompactStripe>::max(),
      "stripeByCpu element type isn't wide enough");

  /// Points to the getcpu-like function we are using to obtain the
  /// current cpu.  It should not be assumed that the returned cpu value
  /// is in range.  We use a static for this so that we can prearrange a
  /// valid value in the pre-constructed state and avoid the need for a
  /// conditional on every subsequent invocation (not normally a big win,
  /// but 20% on some inner loops here).
  static Getcpu::Func getcpuFunc;

  /// For each level of splitting up to kMaxCpus, maps the cpu (mod
  /// kMaxCpus) to the stripe.  Rather than performing any inequalities
  /// or modulo on the actual number of cpus, we just fill in the entire
  /// array.
  static CompactStripe widthAndCpuToStripe[kMaxCpus + 1][kMaxCpus];

  static bool initialized;

  /// Returns the best getcpu implementation for Atom
  static Getcpu::Func pickGetcpuFunc() {
    auto best = Getcpu::resolveVdsoFunc();
    return best ? best : &FallbackGetcpuType::getcpu;
  }

  /// Always claims to be on CPU zero, node zero
  static int degenerateGetcpu(unsigned* cpu, unsigned* node, void*) {
    if (cpu != nullptr) {
      *cpu = 0;
    }
    if (node != nullptr) {
      *node = 0;
    }
    return 0;
  }

  // The function to call for fast lookup of getcpu is a singleton, as
  // is the precomputed table of locality information.  AccessSpreader
  // is used in very tight loops, however (we're trying to race an L1
  // cache miss!), so the normal singleton mechanisms are noticeably
  // expensive.  Even a not-taken branch guarding access to getcpuFunc
  // slows AccessSpreader::current from 12 nanos to 14.  As a result, we
  // populate the static members with simple (but valid) values that can
  // be filled in by the linker, and then follow up with a normal static
  // initializer call that puts in the proper version.  This means that
  // when there are initialization order issues we will just observe a
  // zero stripe.  Once a sanitizer gets smart enough to detect this as
  // a race or undefined behavior, we can annotate it.

  static bool initialize() {
    getcpuFunc = pickGetcpuFunc();

    auto& cacheLocality = CacheLocality::system<Atom>();
    auto n = cacheLocality.numCpus;
    for (size_t width = 0; width <= kMaxCpus; ++width) {
      auto numStripes = std::max(size_t{1}, width);
      for (size_t cpu = 0; cpu < kMaxCpus && cpu < n; ++cpu) {
        auto index = cacheLocality.localityIndexByCpu[cpu];
        assert(index < n);
        // as index goes from 0..n, post-transform value goes from
        // 0..numStripes
        widthAndCpuToStripe[width][cpu] =
            CompactStripe((index * numStripes) / n);
        assert(widthAndCpuToStripe[width][cpu] < numStripes);
      }
      for (size_t cpu = n; cpu < kMaxCpus; ++cpu) {
        widthAndCpuToStripe[width][cpu] = widthAndCpuToStripe[width][cpu - n];
      }
    }
    return true;
  }
};

template <template <typename> class Atom>
Getcpu::Func AccessSpreader<Atom>::getcpuFunc =
    AccessSpreader<Atom>::degenerateGetcpu;

template <template <typename> class Atom>
typename AccessSpreader<Atom>::CompactStripe
    AccessSpreader<Atom>::widthAndCpuToStripe[kMaxCpus + 1][kMaxCpus] = {};

template <template <typename> class Atom>
bool AccessSpreader<Atom>::initialized = AccessSpreader<Atom>::initialize();

// Suppress this instantiation in other translation units. It is
// instantiated in CacheLocality.cpp
extern template struct AccessSpreader<std::atomic>;
</code>```

As far as I understand it's supposed to wrap some data within an atomic class and when it's accessed by multiple threads it should reduce false cache sharing? Could someone who has worked with Folly elaborate a bit how it might work?
I've been looking at it for a while and I don't even see where they put the atomic variable member.

答:
No, this class does not do what you think.

The overall idea is that when you have a number of equivalent resources/data structures, and want different threads to access different instances to minimize contention and maximize data locality, you use AccessSpreader to suggest the best resource/data to use for the current core/thread.

For an example, see e.g. https://github.com/facebook/folly/blob/master/folly/IndexedMemPool.h. This implementation of a memory pool maintains a number of free object lists, to reduce thread contention on allocation/deallocation. And here is how AccessSpreader is used:

```<code>AtomicStruct<TaggedPtr,Atom>& localHead() {
  auto stripe = AccessSpreader<Atom>::current(NumLocalLists);
  return local_[stripe].head;
}
</code>```

i.e. it gives an index of an element (in some array or vector etc.) that is recommended for use by the current thread.

Update (in response to the comment): it is not always possible to assign different indices to different threads - e.g. if the number of possible indices (stripes) is less than the number of CPUs; and the comments explicitly tell that "It does NOT guarantee uncontended access". The class can be used not only to minimize contention but also to maximize data locality; for example, you might want to share some instances of data between threads that have common cache. So, the recommended index is a function of two variables: the current CPU (obtained internally with getCpuFunc) and the number of stripes (passed as the parameter numStripes) - this is why a 2D array is needed. The array is filled at program initialization time using system-specific information (via class CacheLocality), so that the recommended index takes data locality into account.

As for std::atomic, it is used merely to have separate AccessSpreader instantiations for testing and for production use, as explained in the comment right before the class declaration. The class does not have (and does not need) any atomic member variables.

Body:
Here is the code for AccessSpreader from the Facebook Folly library:
https://github.com/facebook/folly/blob/master/folly/concurrency/CacheLocality.h#L212

/// AccessSpreader arranges access to a striped data structure in such a
/// way that concurrently executing threads are likely to be accessing
/// different stripes.  It does NOT guarantee uncontended access.
/// Your underlying algorithm must be thread-safe without spreading, this
/// is merely an optimization.  AccessSpreader::current(n) is typically
/// much faster than a cache miss (12 nanos on my dev box, tested fast
/// in both 2.6 and 3.2 kernels).
///
/// If available (and not using the deterministic testing implementation)
/// AccessSpreader uses the getcpu system call via VDSO and the
/// precise locality information retrieved from sysfs by CacheLocality.
/// This provides optimal anti-sharing at a fraction of the cost of a
/// cache miss.
///
/// When there are not as many stripes as processors, we try to optimally
/// place the cache sharing boundaries.  This means that if you have 2
/// stripes and run on a dual-socket system, your 2 stripes will each get
/// all of the cores from a single socket.  If you have 16 stripes on a
/// 16 core system plus hyperthreading (32 cpus), each core will get its
/// own stripe and there will be no cache sharing at all.
///
/// AccessSpreader has a fallback mechanism for when __vdso_getcpu can't be
/// loaded, or for use during deterministic testing.  Using sched_getcpu
/// or the getcpu syscall would negate the performance advantages of
/// access spreading, so we use a thread-local value and a shared atomic
/// counter to spread access out.  On systems lacking both a fast getcpu()
/// and TLS, we hash the thread id to spread accesses.
///
/// AccessSpreader is templated on the template type that is used
/// to implement atomics, as a way to instantiate the underlying
/// heuristics differently for production use and deterministic unit
/// testing.  See DeterministicScheduler for more.  If you aren't using
/// DeterministicScheduler, you can just use the default template parameter
/// all of the time.
template <template <typename> class Atom = std::atomic>
struct AccessSpreader {
  /// Returns the stripe associated with the current CPU.  The returned
  /// value will be < numStripes.
  static size_t current(size_t numStripes) {
    // widthAndCpuToStripe[0] will actually work okay (all zeros), but
    // something's wrong with the caller
    assert(numStripes > 0);

    unsigned cpu;
    getcpuFunc(&cpu, nullptr, nullptr);
    return widthAndCpuToStripe[std::min(size_t(kMaxCpus), numStripes)]
                              [cpu % kMaxCpus];
  }

 private:
  /// If there are more cpus than this nothing will crash, but there
  /// might be unnecessary sharing
  enum { kMaxCpus = 128 };

  typedef uint8_t CompactStripe;

  static_assert(
      (kMaxCpus & (kMaxCpus - 1)) == 0,
      "kMaxCpus should be a power of two so modulo is fast");
  static_assert(
      kMaxCpus - 1 <= std::numeric_limits<CompactStripe>::max(),
      "stripeByCpu element type isn't wide enough");

  /// Points to the getcpu-like function we are using to obtain the
  /// current cpu.  It should not be assumed that the returned cpu value
  /// is in range.  We use a static for this so that we can prearrange a
  /// valid value in the pre-constructed state and avoid the need for a
  /// conditional on every subsequent invocation (not normally a big win,
  /// but 20% on some inner loops here).
  static Getcpu::Func getcpuFunc;

  /// For each level of splitting up to kMaxCpus, maps the cpu (mod
  /// kMaxCpus) to the stripe.  Rather than performing any inequalities
  /// or modulo on the actual number of cpus, we just fill in the entire
  /// array.
  static CompactStripe widthAndCpuToStripe[kMaxCpus + 1][kMaxCpus];

  static bool initialized;

  /// Returns the best getcpu implementation for Atom
  static Getcpu::Func pickGetcpuFunc() {
    auto best = Getcpu::resolveVdsoFunc();
    return best ? best : &FallbackGetcpuType::getcpu;
  }

  /// Always claims to be on CPU zero, node zero
  static int degenerateGetcpu(unsigned* cpu, unsigned* node, void*) {
    if (cpu != nullptr) {
      *cpu = 0;
    }
    if (node != nullptr) {
      *node = 0;
    }
    return 0;
  }

  // The function to call for fast lookup of getcpu is a singleton, as
  // is the precomputed table of locality information.  AccessSpreader
  // is used in very tight loops, however (we're trying to race an L1
  // cache miss!), so the normal singleton mechanisms are noticeably
  // expensive.  Even a not-taken branch guarding access to getcpuFunc
  // slows AccessSpreader::current from 12 nanos to 14.  As a result, we
  // populate the static members with simple (but valid) values that can
  // be filled in by the linker, and then follow up with a normal static
  // initializer call that puts in the proper version.  This means that
  // when there are initialization order issues we will just observe a
  // zero stripe.  Once a sanitizer gets smart enough to detect this as
  // a race or undefined behavior, we can annotate it.

  static bool initialize() {
    getcpuFunc = pickGetcpuFunc();

    auto& cacheLocality = CacheLocality::system<Atom>();
    auto n = cacheLocality.numCpus;
    for (size_t width = 0; width <= kMaxCpus; ++width) {
      auto numStripes = std::max(size_t{1}, width);
      for (size_t cpu = 0; cpu < kMaxCpus && cpu < n; ++cpu) {
        auto index = cacheLocality.localityIndexByCpu[cpu];
        assert(index < n);
        // as index goes from 0..n, post-transform value goes from
        // 0..numStripes
        widthAndCpuToStripe[width][cpu] =
            CompactStripe((index * numStripes) / n);
        assert(widthAndCpuToStripe[width][cpu] < numStripes);
      }
      for (size_t cpu = n; cpu < kMaxCpus; ++cpu) {
        widthAndCpuToStripe[width][cpu] = widthAndCpuToStripe[width][cpu - n];
      }
    }
    return true;
  }
};

template <template <typename> class Atom>
Getcpu::Func AccessSpreader<Atom>::getcpuFunc =
    AccessSpreader<Atom>::degenerateGetcpu;

template <template <typename> class Atom>
typename AccessSpreader<Atom>::CompactStripe
    AccessSpreader<Atom>::widthAndCpuToStripe[kMaxCpus + 1][kMaxCpus] = {};

template <template <typename> class Atom>
bool AccessSpreader<Atom>::initialized = AccessSpreader<Atom>::initialize();

// Suppress this instantiation in other translation units. It is
// instantiated in CacheLocality.cpp
extern template struct AccessSpreader<std::atomic>;

As far as I understand it's supposed to wrap some data within an atomic class and when it's accessed by multiple threads it should reduce false cache sharing? Could someone who has worked with Folly elaborate a bit how it might work?
I've been looking at it for a while and I don't even see where they put the atomic variable member.

Body:
No, this class does not do what you think.

The overall idea is that when you have a number of equivalent resources/data structures, and want different threads to access different instances to minimize contention and maximize data locality, you use AccessSpreader to suggest the best resource/data to use for the current core/thread.

For an example, see e.g. https://github.com/facebook/folly/blob/master/folly/IndexedMemPool.h. This implementation of a memory pool maintains a number of free object lists, to reduce thread contention on allocation/deallocation. And here is how AccessSpreader is used:

AtomicStruct<TaggedPtr,Atom>& localHead() {
  auto stripe = AccessSpreader<Atom>::current(NumLocalLists);
  return local_[stripe].head;
}

i.e. it gives an index of an element (in some array or vector etc.) that is recommended for use by the current thread.

Update (in response to the comment): it is not always possible to assign different indices to different threads - e.g. if the number of possible indices (stripes) is less than the number of CPUs; and the comments explicitly tell that "It does NOT guarantee uncontended access". The class can be used not only to minimize contention but also to maximize data locality; for example, you might want to share some instances of data between threads that have common cache. So, the recommended index is a function of two variables: the current CPU (obtained internally with getCpuFunc) and the number of stripes (passed as the parameter numStripes) - this is why a 2D array is needed. The array is filled at program initialization time using system-specific information (via class CacheLocality), so that the recommended index takes data locality into account.

As for std::atomic, it is used merely to have separate AccessSpreader instantiations for testing and for production use, as explained in the comment right before the class declaration. The class does not have (and does not need) any atomic member variables.


来源: stackexchange

问:
Connecting to LDAP with PHP Successfully, but cannot connect with C#
I am connecting successfully to the LDAP with PHP, tried a whole lot of things but when I try with C# am always getting either "Server is not operational" or "The LDAP server in unavailable".
Here is the PHP code:

```<code>    <?php
function login($username='user', $password='pass') {
        if (empty($username) || empty($password)) {
            throw new BadCredentialsException('Invalid username or password.');
        }
        if (($ldap = @ldap_connect($url = 'ldap://ds.xyz-example.com', $port = 636)) === false) {
            echo('Error connecting LDAP server with url %s on port %d.');

        }
        if (!@ldap_bind($ldap, sprintf($dn='uid=%s,ou=People,dc=xyz-example,dc=com', $username), $password)) {
            $error = ldap_errno($ldap);
            if ($error === 0x31) {
                echo('Invalid username or password.');

            } else {
                echo('error during authentication with LDAP.');
            }
        }
        return true;
    }

login(); // call the function
?>
</code>```

This is working perfect but I need it with C#. How can I do this with C# using the port and the dn and the user and pass?

Here is what I tried with C# but with an error "Server is not operational"

```<code>string ldapPath = "LDAP://ds.xyz-example.com:636/UID=user,OU=People,DC=xyz-example,DC=com";
            string user = "user";
            string password = "pass";

            DirectoryEntry deSSL = new DirectoryEntry(ldapPath, user, password, AuthenticationTypes.SecureSocketsLayer);
            try
            {
                user = deSSL.Properties["uid"][0].ToString(); //if this works, we bound successfully
                Response.Output.Write("Success... {0} has bound", user);
            }
            catch (Exception ex)
            {
                Response.Output.Write("Bind Failure: {0}", ex.Message);
            }
</code>```

Thanks in advance!

答:
Could it be your library doesn't implement LDAP but rather a weird non-standard Microsoft version of LDAP called ActiveDirectory, which only works when the server is an actual ActiveDirectory Server and doesn't quite work as easily when you use non-microsoft servers, such as OpenLDAP?

Could it be?

ContentLicense: CC BY-SA 3.0

Body:
I am connecting successfully to the LDAP with PHP, tried a whole lot of things but when I try with C# am always getting either "Server is not operational" or "The LDAP server in unavailable".
Here is the PHP code:

    <?php
function login($username='user', $password='pass') {
        if (empty($username) || empty($password)) {
            throw new BadCredentialsException('Invalid username or password.');
        }
        if (($ldap = @ldap_connect($url = 'ldap://ds.xyz-example.com', $port = 636)) === false) {
            echo('Error connecting LDAP server with url %s on port %d.');

        }
        if (!@ldap_bind($ldap, sprintf($dn='uid=%s,ou=People,dc=xyz-example,dc=com', $username), $password)) {
            $error = ldap_errno($ldap);
            if ($error === 0x31) {
                echo('Invalid username or password.');

            } else {
                echo('error during authentication with LDAP.');
            }
        }
        return true;
    }

login(); // call the function
?>

This is working perfect but I need it with C#. How can I do this with C# using the port and the dn and the user and pass?

Here is what I tried with C# but with an error "Server is not operational"

string ldapPath = "LDAP://ds.xyz-example.com:636/UID=user,OU=People,DC=xyz-example,DC=com";
            string user = "user";
            string password = "pass";

            DirectoryEntry deSSL = new DirectoryEntry(ldapPath, user, password, AuthenticationTypes.SecureSocketsLayer);
            try
            {
                user = deSSL.Properties["uid"][0].ToString(); //if this works, we bound successfully
                Response.Output.Write("Success... {0} has bound", user);
            }
            catch (Exception ex)
            {
                Response.Output.Write("Bind Failure: {0}", ex.Message);
            }

Thanks in advance!


问:
Using GDB to Debug VM Running on XEN Hypervisor
I always used GDB to do kernel debug. Normally I would run the target kernel inside a VM and run GDB from the host machine. Currently I am working on a project where I need to use XEN hypervisor and I am in a situation where I feel the need to debug a DOM-U from DOM-0. After some searching I couldn't find a way to use GDB in this scenario. Is it possible to use GDB to debug a guest VM running in XEN? If not, what other alternatives I could use?

答:
You can create a pipe (for example, /tmp/mydebug.pipe), then have this line in the .conf file for your domU:

```<code> serial = 'pipe:/tmp/mydebug.pipe'
</code>```

Then you can simply use a tool such as WinDBG from another domU. See mkfifo.

Other possibly useful links:

https://xenserver.org/partners/developing-products-for-xenserver/18-sdk-development/135-xs-dev-windbg.html

http://www-archive.xenproject.org/files/xensummit_intel09/xen-debugging.pdf

https://www.slideshare.net/xen_com_mgr/from-printk-to-qemu-xenlinux-kernel-debugging

Body:
You can create a pipe (for example, /tmp/mydebug.pipe), then have this line in the .conf file for your domU:

 serial = 'pipe:/tmp/mydebug.pipe'

Then you can simply use a tool such as WinDBG from another domU. See mkfifo.

Other possibly useful links:

https://xenserver.org/partners/developing-products-for-xenserver/18-sdk-development/135-xs-dev-windbg.html

http://www-archive.xenproject.org/files/xensummit_intel09/xen-debugging.pdf

https://www.slideshare.net/xen_com_mgr/from-printk-to-qemu-xenlinux-kernel-debugging


问:
Can't get div to show when unchecked
I am trying to use bootstrap toggle to create a switch to change between monthly and annual plans. I got the toggle to function in the sense it moves and looks right but I can not get the JS part to work. So it will only show the monthly div right now and will not switch to the annual div. Currently this is what I have

Toggle

```<code><div class="container">
   <div class="row">
     <div class="col-md-5"></div>
     <div class="col-md-4 selectCenter">
       <br>
       <input type="checkbox" checked  id="toggle" data-toggle="toggle" data-on="Monthly" data-off="Annual" data-style="ios" data-onstyle="primary" data-offstyle="primary">
     </div>
   </div>
</code>```

Monthly div

```<code><section class="se-section" id="monthly">
    <div class="container">
      <div class="row">
       <div class="col-md-4 col-sm-6">
         <h1>Monthly</h1>
       </div> <!-- end col-md-4 -->
      </div> <!-- end row -->
    </div> <!-- end container -->
  </section>
</code>```

Annual div

```<code><section class="se-section" id="annual">
    <div class="container">
      <div class="row">
       <div class="col-md-4 col-sm-6">
         <h1>Annual</h1>
       </div> <!-- end col-md-4 -->
      </div> <!-- end row -->
    </div> <!-- end container -->
  </section>
</code>```

Then my javascript

```<code>var toggle = document.getElementById("toggle");
var monthly = document.getElementById("monthly");
var annual = document.getElementById("annual");

if(toggle.checked){
  monthly.style.display = 'block';
  annual.style.display = 'none';
}
if(!toggle.checked){
  monthly.style.display = 'none';
  annual.style.display = 'block';
}
</code>```

答:
You need to assign an EventListener to the toggle. The function assigned that way is going to be executed. This function shows then the correct block.</p>

```<code>toggle.addEventListener('change', togglePlanViews);

function togglePlanViews() {
    if(toggle.checked){
      monthly.style.display = 'block';
      annual.style.display = 'none';
    } else {
      monthly.style.display = 'none';
      annual.style.display = 'block';
    }
}
</code>```

Title: Can't get div to show when unchecked

Body:
I am trying to use bootstrap toggle to create a switch to change between monthly and annual plans. I got the toggle to function in the sense it moves and looks right but I can not get the JS part to work. So it will only show the monthly div right now and will not switch to the annual div. Currently this is what I have

Toggle

       <input type="checkbox" checked  id="toggle" data-toggle="toggle" data-on="Monthly" data-off="Annual" data-style="ios" data-onstyle="primary" data-offstyle="primary">

Monthly div

Monthly

Annual div

Annual

Then my javascript

var toggle = document.getElementById("toggle");
var monthly = document.getElementById("monthly");
var annual = document.getElementById("annual");

if(toggle.checked){
  monthly.style.display = 'block';
  annual.style.display = 'none';
}
if(!toggle.checked){
  monthly.style.display = 'none';
  annual.style.display = 'block';
}

Body:
You need to assign an EventListener to the toggle. The function assigned that way is going to be executed. This function shows then the correct block.

toggle.addEventListener('change', togglePlanViews);

function togglePlanViews() {
    if(toggle.checked){
      monthly.style.display = 'block';
      annual.style.display = 'none';
    } else {
      monthly.style.display = 'none';
      annual.style.display = 'block';
    }
}


问:
Unit Testing: Beginner Questions
I'm finally starting out with unit testing, having known that I should be doing it for a while, but I have a few questions:

Should or shouldn't I retest parent
classes when testing the children if
no methods have been overwritten?

Conceptually, how do you test the
submitted part of a form? I'm using
PHP. (Edit: The reason I ask this is that I have a high level form class that generates a form, validates it, filters it, and generates any error messages by taking a JSON-like array as input and delegating to a variety of smaller classes. However, I can't test the errors, etc without submitting the form. Edit: This looks like it might be an answer.)

If you have optional parameter in a
method, should you write a test for
both when they are present and when
they are not?

Should unit testing in any way be
combined with testing code execution
time or should they remain completely
separate?

Is there any valid reason not to run
your full test suite every time?

Just so I'm getting my terminology
right, to what does the unit in unit
testing refer? The class being
tested? The method? The parameter?
Something else?

答:
Test parent, test child; if the child doesn't override the parent method, no need to retest it.

I'm not sure I understand the second one.  You can use Selenium to automate testing a form.  Is that what you mean?

Tests should include the "happy path" and all edge cases.  If you have an optional parameter, write tests to show proper operation with the value present and absent.

Unit tests, integration tests, acceptance tests, load tests are all different ideas that may have some overlap.

I'll bet there are valid reasons, but if you're doing automated builds that run the test suite automatically why would you not run them?  Maybe long run times come to mind, but that's the only reason I can think of.  The value is seeing that all of them continue to pass, and that changes you've made haven't broken anything.

Unit test to me means the class you're testing, which can have several methods.  I associate them with classes, not forms.  Forms mean UI and integration testing to me.

OwnerDisplayName: VirtuosiMedia

ContentLicense: CC BY-SA 2.5

Title: Unit Testing: Beginner Questions

LastEditorDisplayName: VirtuosiMedia


问:
For what reasons it is not preferable to use Thrift API for Cassandra access?
Please enumerate reasons for why its not advisable to use Thrift interface for Cassandra? What are the possible advantages and disadvantages?</p>

答:
If you use the raw Thrift apis the cons will be:

no connection pooling

no monitoring

no object oriented interface (not entirely true)

no failover support


问:
How to add symbol to each word of input and echo back with initial formatting? (PHP)
What I'm trying to do is to input a list of strings containing words via textarea, and add + to each word within these strings.

When I'm exploding with ' ' the first word of each line obviously is not added as separate item. When I use preg_split or 2 loops - formatting is lost, and I'm getting echoed just a long line instead of several strings.
Question is - how to correctly split all strings into words, add symbol to each of them, and then combine them back and output back to user without loosing formatting (such as newlines)?

Since I'm newbie there is surely should be some easy way to do that, but I was unable to find it.

```<code><div class="row">
    <div class="col-lg-6">
        <form class="form-group" action="" method="post" >
                <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" name="un"></textarea>

                <input  class="btn btn-primary" type="submit" value="submit" name="submit" />
          </form>
    </div>
    </div>
        <div class="col-lg-6 offset-lg-1">
                <?php
                    $counter = 0;
                        if (isset($_POST['un'])) {
                                $input = nl2br($_POST["un"]);
                                $rows = explode("\n", $input);
                                $words = array();
                                foreach($rows as $row) {
                                    $temp = explode(" ", $row);
                                    foreach($temp as $word)
                                        echo "+" . $word;
                                }

                            }

                ?>
        </div>
</code>```

答:
Use str_ireplace.  This can replace text in a string with something else.

http://php.net/manual/en/function.str-ireplace.php

You have defined a new word as something following a " " or following a "\n".  Just use str_ireplace to change " " to "+" and "\n" to "\n+".  I suppose you'll also need to remove the final "+" if the end of the string is "\n" as well.

Body:
What I'm trying to do is to input a list of strings containing words via textarea, and add + to each word within these strings.

When I'm exploding with ' ' the first word of each line obviously is not added as separate item. When I use preg_split or 2 loops - formatting is lost, and I'm getting echoed just a long line instead of several strings.
Question is - how to correctly split all strings into words, add symbol to each of them, and then combine them back and output back to user without loosing formatting (such as newlines)?

Since I'm newbie there is surely should be some easy way to do that, but I was unable to find it.

        <form class="form-group" action="" method="post" >
                <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" name="un"></textarea>

                <input  class="btn btn-primary" type="submit" value="submit" name="submit" />
          </form>

                <?php
                    $counter = 0;
                        if (isset($_POST['un'])) {
                                $input = nl2br($_POST["un"]);
                                $rows = explode("\n", $input);
                                $words = array();
                                foreach($rows as $row) {
                                    $temp = explode(" ", $row);
                                    foreach($temp as $word)
                                        echo "+" . $word;
                                }

                            }

                ?>


问:
Call an R function with run-time generated ellipsis arguments (dot-dot-dot / three dots)
I want to call an R function that uses the ... (ellipsis) argument to support an undefined number of arguments:

```<code>f <- function(x, ...) {
  dot.args <- list(...)
  paste(names(dot.args), dot.args, sep = "=", collapse = ", ")
}
</code>```

I can call this function passing the actual arguments predefined during design-time, e. g.:

```<code>> f(1, a = 1, b = 2)
[1] "a=1, b=2"
</code>```

How can I pass actual arguments for ... that I know only at run-time (e. g. input from the user)?

```<code># let's assume the user input was "a = 1" and "b = 2"
# ------
# If the user input was converted into a vector:
> f(1, c(a = 1, b = 2))
[1] "=c(1, 2)"                # wrong result!
# If the user input was converted into a list:
> f(1, list(a = 1, b = 2))
[1] "=list(a = 1, b = 2)"     # wrong result!
</code>```

The expected output of the dynamically generated f call should be:

```<code>[1] "a=1, b=2"
</code>```

I have found some existing questions on how to use ... but they did not answer my question:

How to use R's ellipsis feature when writing your own function?

Usage of Dot / Period in R Functions

Pass ... argument to another function

Can I remove an element in ... (dot-dot-dot) and pass it on?

答:
You can do this by passing the function arguments using do.call. First force to list using as.list.

eg

```<code>input <- c(a = 1, b = 2)
do.call(f,  as.list(input))

input <- list(a = 1, b = 2)
do.call(f,  as.list(input))
</code>```

Body:
I want to call an R function that uses the ... (ellipsis) argument to support an undefined number of arguments:

f <- function(x, ...) {
  dot.args <- list(...)
  paste(names(dot.args), dot.args, sep = "=", collapse = ", ")
}

I can call this function passing the actual arguments predefined during design-time, e. g.:

> f(1, a = 1, b = 2)
[1] "a=1, b=2"

How can I pass actual arguments for ... that I know only at run-time (e. g. input from the user)?

# let's assume the user input was "a = 1" and "b = 2"
# ------
# If the user input was converted into a vector:
> f(1, c(a = 1, b = 2))
[1] "=c(1, 2)"                # wrong result!
# If the user input was converted into a list:
> f(1, list(a = 1, b = 2))
[1] "=list(a = 1, b = 2)"     # wrong result!

The expected output of the dynamically generated f call should be:

[1] "a=1, b=2"

I have found some existing questions on how to use ... but they did not answer my question:

How to use R's ellipsis feature when writing your own function?

Usage of Dot / Period in R Functions

Pass ... argument to another function

Can I remove an element in ... (dot-dot-dot) and pass it on?

Body:
You can do this by passing the function arguments using do.call. First force to list using as.list.

eg

input <- c(a = 1, b = 2)
do.call(f,  as.list(input))

input <- list(a = 1, b = 2)
do.call(f,  as.list(input))


问:
MS SQL Not Like Query
I have 2 tables, one a list of students and one with a list of restaurants.  The people table has PK that is contained within the restaurants table as an FK.  The restaurant table contains the days the students like to eat out at restaurants (along with restaurants they eat at).  I'm trying to find the students who do not like to eat at the restaurant on Monday.  I tried using the query below, but it lists all of the students and not the ones that don't eat out on Monday.</p>

```<code>SELECT DISTINCT SName
FROM Dinner AS D
INNER JOIN Student AS S ON D.SID = S.SID
WHERE DinnerDay NOT LIKE 'Monday'
GROUP BY SName
</code>```

答:
I think you are looking for this:</p>

```<code>SELECT  DISTINCT SName
FROM    Student AS S
WHERE   NOT EXISTS (
                        SELECT      NULL
                        FROM        Dinner AS D
                        WHERE       DinnerDay = 'Monday'
                                AND D.SID = S.SID
                    )
</code>```

Title: MS SQL Not Like Query

Body:
I have 2 tables, one a list of students and one with a list of restaurants.  The people table has PK that is contained within the restaurants table as an FK.  The restaurant table contains the days the students like to eat out at restaurants (along with restaurants they eat at).  I'm trying to find the students who do not like to eat at the restaurant on Monday.  I tried using the query below, but it lists all of the students and not the ones that don't eat out on Monday.

SELECT DISTINCT SName
FROM Dinner AS D
INNER JOIN Student AS S ON D.SID = S.SID
WHERE DinnerDay NOT LIKE 'Monday'
GROUP BY SName

Body:
I think you are looking for this:

SELECT  DISTINCT SName
FROM    Student AS S
WHERE   NOT EXISTS (
                        SELECT      NULL
                        FROM        Dinner AS D
                        WHERE       DinnerDay = 'Monday'
                                AND D.SID = S.SID
                    )


问:
React Native Map Box Execution Failed transform classes with Dex / JarMerging
I've just started using MapBox in react-native but I appear to be getting the following error

```<code>* What went wrong:
Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
</code>```

Enabling multidex with

```<code>multiDexEnabled true
</code>```

I then get the following

FAILURE: Build failed with an exception.

```<code>* What went wrong:
Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: okhttp3/internal/ws/RealWebSocket$1.class
</code>```

Here's the config

build.gradle .../android

```<code>allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        // Add jitpack repository (added by tipsi-stripe)
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}
</code>```

build.gradle ../app

```<code>dependencies {
    compile project(':mapbox-react-native-mapbox-gl')
    compile project(':react-native-branch')
    compile project(':react-native-camera')
    compile project(':tipsi-stripe')
    compile project(':react-native-device-info')
    compile project(':react-native-vector-icons')
    compile project(':react-native-i18n')
    compile project(':react-native-geocoder')
    compile project(':react-native-fbsdk')
    compile(project(':react-native-maps')) {
        exclude group: 'com.google.android.gms', module: 'play-services-base'
        exclude group: 'com.google.android.gms', module: 'play-services-maps'
    }
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:25.0.0"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile 'com.google.android.gms:play-services-base:11.+'
    compile 'com.google.android.gms:play-services-maps:11.+'
}
</code>```

settings.gradle

```<code>include ':mapbox-react-native-mapbox-gl'
project(':mapbox-react-native-mapbox-gl').projectDir = new File(rootProject.projectDir, '../node_modules/@mapbox/react-native-mapbox-gl/android/rctmgl')
include ':react-native-branch'
project(':react-native-branch').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-branch/android')
include ':react-native-camera'
project(':react-native-camera').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-camera/android')
include ':tipsi-stripe'
project(':tipsi-stripe').projectDir = new File(rootProject.projectDir, '../node_modules/tipsi-stripe/android')
include ':react-native-device-info'
project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')
include ':react-native-vector-icons'
project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
include ':react-native-i18n'
project(':react-native-i18n').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-i18n/android')
include ':react-native-geocoder'
project(':react-native-geocoder').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-geocoder/android')
include ':react-native-fbsdk'
project(':react-native-fbsdk').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fbsdk/android')
include ':react-native-maps'
project(':react-native-maps').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-maps/lib/android')

include ':app'
</code>```

MainApplication.java

```<code>import android.app.Application;
import android.content.Intent;

import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.facebook.react.ReactApplication;
import com.mapbox.rctmgl.RCTMGLPackage;
import io.branch.rnbranch.RNBranchPackage;
import io.branch.referral.Branch;
import com.lwansbrough.RCTCamera.RCTCameraPackage;
import com.gettipsi.stripe.StripeReactPackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import com.oblador.vectoricons.VectorIconsPackage;
import com.i18n.reactnativei18n.ReactNativeI18n;
import com.devfd.RNGeocoder.RNGeocoderPackage;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.airbnb.android.react.maps.MapsPackage;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

    private static CallbackManager mCallbackManager = CallbackManager.Factory.create();

    protected static CallbackManager getCallbackManager() {
        return mCallbackManager;
    }

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(
                    new MainReactPackage(),
            new RCTMGLPackage(),
            new RNBranchPackage(),
            new RCTCameraPackage(),
            new StripeReactPackage(),
            new RNDeviceInfo(),
                    new MapsPackage(),
                    new VectorIconsPackage(),
                    new ReactNativeI18n(),
                    new RNGeocoderPackage(),
                    new FBSDKPackage(mCallbackManager)
            );
        }
    };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        FacebookSdk.sdkInitialize(getApplicationContext());
        SoLoader.init(this, /* native exopackage */ false);
        // initialize the Branch object
        Branch.setPlayStoreReferrerCheckTimeout(0);
        Branch.getAutoInstance(this);
    }
}
</code>```

Stacktrace

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformDexArchiveWithDexMergerForDebug'.
> com.android.build.api.transform.TransformException: com.android.dex.DexException: Multiple dex files define Lokhttp3/internal/ws/WebSocketReader;

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformDexArchiveWithDexMergerForDebug'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: java.lang.RuntimeException: com.android.build.api.transform.TransformException: com.android.dex.DexException: Multiple dex files define Lokhttp3/internal/ws/WebSocketReader;
        at com.android.builder.profile.Recorder$Block.handleException(Recorder.java:55)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:104)
        at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:213)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
        ... 27 more
Caused by: com.android.build.api.transform.TransformException: com.android.dex.DexException: Multiple dex files define Lokhttp3/internal/ws/WebSocketReader;
        at com.android.build.gradle.internal.transforms.DexMergerTransform.transform(DexMergerTransform.java:230)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:222)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:218)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
        ... 39 more
Caused by: com.android.dex.DexException: Multiple dex files define Lokhttp3/internal/ws/WebSocketReader;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:661)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:616)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:598)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
        at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:61)
        at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:36)

* Get more help at https://help.gradle.org

BUILD FAILED in 8s
148 actionable tasks: 4 executed, 144 up-to-date
</code>```

I'm not sure if this is a matter of my current project config or what not, but i've not seen reports of this so far.

Update with adding in workaround enables app to launch but then another issue arises: NoClassDefFoundError: com.google.android.gms.wallet.MaskedWalletRequest

I've now added in configurations.all { resolutionStrategy.force 'com.squareup.okhttp3:okhttp:3.4.1' } as suggested by https://github.com/facebook/react-native/issues/12646 which enables the app to build succesfully but then there is an issue of NoClassDefFoundError: com.google.android.gms.wallet.MaskedWalletRequest

Just to clarify moving over to mapbox, I'll no longer need react-native-maps, and the reason for the move over is the greater level of detail i.e. in the buildings.

Thanks, appreciate you're help

答:
Looks like a similar issue was raised against the repo and can probably be resolved if you...

exclude android.arch.core module from the mapbox project

Body:
I've just started using MapBox in react-native but I appear to be getting the following error

* What went wrong:
Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

Enabling multidex with

multiDexEnabled true

I then get the following

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: okhttp3/internal/ws/RealWebSocket$1.class

Here's the config

build.gradle .../android

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        // Add jitpack repository (added by tipsi-stripe)
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}

build.gradle ../app

dependencies {
    compile project(':mapbox-react-native-mapbox-gl')
    compile project(':react-native-branch')
    compile project(':react-native-camera')
    compile project(':tipsi-stripe')
    compile project(':react-native-device-info')
    compile project(':react-native-vector-icons')
    compile project(':react-native-i18n')
    compile project(':react-native-geocoder')
    compile project(':react-native-fbsdk')
    compile(project(':react-native-maps')) {
        exclude group: 'com.google.android.gms', module: 'play-services-base'
        exclude group: 'com.google.android.gms', module: 'play-services-maps'
    }
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:25.0.0"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile 'com.google.android.gms:play-services-base:11.+'
    compile 'com.google.android.gms:play-services-maps:11.+'
}

settings.gradle

include ':mapbox-react-native-mapbox-gl'
project(':mapbox-react-native-mapbox-gl').projectDir = new File(rootProject.projectDir, '../node_modules/@mapbox/react-native-mapbox-gl/android/rctmgl')
include ':react-native-branch'
project(':react-native-branch').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-branch/android')
include ':react-native-camera'
project(':react-native-camera').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-camera/android')
include ':tipsi-stripe'
project(':tipsi-stripe').projectDir = new File(rootProject.projectDir, '../node_modules/tipsi-stripe/android')
include ':react-native-device-info'
project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')
include ':react-native-vector-icons'
project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
include ':react-native-i18n'
project(':react-native-i18n').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-i18n/android')
include ':react-native-geocoder'
project(':react-native-geocoder').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-geocoder/android')
include ':react-native-fbsdk'
project(':react-native-fbsdk').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-fbsdk/android')
include ':react-native-maps'
project(':react-native-maps').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-maps/lib/android')

include ':app'

MainApplication.java

import android.app.Application;
import android.content.Intent;

import com.facebook.CallbackManager;
import com.facebook.FacebookSdk;
import com.facebook.react.ReactApplication;
import com.mapbox.rctmgl.RCTMGLPackage;
import io.branch.rnbranch.RNBranchPackage;
import io.branch.referral.Branch;
import com.lwansbrough.RCTCamera.RCTCameraPackage;
import com.gettipsi.stripe.StripeReactPackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import com.oblador.vectoricons.VectorIconsPackage;
import com.i18n.reactnativei18n.ReactNativeI18n;
import com.devfd.RNGeocoder.RNGeocoderPackage;
import com.facebook.reactnative.androidsdk.FBSDKPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.airbnb.android.react.maps.MapsPackage;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

    private static CallbackManager mCallbackManager = CallbackManager.Factory.create();

    protected static CallbackManager getCallbackManager() {
        return mCallbackManager;
    }

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(
                    new MainReactPackage(),
            new RCTMGLPackage(),
            new RNBranchPackage(),
            new RCTCameraPackage(),
            new StripeReactPackage(),
            new RNDeviceInfo(),
                    new MapsPackage(),
                    new VectorIconsPackage(),
                    new ReactNativeI18n(),
                    new RNGeocoderPackage(),
                    new FBSDKPackage(mCallbackManager)
            );
        }
    };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        FacebookSdk.sdkInitialize(getApplicationContext());
        SoLoader.init(this, /* native exopackage */ false);
        // initialize the Branch object
        Branch.setPlayStoreReferrerCheckTimeout(0);
        Branch.getAutoInstance(this);
    }
}

Stacktrace

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformDexArchiveWithDexMergerForDebug'.
> com.android.build.api.transform.TransformException: com.android.dex.DexException: Multiple dex files define Lokhttp3/internal/ws/WebSocketReader;

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformDexArchiveWithDexMergerForDebug'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: java.lang.RuntimeException: com.android.build.api.transform.TransformException: com.android.dex.DexException: Multiple dex files define Lokhttp3/internal/ws/WebSocketReader;
        at com.android.builder.profile.Recorder$Block.handleException(Recorder.java:55)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:104)
        at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:213)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
        ... 27 more
Caused by: com.android.build.api.transform.TransformException: com.android.dex.DexException: Multiple dex files define Lokhttp3/internal/ws/WebSocketReader;
        at com.android.build.gradle.internal.transforms.DexMergerTransform.transform(DexMergerTransform.java:230)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:222)
        at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:218)
        at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
        ... 39 more
Caused by: com.android.dex.DexException: Multiple dex files define Lokhttp3/internal/ws/WebSocketReader;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:661)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:616)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:598)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
        at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:61)
        at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:36)

* Get more help at https://help.gradle.org

BUILD FAILED in 8s
148 actionable tasks: 4 executed, 144 up-to-date

I'm not sure if this is a matter of my current project config or what not, but i've not seen reports of this so far.

Update with adding in workaround enables app to launch but then another issue arises: NoClassDefFoundError: com.google.android.gms.wallet.MaskedWalletRequest

I've now added in configurations.all { resolutionStrategy.force 'com.squareup.okhttp3:okhttp:3.4.1' } as suggested by https://github.com/facebook/react-native/issues/12646 which enables the app to build succesfully but then there is an issue of NoClassDefFoundError: com.google.android.gms.wallet.MaskedWalletRequest

Just to clarify moving over to mapbox, I'll no longer need react-native-maps, and the reason for the move over is the greater level of detail i.e. in the buildings.

Thanks, appreciate you're help


问:
Windows batch file file download from a URL
I am trying to download a file from a website (ex. http://www.example.com/package.zip) using a Windows batch file.  I am getting an error code when I write the function below:

```<code>xcopy /E /Y "http://www.example.com/package.zip"
</code>```

The batch file doesn't seem to like the "/" after the http.  Are there any ways to escape those characters so it doesn't assume they are function parameters?

答:
Downloading files in PURE BATCH...
Without any JScript, VBScript, Powershell, etc... Only pure Batch!

Some people are saying it's not possible of downloading files with a batch script without using any JScript or VBScript, etc... But they are definitely wrong!

Here is a simple method that seems to work pretty well for downloading files in your batch scripts. It should be working on almost any file's URL. It is even possible to use a proxy server if you need it.

For downloading files, we can use BITSADMIN.EXE from the Windows system. There is no need for downloading/installing anything or using any JScript or VBScript, etc. Bitsadmin.exe is present on most Windows versions, probably from XP to Windows 10.

Enjoy!

USAGE:

You can use the BITSADMIN command directly, like this:

bitsadmin /transfer mydownloadjob /download /priority FOREGROUND "http://example.com/File.zip" "C:\Downloads\File.zip"

Proxy Server:

For connecting using a proxy, use this command before downloading.

bitsadmin /setproxysettings mydownloadjob OVERRIDE "proxy-server.com:8080"

Click this LINK if you want more info about BITSadmin.exe

TROUBLESHOOTING:

If you get this error: "Unable to connect to BITS - 0x80070422"

Make sure the windows service "Background Intelligent Transfer Service (BITS)" is enabled and try again. (It should be enabled by default.)

CUSTOM FUNCTIONS

Call :DOWNLOAD_FILE "URL"

Call :DOWNLOAD_PROXY_ON "SERVER:PORT"

Call :DOWNLOAD_PROXY_OFF

I made these 3 functions for simplifying the bitsadmin commands. It's easier to use and remember. It can be particularly useful if you are using it multiple times in your scripts.

PLEASE NOTE...

Before using these functions, you will first need to copy them from CUSTOM_FUNCTIONS.CMD to the end of your script. There is also a complete example: DOWNLOAD-EXAMPLE.CMD

:DOWNLOAD_FILE "URL"

The main function, will download files from URL.

:DOWNLOAD_PROXY_ON "SERVER:PORT"

(Optional) You can use this function if you need to use a proxy server.

Calling the :DOWNLOAD_PROXY_OFF function will disable the proxy server.

EXAMPLE:

CALL :DOWNLOAD_PROXY_ON "proxy-server.com:8080"

CALL :DOWNLOAD_FILE "http://example.com/File.zip" "C:\Downloads\File.zip"

CALL :DOWNLOAD_PROXY_OFF

CUSTOM_FUNCTIONS.CMD

```<code>:DOWNLOAD_FILE
    rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
    bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF

:DOWNLOAD_PROXY_ON
    rem FUNCTION FOR USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
GOTO :EOF

:DOWNLOAD_PROXY_OFF
    rem FUNCTION FOR STOP USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF
</code>```

DOWNLOAD-EXAMPLE.CMD

```<code>@ECHO OFF
SETLOCAL

rem FOR DOWNLOADING FILES, THIS SCRIPT IS USING THE "BITSADMIN.EXE" SYSTEM FILE.
rem IT IS PRESENT ON MOST WINDOWS VERSION, PROBABLY FROM WINDOWS XP TO WINDOWS 10.

:SETUP

rem URL (5MB TEST FILE):
SET "FILE_URL=http://ipv4.download.thinkbroadband.com/5MB.zip"

rem SAVE IN CUSTOM LOCATION:
rem SET "SAVING_TO=C:\Folder\5MB.zip"

rem SAVE IN THE CURRENT DIRECTORY
SET "SAVING_TO=5MB.zip"
SET "SAVING_TO=%~dp0%SAVING_TO%"

:MAIN

ECHO.
ECHO DOWNLOAD SCRIPT EXAMPLE
ECHO.
ECHO FILE URL: "%FILE_URL%"
ECHO SAVING TO:  "%SAVING_TO%"
ECHO.

rem UNCOMENT AND MODIFY THE NEXT LINE IF YOU NEED TO USE A PROXY SERVER:
rem CALL :DOWNLOAD_PROXY_ON "PROXY-SERVER.COM:8080"

rem THE MAIN DOWNLOAD COMMAND:
CALL :DOWNLOAD_FILE "%FILE_URL%" "%SAVING_TO%"

rem UNCOMMENT NEXT LINE FOR DISABLING THE PROXY (IF YOU USED IT):
rem CALL :DOWNLOAD_PROXY_OFF

:RESULT
ECHO.
IF EXIST "%SAVING_TO%" ECHO YOUR FILE HAS BEEN SUCCESSFULLY DOWNLOADED.
IF NOT EXIST "%SAVING_TO%" ECHO ERROR, YOUR FILE COULDN'T BE DOWNLOADED.
ECHO.

:EXIT_SCRIPT
PAUSE
EXIT /B

rem FUNCTIONS SECTION

:DOWNLOAD_FILE
    rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
    bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF

:DOWNLOAD_PROXY_ON
    rem FUNCTION FOR USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
GOTO :EOF

:DOWNLOAD_PROXY_OFF
    rem FUNCTION FOR STOP USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF
</code>```

Body:
I am trying to download a file from a website (ex. http://www.example.com/package.zip) using a Windows batch file.  I am getting an error code when I write the function below:

xcopy /E /Y "http://www.example.com/package.zip"

The batch file doesn't seem to like the "/" after the http.  Are there any ways to escape those characters so it doesn't assume they are function parameters?

Body:
Downloading files in PURE BATCH...
Without any JScript, VBScript, Powershell, etc... Only pure Batch!

Some people are saying it's not possible of downloading files with a batch script without using any JScript or VBScript, etc... But they are definitely wrong!

Here is a simple method that seems to work pretty well for downloading files in your batch scripts. It should be working on almost any file's URL. It is even possible to use a proxy server if you need it.

For downloading files, we can use BITSADMIN.EXE from the Windows system. There is no need for downloading/installing anything or using any JScript or VBScript, etc. Bitsadmin.exe is present on most Windows versions, probably from XP to Windows 10.

Enjoy!

USAGE:

You can use the BITSADMIN command directly, like this:

bitsadmin /transfer mydownloadjob /download /priority FOREGROUND "http://example.com/File.zip" "C:\Downloads\File.zip"

Proxy Server:

For connecting using a proxy, use this command before downloading.

bitsadmin /setproxysettings mydownloadjob OVERRIDE "proxy-server.com:8080"

Click this LINK if you want more info about BITSadmin.exe

TROUBLESHOOTING:

If you get this error: "Unable to connect to BITS - 0x80070422"

Make sure the windows service "Background Intelligent Transfer Service (BITS)" is enabled and try again. (It should be enabled by default.)

CUSTOM FUNCTIONS

Call :DOWNLOAD_FILE "URL"

Call :DOWNLOAD_PROXY_ON "SERVER:PORT"

Call :DOWNLOAD_PROXY_OFF

I made these 3 functions for simplifying the bitsadmin commands. It's easier to use and remember. It can be particularly useful if you are using it multiple times in your scripts.

PLEASE NOTE...

Before using these functions, you will first need to copy them from CUSTOM_FUNCTIONS.CMD to the end of your script. There is also a complete example: DOWNLOAD-EXAMPLE.CMD

:DOWNLOAD_FILE "URL"

The main function, will download files from URL.

:DOWNLOAD_PROXY_ON "SERVER:PORT"

(Optional) You can use this function if you need to use a proxy server.

Calling the :DOWNLOAD_PROXY_OFF function will disable the proxy server.

EXAMPLE:

CALL :DOWNLOAD_PROXY_ON "proxy-server.com:8080"

CALL :DOWNLOAD_FILE "http://example.com/File.zip" "C:\Downloads\File.zip"

CALL :DOWNLOAD_PROXY_OFF

CUSTOM_FUNCTIONS.CMD

:DOWNLOAD_FILE
    rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
    bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF

:DOWNLOAD_PROXY_ON
    rem FUNCTION FOR USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
GOTO :EOF

:DOWNLOAD_PROXY_OFF
    rem FUNCTION FOR STOP USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF

DOWNLOAD-EXAMPLE.CMD

@ECHO OFF
SETLOCAL

rem FOR DOWNLOADING FILES, THIS SCRIPT IS USING THE "BITSADMIN.EXE" SYSTEM FILE.
rem IT IS PRESENT ON MOST WINDOWS VERSION, PROBABLY FROM WINDOWS XP TO WINDOWS 10.

:SETUP

rem URL (5MB TEST FILE):
SET "FILE_URL=http://ipv4.download.thinkbroadband.com/5MB.zip"

rem SAVE IN CUSTOM LOCATION:
rem SET "SAVING_TO=C:\Folder\5MB.zip"

rem SAVE IN THE CURRENT DIRECTORY
SET "SAVING_TO=5MB.zip"
SET "SAVING_TO=%~dp0%SAVING_TO%"

:MAIN

ECHO.
ECHO DOWNLOAD SCRIPT EXAMPLE
ECHO.
ECHO FILE URL: "%FILE_URL%"
ECHO SAVING TO:  "%SAVING_TO%"
ECHO.

rem UNCOMENT AND MODIFY THE NEXT LINE IF YOU NEED TO USE A PROXY SERVER:
rem CALL :DOWNLOAD_PROXY_ON "PROXY-SERVER.COM:8080"

rem THE MAIN DOWNLOAD COMMAND:
CALL :DOWNLOAD_FILE "%FILE_URL%" "%SAVING_TO%"

rem UNCOMMENT NEXT LINE FOR DISABLING THE PROXY (IF YOU USED IT):
rem CALL :DOWNLOAD_PROXY_OFF

:RESULT
ECHO.
IF EXIST "%SAVING_TO%" ECHO YOUR FILE HAS BEEN SUCCESSFULLY DOWNLOADED.
IF NOT EXIST "%SAVING_TO%" ECHO ERROR, YOUR FILE COULDN'T BE DOWNLOADED.
ECHO.

:EXIT_SCRIPT
PAUSE
EXIT /B

rem FUNCTIONS SECTION

:DOWNLOAD_FILE
    rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
    bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF

:DOWNLOAD_PROXY_ON
    rem FUNCTION FOR USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
GOTO :EOF

:DOWNLOAD_PROXY_OFF
    rem FUNCTION FOR STOP USING A PROXY SERVER:
    bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF

ContentLicense: CC BY-SA 4.0


问:
Buttons that update labels in a grid for each respective row
I have a QGrid with 2 columns and 3 rows. The first column consists of QPushButtons's and the second column consists of QLabel's.
The buttons => ["This Button", "That Button", "A Button"]. All the labels start at the text 0. Pressing the button in a row should change the text (number) of the label in that same row by adding 1.

The above is a simplified version of the problem, where in reality I have 10+ rows, and 5+ columns.

How would I create all of these rows and columns in a grid with as little code as possible? And how would I link each button to it's respective label without having to create a function for each separate button?

答:
There are several ways to solve it, I will show some:

lambda functios:

```<code>class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        lay = QGridLayout(self)
        for i in range(3):
            btn = QPushButton("button-{}".format(i), self)
            lbl = QLabel("{}".format(0))
            lay.addWidget(btn, i, 0)
            lay.addWidget(lbl, i, 1)
            btn.clicked.connect(lambda checked, l=lbl: self.fun(l))

    def fun(self, lbl):
        n = int(lbl.text()) + 1
        lbl.setText(str(n))
</code>```

dictionary

```<code>class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        lay = QGridLayout(self)
        self.connections = {}
        for i in range(3):
            btn = QPushButton("button-{}".format(i), self)
            lbl = QLabel("{}".format(0))
            lay.addWidget(btn, i, 0)
            lay.addWidget(lbl, i, 1)
            self.connections[btn] = lbl
            btn.clicked.connect(self.fun)

    def fun(self):
        lbl = self.connections[self.sender()]
        n = int(lbl.text()) + 1
        lbl.setText(str(n))
</code>```

Body:
There are several ways to solve it, I will show some:

lambda functios:

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        lay = QGridLayout(self)
        for i in range(3):
            btn = QPushButton("button-{}".format(i), self)
            lbl = QLabel("{}".format(0))
            lay.addWidget(btn, i, 0)
            lay.addWidget(lbl, i, 1)
            btn.clicked.connect(lambda checked, l=lbl: self.fun(l))

    def fun(self, lbl):
        n = int(lbl.text()) + 1
        lbl.setText(str(n))

dictionary

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        lay = QGridLayout(self)
        self.connections = {}
        for i in range(3):
            btn = QPushButton("button-{}".format(i), self)
            lbl = QLabel("{}".format(0))
            lay.addWidget(btn, i, 0)
            lay.addWidget(lbl, i, 1)
            self.connections[btn] = lbl
            btn.clicked.connect(self.fun)

    def fun(self):
        lbl = self.connections[self.sender()]
        n = int(lbl.text()) + 1
        lbl.setText(str(n))


答:
You need to understand a very basic concept in JavaScript, which is doing stuff when something else happens. In technical terms, binding to an event. You bind execution of some code (usually wrapped up in a function) every time some event happens:

```<code>target.addEventListener(type, listener[, options]);
</code>```

type is the event itself (its name)

listener is the name of the function to be executed (you can have an anonymous function instead of a name, but it's better to keep it tidy and just put your code inside a named function

options are:

capture: A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.

once: A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

passive: A Boolean indicating that the listener will never call preventDefault(). If it does, the user agent should ignore it and generate a console warning. See Improving scrolling performance with passive listeners to learn more.

mozSystemGroup: A Boolean indicating that the listener should be added to the system group. Available only in code running in XBL or in Firefox's chrome.

options is optional

Now, back to your example:

```<code>var toggle = document.getElementById("toggle"),
    monthly = document.getElementById("monthly"),
    annual = document.getElementById("annual");

// define functionality:
function toggleDivs() {
   monthly.style.display = toggle.checked ? 'block' : 'none';
   annual.style.display = toggle.checked? 'none' : 'block';
}

// bind to `change` on toggle:
toggle.addEventListener('change', toggleDivs, {passive:true});

// bind to `window.onload` (so it runs once when the page is loaded):
window.onload = toggleDivs;
</code>```

That's about it. Please note binding a function like this on window.onload is not exactly best practice (it can override another bind on it or can be overridden by a subsequent similar function). Read this for details.

Alternatively, since you're using Bootstrap, it means you're also using jQuery, which enables a more concise syntax:

```<code>// define the function:
function toggleDivs() {
  $('#monthly').css('display', $('#toggle').prop('checked') ?
    'block':'none');
  $('#weekly').css('display', $('#toggle').prop('checked') ?
    'none':'block');
}
// bind to `change` on `#toggle` :
$('#toggle').on('change', toggleDivs);

// bind to `load` on `window` :
$(window).on('load', toggleDivs);
</code>```

Title: Can't get div to show when unchecked

Body:
You need to understand a very basic concept in JavaScript, which is doing stuff when something else happens. In technical terms, binding to an event. You bind execution of some code (usually wrapped up in a function) every time some event happens:

target.addEventListener(type, listener[, options]);

type is the event itself (its name)

listener is the name of the function to be executed (you can have an anonymous function instead of a name, but it's better to keep it tidy and just put your code inside a named function

options are:

capture: A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.

once: A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.

passive: A Boolean indicating that the listener will never call preventDefault(). If it does, the user agent should ignore it and generate a console warning. See Improving scrolling performance with passive listeners to learn more.

mozSystemGroup: A Boolean indicating that the listener should be added to the system group. Available only in code running in XBL or in Firefox's chrome.

options is optional

Now, back to your example:

var toggle = document.getElementById("toggle"),
    monthly = document.getElementById("monthly"),
    annual = document.getElementById("annual");

// define functionality:
function toggleDivs() {
   monthly.style.display = toggle.checked ? 'block' : 'none';
   annual.style.display = toggle.checked? 'none' : 'block';
}

// bind to `change` on toggle:
toggle.addEventListener('change', toggleDivs, {passive:true});

// bind to `window.onload` (so it runs once when the page is loaded):
window.onload = toggleDivs;

That's about it. Please note binding a function like this on window.onload is not exactly best practice (it can override another bind on it or can be overridden by a subsequent similar function). Read this for details.

Alternatively, since you're using Bootstrap, it means you're also using jQuery, which enables a more concise syntax:

// define the function:
function toggleDivs() {
  $('#monthly').css('display', $('#toggle').prop('checked') ?
    'block':'none');
  $('#weekly').css('display', $('#toggle').prop('checked') ?
    'none':'block');
}
// bind to `change` on `#toggle` :
$('#toggle').on('change', toggleDivs);

// bind to `load` on `window` :
$(window).on('load', toggleDivs);


问:
I am trying to use scapy on python3 on my macosX; however, I get the following error: OSError: Cannot find libdnet.so
I am trying to use scapy to read a pcap file on my MacOSx using Python 3.
However, when I run the following code:

from scapy.all import rdpcap

I get the following error:

OSError: Cannot find libdnet.so

I looked up how to install libdnet, but I was not able to find out how to install for Python 3. How do you either fix this error or download this package?

答: You have to upgrade to Scapy's current development version from the official repository.</p>


问:
Using DomPDF in Cakephp Delivers an error Cannot redeclare class Dompdf\View\PdfView
I have a problem printing a PDF using CakePHP and DomPDF as soon I want to fetch some data from the Database before printing the pdf. Without fetching the Data, it works like a charme. My function is the following:

```<code>public function tourpdf($tourid = null){

  $contain = ['Deliveries','Deliveries.Articletransactions','Deliveries.Orders','Deliveries.Orders.Customers',
            'Deliveries.Articletransactions.Orderarticles','Deliveries.Articletransactions.Orderarticles.Articles'];

  $tour = $this->Tours->get($tourid)
            ->contain($contain);

  $this->viewBuilder()
    ->className('Dompdf.Pdf')
    ->layout('Dompdf.default')
    ->options(['config' => [
        'filename' => $filename,
        'render' => 'browser',
        'size' => 'A4',
        'orientation' => 'landscape'
    ]]);

  $this->set('Test', 'Hallo');
  $this->set('Tour',$tour);
}
</code>```

As soon as I set the Data from the last line, that I fetched above, I get the error Message "Fatal error: Cannot redeclare class Dompdf\View\PdfView in .../src/View/PdfView.php on line 66".

However commenting the last line out, the first set with Test is working and the PDF is generated. How can I set data retrieving from a query to the pdf file?

答:
Amazing!

Had this issue on Mac 10.12.6
PHP Version 5.6.30
libxml Version 2.9.4

Using the regex to remove whitespace between the tags fixed the issue.

```<code>$html = preg_replace('/>\s+</', '><', $html);
</code>```

Body:
I have a problem printing a PDF using CakePHP and DomPDF as soon I want to fetch some data from the Database before printing the pdf. Without fetching the Data, it works like a charme. My function is the following:

public function tourpdf($tourid = null){

  $contain = ['Deliveries','Deliveries.Articletransactions','Deliveries.Orders','Deliveries.Orders.Customers',
            'Deliveries.Articletransactions.Orderarticles','Deliveries.Articletransactions.Orderarticles.Articles'];

  $tour = $this->Tours->get($tourid)
            ->contain($contain);

  $this->viewBuilder()
    ->className('Dompdf.Pdf')
    ->layout('Dompdf.default')
    ->options(['config' => [
        'filename' => $filename,
        'render' => 'browser',
        'size' => 'A4',
        'orientation' => 'landscape'
    ]]);

  $this->set('Test', 'Hallo');
  $this->set('Tour',$tour);
}

As soon as I set the Data from the last line, that I fetched above, I get the error Message "Fatal error: Cannot redeclare class Dompdf\View\PdfView in .../src/View/PdfView.php on line 66".

However commenting the last line out, the first set with Test is working and the PDF is generated. How can I set data retrieving from a query to the pdf file?

Body:
Amazing!

Had this issue on Mac 10.12.6
PHP Version 5.6.30
libxml Version 2.9.4

Using the regex to remove whitespace between the tags fixed the issue.

$html = preg_replace('/>\s+</', '><', $html);


问:
Why not spark-streaming alone
I don't have much of an experience with Kafka/ Spark-Streaming, but I have read many articles on how great the combo is in building real time systems for analysis/dashboards. Can someone explain to me why spark-streaming can't do it alone? In other words, why is Kafka in between the data source and spark-streaming?

Thanks

答:
Can someone explain to me why spark-streaming can't do it alone?

Spark streaming is meant for live data and data needs to be ingested from somewhere. Like Kafka, Flume, Kinesis, or TCP sockets. Even you can read data from file.

https://spark.apache.org/docs/latest/streaming-programming-guide.html

In case if your use case is simple enough to read from file, i would say to go for apache nifi.

https://www.youtube.com/watch?v=gqV_63a0ABo&list=PLzmB162Wvzr05Pe-lobQEZkk0zXuzms56

In other words, why is Kafka in between the data source and
  spark-streaming?

Depending on scenarios, Kafka is often suitable option to store data and then consume from different aspects.

Title: Why not spark-streaming alone


问:
Optimize Create
I got 20 000 apples.

How do I create them in a smarter way than this?

```<code>        foreach (var a in apples)
        {
            graphClient.Cypher
                .Create("(a:Apple {newApple})")
                .WithParam("newApple", a)
                .ExecuteWithoutResults();
        }
</code>```

Looking for a generic way to be able to pass objects without specifying each property.

```<code>class Fruit
{
    [JsonProperty(PropertyName = "Color")]
    public bool Color { get; set; }
}

class Apple : Fruit
{
    [JsonProperty(PropertyName = "Variety")]
    public String Variety { get; set; }
}
</code>```

答:
I suppose apples is a list of dictionaries. In that case, a more optimized query in plain Cypher would look like this:

```<code>UNWIND {apples} AS newApple
CREATE (a:Apple)
SET a = newApple
</code>```

I have not yet used the Neo4jClient .NET lib, but something along these lines should work:

```<code>graphClient.Cypher
    .Unwind(apples, "newApple")
    .Create("(a:Apple)")
    .Set(...)
    .ExecuteWithoutResults();
</code>```

20k nodes might work in a single transaction, but it's worth to implement some batching and use batches of approx. 10k nodes.

Update. Updated the implementation per Chris Skardon's suggestion.

Remark. In the Cypher query, if you are using Neo4j 3.2+, you should switch to the new parameter syntax, that uses $param style parameters, so the query is slightly easier to read:

```<code>UNWIND $apples AS newApple
CREATE (a:Apple)
SET a = newApple
</code>```

Title: Optimize Create

Body:
I got 20 000 apples.

How do I create them in a smarter way than this?

        foreach (var a in apples)
        {
            graphClient.Cypher
                .Create("(a:Apple {newApple})")
                .WithParam("newApple", a)
                .ExecuteWithoutResults();
        }

Looking for a generic way to be able to pass objects without specifying each property.

class Fruit
{
    [JsonProperty(PropertyName = "Color")]
    public bool Color { get; set; }
}

class Apple : Fruit
{
    [JsonProperty(PropertyName = "Variety")]
    public String Variety { get; set; }
}

Body:
I suppose apples is a list of dictionaries. In that case, a more optimized query in plain Cypher would look like this:

UNWIND {apples} AS newApple
CREATE (a:Apple)
SET a = newApple

I have not yet used the Neo4jClient .NET lib, but something along these lines should work:

graphClient.Cypher
    .Unwind(apples, "newApple")
    .Create("(a:Apple)")
    .Set(...)
    .ExecuteWithoutResults();

20k nodes might work in a single transaction, but it's worth to implement some batching and use batches of approx. 10k nodes.

Update. Updated the implementation per Chris Skardon's suggestion.

Remark. In the Cypher query, if you are using Neo4j 3.2+, you should switch to the new parameter syntax, that uses $param style parameters, so the query is slightly easier to read:

UNWIND $apples AS newApple
CREATE (a:Apple)
SET a = newApple


问:
How to use a promise in ngrx/effects
I'm using @ngrx/store and @ngrx/effects with Firebase authentication in Angular.

This is the constructor:

```<code>constructor(
        private actions: Actions,
        private afAuth: AngularFireAuth,
        private db: AngularFirestore,
        private router: Router
    ) {}
</code>```

This is the effect:

```<code>@Effect()
    getUser: Observable<Action> = this.actions
        .ofType(authActions.GET_USER)
        .map((action: authActions.GetUser) => action.payload)
        .switchMap(payload => this.afAuth.authState)
        .map(authData => {
            if (authData) {
                const user = new User(
                    authData.uid,
                    authData.displayName,
                    authData.email,
                    authData.photoURL
                );

                return new authActions.Authenticated(user);
            } else {
                return new authActions.NotAuthenticated();
            }
        })
        .catch(err => Observable.of(new authActions.AuthError()));
</code>```

this code works as expected, but I need other values that are stored in a Firestore document and I can retrieve them in this way:

```<code>[...]
if (authData) {
    const userRef = this.db.firestore
        .collection('users')
        .doc(authData.uid)
        .get()
        .then(doc => {
            const userData = doc.data();
                return {
                    uid: userData.uid,
                    displayName: userData.displayName,
                    email: userData.email,
                    photoURL: userData.photoURL,
                    role: userData.roles
                };
            });
[...]
</code>```

But since it is a promise I can't use userRef where I'm using user.
Is there a solution to this problem?

答:
Only a matter to move a level up the switchMap.</p>

```<code>@Effect()
getUser: Observable<Action> = this.actions
    .ofType(authActions.GET_USER)
    .map((action: authActions.GetUser) => action.payload)
    .switchMap(payload =>
        this.afAuth.authState.switchMap(auth => {
            if (auth) {
                return this.db.doc<User>(`users/${auth.uid}`).valueChanges();
            } else {
                return Observable.of(null);
            }
        })
    )
    .map(authData => {
        if (authData) {
            const user = new User(
                authData.uid,
                authData.displayName,
                authData.email,
                authData.photoURL,
                authData.roles
            );

            return new authActions.Authenticated(user);
        } else {
            return new authActions.NotAuthenticated();
        }
    })
    .catch(err => Observable.of(new authActions.AuthError()));
</code>```

Title: How to use a promise in ngrx/effects

Body:
I'm using @ngrx/store and @ngrx/effects with Firebase authentication in Angular.

This is the constructor:

constructor(
        private actions: Actions,
        private afAuth: AngularFireAuth,
        private db: AngularFirestore,
        private router: Router
    ) {}

This is the effect:

@Effect()
    getUser: Observable<Action> = this.actions
        .ofType(authActions.GET_USER)
        .map((action: authActions.GetUser) => action.payload)
        .switchMap(payload => this.afAuth.authState)
        .map(authData => {
            if (authData) {
                const user = new User(
                    authData.uid,
                    authData.displayName,
                    authData.email,
                    authData.photoURL
                );

                return new authActions.Authenticated(user);
            } else {
                return new authActions.NotAuthenticated();
            }
        })
        .catch(err => Observable.of(new authActions.AuthError()));

this code works as expected, but I need other values that are stored in a Firestore document and I can retrieve them in this way:

[...]
if (authData) {
    const userRef = this.db.firestore
        .collection('users')
        .doc(authData.uid)
        .get()
        .then(doc => {
            const userData = doc.data();
                return {
                    uid: userData.uid,
                    displayName: userData.displayName,
                    email: userData.email,
                    photoURL: userData.photoURL,
                    role: userData.roles
                };
            });
[...]

But since it is a promise I can't use userRef where I'm using user.
Is there a solution to this problem?

Body:
Only a matter to move a level up the switchMap.

@Effect()
getUser: Observable<Action> = this.actions
    .ofType(authActions.GET_USER)
    .map((action: authActions.GetUser) => action.payload)
    .switchMap(payload =>
        this.afAuth.authState.switchMap(auth => {
            if (auth) {
                return this.db.doc<User>(`users/${auth.uid}`).valueChanges();
            } else {
                return Observable.of(null);
            }
        })
    )
    .map(authData => {
        if (authData) {
            const user = new User(
                authData.uid,
                authData.displayName,
                authData.email,
                authData.photoURL,
                authData.roles
            );

            return new authActions.Authenticated(user);
        } else {
            return new authActions.NotAuthenticated();
        }
    })
    .catch(err => Observable.of(new authActions.AuthError()));