text:
Q: How to redraw correctly angle on circle, which starts from current time, to the point affected on the circle? I have a circle drawn on canvas. On top on this circle I draw an angle, which starts from part of the circle equal to current time.
Then onTouchEvent, the angle should be redrawn from start point (current time), to end point, based on a point on the circle.
The problem is with calculation dynamically sweep angle in method onTouchEvent.
I've tried different calculations, taken from different Stackoverflow posts / suggestions, and none did not work according to my expectation. The reaction of the angle, onTouchEvent, was always a bit unpredicted.
My code snippet:
@Override
public void draw(Canvas canvas) {
    super.draw(canvas);

    int radius = getRadius();
    int startAngle = getStartAngle();

    canvas.drawCircle(getWidth() / 2, getHeight() / 2, radius, this.bkgPaint);

    this.arcRect = new RectF((getWidth() / 2) - radius, (getHeight() / 2) - radius, (getWidth() / 2) + radius, (getHeight() / 2) + radius);
    canvas.drawArc(this.arcRect, startAngle, sweepAngle, true, arcPaint);
}

@Override
public boolean onTouchEvent(MotionEvent e) {
    if (e.getAction() == MotionEvent.ACTION_MOVE) {
        sweepAngle = (int) ((360.0D + Math.toDegrees(Math.atan2(e.getX() - 360.0D, 360.0D - e.getY()))) % 360.0D);
        invalidate();
    }
    return true;
}

private int getStartAngle() {
    Calendar cal = Calendar.getInstance();
    int minutes = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
    if (minutes > 720) {
        minutes -= 720;
    }
    int angle = minutes / 2;
    return (angle += 270) % 360;
}

private int getRadius() {
    return ((80 * getWidth()) / 100) / 2;
}

A: I've used similar calculations in my color picker. It's open source, you can find sources here.
In your case I would start with calculating end angle, like this:
@Override
public boolean onTouchEvent(MotionEvent e) {
    int action = e.getAction();
    switch (action) {
    case MotionEvent.ACTION_DOWN:
    case MotionEvent.ACTION_MOVE:

        int x = (int) e.getX();
        int y = (int) e.getY();
        int cx = x - getWidth() / 2;
        int cy = y - getHeight() / 2;

        endAngle = (float) (Math.toDegrees(Math.atan2(cy, cx)) + 360f) % 360f;

        invalidate();

        return true;
    }
    return super.onTouchEvent(e);
}

Adding 360 degrees with modulo is required. After this operation you'll have 0 degrees on the right side of the circle, 90 at the bottom, 180 on the left and 270 at the top.
Now your sweep angle will be endAngle - startAngle. And that's it!


text:
Q: Solve $\lim_{N\to\infty} \frac{\sum_{n=0}^N \sin^4 (5n)}{N}$ $$\lim_{N\to\infty} \frac{\sum_{n=0}^N \sin^4 (5n)}{N}$$
This is an Olympiad problem from India. I tried solving it by trying to manipulate such that n/N is x and then integrate it along with reducing the sin^4 to cos using double angle formulae twice. But I got stuck when a term to be integrated resembled cosx/x which I was unable to integrate by the methods I know. But judging the kind of problems this exam asks, I think there is a more elegant approach that does not require knowledge of integrating the aforementioned.
Source

A: \begin{align}&\frac1N\sum_{k=0}^N\sin^4(5k)=\\=&\frac1N\sum_{k=0}^N\left(\frac{e^{5ik}-e^{-5ik}}{2i}\right)^4=\frac1{16N}\sum_{k=0}^Ne^{20ik}-4e^{10ik}+6-4e^{-10ik}+e^{-20ik}=\\=&\frac1{16N}\left(\frac{e^{20i(N+1)}-1}{e^{20i}-1}+\frac{e^{-20i(N+1)}-1}{e^{-20i}-1}-4\frac{e^{4i(N+1)}-1}{e^{4i}-1}-4\frac{e^{-4i(N+1)}-1}{e^{-4i}-1}+6(N+1)\right)=\\=&\frac38+\frac1{16N}\left(\frac{e^{20i(N+1)}-1}{e^{20i}-1}+\frac{e^{-20i(N+1)}-1}{e^{-20i}-1}-4\frac{e^{4i(N+1)}-1}{e^{4i}-1}-4\frac{e^{-4i(N+1)}-1}{e^{-4i}-1}+1\right)\end{align}
And here it depends how familiar are with limits of complex-valued functions. I would say that the quantity between parenthesis is bounded in $N$ (for instance, its absolute value is bounded by $1+\frac{8}{(\cos20-1)^2+\sin^220}+\frac{32}{(\cos 4-1)^2+\sin^24}$) and therefore the limit as $N\to \infty$ is $\frac38$. Otherwise you calculate the $a+bi$ form of that quantity (which will have $b=0$) and then draw the same conclusion with the resulting expression in $\sin(N+1)$ and $\cos(N+1)$.

A: Consider $5n$ mod $\pi$. As $n$ increases, you get a dense covering of $[0,\pi]$. So one way to express the following integral as a Riemann sum is $$\int_0^{\pi}\sin^4(x)\,dx=\lim_{N\to\infty}\sum_{n=1}^N\sin^4(5n)\Delta x_n$$ You could argue the sampling is uniformly dense such that it is OK to take $\Delta x_n=\frac{\pi}{N}$. Then you conclude
$$\begin{align}
\lim_{N\to\infty} \frac{\sum_{n=0}^N \sin^4 (5n)}{N}
&=\lim_{N\to\infty} \frac{\sum_{n=1}^N \sin^4 (5n)}{N}\\
&=\frac{1}{\pi}\int_0^{\pi}\sin^4(x)\,dx\\
&=\frac{1}{4\pi}\int_0^{\pi}\left(1-\cos(2x)\right)^2\,dx\\
&=\text{... more elementary integration ...}\\
&=\frac{1}{4\pi}\int_0^{\pi}\frac32\,dx\\
&=\frac38
\end{align}$$

A: @Gae.S has answered before me.
Here's an approach using trigonometry
$\begin{align}\sin^4(5n) = \left(\dfrac{1-\cos(10n)}{2}\right)^2 = \dfrac{1-2\cos(10n)+\cos^2(10n)}{4} = \dfrac{1-2\cos(10n)+\frac{1+\cos(20n)}{2}}{4}=\dfrac{3-4\cos(10n)+\cos(20n)}{8}\end{align}$
Now $\begin{align}\lim_{n\to\infty}\frac1N\sum_{n=0}^N\frac38 = \lim_{N\to\infty}\frac38\left(\frac{N+1}{N}\right)=\frac38\end{align}$
Using the formula,

$$\sum_{n=0}^N\cos(kn) = \frac{\sin((N+1)\frac k2)}{\sin\frac k2}\cos\frac {Nk}2$$

$$\begin{align}&\lim_{N\to\infty}\frac1N\sum_{n=0}^N\frac{\cos(20n)-4\cos(10n)}{8} \\&= \lim_{N\to\infty}\frac{\sin(10N+10)}{8\sin(10)}\frac{\cos(10N)}N-\lim_{N\to\infty}\frac{\sin(5N+5)\cos(5N)}{2\sin(5)}\frac{\cos(5N)}N\\
&=0 ~~(\text{As}, \lim_{x\to\infty}\frac{\cos x}x = 0)\end{align}$$
So the final result is $\frac38$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Excel: Check if a vendor sells a specified product I have two sheets in Excel
The Table in Sheet 1 contains the list of vendors and the materials they each sell. Each vendor may sell one or more materials, and each material may be sold by one or more vendors. Each line represents one of these relationships:

Information entered into Sheet 2 needs to be checked to make sure it is valid:

For each line on Sheet 2, I want to check that the material entered into Column A is sold by the vendor in Column B, and place the result in Column D.
Example results:

*

*Row 1

*

*Material: 1150051

*Vendor: 209401

*False

*Row 12

*

*Material: 1050010201

*Vendor: 229250

*True

*Row 13

*

*Material: 1010210203

*Vendor: 225780

*False

A: It's difficult to understand your problem, but this may be the answer you're looking for. My answer presumes that you simply want a 'True' or 'False' answer if the vendor does sell the material or not for each row in Sheet 2, but it wont give specific references of where in Sheet 1 the information is found.
As there could be a combination of Vendor ID's and Material ID's I would first create a unique field which joins these together. In Sheet 1 use Column C to join them together with:
=A2&B2

In Sheet 2 Column D use the following formula:
=IF(ISERROR(MATCH(B2&A2,Sheet1!C:C,0)),"False","True")

If the combination of Material ID & Vendor ID can be found in Sheet 1 (Column C) then Column D will equal "True"; If it cant be found then Column D will equal "False".


text:
Q: how to align menu items I am just working on an eCommerce site where I am trying to create a mega menu using CSS MEGA SITE NAVIGATION from Codyhouse.
Everything is perfect except the horizontal alignment of the 2nd level menu.
I tried positioning list but there is no use.
Can anyone guide me to solve this?

A: In this situation, the issue is that float: left; will continue to try and float as it moves down the page, taking the easiest option first (there's room at column 6, that's why it's chosen that one).
So, in addition to floating I would instruct the 8th column to clear each of the first 7 items, no matter their height.
I can't see what your HTML structure is but something like this should do the trick. Replace li whatever child element you're using.
li:nth-child(7n + 8){
  clear: both;
}

To explain: 7n is the number of columns you want to have before starting a new row, and 8 is targeting the next column as you want this one to clear all of the first row's children.


text:
Q: Selected all rows with checkbox but for multiple tables displaying with a loop In my application, I have several tables that are built with a loop.
<div v-for="(dimension, index) in listQuestions" :key="index" :header="`${dimension.name}`">

                    <input type="checkbox" @click="onClickCheckAll(dimension)"  />
                    Sous-dimension
                    Item

                    <input type="checkbox" checked disabled :id="'choice-' + item.id"/>
                    <input type="checkbox" @click="onClickOneCheckbox(item.id)"  :id="'choice-' + item.id" />
                    {{question.name}}
                    {{item.item}}

I would like to be able to select all the rows of each table with a checkbox.
I have seen this tuto: vuejs tables and select all checkbox which seems to me very good. But I can't apply it in my case of several tables.
How can I use the data selected and selectAll like in the example but for several tables?
I have started to build a function to access the items like this and I have my ID of items :
EDIT.
I try to do this :

    onClickCheckAll(value) { //when click to all chekckbox
      console.log("click")
      console.log(value)
      console.log(value.sousDimensions)

      for (var sousdim of value.sousDimensions)
      {
        for (var item of sousdim.questions)
        {
          console.log(this.selectCheck)

          const p = this.selectCheck.indexOf(item.id) //looking for index for each item

          const checkboxItem = document.querySelector("#choice-" + item.id) //all inputs with id choice-ID and then add or remove "checked" attribute

          if (p > -1) { //if still there, delete
            this.selectCheck.splice(p, 1);

            if (!item.barometre)
            {
              checkboxItem.checked=false
            }

          }
          else { //if not, adding in array
            this.selectCheck.push(item.id)
            checkboxItem.checked=true
          }

        }
      }
    },

    onClickOneCheckbox(val) {

      const index = this.selectCheck.indexOf(val);
      if (index > -1) //delete item if still in the array
      {
        this.selectCheck.splice(index, 1);
      }
      else
      {
        this.selectCheck.push(val)
      }

      console.log(this.selectCheck)
    }

And it's partially works : when I click individually on the first two rows of my table and then click on the checkbox to select all, all rows get selected...Except the first two!
See the problem here : https://jsfiddle.net/chtouk/rc80ksno/35/
Thanks for help


text:
Q: What is the proper design to deal with this? I'm working on a legacy Java application, that deals with "fruits" and "vegetables", let's say, for the sake of the question.
They are treated as different things internally, cause they don't have all methods/properties in common, but a lot of things are DONE very similar to both of them.
So, we have a ton of methods doSomethingWithAFruit(Fruit f) and doSomethingWithAVegetable(Veg v), that use the proper doOtherStuffWithAFruit(Fruit f) / doOtherStuffWithAVeg(Veg v). And those are very similar, except that methods that do things with fruits only call the methods that do things with fruits, and the same thing for vegetables.
I want to refactor this to reduce the duplication, but I'm not sure what is the best way to accomplish that. I've read a bit about some design patterns, but I don't know if it has made any clearer to me. (I can recognize some patterns in the code I use, but I don't really know when I should be applying a pattern to improve things around. Maybe I should be reading more about refactoring itself...)
I was thinking of these two options:
1. Creating a class that can have an instance of either a Fruit or a Vegetable and pass it around to the methods, trying to minimize the duplication. It would go like this:
public void doSomething(Plant p) {
   // do the stuff that is  common, and then...
   if (p.hasFruit()) {
       doThingWithFruit(p.getFruit());
   } else {
       doThingWithVegetable(p.getVegetable());
   }
}

This would get things a bit better, but I don't know... it still feels wrong.
2. The other alternative I thought was to put an interface in Fruit and Vegetable with the stuff that is common to them, and use that to pass it around. I feel this is the cleaner approach, although I will have to use instanceof and cast to Fruit/Vegetable when it needs stuff that is specific to them.
So, what more can I do here? And what are the shortcomings of these approaches?
UPDATE: Note that the question is a bit simplified, I'm looking for way to do things WITH the "plants", that is, code that mostly "uses" them instead of doing things TO them. Having said that, those similar methods I refer to cannot be inside the "Plants" classes, and they usually have another argument, like:
public void createSomethingUsingFruit(Something s, Fruit f);
public void createSomethingUsingVegetable(Something s, Vegetable v);

Namely, those methods have other concerns besides Fruits/Vegetables, and aren't really appropriated to be in any Fruit/Vegetable class.
UPDATE 2: Most code in those methods only reads state from the Fruit/Vegetable objects, and create instances of other classes according to the appropriate type, store in the database and so on -- from my answer to a question in the comments that I think it's important.

A: I think the 2nd approach would be better.. Designing to an interface is always a better way to design.. That way you can switch between your implementation easily..
And if you use interfaces, you won't need to do typecast as you can easily exploit the concept of polymorphism.. That is, you will have `Base class reference pointing to a subclass object..
But if you want to keep only methods common to fruits and vegetables in your interface, and specific implementation in your implementation class.. Then in that case typecasting would be required..
So, you can have a generic method at interface level.. And more specific method at implementation level..
public interface Food {
    public void eat(Food food);
}

public class Fruit implements Food {

    // Can have interface reference as parameter.. But will take Fruit object
    public void eat(Food food) {
        / ** Fruit specific task **/
    }
}

public class Vegetable implements Food {

    // Can have interface reference as parameter.. But will take Vegetable object
    public void eat(Food food) {
        /** Vegetable specific task **/
    }
}

public class Test {
    public static void main(String args[]) {
         Food fruit = new Fruit();
         fruit.eat(new Fruit());    // Invoke Fruit Version

         Food vegetable = new Vegetable();
         vegetable.eat(new Vegetable());   // Invoke vegetable version

    }
}

OK, I have modified a code to make eat() method to take parameters of type Food.. That will not make much of a difference.. You can pass Vegetable object to Food reference..

A: If you have functionality that is specific to fruits and vegetables respectively and a client using both types has to distinguish (using instanceof) - that is a coherence vs. coupling problem.
Maybe consider if said functionality is not better placed near fruit and vegetable themselves instead of with the client. The client may then somehow be refered to the functionality (through a generic interface) not caring what instance he is dealing with. Polymorphism would be preserved at least from the client's perspective.
But that is theoretical and may not be practical or be over-engineered for your use case. Or you could end up actually just hiding instanceof somewhere else in your design. instanceof is going to be a bad thing when you start having more inheritance siblings next to fruits and vegetables. Then you would start violating the Open Closed Principle.

A: Another option you can use, or perhaps include it as part of your solution, is to ask the consumer if it can manage the object that you are passing it.  At this point, it becomes the consumer's responsibility to ensure it knows how to handle the object you are sending it.
For instance, if your consumer is called Eat, you would do something like:
Consumer e = new Eat();
Consumer w = new Water();
if( e.canProcess( myFruit ) )
   e.doSomethingWith( myFruit );
else if ( w.canProcess( myFruit ) )
   w.doSomethingWith( myFruit );

.... etc

But then you end up with a lot of it/else classes, so you create yourself a Factory which determines which consumer you want.  Your Factory basically does the if/else branching to determine which consumer can handle the object you pass, and returns the consumer to you.
So it looks something like
public class Factory {
   public static Consumer getConsumer( Object o ){
    Consumer e = new Eat();
    Consumer w = new Water();
    if( e.canProcess( o ) )
       return e;
    else if ( w.canProcess( o ) )
       return w;
   }
}

Then your code becomes:
Consumer c = Factory.getConsumer( myFruit );
c.doSomethingWith( myFruit );

Of course in the canProcess method of the consumer, it would be basically an instanceof or some other function your derive to determine if it can handle your class.
public class Eat implements Consumer{
   public boolean canProcess(Object o ){
     return o instanceof Fruit;
   }
}

So you end up shifting the responsibility from your class to a Factory class to determine which objects can be handled.  The trick, of course, is that all Consumers must implement a common interface.
I realize that my pseudo-code is very basic, but it is just to point out the general idea.  This may or may not work in your case and/or become overkill depending on how your classes are structured, but if well designed, can significantly improve readability of your code, and truely keep all logic for each type self-contained in their own class without instanceof and if/then scattered everywhere.

A: I would create and abstract base class (let's say - Food, but I don't know your domain, something else might fit better) and start to migrate methods to it one after another.
In case you see that 'doSomethingWithVeg' and 'doSomthingWithFruit' are slightly different - create the 'doSomething' method at the base class and use abstract methods to do only the parts that are different (I guess the main business logic can be united, and only minor issues like write to DB/file are different).
When you have one method ready - test it. After you're sure it's ok - go to the other one. When you are done, the Fruit and Veg classes shouldn't have any methods but the implementations of the abstract ones (the tiny differences between them).
Hope it helps..

A: This is a basic OOD question. since fruits and vegetables are of type Plant.
I would suggest:
interface Plant {
    doSomething();
}

class Vegetable {
    doSomething(){
    ....
    }
}

and the same with the fruit.
it seems to me that doOtherStuff methods should be private for the relevant class.

A: You can also consider having them both implement multiple interfaces instead of just one. That way you code against the most meaningful interface according the circumstances which will help avoid casting. Kind of what Comparable<T> does. It helps the methods (like the ones that sort objects), where they don't care what the objects are, the only requirement is that they have to be comparable. e.g. in your case both can implement some interfaces called Edible, then take both of them as Edible where an Edible is expected.


text:
Q: Create GCE instance using Python API I want to create a Google Compute Engine instance using the Python api. In particular, I want the source image to be Ubuntu 14.04.
In the doc, it is written to specify the json body of the request as follows:
{
  "name": "example-instance",
  "machineType": "zones/us-central1-f/machineTypes/f1-micro"
  "networkInterfaces": [{
    "accessConfigs": [{
      "type": "ONE_TO_ONE_NAT",
      "name": "External NAT"
     }],
    "network": "global/networks/default"
  }],
  "disks": [{
     "autoDelete": "true",
     "boot": "true",
     "type": "PERSISTENT",
     "initializeParams": {
        "sourceImage": "projects/debian-cloud/global/images/v20150818"
     }
   }]
}

How can I modify the sourceImage parameter value so that it points to the ubuntu 14.04 image? Indeed, the syntax "projects/debian-cloud/global/images/v20150818" is too specific to understand how to use it for other public images.

A: I am guessing you're referring to these docs (source code) which use the following URL format:
"projects/debian-cloud/global/images/debian-7-wheezy-v20150320"

The pattern here is:
"projects/${PROJECT}/global/images/${IMAGE}"

You can find the available images via:
$ gcloud compute images list

which will show you output similar to the following:
NAME                                PROJECT            ALIAS              DEPRECATED STATUS
centos-6-v20151104                  centos-cloud       centos-6                      READY
centos-7-v20151104                  centos-cloud       centos-7                      READY
coreos-alpha-891-0-0-v20151211      coreos-cloud                                     READY
coreos-beta-877-1-0-v20151202       coreos-cloud                                     READY
coreos-stable-835-9-0-v20151208     coreos-cloud       coreos                        READY
backports-debian-7-wheezy-v20151104 debian-cloud       debian-7-backports            READY
debian-7-wheezy-v20151104           debian-cloud       debian-7                      READY
debian-8-jessie-v20151104           debian-cloud       debian-8                      READY
container-vm-v20151103              google-containers  container-vm                  READY
opensuse-13-1-v20150822             opensuse-cloud     opensuse-13                   READY
opensuse-13-2-v20150511             opensuse-cloud     opensuse-13                   READY
opensuse-leap-42-1-v20151124        opensuse-cloud                                   READY
rhel-6-v20151104                    rhel-cloud         rhel-6                        READY
rhel-7-v20151104                    rhel-cloud         rhel-7                        READY
sles-11-sp4-v20150714               suse-cloud         sles-11                       READY
sles-12-sp1-v20151215               suse-cloud         sles-12                       READY
ubuntu-1204-precise-v20151119       ubuntu-os-cloud    ubuntu-12-04                  READY
ubuntu-1404-trusty-v20151113        ubuntu-os-cloud    ubuntu-14-04                  READY
ubuntu-1504-vivid-v20151120         ubuntu-os-cloud    ubuntu-15-04                  READY
ubuntu-1510-wily-v20151114          ubuntu-os-cloud                                  READY
windows-server-2008-r2-dc-v20151006 windows-cloud      windows-2008-r2               READY
windows-server-2012-r2-dc-v20151006 windows-cloud      windows-2012-r2               READY

So in the case of Ubuntu 14.04, the image path would be:
"projects/ubuntu-os-cloud/global/images/ubuntu-1404-trusty-v20151113"

You can also find out more metadata about an image via:
$ gcloud compute images describe --project ubuntu-os-cloud ubuntu-1404-trusty-20151113

and the selfLink attribute in the output will provide a full URL to the image.


text:
Q: Binding a value to input form select-element in Blazor only sets the value after making a selection I am using Blazor Server and trying to bind a value to the selected option in a HTML form.
My code is basically like this:
<select @bind="@formData.Cat">
<option>Cute cat</option>
<option>Bad cat</option>
<option>Hungry cat</option>
</select>

My formData is a class with this property:
public class FormData
{
    public string Cat { get; set; }
}

This works fine after I make a selection. But by default it's not being set to "Cute cat", even though it shows up default in the select box.
What's the easiest way to make it do that right away? The "value" attribute in HTML can't be used, it throws an error because the @bind is already using it.
I came up this:
public class FormData
{
    public string Cat { get; set; } = "Cute cat";
}

I don't think it's too elegant.
Any ideas?


text:
Q: Reflection/Introspection of JavaScript Modules Assume I have:
// test.js
function myFunc(a,b,c) {
    return "Test";
}
module.exports.myFunc = myFunc;

How can I dynamically find out that test.js has a function myFunc which takes 3 parameters, so:
x = require('test.js')
if ( x has function defined myFunc ) {
  if ( function myFunc in x has 3 arguments) {
     "OK"
  } else { "Expect 3 params"}
} else {
  "test.js does not expose myFunc" }

Is this possible using reflection/introspection?
Thanks

A: This isn't specific to modules. Function arity can be determined with length property in JavaScript, myFunc.length === 3.
Relying on length in production is contradictory practice that often designates code smell. In tests, expected length behaviour may be undesirable.
Not too good:
function myFunc(...args) {
   const [a,b,c] = args;
}

myFunc.length === 0;

Not good at all:
function myFunc(a, b = 1, c = 2) {}

myFunc.length === 1;

If myFunc.length is expected to be used in unit tests, it's recommended to skip this assertion and focus on function behaviour instead.


text:
Q: Input protection with MAX366 exhibits very slow falling edge. Why? I'm using the following circuitry to protect my microcontroller input pin from the dangers of the bad and ugly outside world (a trigger signal coming from an unknown source).
The signal comes in from the right, goes through some preliminary filtering/clamping, and then enters the MAX366CSA (a signal-line protector IC, see datasheet). The output pin of the MAX366 goes straight to the microcontroller pin (Atmega2560).

For the measurement I'm using a 10x/500MHz/8pF, properly compensated scope probe. The blue curve is measured at the MAX366 output pin, The yellow curve shows the 4.5V square wave that's being fed into the TRIG IN connector.

As you can see, the rising edge is fine, but the falling edge shows a strange double-decay characteristic. After a fast drop to about 1.6V, a very slow decay with a time constant of around 500µs follows. From the MAX366 datasheet I couldn't find an obvious reason for that behaviour, i.e. their application examples never show any special requirement for the output, like a pull-down to discharge the output or something. The signal at the MAX366 input is fine and has a fall time comparable to the rise time.
Can anyone shed light onto this behaviour? Is there a design flaw on my side, or something obvious I've overlooked in the datasheet?
To improve the falling edge, would you suggest a ~20k pulldown to do the job?

A: Quoting the MAX366 datasheet:-

"When signal voltages exceed or are within approximately 1.5V of either power-supply voltage (including when power is off), the two-terminal resistance increases dramatically,
  limiting fault current as well as output voltage to sensitive circuits"

The slow edge starts when you get within 1.5V of the negative rail, so the part is behaving as it should. Without more knowledge of what is on the other side it's hard to tell what would help.
If you want to use the MAX366 you could use a comparator with a 2.5V reference, then you wouldn't care about what happens below 1.5V or above 3.5V. You could even have some hysteresis so slow rise/fall would give a clean trigger pulse (a few comparators have hysteresis built in). Or just use a NC7WZ14P6X, which I think would give you enough margin (but check).


text:
Q: How to parse the soap web service coming from server object? I am able to get response from server while doing soap programming.My problem is the I am getting object from the server,Now I need to get values from server response .Here is my code and response
package com.example.networkconnectivity;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    AutoCompleteTextView autocompletetextview;

    String[] array = { "One", "Two", "Three", "Four", "Five", "Six", "Seven",
            "Eight", "Nine", "Ten" };
    private static final String SOAP_ACTION = "http://wsendpoints.bbrailapps.firstgroup.com/getDestinationStationDashboard";
    private static final String METHOD_NAME = "getDestinationStationDashboard";
    private static final String NAMESPACE = "http://wsendpoints.bbrailapps.firstgroup.com";
    private static final String URL = "http://railapps.firstgroup.com/FirstGroupRailApps/services/RailAppsCAWS?wsdl";
    private SoapObject resultRequestSOAP = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        autocompletetextview = (AutoCompleteTextView)     findViewById(R.id.autocompletetextview);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.select_dialog_item, array);

        autocompletetextview.setThreshold(2);

        autocompletetextview.setAdapter(adapter);

        System.out.println("=====================" + haveNetworkConnection());

        new AsyncTask<Void, Void, Object>() {
            ProgressDialog dialog = new ProgressDialog(MainActivity.this);
            private PropertyInfo pi1;
            private String SoapResult;

            protected void onPreExecute() {
                dialog.show();
            };

            protected Object doInBackground(Void[] params) {

                /*resultRequestSOAP = new SoapObject(NAMESPACE, METHOD_NAME);

                SoapSerializationEnvelope envp = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                envp.dotNet = true;
                envp.setOutputSoapObject(resultRequestSOAP);
                AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
                        URL);
                try {
                    androidHttpTransport.call(SOAP_ACTION, envp);
                    SoapPrimitive resultsString = (SoapPrimitive)envp.getResponse();
                    System.out.println("resultsString"+resultsString);
                    return resultsString.toString();

                } catch (Exception e) {
 System.out.println("---------------------------"+e.toString());
 Log.d("ppp", e.toString());
                    Toast.makeText(Soapclass.this,
                            "Check Network connectivety" + e.toString(),
                            Toast.LENGTH_LONG).show();
                    Log.v("WS Error->", e.toString());
                    return e.toString();
                }*/

                resultRequestSOAP = new SoapObject(NAMESPACE, METHOD_NAME);
                 pi1 = new PropertyInfo();
                 pi1.setName("crsCode");
                 pi1.setValue("HNH");//get the string that is to be sent to the web service
                 pi1.setType(String.class);
                 resultRequestSOAP.addProperty(pi1);
                SoapSerializationEnvelope envp = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);
                envp.dotNet = true;
                envp.setOutputSoapObject(resultRequestSOAP);
                AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
                        URL);
                try {
                    androidHttpTransport.call(SOAP_ACTION, envp);
                    if (envp.bodyIn instanceof SoapFault) {
                        SoapResult = ((SoapFault) envp.bodyIn).faultstring;
                        System.out.println("==SoapResulght==="+SoapResult);
                    } else {
                        SoapObject resultsRequestSOAP = (SoapObject) envp.bodyIn;
                        SoapResult = resultsRequestSOAP.getProperty(0).toString();
                        System.out.println("==SoapResult==="+SoapResult);
                    }
//                    SoapObject obj = (SoapObject)envp.getResponse();
//
//                    System.out.println("resultsString"+obj);
                    return SoapResult;

                } catch (Exception e) {
 System.out.println("---------------------------"+e.toString());
 Log.d("ppp", e.toString());
                    Toast.makeText(MainActivity.this,
                            "Check Network connectivety" + e.toString(),
                            Toast.LENGTH_LONG).show();
                    Log.v("WS Error->", e.toString());
                    return e.toString();
                }

            };

            protected void onPostExecute(Object result) {
                dialog.dismiss();
                Toast.makeText(MainActivity.this,
                        "Check Network connectivety" + result,
                       Toast.LENGTH_LONG).show();
            };
        }.execute();

    }

    public boolean haveNetworkConnection() {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;
    }

}

System.out.println("==SoapResult==="+SoapResult);
Response
anyType{RID=201309201377831; alertDetailPopulated=false; alertsId=0; alertsSummary=null; destExpArrival=08:01; destSchArrival=08:00; destinationStation=anyType{crsCode=BKJ; stationName=Beckenham Junction; }; expArrival=07:49; expDepart=07:49; otherAlertPresent=false; platformNo=3; routeDetailPopulated=false; routeDetails=null; rsID=null; schArrival=07:49; schDepart=07:49; serviceAlertPresent=false; toc=SE; tocName=Southeastern; trainID=2M18; trainLastReportedAt=null; }

Now I want to print RID and alertDetailPopulated values.

A:        @Override
protected SoapObject doInBackground(String... params) {
    // TODO Auto-generated method stub
    Intent i=getIntent();
     String a=i.getStringExtra("code");
     CallSoap cs=new CallSoap();
     resp= cs.Call(a);
     System.out.println("ssssssssssssssssssssssssssssssssss"+resp);
     return resp;
}
protected void onPostExecute(Object result) {
    if(result!= null)
    {
  String[] testValues = new String[result.getPropertyCount()];
    for(int j= 0; j< result.getPropertyCount(); j++){
        testValues[j] = result.getProperty(j).toString();
        String name=(result.getProperty(0).toString());

            Toast.makeText(MainActivity.this,
                    "Check Network connectivety" + name
                   Toast.LENGTH_LONG).show();
        };


text:
Q: Debugging ASP.NET MVC3 application hosted on Local IIS Webserver I've managed to use the local IIS Webserver to host my MVC3 application, and I can debug it and everything, from the machine that is hosting it. - however, when I send a request from another machine (my Mac, which is running my Windows in a Parallels VM), I get the expected result, but the debugger wont stop at my breakpoints!
I tried adding a Debugger.Break(); to my action, and that crashes the w3wp.exe ..
To, so summarize: Local requests are working, and can be debugged. External requests are working, but they cannot be debugged.
In my project's properties, I set the Use Local IIS Webserver, Use IIS Express is unchecked.
I'm using Visual Studio 2012 Professional. The project is Azure SDK-based, and the attached process is WaIISHost.exe.

A: I can see that the remote requests are served by IIS, but the local ones are served via "Cassini" server or the server of visual studio.
Make sure that you are using IIS to debug your code, You can attache visual studio to w3wp.exe to debug via IIS. and you should start visual studio as Administrator.
To attache Visual studio to w3wp.exe (IIS process): From visual studio, from the debug menu select "Attach to process..." :

*

*Check "Show processes from all users".

*Check "Show processes in all sessions".

*Choose "Managed (v....) code" from (Attach to.) by pressing select button.

*Press "Refresh" button
w3wp.exe should be shown!

A: When you start Visual Studio, start it as Administrator (right click and 'Run as administrator'), then load your project's solution.
Then from the debug menu select "Attach to process..." and ensure that the "Show processes from all users" and "show processes in all sessions" checkboxes are checked, within the Available Processes panel you should be able to scroll through and locate a process that relates to the IIS app pool that you are trying to debug (usually called w3wp.exe).
Attach to this process and refresh the page in your browser, this should allow you to debug.
Many Thanks.
Benjamin

A: You are probably attaching the wrong process.
Try to do the below to confirm you are debugging the wrong process.

*

*From your local machine start the web application in debug mode (press F5).

*Go on Debug -- > Attach process

Now if you scroll down you should see which is the process VS has attached to debug your application (It should appear in a different color -light gray).  If the process is not the w3wp.exe it means you are not using IIS for hosting your application and you are probably debugging the wrong process when you make a request from another machine

A: The issue was that since I had set up my IIS server to serve on port 83, while locally I would access on port 81, the debugger would not monitor those requests.
To solve this (or, generally, to debug remotely on the Cassini Web Server), download a tool called rinetd, which is a very simple traffic redirector daemon, and create a config.cfg in the folder where you extracted it to. The format is <source ip> <source port> <dest. ip> <dest port>. So, on my Mac, I go to this address in Safari: 192.168.1.23:8080/Controller/Action , and that is then redirected to localhost:81/Controller/Action , as if it was a local request! Here is the example config.cfg:
192.168.1.23 8080 127.0.0.1 81

Alternatively, you can use your PC name, to avoid having to assign a static IP or change the config when DHCP gives you a new address:
Jeff-PC 8080 127.0.0.1 81

Then, open a command prompt, and cd to your rinetd folder, and run rinetd.exe -c config.cfg.
Works like a charm.


text:
Q: How to send JSON request from HTML form and receive in PHP I use a HTML form with several fields.
But i need to have the value from the select fields ( dropdown ) translated into a php aray.
My form contains below fields:
City - Text
IN - Text/Date
OUT - Text/Date
Rooms - Select ( 1->5 )
Adults - Select ( 1->5 )
Childs - Select ( 0->5 )

The php array that i need to receive is
Example If Rooms is - 1 and Adults - 2 the response must be:
$rooms[] = array(array("paxType" => "Adult"), array("paxType" => "Adult"));

Example If Rooms is - 2 and Adults - 3 the response must be:
$rooms[] = array(array("paxType" => "Adult"), array("paxType" => "Adult"));
$rooms[] = array(array("paxType" => "Adult"));

I am using the below code
$Adults = intval($_POST["Adults"]);
$rooms = array();
for ($x = 0; $x < $Adults; $x++) {
    array_push($rooms,array("paxType" => "Adult"));
}

but i am receive onbly the response with 1 room and 1 adult.

A: It is easy to do this, even with plain HTML Form Submit ( can be done with JSON XHR request too)
I assume that your SELECT HTML form element name is "adultCount"
$adultCount = intval($_GET["adultCount"]);
$rooms = array();
for ($x = 0; $x < $adultCount; $x++) {
    array_push($rooms,array("paxType" => "Adult"));
}

FYI, We don't use SOAP for web pages, even though it can be done ( it is unnecessary).


text:
Q: Are magnets sticky? A common definition of sticky is

Having the property of adhering or sticking to a surface; adhesive.

Is there any reason its not correct to call magnets sticky, even though they can be described as sticking to things?
The only counter point I can find is sticky is sometimes described as

coated with a adhesive substance

but this definition would also exclude things like sap and glue.

A: This question, like many others that appear on this site, presupposes that words have sharply delineated meanings, and that it is always possible to determine, in a definite yes-or-no manner, whether something is covered by the meaning of a word. Most words of everyday English (unlike legal and scientific terminologies) are, however, not like that.
Magnets are not within the core of the meaning of sticky; they are not what a typical speaker of the language thinks of upon hearing the word. Most people would not spontaneously characterise magnets as sticky. On the other hand, if somebody insisted on saying that magnets are sticky, we would probably understand what is meant; we would find this person's choice of words eccentric, but not unintelligible. If the question were then posed whether this unusual use of sticky is literal or metaphorical, it is unlikely that there would be a consensus.

A: No, as magnets are  considered by definition to be "Fructating in nature coincidently to applied force."
granted, not all glues are sticky, but you catch my proverbial drift...

A: I think magnets can most definitely be considered "sticky". Upon doing some research into the semantics surrounding "stickiness", most definitions do seem to be very loose.

Having the property of adhering or sticking to a surface; adhesive.

Based on this definition, I think it's more than acceptable to consider magnets to be "sticky". Magnets definitely "stick" to things!!!!
Regardless, what an interesting question!!! A beautiful combination of electromagnestism and semantics. The study of magnets is absolutely fascinating. They're so interesting. Thanks!

A: At most you might get away with using 'sticky' in a metaphorical way.  It already is used in that way, for example in the old pop song "I'm stuck on you". The idea that you are an adhesive surface onto which I am 'stuck' is metaphorical.  I can be 'stuck on' somebody in this sense even at a distance of hundreds of miles.
Magnetism is, of course, a weird kind of 'adhesive'.  Two pieces of sticky paper will stick together even more strongly than sticky paper to something non-sticky.  Two magnets are equally likely to repel as to attract each other.  It depends on the poles.
But it's a free language:  you can use a metaphor if you think it will be understood.  Simply, I should advise 'scare' quotes when you describe a magnet as 'sticky'.


text:
Q: When the canvas tag is not supported do somehting For when a browser does not support the canvas tag I show an image.
I have placed this image as a background of a div inside the canvas tag:
<canvas width="1200" height="470">

</canvas>

The image still downloads though, even if the canvas tag is supported, is there a way to prevent the image downloading to the browser if the canvas tag is supported?

A: No, not really. But you can test for it the other way around.
Check for a solution here.

A: What you need to do is determine if the browser supports canvas before it is drawn or the image is loaded.  Try using JavaScript like (retrieved from https://stackoverflow.com/a/2746983/3869056):
function isCanvasSupported() {
 var elem = document.createElement('canvas');
 return !!(elem.getContext && elem.getContext('2d'));
}
if(!isCanvasSupported())
 document.getElementById('canvas').innerHTML = '

';

Of course, this may not be exactly what you want, but it should do the work for you.


text:
Q: Syncing DynamoDB with ElasticSearch for old Data I'm using this function https://github.com/bfansports/dynamodb-to-elasticsearch to sync my DynamoDB table with ElasticSearch. Unfortunately it's only processing the newly added data and Updated ones and not the previously existing rows in the table despite i chose "New and old images - both the new and the old images of the item
" in the Manage stream section.
How to fix that ?

A: Ok, i ended up with updating the DynamoDB and that triggers the Stream so Sync between ElasticSearch and DynamoDB can be done.
This is the script that i use :
import json
import boto3
import random

def lambda_handler(event, context):

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('image-library')

response = table.scan(
    ProjectionExpression='#k',
    ExpressionAttributeNames={
        '#k' : 'id', #partition key
    }
)

items = response['Items']

random_number = random.randint(0,1000)

for item in items:
    response = table.update_item(
        Key=item,
        UpdateExpression='SET #f = :f',
        ExpressionAttributeNames={
            '#f' :'force_update'
        },
        ExpressionAttributeValues={
            ':f' : random_number
        }

    )


text:
Q: Get-ChildItem: Illegal characters in path I'm trying to login to multiple servers and then get list of files from those servers.
Below is my script:
$ServerName=Get-content "D:\HOMEWARE\BLRMorningCheck\Jerry\servername.txt"
foreach ($server in $ServerName)
{
  $server_host=echo $server | %{$data = $_.split(";"); Write-Output "$($data[0])"}
  $Targetfolder=echo $server | %{$data = $_.split(";"); Write-Output "$($data[1])"}

  $Extension =@("*.log","*.txt*")

  $Files = Get-Childitem $TargetFolder -Include $Extension -Recurse

  echo $Files
}

When I run I debug mode I see that it really doesnt pick the files.
Error:
Get-ChildItem : Illegal characters in path.
At D:\HOMEWARE\BLRMorningCheck\Jerry\test.ps1:14 char:23
+ $Files = Get-Childitem <<<<  $TargetFolder -Include $Extension -Recurse
    + CategoryInfo          : InvalidArgument: (D:\HOMEWARE\BLR...ck\Jerry\Check":String) [Get-ChildItem], ArgumentException
    + FullyQualifiedErrorId : ItemExistsArgumentError,Microsoft.PowerShell.Commands.GetChildItemCommand

Get-ChildItem : Cannot find path 'D:\HOMEWARE\BLRMorningCheck\Jerry\"\srvparrtfh01\d$\HOMEWARE\BLRMorningCheck\Jerry\Check"' because it does not exist.
At D:\HOMEWARE\BLRMorningCheck\Jerry\test.ps1:14 char:23
+ $Files = Get-Childitem <<<<  $TargetFolder -Include $Extension -Recurse
    + CategoryInfo          : ObjectNotFound: (D:\HOMEWARE\BLR...ck\Jerry\Check":String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Note: If I run it manually, example
$Files = Get-Childitem \\servername\d$\HOMEWARE\BLRMorningCheck\Jerry\Check -Include "*.log","*.txt*" -Recurse

I get the output.

A: As @arco444 and @PetSerAl mentioned in the comments: your path string has leading/trailing double quotes, which are invalid characters in a path. You need to remove them to make the path work as intended:
$Files = Get-Childitem ($TargetFolder -replace '^"|"$') -Include $Extension -Recurse

Of course, since your input file seems to be a some sort of CSV, you could use Import-Csv instead of reading the file with Get-Content and manually splitting the fields. That would already take care of the double quotes on file import.
$filename  = 'D:\HOMEWARE\BLRMorningCheck\Jerry\servername.txt'
$extension = '*.log', '*.txt*'

Import-Csv $filename -Delimiter ';' -Header 'ComputerName', 'TargetFolder' | % {
  Get-Childitem $_.TargetFolder -Include $extension -Recurse
}

A: This was an absolute nightmare, get-childitem cannot except a string variable if there are multiple paths.

Get-ChildItem -Path "\server1\c$\temp", "\server1\d$\temp" -File
-recurse # works

$path = '"\server1\c$\temp", "\server1\d$\temp"'; Get-ChildItem -Path "\server1\c$\temp", "\server1\d$\temp" -File
-recurse # fails with cannot find path

$path = "'"\server1\c$\temp", "\server1\d$\temp'""; Get-ChildItem -Path "\server1\c$\temp", "\server1\d$\temp" -File
-recurse # fails with illegal character message (the tick)

Any string that has multiple paths fails, however an array with += as shown below will work.
$servers = @("server1", "server2");
$partialPaths = @("\c$\temp\", "\d$\temp\");
foreach ($server in $servers)
    {
        $paths = @();
        foreach ($partialPath in $partialPaths)
        {
            $paths += "\\" + $server + $partialPath;
        }
    }
Get-ChildItem -Path $paths -File -recurse;


text:
Q: Overhead of memory allocator I've been creating a temporary object stack- mainly for the use of heap-based STL structures which only actually have temporary lifetimes, but any other temporary dynamically sized allocation too. The one stack performs all types- storing in an unrolled linked list.
I've come a cropper with alignment. I can get the alignment with std::alignment_of<T>, but this isn't really great, because I need the alignment of the next type I want to allocate. Right now, I've just arbitrarily sized each object at a multiple of 16, which as far as I know, is the maximal alignment for any x86 or x64 type. But now, I'm having two pointers of memory overhead per object, as well as the cost of allocating them in my vector, plus the cost of making every size round up to a multiple of 16.
On the plus side, construction and destruction is fast and reliable.
How does this compare to regular operator new/delete? And, what kind of test suites can I run? I'm pretty pleased with my current progress and don't want to find out later that it's bugged in some nasty subtle fashion, so any advice on testing the operations would be nice.

A: This doesn't really answer your question, but Boost has just recently added a memory pool library in the most recent version.
It may not be exactly what you want, but there is a thorough treatment of alignment which might spark an idea? If the docs are not enough, there is always the source code.


text:
Q: Condition based on response value in karate I want to do a Query API which returns me a 200 always, then check if the result has an array of elements and if it does not have then create the entity using POST API, if found, validate the entity details.
This is my code:
Given url url
And path 'offering'
When method GET
* def expected1 = response != null ? { expected: 'in if' } : { expected: 'in else' }

But this checks only for null value in response and does not check for null array in response

A: This can be achieved by response.length:
Sample code:
eval if (response.length<=1) karate.call('offeringcreate.feature')


text:
Q: InterIMAP, Viewing UNREAD IMAP mail and Downloading Attachments in C# I was wondering if anyone can help me on this cause its driving me mad trying get this working
I was working with the trail of mail.dll from http://www.lesnikowski.com/mail/ which is an extremely fantastic tool which unfortunately i cannot afford being a student (even though its around 150eur, its still very expensive to me :/) and this would be a small module in my thesis and my faculty cannot afford to buy these things for students either :/ so anyway I had to go for a free tool  (so please dont suggest any non open source ones - trust me i have tried them ALL)..
Well, i'm trying to explore  InterIMAP, and for several hours have been trying to list unread emails from my gmail account but it just doesn't seem to be working. I can connect just fine but finding the unread emails seems to be no easy task.. I have tried countless approaches but non seem to give me unread emails in my inbox (I have loads of emails in my inbox and i just want the unread ones). Would someone please assist me? I have been trying to get this working for ages now, but documentation is rather lacking and my every attempt has resulted in a fail so far.
Please help!!
Some code i currently have:
`            IMAPConfig config = new IMAPConfig("myhost", "username", "pass", true, true, "");
        config.CacheFile = "";

        IMAPClient client = null;
        try
        {
            client = new IMAPClient(config, null, 5);
        }
        catch (IMAPException e)
        {
            Console.WriteLine(e.Message);
            return;
        }
        Console.WriteLine(DateTime.Now.ToString());

        IMAPFolder f = client.Folders["INBOX"];
        IMAPSearchResult sResult = f.Search(IMAPSearchQuery.QuickSearchNew()); // <--- Gives me no results even though i do have unread messages!

A: If you did't reach your goal, here we go:
You should code in the following way:
1st: Inside your SearchQuery class, add a new property "unread", for example.
2nd: Add a new Method that returns an IMAPSearchQuery. It'll quick search unread mails. Something like that:
    public static IMAPSearchQuery QuickSearchUnread()
    {
        IMAPSearchQuery query = new IMAPSearchQuery();
        query.unread = true;

        return query;
    }

3td: Inside your class IMAPFolder, you have a method called that will return an IMAPSearchResult type and that receives an IMAPSearchQuery as parameter.
This method "build" your query with IMAP command queries (IMAP based protocol).
To the Unread query you should add:
            public IMAPSearchResult Search(IMAPSearchQuery query)
            {
                ...
                if (query.Unread)
                    searchTerms.Add("UNSEEN");
                .
                .
                ...
            }

4th: Call the Search method with the new QuickSearch:
config.CacheFile = "";

    IMAPClient client = null;
    try
    {
        client = new IMAPClient(config, null, 5);
    }
    catch (IMAPException e)
    {
        Console.WriteLine(e.Message);
        return;
    }
    Console.WriteLine(DateTime.Now.ToString());

    IMAPFolder f = client.Folders["INBOX"];
    IMAPSearchResult sResult = f.Search(IMAPSearchQuery.QuickSearchUnread());

Let me know about your progress.
I hope it can be helpful.
Bye.

A: I honestly just ended up using Mail.dll trial version as interIMAP was not working properly for me and way to slow because it indexes the emails for some reason :s


text:
Q: Having trouble with installing drivers for TL-WN722N I have some major issues when I try to install my new TL-WN722N V3. I've tried with a bunch of different rlt8188eu drivers wich TP-Link suggest. Whenever I try to compile the drivers it always fails.
jones@pilotz-MunchCave:~/Desktop/rtl8188eus$ make all
"******************************************"
"NO SKRC,we will use default KSRC"
"******************************************"
make ARCH=x86_64 CROSS_COMPILE= -C /lib/modules/5.3.0-28-generic/build M=/home/jones/Desktop/rtl8188eus  modules
make[1]: Entering directory '/usr/src/linux-headers-5.3.0-28-generic'
"******************************************"
"NO SKRC,we will use default KSRC"
"******************************************"
  CC [M]  /home/jones/Desktop/rtl8188eus/os_dep/osdep_service.o
In file included from /home/jones/Desktop/rtl8188eus/include/drv_types.h:35:0,
                 from /home/jones/Desktop/rtl8188eus/os_dep/osdep_service.c:24:
/home/jones/Desktop/rtl8188eus/include/wifi.h:988:0: warning: "IEEE80211_MAX_AMPDU_BUF" redefined
 #define IEEE80211_MAX_AMPDU_BUF 0x40

In file included from ./include/net/cfg80211.h:21:0,
                 from /home/jones/Desktop/rtl8188eus/include/osdep_service_linux.h:83,
                 from /home/jones/Desktop/rtl8188eus/include/osdep_service.h:45,
                 from /home/jones/Desktop/rtl8188eus/include/drv_types.h:32,
                 from /home/jones/Desktop/rtl8188eus/os_dep/osdep_service.c:24:
./include/linux/ieee80211.h:1441:0: note: this is the location of the previous definition
 #define IEEE80211_MAX_AMPDU_BUF  0x100

/home/jones/Desktop/rtl8188eus/os_dep/osdep_service.c: In function 'isFileReadable':
/home/jones/Desktop/rtl8188eus/os_dep/osdep_service.c:1833:28: error: implicit declaration of function 'get_ds'; did you mean 'get_da'? [-Werror=implicit-function-declaration]
   oldfs = get_fs(); set_fs(get_ds());
                            ^~~~~~
                            get_da
/home/jones/Desktop/rtl8188eus/os_dep/osdep_service.c:1833:28: error: incompatible type for argument 1 of 'set_fs'
In file included from ./include/linux/uaccess.h:11:0,
                 from ./include/linux/sched/task.h:11,
                 from ./include/linux/sched/signal.h:9,
                 from /home/jones/Desktop/rtl8188eus/include/osdep_service.h:37,
                 from /home/jones/Desktop/rtl8188eus/include/drv_types.h:32,
                 from /home/jones/Desktop/rtl8188eus/os_dep/osdep_service.c:24:
./arch/x86/include/asm/uaccess.h:29:20: note: expected 'mm_segment_t {aka struct <anonymous>}' but argument is of type 'int'
 static inline void set_fs(mm_segment_t fs)
                    ^~~~~~
/home/jones/Desktop/rtl8188eus/os_dep/osdep_service.c: In function 'retriveFromFile':
/home/jones/Desktop/rtl8188eus/os_dep/osdep_service.c:1861:29: error: incompatible type for argument 1 of 'set_fs'
    oldfs = get_fs(); set_fs(get_ds());
                             ^~~~~~
In file included from ./include/linux/uaccess.h:11:0,
                 from ./include/linux/sched/task.h:11,
                 from ./include/linux/sched/signal.h:9,
                 from /home/jones/Desktop/rtl8188eus/include/osdep_service.h:37,
                 from /home/jones/Desktop/rtl8188eus/include/drv_types.h:32,
                 from /home/jones/Desktop/rtl8188eus/os_dep/osdep_service.c:24:
./arch/x86/include/asm/uaccess.h:29:20: note: expected 'mm_segment_t {aka struct <anonymous>}' but argument is of type 'int'
 static inline void set_fs(mm_segment_t fs)
                    ^~~~~~
/home/jones/Desktop/rtl8188eus/os_dep/osdep_service.c: In function 'storeToFile':
/home/jones/Desktop/rtl8188eus/os_dep/osdep_service.c:1895:29: error: incompatible type for argument 1 of 'set_fs'
    oldfs = get_fs(); set_fs(get_ds());
                             ^~~~~~
In file included from ./include/linux/uaccess.h:11:0,
                 from ./include/linux/sched/task.h:11,
                 from ./include/linux/sched/signal.h:9,
                 from /home/jones/Desktop/rtl8188eus/include/osdep_service.h:37,
                 from /home/jones/Desktop/rtl8188eus/include/drv_types.h:32,
                 from /home/jones/Desktop/rtl8188eus/os_dep/osdep_service.c:24:
./arch/x86/include/asm/uaccess.h:29:20: note: expected 'mm_segment_t {aka struct <anonymous>}' but argument is of type 'int'
 static inline void set_fs(mm_segment_t fs)
                    ^~~~~~
cc1: some warnings being treated as errors
scripts/Makefile.build:288: recipe for target '/home/jones/Desktop/rtl8188eus/os_dep/osdep_service.o' failed
make[2]: *** [/home/jones/Desktop/rtl8188eus/os_dep/osdep_service.o] Error 1
Makefile:1655: recipe for target '_module_/home/jones/Desktop/rtl8188eus' failed
make[1]: *** [_module_/home/jones/Desktop/rtl8188eus] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-5.3.0-28-generic'
Makefile:1367: recipe for target 'modules' failed
make: *** [modules] Error 2

lsusb output
jones@pilotz-MunchCave:~/Desktop/rtl8188eus$ lsusb
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 003: ID 04f2:b62a Chicony Electronics Co., Ltd
Bus 001 Device 007: ID 2357:010c
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Please help me.


text:
Q: jQuery click not getting picked up I have a input in a td and the click script is not getting picked up and im not sure why? There are no errors in the console.
<td>
    <input type="button" class="edit btn btn-primary" value="Edit"></input>
</td>

Script below:
<script>
    $('.edit').click(function () {
        console.log("Test")
    })
</script>

A: The 'click' even listener might run before the .edit element is rendered to the page. maybe wrap it in a document ready function to ensure it doesn't run till the page is loaded. like this:
$( document ).ready(function() {
  $('.edit').click(function () {
    console.log("Test")
  })
});

A: Please add jquery.js file first like this.
<script src="https://code.jquery.com/jquery-3.6.0.js"> </script>
<script type="text/javascript">
 $('.edit').click(function () {
        console.log("Test")
    })
</script>


text:
Q: I'm trying create a safety rating for an application i'm working on but i'm new and lost I'm trying create a safety rating for an application i'm working on but i cant figure out how to get three separate variable to compare to one variable, i'm not really good at coding but and this is all i can come up with but it doesn't work, it just disregards everything and only prints "this area is safe" regardless of the variables present:
if ('AssaultSafe' > 131) {
            print("This area is not safe");
    }else if ('AssaultSafe' < 69){
            print("This area is safe");
    }
    if else (print("This ares is neutral"));

A: First up, if else (print("This ares is neutral")); should give you an error:

Parse error: syntax error, unexpected 'else' (T_ELSE), expecting '(' in ...

Your code is comparing a string AssaultSafe to integers, which results in the string being converted to an integer. The integer value of AssaultSafe is 0, so your second else if is hit, resulting in "This area is safe".
https://www.php.net/manual/en/language.operators.comparison.php

Assuming you have a variable called $AssaultSafe somewhere, your code should be:
$AssaultSafe = 132;
if ($AssaultSafe > 131) {
  print("This area is not safe");
} else if ($AssaultSafe < 69){
  print("This area is safe");
} else {
  print("This area is neutral");
}

A: In your case switch statement being more better solution:
$neutralBorder = 69;
$dangerBorder = 131;

$score = (int) `your value`;
switch (true) {
    case $score < $neutralBorder:
        print("This area is neutral");
        break;
     case $score >= $neutralBorder && $score <= $dangerBorder:
        print("This area is safe");
        break;
     case $score > $dangerBorder:
        print("This area is not safe");
        break;
}


text:
Q: Python function Q1) How to write the function countLetter(word, letter) that takes in a word and a letter and returns the number of occurrence of that letter in the word.
Q2) Write a function removeLetter(word, letter) that takes in a word and remove all the occurrence of a particular letter from the word.
Q3) Write a function getVowels(word) that returns the vowels ('a', 'e', 'i', 'o', 'u') in a word as a list in sequence of appearance in the word.

A: countLetter = lambda word, letter:word.count(letter)
removeLetter = lambda word, letter:word.replace(letter, '')
getVowels = lambda word:[c for c in word if c in 'aeiou']

A: question 1

len(filter(lambda x: x == letter, word))

question 2

"".join([x for x in word if x != letter])

question 3

"".join([x for x in word if x in 'aeiou'])


text:
Q: SQL SUM statement in VBA function My database has three tables, Holder, Product (which is an account) and Transaction. I have set up a form from the Holder table that has a subform from the Product table and the Product subform has the Transaction table as a subform. On the Holder portion of the form, I have put an Outstanding unbound text field that should display the total amount and tax fields of transactions from the transaction table that have not been paid (indicated by a checkbox on the Transaction table). I have set the control source of the unbound text box to =calcOutstanding() and written the following function for the form.
Public Function calcOutstanding()
Dim db As Database
Dim strSQL As String

Set db = CurrentDb

strSQL = "SELECT SUM(tblTransaction.TxAmount + tblTransaction.TxTax) As Outstanding" _
    & "FROM tblTransaction" _
    & "INNER JOIN tblProduct ON tblTransaction.fkProductID = tblProduct.ProductID" _
    & "INNER JOIN tblHolder ON tblProduct.fkHolderID = tblHolder.HolderID" _
    & "WHERE tblTransaction.TxPaid = False" _
    & "AND tlbHolder.HolderID = Me.HolderID;"

DoCmd.RunSQL strSQL

calcOutstanding = Outstanding

End Function
The field now just shows #Error. What am I doing wrong?

A: There's a bunch wrong with your approach:

*

*DoCmd.RunSQL is just for action queries (INSERT, UPDATE, DELETE).

*You cannot return a value from DoCmd.RunSQL like you are attempting to and push it into a variable.

*Your concatenation for the where clause is incorrect.

*As HansUp mentioned, Access is very picky about parentheses in JOINs in its SQL.

Assuming the SQL is correct, this code lives on the parent form, and you dno't get multiple rows back in your query, maybe something like this would work:
Public Function calcOutstanding() As Currency

    Dim db As DAO.Database
    Dim rst As DAO.Recordset
    Dim strSQL As String

    Set db = CurrentDb

    strSQL = "SELECT SUM(tblTransaction.TxAmount + tblTransaction.TxTax) As Outstanding " _
        & "FROM (tblTransaction " _
        & "INNER JOIN tblProduct ON tblTransaction.fkProductID = tblProduct.ProductID) " _
        & "INNER JOIN tblHolder ON tblProduct.fkHolderID = tblHolder.HolderID " _
        & "WHERE tblTransaction.TxPaid = False " _
        & "AND tlbHolder.HolderID = " & Me.HolderID

    Set rst = db.OpenRecordset(strSQL, dbForwardOnly)

    calcOutstanding = rst![Outstanding]

    Set rst = Nothing
    set db = Nothing

End Function

Notice the concatenation in the WHERE clause to get the value from the form's data source (otherwise the SQL couldn't reconcile Me.HolderID within the scope of the SQL itself).  Also, we push the returning dataset into a recordset and read from that.  Something along these lines should work, I think.  (Not in front of Access now, so sorry if any non-compiling statements.)
EDIT: Added the function return type as integer for specificity's sake.
EDIT 2: Added the function return type as currencyfor specificity's sake.  Doh.

A: I doubt you need an external function to do this. MS Access allows you to reference fields from subform simply by Me.Subform!FieldName.Value
This means, you could simply access the subform fields that are related to your current record. Even perform IIF(condition, truevalue, falsevalue) on that field
read more about accessing forms and subforms here: http://access.mvps.org/access/forms/frm0031.htm
EDIT:
in your third subform (tbl_transaction), create a new unbound TextBox called (txt_outstanding) and assign this expression
=IIF([txPaid]=false, sum(txAMount +TxTax),0)

now you can access this field in your parent form something similar to this:
me.txt_someTextbox.value = nz(me.tbltransactionsubform!txt_outstanding.value,"")

A: Right off the bat, I see a problem in the code you posted:
strSQL = "SELECT SUM(tblTransaction.TxAmount + tblTransaction.TxTax) As Outstanding" _
& "FROM tblTransaction" _
& "INNER JOIN tblProduct ON tblTransaction.fkProductID = tblProduct.ProductID" _
& "INNER JOIN tblHolder ON tblProduct.fkHolderID = tblHolder.HolderID" _
& "WHERE tblTransaction.TxPaid = False" _
& "AND tlbHolder.HolderID = Me.HolderID;"

There should be a space either at the end of each line Outstanding " _ or at the beginning of each line like " FROM tblTransaction otherwise your string will read OutstandingFROM tblTransaction when parsed, which will give you an error.


text:
Q: Express using logic symbols: I have to also decide whether it is true or not after I express it in logic symbols. This is what I have so far..Am I correct? and I don't know how to do a)..
a) There is a smallest positive number
-no idea how to approach this one? Perhaps somehow denote this as infinity? and how can I even state a true/false value? Is this even a statement?
b) Every integer is a product of two integers
True: (x,y belong to the set of integers): ∀x∀y(x * y = (set of integers))
c) The equation x^2+y^2 = 1 has a solution (x,y) in which both x and y are natural numbers
True: (x,y belong to the set of natural numbers): ∀x∀y(x^2+y^2 = 1)
d) Every real number can be written as a difference of two positive real numbers
True: (x,y belong to the set of real numbers): ∀x∀y(x-y = (set of real numbers))
Thank you very much!

A: Here are the two most direct ways to say that there is no smallest positive number:
$$\begin{align*}
&\neg\exists x\forall y(y>0\to y\ge x)\\
&\forall x\big(x>0\to\exists y(y>0\land y<x)\big)
\end{align*}$$
In words:

*

*There is no number $x$ such that whenever $y$ is positive, $y$ is at least as large as $x$.

*For every positive number $x$ there is a positive number $y$ that is smaller than $x$.

Your formula for (b) does not say what you want it to say: it says that the product of any two integers whatsoever is the set of integers. That's clearly not right: the product is an integer, not the whole set of integers. But even if you changed it to $\forall x\forall y(xy\in\Bbb Z)$, which is at least a true statement (meaning that the product of any $x$ and $y$ is an integer), it wouldn't say what you want. You want to say that whenever $x$ is an integer, there are integers $y$ and $z$ whose product is $x$. Notice the existence statement there: you're almost certainly going to want some existential quantifiers. And in fact the English translates pretty directly into symbols: $\forall x\exists y\exists z(yz=x)$. Note, though, that this works only if it's understood that that $x,y$, and $z$ range over the integers. If not, you have to specify that as well, either as
$$\forall x\in\Bbb Z\exists y\in\Bbb Z\exists z\in\Bbb Z(yz=x)$$
or, more formally, as
$$\forall x\Big(x\in\Bbb Z\to\exists y\exists z(y\in\Bbb Z\land z\in\Bbb Z\land yz=x\Big)\;.$$
Your answer to (c) is also wrong, I'm afraid: you've said that no matter what real numbers you substitute for $x$ and $y$, $x^2+y^2$ will be $1$. The sentence that you're supposed to be translating makes a much weaker claim: it says that there is at least one pair of numbers $x$ and $y$ such that $x^2+y^2=1$. That's $\exists x\in\Bbb R\exists y\in\Bbb R\left(x^2+y^2=1\right)$.
In (d) you've made the same kind of mistake as in (b). It makes no sense to say that $x-y$ is equal to the whole bloomin' set of real numbers: it's just one real number! And when we fix that, so that it says $\forall x\in\Bbb R\forall y\in\Bbb R(x-y\in\Bbb R)$, we're just saying that if you take the difference of two real numbers, you get a real number. That's not the same as saying that if you start with any real number $x$, you can find two real numbers whose difference is $x$, which is what you're supposed to be saying. That requires a couple of existential quantifiers: $$\forall x\in\Bbb R\exists y\in\Bbb R\exists z\in\Bbb R(y-z=x)\;.$$ Structurally this is exactly like (b).

A: There is a smallest positive number $\epsilon > 0$ such that $\forall a, b \in R : a - b > \epsilon$. This is denoted as $\mathbf{epsilon}$.
The second one would be similar to yours:
$\forall x \in \mathbb{Z}[\exists a, b \in \mathbb{Z} : ab = x]$
I think these provide enough hints for you to finish.

A: I will show the first problem for you. We are talking about a smallest positive number, let's call this number $a$. Then the number $a$ has two properties:
$\bullet$ $a$ is positive, or in formal language: $a \in \mathbb{R}_+$.
$\bullet$ $a$ is the smallest positive number, so any other positive number $b$ is greater or equal to $a$.
We can then write the statement "there exists a smallest positive number" as follows: $\exists a \in \mathbb{R}_+ \forall b \in \mathbb{R}_+ : a \leq b$.
Can you solve the other problems now?

A: A) "There is a smallest positive number" should be
$$ \exists N \in PositiveNumbers : smallest(N) $$
Any clarification of the concept of numbers and smallest is speculation and thus not logically correct.


text:
Q: Rancher: Able to do get, but not create objects ( dial tcp [::1]:6443: connect: network is unreachable) I have created a cluster using Rancher 2.6.0. Till yesterday everything was fine. But all of a sudden I am not able to create any objects on cluster. However, I am able to query the objects without any issue.
ex: I can get secrets list
$ k get secrets
NAME                        TYPE                                  DATA   AGE
default-token-j4zfb         kubernetes.io/service-account-token   3      24h
imgcred                     kubernetes.io/dockerconfigjson        1      21h
sh.helm.release.v1.rmq.v1   helm.sh/release.v1                    1      22h

But can't create secrets
$ k create secret generic splunktoken --from-literal=token=<token>
Error from server: Get "https://[::1]:6443/api/v1/namespaces/default/resourcequotas": dial tcp [::1]:6443: connect: network is unreachable

New Rancher, Completely revamped and causing a lot of problems.

A: I was able to fix the issue by restarting the docker container in all the nodes. Not sure why this problem occured. Even when the required ports are working and configs are in place.


text:
Q: Ideal in compact Hausdorff space This is exercise 70, chapter 4. from Folland (page 142)
Let $X$ be a compact Hausdorff space. An ideal in $C(X, \mathbb{R})$ is a subalgebra $J$ of
$C(X, \mathbb{R})$ such that if $f\in J$ and $g\in C(X, \mathbb{R})$ then $fg\in J$.

*

*If $J$ is an ideal in $C(X, \mathbb{R})$, let $h(J) = \{x \in X: f(x) = 0,\ \forall f \in J\}$. Then $h(J)$ is a closed subset of $X$, called the hull of $J$.

*If $E\subset X$, let $k(E)=\{f \in C(X, \mathbb{R}) : f(x)=0,\  \forall x \in E\}$. Then $k(E)$ is a closed ideal in $C(X, \mathbb{R})$, called the kernel of $E$.

*If $E\subset X$, then $h(k(E)) =\overline{E}$.

*If $J$ is an ideal in $C(X, \mathbb{R})$ then $k(h(J))=\overline{J}$. (Hint: $k(h(J))$ may be identified with a subalgebra of $C_0(U, \mathbb{R})$ where $U=X\setminus h(J)$)

I've managed to prove assignments 1-3. In (4)
if $f$ is from $J$ then for each $y\in h(J)$ is $f(y)=0$, then must be $f\in k(h(J))$. Since $k(h(J))$ is closed, also $\overline J\subset k(h(J))$.
For other way around, I've proven the hint ($k(h(J))$ may be identified with a subalgebra of $C_0(U, \mathbb{R})$ where $U=X\setminus h(J)$), using some corollary fo Stone-Weierstrass), but don't understand how to make conection between $C_0(X\setminus h(J), \mathbb{R})$ and $\overline{J}$
ANY HELP WOULD BE APPRECIATED.
P.S. This is my first time asking question, but I've found this site very helpfull, so thanks!

A: I don't know for the moment how to use the hint. However, we can try the following.

*

*Fix $f\in k(h(J))$ and $\varepsilon>0$. Let $K:=\{x\in X, |f(x)|\geqslant \varepsilon\}$. By compactness, we can find $g\in J$ non-negative such that $g>0$ on $K$. Indeed, $K$ is compact, and the intersection $\bigcap_{g\in J}g^{-1}(\{0\})\cap K$ is empty, so there are $g_1,\dots,g_n$ such that $K\cap\bigcap_{j=1}^ng_j^{-1}(\{0\})\cap K$ is empty. Then take $g:=\sum_{j=1}^ng_j^2$.

*Let $f_n(x):=\frac{f(x)}{\frac 1n+g(x)}g(x)$. It's an element of $J$ such that $\lVert f_n-f\rVert\leqslant 2\varepsilon$.
It's also exercise 1.5.b) in Elements of Functional Analysis, by F. Hirsch and G. Lacombe, Springer


text:
Q: C++ matrix class template I am coding a matrix template class and the problem I am having is that the array is created and the values are filled but when I use the print() function, the array is empty again. Could anyone perhaps indicate what I'm doing wrong please?
data is defined as such:
T **data;

template<class T>
CMatrix<T>::CMatrix( int rows, int cols)
{
setRow(rows);
setCol(cols);

data = new int*[rows];
// Create matrix with dimensions given

for (int i = 0; i < row; i++) {
    data[i] = new int [cols];
}

for(int i = 0; i < row; i++) {
    for(int j = 0; j < cols; j++) {
        data[i][j] = (int) i * j;
    }
}
}

template<class T>
void CMatrix<T>::print()
{
int i,j;

for (i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
    printf("%.1f    ",data[i][j]);
}
printf("\n");
}
}

Main function:
int main (){

int rows =4;
int cols = 4;

CMatrix<int>* matrixOne= new CMatrix<int>(rows, cols);
matrixOne->print();

    return(0);
}

Declarations of template:
template<class T>
class CMatrix

{
private:
    int row;  // number of rows
    int column;  // number of columns

public:

    CMatrix(int rows, int cols);

    CMatrix(const CMatrix& data); //Copy constructor

    //Constructor taking an array of 16 elements
    CMatrix(T Matrix[16]);
    ~CMatrix();

    T **data;
    void setRow(int r);
    void setCol(int c);
    int getRow();
    int getCol();

    //Subscript operators
    T& operator()(int row, int col);
    T operator()(int row, int col) const;
    void print();

};

A: I would make sure you are using your data variable and your row and column variables in a class.  This is by no means the most complete version, but it compiles and runs fine.
Also make sure that you use "T" and not "int" in your constructor.  See the comments.
Note the two comments in the print function about using row and col instead of hard coding the values.
#ifndef CMATRIX_H
#define CMATRIX_H

#include <stdio.h>

template <class T>
class CMatrix
{
public:
    CMatrix( int rows, int cols)
    {
        setRow(rows);
        setCol(cols);

        data = new T*[rows]; // replaced "int" for "T"

        for (int i = 0; i < row; i++) {
            data[i] = new T [cols]; // replaced "int" for "T"
        }

        for(int i = 0; i < row; i++) {
            for(int j = 0; j < cols; j++) {
                data[i][j] = (T) i * j; // replaced "int" for "T"
            }
        }
    }

    void print();
    void setRow(int r){row = r;}
    void setCol(int c){col = c;}
    T& operator()(int row, int col);
private:
    T **data;
    int row,col;
};

template <class T>
void CMatrix<T>::print ()
{
    int i,j;

    for (i=0;i < row;i++) // Here you used to have row hard coded to 4
    {
        for(j=0;j < col;j++) // Here you used to have col hard coded to 4
        {
            printf("%.1f    ",(float) data[i][j]);
        }
        printf("\n");
    }
}

// Recently added
template<class T> T& CMatrix<T>::operator()(int row, int col)
{
    return data[row][col];
}

#endif // CMATRIX_H

Here is the main.
#include "cmatrix.h"
#include <iostream>

int main(int argc, char *argv[])
{
    CMatrix <float> m(4,4);

    m.print();

    // Recently added
    std::cout << m(1,1);

    return 0;
}


text:
Q: Difference in if statement selector I don't understand the difference between this condition:
if ($("div")) { /* code */ }

and
if ($("div").length) { /* code */ }

What's the difference?

A: The first if condition is incorrect as $('div') returns an object. Type coercion to a boolean from an object - even an empty one - will always equate to true.
The second condition is checking the length property of the object, which is an integer. Type coercion on that type will be false if the value is 0 and true for anything else, either positive or negative, hence it works.


text:
Q: How to integrate SAP Crystal Reports in Visual Studio 2017 Is it possible to use the report designer in the current release of Visual Studio 2017?
The SAP crystal report wiki for visual studio integration only states: "RC build currently not supported - Tested opening existing app and it works".
I have installed the latest developer SDK (Support Pack 19 v.13.0.19.2312), but when I try to open an existing report (.rpt), i got the following message:

There is no editor available for 'C:...\Report.rpt'.
Make sure the application for the file type (.rpt) is installed.

EDIT (2018/02/28)
By the time of asking this question I had installed SP19 on my machine. The current version which should resolve all my issues is SP22, which was released at 2018/01/11. All necessary information and download links are still available in the SAP crystal report wiki.

EDIT (2019/03/20)
Thanks to @ANewGuyInTown: The current version is 13.0.24.

A: Please wait Support Pack 21 in September 2017
UPDATE:
More info
https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads
VS 2017 - Tested opening existing app and it works, CR for VS is not integrated into the app so no new CR projects available- should be fully integrated in SP 21

About release
Link: https://answers.sap.com/questions/168439/crystal-report-for-vs-2017.html
Moderator Don Williams said:
Not supported yet, I tried to get it into SP 20 but due to time constraints DEV can't get it into VS until SP 21, due out in September time...

A: Visual Studio 2017 is supported in Crystal Reports SP 21, which is available for download as of 1 Sep 2017.

A: I had a workaround for this problem. I created dll project with viewer in vs2015 and used this dll in vs2017. Report showing perfectly.

A: Starting with Visual Studio 2010, crystal reports is no longer installed with Visual Studio. It can be installed separately by downloading the install from SAP crystal reports website. SAP crystal reports provides two installations. The first is SAP Crystal Reports version for visual studio that is installed for working with crystal reports in visual studio. The other is SAP Crystal Reports runtime engine for .NET Framework that is installed when the application is deployed on server machine.
SAP Crystal Reports in Visual Studio 2017 is now planned for Service Pack/Support Pack 21 (as of Apr 04'2017). The current available service/support pack is 19. Service/Support Pack 21 is expected to be released in September 2017.
You can use the MSI to install on the VS PC, it won't integrate into VS so you won't be able to design reports within the VS IDE but your app will compile. There will not be any Templates either so just add the CR Viewer to the Tool bar. Upgrading an exist VS app will simply work.
So in the meantime to edit rpt files you'll need the stand-alone Crystal Reports Designer until Support Pack 21 comes along.
Sources:
https://forums.asp.net/t/2110984.aspx?VS+2017+and+Crystal+Reports
https://answers.sap.com/questions/168439/crystal-report-for-vs-2017.html

A: To integrate SAP Crystal Reports with Visual Studio 2017 below steps needs to be followed right:

*

*Uninstall all installed components from system related to Crystal Report. [If any]

*Install compatible Crystal Report Developer Edition (as per target VS) with administrator priviledge. [As of writing, latest compatible service pack is 23]

*

*Install appropriate Crystal Report Runtime (x86/ x64) for Visual Studio. [Not mandatory]

*Open solution in VS and remove all assembly references from project related to Crystal Report. [If any]

*Include following assembly references in project:

*

*CrystalDecisions.CrystalReports.Engine

*CrystalDecisions.ReportSource

*CrystalDecisions.Shared

*CrystalDecisions.CrystalReports.Design

*CrystalDecisions.VSDesigner

*Make sure "Copy Local" property is set to "True" in reference properties.

*Build/ Rebuild project.

A: Crystal Reports SP 19 does not support Visual Studio 2017. According to SAP they are targeting Visual Studio 2017 compatibility in SP 20 which is tentatively scheduled for June 2017.

A: I post an answer because I can't comment but I followed @DrCJones steps. I installed the new Crystal Reports SP21 for Visual Studio 2017 with an older version running on my Windows 10. Installer warned me that it detected an older version and that it will overwrite it. Installation were through but I had the following message when I tried to open a project with reports in VS2017:

The Crystal Reports Tools Package did not load correctly

I couldn't edit reports either. So, I manually uninstalled CR Runtime Engine & CR for VS, then reinstalled SP21, finally rebooted.
Now it works :)

A: Extracted from official SAP site https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads.
Item # 3 fixed my installation.
This applies for ANY Patch after SP 21

*

*FlexNet and In-Place Upgrade does not work:  Once user receive the update notification from FlexNet server and finish SP21 upgrade, the product will NOT work. User MUST repair CR4VS and CRRuntime64 in Control Panel\Programs. That's a by design change to installer.
a.    Please notice that we are still facing problems on configuring FlexNet upgrade server, so currently user will NOT receive SP21 notification

*Microsoft Windows Update KB2999226 is a prerequisite for SP21.
a.    This is same as BI 4.2 SP4 and BI 4.1 SP10. Please refer to SAP Note 2451830.

*For VS2017 integration, user needs use "run as Administrator" by right-clicking setup.exe, even if you are already log on by using Administrator account

*As most of CR/RAS .NET Assemblies are now re-versioned from 13.0.2000.0 to 13.0.3500.0, user MUST remove all old CR assemblies from Reference list and add the new version of CR assemblies, then rebuild the application.
a.    For those customer/user who do not wanted to rebuilt their application, there's workaround to use  in app.config/web.config, please see attachment.
WinFormCRViewer.zip

*For reports using the ADO.Net DB connection, in previous SP's, you could only work under .Net Framework 2.0/3.5, so using  in app.config is required. Now in SP21, ADO.Net is only supported on .Net Framework 3.5 or above.

A: This error occurs because at the end of the installation of Crystal Reports SP21 for Visual Studio 2017, the following screen appears:

Do not check to install in runtime, this default to come marked to me is wrong. Install only Crystal Reports SP21 for Visual Studio 2017.

A: I had exactly the same problem with my VS 2013 solutions when I install VS 2017 and Crystal Reports SP21.
In fact it's because VS does not necessarily convert the solution in the first launch.
Once you have installed Crystal Report SP 21, make sure that VS 2017 upgrade your solution : a window must appear "SAP Crystal Reports, version for Visual" with a radio button "Convert the solution".
Screenshot in french :

When I used the menu "File / Open / Project/Solution", the conversion was not done.
I have to do that :

*

*Add VS 2017 on the tasks bar

*Run VS 2017 and Open the solution with File menu

*Try to build the project, errors appear with Crystal Reports

*Close VS 2017

*Right click on VS 2017 shortcur in then tasks bar and open the solution directly

*The conversion run this time, you can open .rpt and the solution build without error.

A: I had the same problem and I solved by installing Service pack 22 and it fixed it.

A: So to sum up, this is what worked for me after upgrading my VB 2010 (CR18) to VB 2017:

*

*Uninstall all runtimes AND CRforVS.

*Reboot

*Install CRforVS SP23 (no runtimes needed on developer machine).

*Open project, remove old DLL references.

*Add new references (DLL files that you need from C:\Program Files (x86)\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Common\SAP BusinessObjects Enterprise XI 4.0\win32_x86\dotnet)

*Rebuild All.

*Have fun.

A: As of 20/03/2019 -> There is a new version of Crystal report for Visual Studio.
The version is 13.0.24.
The provided version in the accepted answer is 13.0.21.
The newer version worked for me without having to do any workaround.

A: FYI: Taken from: https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads
Overview
Support Packs for "SAP Crystal Reports, developer version for Microsoft Visual Studio" (SAP Crystal Reports for Visual Studio) are scheduled on a quarterly bases and support the following versions of Visual Studio:

*

*VS 2010 – original release and higher

*VS 2012 – SP 7 and higher

*VS 2013 – SP 9 and higher

*VS 2015RC – SP14

*VS 2015 – SP 15 and higher

*VS 2017 - SP 21 and higher

Download Crystal Reports developer, for Microsoft Visual Studio


text:
Q: Adjoint representation of $\mathfrak{so}(n)$ So I know $\mathfrak{so}(n)$ consists of anti-symmetric matrices, but I don't see why the adjoint representation is isomorphic to the anti-symmetric tensor square of the vector representation. I see that we can associate each matrix with an anti-symmetric tensor, but I don't get how it relates with the adjoint representation. Can someone please help me clarify some of this confusion. Thanks.

A: The adjoint representation $\mathfrak{so}(n)$ is isomorphic to the second exterior power and not to the second symmetric power. The isomorphisms are given as follows: For a matrix $X\in\mathfrak{so}(n)$, the map $(v,w)\mapsto \langle Xv,w\rangle$ is bilinear and skew symmetric, thus defining an element of $\Lambda^2\mathbb R^{n*}\cong \Lambda^2\mathbb R^n$. Conversely, you associate to $w_1\wedge w_2$ to the map $f:\mathbb R^n\to\mathbb R^n$ defined by $v\mapsto \langle v,w_1\rangle w_2-\langle v,w_2\rangle w_1$. One immediately verifies that this map lies in $\mathfrak{so}(n)$ and that the two constructions are inverse to each other.


text:
Q: How do I return a different value from a stub based on a lambda argument I have the following sample test code
    public Stage Test(Stage Stage)
    {
        var StartStage = StageRepository.Single(x => x.Order == 1);
        var EndStage = StageRepository.Single(x => x.Order == 5);
        var ErrorStage = StageRepository.Single(x => x.Name == "Error");

        if (Stage == StartStage)
        {
            return EndStage;
        }
        else
        {
            return ErrorStage;
        }
    }

And I am trying to test it using the following unit test
    [TestMethod]
    public void XXXTest()
    {
        //// Arrange
        var AutoMocker = new RhinoAutoMocker<StageService>(MockMode.AAA);

        MockRepository mockRepository = new MockRepository();

        var MockStageRepository = AutoMocker.Get<IRepository<Stage>>();

        Stage StartStage = mockRepository.Stub<Stage>();
        StartStage.Order = 1;

        Stage EndStage = mockRepository.Stub<Stage>();
        EndStage.Order = 5;

        Stage ErrorStage = mockRepository.Stub<Stage>();
        ErrorStage.Name = "Error";

        System.Linq.Expressions.Expression<Func<Entities.Stage, bool>> StartParam = x => x.Order == 1;
        MockStageRepository
            .Stub(x => x.Single(Arg<System.Linq.Expressions.Expression<Func<Entities.Stage, bool>>>.Is.Equal(StartParam)))
            .Return(StartStage);

        System.Linq.Expressions.Expression<Func<Entities.Stage, bool>> EndParam = x => x.Order == 1;
        MockStageRepository
            .Stub(x => x.Single(Arg<System.Linq.Expressions.Expression<Func<Entities.Stage, bool>>>.Is.Equal(EndParam)))
            .Return(EndStage);

        System.Linq.Expressions.Expression<Func<Entities.Stage, bool>> ErrorParam = x => x.Order == 1;
        MockStageRepository
            .Stub(x => x.Single(Arg<System.Linq.Expressions.Expression<Func<Entities.Stage, bool>>>.Is.Equal(ErrorParam)))
            .Return(ErrorStage);

        StageService StageService = AutoMocker.ClassUnderTest;

        //Act
        var ReturnStage = StageService.Test(StartStage);

        //Assert
        Assert.AreEqual(ReturnStage, EndStage);
    }

However this is not working as it is not returning anything when I call StageRepository.Single(). If I change the stub code to ignore the argument then it does return something but it will be the same object returned for each call to Single() which I don't want.
Is it possible to configure RhinoMocks in such a way as to return different objects from a stub depending on the lambda that is passed into it?

A: I think the root of your problem is that equality on the Expression<Func<T,U>> type is performed by reference rather than value. That means your telling Rhino Mocks to look for instances of expressions created in the test rather than the ones created in the code your testing.
Two possible approaches come to mind:

*

*One would be to provide a way to pass the lambda expressions in to the Stage class from the test, so that when the argument checks happen they are working against the same instances.
Maybe something like:
internal void SetStartStage(Expression<Func<Entities.Stage,bool>> predicate)
{
    ...
}

The inverse of this would also work, i.e. provide the Expression objects as   fields/properties that can be accessed by you're test, and then use those when setting up your mock:
internal Expression<Func<Entities.State,bool>> StartStagePredicate
{
    get{ return x => x.Order == 1; }
}

*Another option would be to use the Matches method on Args to see if the argument checks the Stage object state correctly.  This would require creating some Stage objects in your test that would match the criteria:
var startStageTester = new Stage { Order = 1 };
MockStageRepository
        .Stub(x => x.Single(Arg<System.Linq.Expressions.Expression<Func<Entities.Stage, bool>>>.Matches(y => y.Compile()(startStageTester)))
        .Return(StartStage);

The call to Compile() is a little jarring, but since you're dealing with an Expression and not a straight-up lambda, you've got to compile it in order to evaluate it.
Now, if a Stage is something that is hard to create, then you may need to create a Mock/Stub of one (or use you're StartStage) and have it return 1 from the Order property (in the case of the StartStage anyway).
There are probably some others I'm not thinking of at the moment as well.

A: IF the linq condition is not important, I would propose to match it as any, something like this
repository.Stub(x => x.Find(Arg<System.Linq.Expressions.Expression<Func<Entity, bool>>>.Is.Anything)).Return(entitiesList.AsQueryable());

Hope this help.

A: Thanks for that. That worked a treat. The one thing that I was missing was the Compile method on an ExpressionTree. There is a small bug in your sample code (you use x twice). For completeness here is the working code.
        MockStageRepository2
            .Stub(x => x.Single(Arg<System.Linq.Expressions.Expression<Func<Entities.Stage, bool>>>.Matches(y => y.Compile()(StartStage2))))
            .Return(StartStage2);


text:
Q: Symfony2, Sonata : Checkbox from entity I successfully displayed a list of checkbox from an entity "category"

*

*Cat1

*Cat2

But when i submit the form it returns an error :

Expected value of type "Doctrine\Common\Collections\Collection|array" for association field "SE\ApiBundle\Entity\Post#$postCategories", got "SE\ApiBundle\Entity\Category" instead.

So i guess i'm doing it the wrong way but can't find how to do.
It is similar to a ManyToMany relationship but i created an entity for my relation table :
/**
 * @ORM\Entity
 * @ORM\Table(name="post_category")
 */
class PostCategory
{

    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Post", inversedBy="postCategories")
     * @ORM\JoinColumn(name="post_id", referencedColumnName="id")
     */
    private $post;

    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Category")
     * @ORM\JoinColumn(name="category_slug", referencedColumnName="slug")
     */
    private $category;

}

Post :
/**
 * @ORM\Entity
 * @ORM\Table(name="post")
 */
class Post
{

    ...

    /**
     * @ORM\OneToMany(targetEntity="PostCategory", mappedBy="post")
     **/
    private $postCategories;

 }

Category :
/**
 * @ORM\Entity
 * @ORM\Table(name="category")
 */
class Category
{

    /**
     * @ORM\Id
     * @Gedmo\Slug(fields={"name"})
     * @ORM\Column(type="string", length=32, name="slug")
     */
    private $slug;

    /**
     * @ORM\Column(type="string", length=32, name="name")
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=32, name="class_icon")
     */
    private $classIcon;

}

Sonata Admin :
->add('postCategories', 'entity',
    array(
        'class' => 'ApiBundle:Category',
        'property' => 'name',
        'multiple' => true,
        'expanded' => true
    )
)

This is working with a ManyToMany relationship but i soon as i try with a relation table managed by my own entity it fails.
Any ideas what am i doing wrong?


text:
Q: How to iterate row by row in a pandas dataframe and look for a value in its columns I must read each row of an excel file and preform calculations based on the contents of each row. Each row is divided in columns, my problem is that I cannot find a way to access the contents of those columns.
I'm reading the rows with:
for i in df.index,:
    print(df.loc[i])

Which works well, but when I try to access, say, the 4h column with this type of indexing I get an error:
for i in df.index,:
    print(df.loc[i][3])

I'm pretty sure I'm approaching the indexing issue in the wrong way, but I cannot figure put how to solve it.

A: You can use iterrows(), like in the following code:
for index, row in dataFrame.iterrows():
  print(row)

But this is not the most efficient way to iterate over a panda DataFrame, more info at this post.