text:
Q: Geopandas map layering I am learning to create 'layered' maps in Spyder IDE with geopandas package with using this code:
import geopandas as geopandas
import matplotlib.pyplot as plt

world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities'))

world.plot()

ax = plt.subplot(1, 1)
world.plot(column='pop_est', ax=ax, legend=True)

I execute code line by line as in RStudio.
Unfortunately, I am only able to obtain a white blank sheet instead of a map.

A: I ran the example on Jupyter but I don't think it should change anything as long as you have the packages installed.
f, ax = plt.subplots(1,1,figsize=(10,10))
world.plot(column='pop_est', ax=ax, legend=True)

If you are only interested in the geometry, you can do the following:
world.geometry.plot(color="white", edgecolor='k')

If, in the future, you want to add this geometry to a map, you can do
world.geometry.plot(color=None, edgecolor='k')


text:
Q: Is there an easy formula to calculate this angle? If $|AB|=|BC|=|CD|$ is there a (better not absurdly complicated) general formula for the angle $APD$ depending on the radius $r$ and $|AB|$?

A: Let $l=\left|AB\right|$. There are obvious limits where the angle is zero when $l=r\sqrt 2$ and if you want $P$ to stay outside the circle, then the angle is $60^\circ$ when $l=r\sqrt 3$. Some simple geometry shows the angle is
$$ \pi-4\cos^{-1}\frac{l}{2r} $$
radians.

A: The arcs subtended by chords AB, BC and CD are all equal; cal the central angle in each of those arcs $\alpha$.  The arc DA subtends $2\pi - 3\alpha$.  Angle APD is given by half the distance between the arcs subtended by BC and AD, that is,
$$
\angle APD = \frac{1}{2}( \alpha - (2\pi-3\alpha) = 2\alpha - \pi
$$
It is easy enough to find $\alpha$ from right triangle OAM where O is the center of the circle and M the midpoint of AB:
$$
\sin \left(\frac{1}{2}\alpha\right) = \frac{|AB|}{2r}
$$
Then
$$
\angle APD =  2 \cdot 2\sin^{-1} \frac{|AB|}{2r} - \pi =  4\sin^{-1} \frac{|AB|}{2r} -  \pi
$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Twilio + Nodejs react app. Cannot find module "net" I'm trying to create a web app using React and Express and using webpack-dev-server for development. I want to send text messages but I keep getting this error when I try to use Twilio or Plivo Uncaught Error: Cannot find module "net"
Another error I get is:
./~/twilio/package.json
Module parse failed: /Users/H/github/app/node_modules/twilio/package.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
|   "_args": [
|     [
|       "twilio",
 @ ./~/twilio/lib/Client.js 5:17-43

And I get a lot more of errors similar to that one. I'm trying to follow the example Twilio has in the docs but just by requiring twilio in the app it gives me those errors.

A: Twilio developer evangelist here.
The twilio module for Node.js is not recommended to be used in the front end, so is not built for the front end. The library uses your Account Sid and Auth Token from your Twilio account to authenticate with the API. You should keep those credentials secret, otherwise an attacker could steal them and use your Twilio account.
We recommend making calls to the Twilio API from your own server. You could then build a React component to make calls to that server via AJAX, rather than calling the API directly in the front end.

A: According to error message you need specify appropriate loader for json files (it requires here) in your webpack-config.
{test: /\.json$/, loader: 'json'}


text:
Q: Caused by: org.springframework.data.redis.serializer.SerializationException: Cannot deserialize; nested exception is org.springframework.core.seriali I'm developing Spring Boot + Spring Data Redis example. In this example, trying to use the @EnableRedisHttpSession and have taken a code reference from https://www.youtube.com/watch?v=_M8xoagybzU&t=231s.
I developed the code and when I tried to run the example. I get the below error. I am not getting clue what's wrong going on ? Also, I am not clear why error Caused by: java.lang.ClassNotFoundException: com.example.Order.
Caused by: org.springframework.data.redis.serializer.SerializationException: Cannot deserialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to deserialize payload. Is the byte array a result of corresponding serialization for DefaultDeserializer?; nested exception is org.springframework.core.NestedIOException: Failed to deserialize object type; nested exception is java.lang.ClassNotFoundException: com.example.Order
    at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.deserialize(JdkSerializationRedisSerializer.java:84) ~[spring-data-redis-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.data.redis.serializer.DefaultRedisElementReader.read(DefaultRedisElementReader.java:48) ~[spring-data-redis-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.data.redis.serializer.RedisSerializationContext$SerializationPair.read(RedisSerializationContext.java:226) ~[spring-data-redis-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.data.redis.cache.RedisCache.deserializeCacheValue(RedisCache.java:254) ~[spring-data-redis-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.data.redis.cache.RedisCache.lookup(RedisCache.java:88) ~[spring-data-redis-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    at org.springframework.cache.support.AbstractValueAdaptingCache.get(AbstractValueAdaptingCache.java:58) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.cache.interceptor.AbstractCacheInvoker.doGet(AbstractCacheInvoker.java:73) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.cache.interceptor.CacheAspectSupport.findInCaches(CacheAspectSupport.java:554) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.cache.interceptor.CacheAspectSupport.findCachedItem(CacheAspectSupport.java:519) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:401) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:345) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61) ~[spring-context-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at com.example.service.OrderService$$EnhancerBySpringCGLIB$$2fc6ad4.byId(<generated>) ~[classes/:na]
    at com.example.RedisApplication.lambda$4(RedisApplication.java:97) [classes/:na]
    at com.example.RedisApplication.measure(RedisApplication.java:89) [classes/:na]
    at com.example.RedisApplication.lambda$3(RedisApplication.java:98) [classes/:na]
    at com.example.RedisApplication.lambda$0(RedisApplication.java:57) [classes/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:804) [spring-boot-2.1.0.RELEASE.jar:2.1.0.RELEASE]
    ... 5 common frames omitted
Caused by: org.springframework.core.serializer.support.SerializationFailedException: Failed to deserialize payload. Is the byte array a result of corresponding serialization for DefaultDeserializer?; nested exception is org.springframework.core.NestedIOException: Failed to deserialize object type; nested exception is java.lang.ClassNotFoundException: com.example.Order
    at org.springframework.core.serializer.support.DeserializingConverter.convert(DeserializingConverter.java:78) ~[spring-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.core.serializer.support.DeserializingConverter.convert(DeserializingConverter.java:36) ~[spring-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.deserialize(JdkSerializationRedisSerializer.java:82) ~[spring-data-redis-2.1.2.RELEASE.jar:2.1.2.RELEASE]
    ... 24 common frames omitted
Caused by: org.springframework.core.NestedIOException: Failed to deserialize object type; nested exception is java.lang.ClassNotFoundException: com.example.Order
    at org.springframework.core.serializer.DefaultDeserializer.deserialize(DefaultDeserializer.java:75) ~[spring-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at org.springframework.core.serializer.support.DeserializingConverter.convert(DeserializingConverter.java:73) ~[spring-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    ... 26 common frames omitted
Caused by: java.lang.ClassNotFoundException: com.example.Order
    at java.net.URLClassLoader.findClass(Unknown Source) ~[na:1.8.0_151]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_151]
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) ~[na:1.8.0_151]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[na:1.8.0_151]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_151]
    at java.lang.Class.forName(Unknown Source) ~[na:1.8.0_151]
    at java.io.ObjectInputStream.resolveClass(Unknown Source) ~[na:1.8.0_151]
    at org.springframework.core.ConfigurableObjectInputStream.resolveClass(ConfigurableObjectInputStream.java:80) ~[spring-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source) ~[na:1.8.0_151]
    at java.io.ObjectInputStream.readClassDesc(Unknown Source) ~[na:1.8.0_151]
    at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source) ~[na:1.8.0_151]
    at java.io.ObjectInputStream.readObject0(Unknown Source) ~[na:1.8.0_151]
    at java.io.ObjectInputStream.readObject(Unknown Source) ~[na:1.8.0_151]
    at org.springframework.core.serializer.DefaultDeserializer.deserialize(DefaultDeserializer.java:72) ~[spring-core-5.1.2.RELEASE.jar:5.1.2.RELEASE]
    ... 27 common frames omitted

ShoppingCart.java
public class ShoppingCart implements Serializable{
    private static final long serialVersionUID = 1L;

    private final Collection<Order> orders = new ArrayList<>();

    public void addOrder(Order order) {
        this.orders.add(order);
    }

    public Collection<Order> getOrders(){
        return this.orders;
    }
}

CartSessionController.java
@Log
@Controller
@SessionAttributes("cart")
public class CartSessionController {

    private final AtomicLong ids = new AtomicLong();

    @ModelAttribute("cart")
    ShoppingCart cart() {
        log.info("Creating new cart");
        return new ShoppingCart();
    }

    @GetMapping("/orders")
    String Order(@ModelAttribute("cart") ShoppingCart cart, Model model) {
        cart.addOrder(new Order(ids.incrementAndGet(), new Date(), Collections.emptyList()));
        model.addAttribute("orders", cart.getOrders());
        return "orders";
    }
}

Order.java
@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("orders")
public class Order implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private Long Id;

    @Indexed
    private Date when;

    @Reference
    private List<LineItem> lineItems;
}

LineItem.java
@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("lineItems")
public class LineItem implements Serializable {
    private static final long serialVersionUID = 1L;

    @Indexed
    private Long orderId;

    @Id
    private Long id;

    private String description;
}

RedisApplication.java
@Log
@SpringBootApplication
@EnableRedisHttpSession
@EnableCaching
public class RedisApplication {

    private final String TOPIC = "Chat";
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private LineItemRepository lineItemRepository;
    @Autowired
    private OrderService OrderService;

    private ApplicationRunner titleRunner(String title, ApplicationRunner rr) {
        return args -> {
            log.info(title.toUpperCase() + ":");
            rr.run(args);
        };
    }

    @Bean
    ApplicationRunner geography(RedisTemplate<String, String> rt) {
        return titleRunner("geography", args -> {
            GeoOperations<String, String> geo = rt.opsForGeo();
            geo.add("Sicily", new Point(13.361389, 38.155556), "Arigento");
            geo.add("Ramesh", new Point(15.087269, 37.502669), "Catania");
            geo.add("Anup", new Point(13.583333, 37.316667), "Palermo");

            Circle circle = new Circle(new Point(13.583333, 37.316667),
                    new Distance(100, RedisGeoCommands.DistanceUnit.KILOMETERS));

            GeoResults<GeoLocation<String>> radius = geo.radius("Sicily", circle);
            radius.getContent().forEach(c -> log.info(c.toString()));
        });
    }

    public static void main(String[] args) {
        SpringApplication.run(RedisApplication.class, args);
    }

    //#####################
    @Bean
    CacheManager redisCache(RedisConnectionFactory connectionFactory) {
        return RedisCacheManager.builder(connectionFactory).build();
    }

    private long measure(Runnable r) {
        long start = System.currentTimeMillis();
        r.run();
        long stop = System.currentTimeMillis();
        return start - stop;
    }

    @Bean
    ApplicationRunner cache() {
        return titleRunner("caching", a ->{
            Runnable measure = () -> OrderService.byId(1L);
            log.info("first  "+measure(measure));
            log.info("two  "+measure(measure));
            log.info("three  "+measure(measure));
        });
    }

    //#####################

    @Bean
    ApplicationRunner repositories() {
        return titleRunner("repositories", args -> {
            Long orderId = generateId();

            List<LineItem> itemsList = Arrays.asList(
                        new LineItem(orderId, generateId(), "plunger"),
                        new LineItem(orderId, generateId(), "soup"),
                        new LineItem(orderId, generateId(), "cofee mug"));

            itemsList.stream().map(lineItemRepository::save).forEach(li -> log.info(li.toString()));

            Order order = new Order(orderId, new Date(), itemsList);
            orderRepository.save(order);

            Collection<Order> found = orderRepository.findByWhen(order.getWhen());
            found.forEach(o -> log.info("found : " + o.toString()));
        });
    }

    private Long generateId() {
        long tmp = new Random().nextLong();
        return Math.max(tmp, tmp * -1);
    }

    @Bean
    ApplicationRunner pubSub(RedisTemplate<String, String> rt) {
        return titleRunner("publish/subscribe", args ->{
            rt.convertAndSend(TOPIC, "Hello World @ "+Instant.now().toString());
        });
    }

    @Bean
    RedisMessageListenerContainer listener(RedisConnectionFactory rcf) {
        MessageListener ml = (message, pattern) -> {
            String str = new String(message.getBody());
            log.info("message from ' " + TOPIC + "':'" + str);
        };

        RedisMessageListenerContainer mlc = new RedisMessageListenerContainer();
        mlc.setConnectionFactory(rcf);
        mlc.addMessageListener(ml, new PatternTopic(TOPIC));
        return mlc;
    }
}

A: I flush the Redis DB using >FLUSHALL as suggested by @Arnaud, then it worked fine. Even now I can see the details of the SessionAttributes and SessionExpire etc are persisted into the cache.
127.0.0.1:6379> KEYS *
 1) "lineItems:3544713235909729939:idx"
 2) "order-by-id::1"
 3) "lineItems:orderId:4510658827505526003"
 4) "Sicily"
 5) "spring:session:expirations:1541668980000"
 6) "lineItems:6802678421112514562"
 7) "lineItems:4083773252419547322:idx"
 8) "lineItems:4083773252419547322"
 9) "lineItems:6802678421112514562:idx"
10) "spring:session:sessions:expires:ea0c3a35-b821-461b-8568-1cf972ba99cb"
11) "Anup"
12) "lineItems:3544713235909729939"
13) "orders:4510658827505526003:idx"
14) "orders:4510658827505526003"
15) "orders:when:1541667065759"
16) "Ramesh"
17) "lineItems"
18) "spring:session:sessions:ea0c3a35-b821-461b-8568-1cf972ba99cb"
19) "orders"
127.0.0.1:6379>

A: i think you can try different serialVersion


text:
Q: Fetching latest user status in Weibo I want to fetch the latest (public) status from our Weibo account and show it (reformatted and styled) on our website.
I can use the OAuth2 API, but that only provides a temporary auth token (and no refresh token). So whenever that expires (currently every day or two), I have to manually authorize and then add the auth token back into our web app.
There doesn't seem to be a way to get our latest public status without requiring an expiring auth token.
There are a few sites that provide RSS feeds, but they rewrite the content, and they seem flakey as well.
Is this basically impossible with Weibo, or am I missing something?


text:
Q: Particular case of Gauss-Bonnet for polygons in $\mathbb{R}^2, \mathbb{H}^2$ and $\mathbb{S}^2$ (Exercise 5.16, Bonahon, Low-dimensional geometry) Let $X$ be a bounded polygon in $\mathbb{R}^2, \mathbb{H}^2$ or $\mathbb{S}^2$ consisting of finitely many disjoint convex polygons $X_1, X_2,\dotsc, X_m$. Let $\bar{X}$ be obtained by gluing together pairs of edges of $X$.
We assume that for every vertex $P$ of $X$, the angles of $X$ at the vertices that are glued together to $P$ add up to $2\pi$, so that $\bar{X}$ is a euclidean, hyperbolic, or spherical surface.
The quotient space $\bar{X}$ is now decomposed into $m$ images of the convex polygons $X_i$, $n$ images of the $2n$ edges of $X$ and $p$ point images of the vertices of $X$.
The Euler characteristic of $X$ is defined as the integer
$$\chi(\bar{X})=m-n+p$$
I have shown the second part of the question which states: For each of the convex polygons $X_i$, $$\sum_{j=1}^{v_i} \theta_j = (v_i-2)\pi + K \text{Area}(X_i),$$ where $X_i$ has $v_i$ vertices, and $\theta_j$ are the angles of $X_i$ at the vertices. For the euclidean case we mean the usual are and $K=0$, for the hyperbolic case we have in mind the hyperpolic area and $K=-1$, whereas for the spherical case $K=1$ and Area$(X_i)$ denotes the spherical area.
We shall use the above result in order to show that $$2\pi \chi(\bar{X}) = K \text{Area}(X)\enspace (*)$$
I have tried to write down what I know, namely $K\text{Area}(X)= K\sum_{i=1}^{m} \text{Area}(X_i)= (\sum_k \theta_k)[(\sum_i v_i)-2m]\pi $, where $k$ ranges over all the vertices in $X$ so that we sum all the angles of the polygons in $X$ and
$\sum_i v_i$ represents the sum of all the vertices in $X$. The term $-2\pi m$  in the latter expression and the term $2\pi m$ of the left hand side in $(*)$ differ by a sign, so this may be a good start. Do you have any suggestions how to proceed?

A: Hint (assuming you use the correction in my comment above): You have not yet taken advantage of one of the key pieces of information given in the problem: "for every vertex $P$ of $\bar X$, the angles of $X$ at the vertices that are glued together to $P$ add up to $2\pi$". Each such set of vertices of $X$, one per vertex $P$ of $\bar X$, is called a vertex cycle of the polygon $X$.
The general strategy here is that you want to rearrange your sum of angles $\sum \theta_j$ (where the sum is taken over all vertices of the polygon $X$) into a sum of terms with each term being a sum over a vertex cycle, hence the number of such terms equals $p$, each individual term sums to $2\pi$, and so $\sum \theta_j = 2 \pi p$. This should simplify the problem quite a bit.

A: Following the advice of Lee Mosher: So when I rewrite $\text{Area}(X)$ by using what I have shown, namely $\sum_{j=1}^{v_i} \theta_j = (v_i-2)\pi + K \text{Area}(X_i)$ for every polygon $X_i$ I obtain $$\text{Area}(X)=\sum_{i=1}^m \text{Area}(X_i) =\sum_{i=1}^m \left[  \left( \sum_{j=1}^{v_i} \theta_j\right) - (v_i -2) \pi \right] =  \sum_{i=1}^m    \sum_{j=1}^{v_i} \theta_j  - \sum_{i=1}^m v_i \pi + \sum_{i=1}^m 2\pi.$$ The first term of the sum can be rewritten by using the hypothesis that for every vertex $P$ of $X$, the angles of $X$
 at the vertices that are glued together to $P$
add up to $2\pi$. The angles at one image point of $X$ add up to $2\pi$ and since there are $p$ image points, we obtain $\sum_{i=1}^m    \sum_{j=1}^{v_i} \theta_j  = 2\pi p$. For the latter equality we also use the fact that the $2n$ edges of $X$ get glued together pair by pair so every angle $\theta_j$ is "around" one of the vertices $p$ and conversely every vertex $p$ of $\bar{X}$ has one of the angles $\theta_j$ "around" them. As for the term $\sum_{i=1}^m v_i \pi$ we observe that the number of edges in $X$, namely $2n$ equals the number of vertices in $X$, namely $\sum_{i=1}^m v_i $ since $v_i$ is the number of vertices of the polygon $X_i$. This is a purely combinatorial fact (a triangle has 3 vertices and 3 edges, a square has 4 vertices and 4 edges and so on) and leads to the equality $\sum_{i=1}^m v_i \pi = 2\pi n$. Finally we obtain
$$\text{Area}(X) = \sum_{i=1}^m    \sum_{j=1}^{v_i} \theta_j  - \sum_{i=1}^m v_i \pi + \sum_{i=1}^m 2\pi = 2\pi (p-n+m) = 2\pi \chi(\bar{X}).$$
Now my question is: What should I do with the constant $K$ in order to complete the proof by showing $2\pi \chi(\bar{X})= K \text{Area}(X)$? What I know is that this comes from the fact that the Euler characteristic for the euclidean case is zero, positive for the spherical case and negative for the hyperbolic case, but isn't this reasoning somewhat circular since this fact also comes from what I want to show?


text:
Q: Oracle ADF stop validation on empty table row, validate in popup form instead I'm currently developing a simple application which does crud operations on a few tables.
It looks like this:

I have a problem with the add item form, invoked by pressing the button saying "Nova jedinica mjere". It opens a popup containing an ADF form as follows:

As you can see it does a create insert operation on popup fetch event, creating an empty row. When I fill the form with data, and press OK(the ok button is handled in the bean, doing a commit operation), I get an empty error message as follows:

This only happens if the table is editable(consisting of input text elements). If it is set to click to edit, this problem does not occur. How can I make validation only occur on form fields?
If you need any more info, please let me know because I too am new to adf.
EDIT:
This is the page in question:(posted as a pastebin link to not take up much space).
http://pastebin.com/5TKyPxEs
The form in the popup is a static region from a task flow with a method call and a page:
http://pastebin.com/9h69fRW4

A: You mean to say that when you enter the value in the form and Click OK, it should be there in the Table,If so, the values are not getting displayed in Table. It means your Iterator is not fetching the values. You have to Refresh your Iterator, VO and Table Compoent through Bean. So that the values in the form once you click OK, it will be there in the Table.


text:
Q: How do I unit test unsubscribe in Angular and Jasmine? I got private class members in my component, for example
private querySubscription: Subscription;.
In my ngOnDestroy() I unsubscribe from my subscription:
ngOnDestroy(): void {
    this.querySubscription.unsubscribe();
    this.userSettingsSubscription.unsubscribe();
  }
How do I test that I have really unsubscribed correctly in my unit test in jasmine? I can programmatically call the ngOnDestory() because it is public, but I can not test my private class members.

A: You should mock your private variable (which you can access through array notation), then call your function, and expect the subscrpition to be closed.
Stackblitz
  it('should unsubscribe on destroy', () => {
    component['querySubscription'] = of(true).subscribe();

    component.ngOnDestroy();

    expect(component['querySubscription'].closed).toBeTruthy();
  });

EDIT 1
This solution works because of array notation. In javascript, you don't have private or public variables : you only have variables.
Typescript forces you to comply with private/public, but you can always work around that.
If you wish not to do that, you should create a public function that creates a subscription like so
createSubscription() {
  this.querySubscription = this.someFunction().subscribe();
}

This is the only other viable solution if you don't want to use the array notation (which, I forgot to mention, is not a bad practice at all).
Up to you to choose which one you prefer !

A: In my beforeEach I set the Subscription to a new instance of the rxjs class then I can spy directly on it.
import { Subject, Subscription } from 'rxjs';
....
let pagingSubscriptionSpy: jasmine.Spy;
beforeEach(() => {
 service.pagingSubscription = new Subscription();
 pagingSubscriptionSpy = spyOn(service.pagingSubscription, 'unsubscribe');
})
....
it('calls getEventunsubscribesPaged', () => {
   expect(pagingSubscriptionSpy).toHaveBeenCalledTimes(1);
});

A: May be something like:
export class ObservableHelper {
    getMockObservable() {
        const s = new Subscription();
        const obs = new Observable();
        spyOn(obs, 'subscribe').and.returnValue(s);
        spyOn(s, 'unsubscribe');
        return {obs, s};
    }
}

in your spec file:
let helper = new ObservableHelper();
let o1 = helper.getMockObservable();

One of the comment it is already mentioned that Mock has to be done when a new subscription is created. If you are calling an external service and that returns an observable, o1.obs can be used as return value for same.
e.g. if you are subscribing for a PubSub service:
pubSubSpy.sub.withArgs(jasmine.any(Object), 'test').and.returnValue(o1.obs);

// Act
service.ngOnDestroy();

// Assert
expect(o1.s.unsubscribe).toHaveBeenCalledTimes(1);

A: If you're using Typescript and I suppose you are to test private members in your test module when setting up testBed you have to call your service using injector.
beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [
            YourService,
        ],
        imports: [ HttpClientTestingModule ],
    });
    const injector = getTestBed();
    service = injector.get(YourService);
});

Now you can access your service public methods by using service.myMethod and your private ones by using (service as any).privateMethod().
As typescript is always compiled to JavaScript and in JavaScript you do not have public private members you have to use the (service as any) construct.
EDIT 1
After you are able to access a private, you can access it's properties, so what you then do is (in pseudocode):
    spyOn((service as any).privateMethod, 'setBar');

    service.ngOnDestroy()

    expect((service as any).privateMethod.setBar).toHaveBeenCalled();


text:
Q: Matlab: How do I remove rows that contain any of the numbers stored in a vector? I have 163x2 matrix called A, and a 15x1 vector called delindex.
Now I want to delete every row from A, that has any of the numbers stored in delindex as a value in the first row.
short example:
A =
           1       29292
           2       44652
           3       56569
           4       68909
           5       81053
           6       93343
         101      105585
         102      118870
         103      132163
           7      144257
         104      156616
           8      205344
           9      216865
         105      228979
         106      229307
         107      240849
         108      253306

And my delindex =
4
101
7
105

(And for possible future implications: how do I do the same for other rows, in this example the seconde one?)
I have looked up removerows and the any() function, but can't get them to work for me. I'm totally new to matlab and programming, so a place to look in documentation on this might help me as well!
Thanks in advance!

A: Use ismember (@Prashant's suggestion):
ia = ismember(A(:,1), delindex);

Or intersect:
[~,ia,~] = intersect(A(:,1), delindex);

To find which rows should be removed.
Then remove the rows:
A(ia,:) = []

Note
ismember returns logical indices, while in [C,ia,ib] =intersect(A,B), ia and ib are indices.
Both could be used for indexing. For more info read Matrix Indexing in MATLAB.


text:
Q: How to fix slow Spotlight and Time Machine after upgrading to  10.7.5? Since updating to 10.7.5 both Spotlight and Time Machine are very slow.

*

*To index a normal system drive Spotlight calculates to need several days.

*As a result Time Machine takes up to an hour or more for an incremental backup of ~100 Mib.

What solution is there for these slow Time Machine backups and Spotlight indexing?

A: Check your console log file and look for lines like this (the real log lines will have process IDs and dates):
sandboxd: mdworker deny mach-lookup com.apple.ls.boxd
mdworker: Unable to talk to lsboxd

If you're seeing that, it is probably the source of the problem. Something Appple did with this latest release (also affects Mountain Lion 10.8.2).
I don't know what's really going on other than to say that mdworker (which scans and indexes files for Spotlight) calls LSCopyLibraryItemURLs() which eventually sends a message to lsboxd.  The Sandbox policy doesn't allow that, so the worker is killed.
So maybe the policy file is wrong, or maybe mdworker shouldn't be making that call.  I don't know.  However, fixing the policy file is relatively easy.  POTENTIALLY DANGEROUS, but easy.
Edit these files as root:
/usr/share/sandbox/mdworker.sb
/usr/share/sandbox/mdworker-bundle.sb

Inside the files you'll find the line:
(allow mach-lookup (global-name "com.apple.ocspd"))

Right below it, add the line:
(allow mach-lookup (global-name "com.apple.ls.boxd"))

That's it!
If you want extra comfort, maybe reboot.  Maybe erase your spotlight index and start over:
sudo mdutil -E /

In fact, I still see mdworker: Unable to talk to lsboxd in my log files but at least now the indexing will finish and Time Machine moves quickly again.

A: You can completely fix all the mdworker related sandbox errors in Console (including the cannot talk to lsboxd) by editing the system.sb profile rather than the mdworker ones. The system.sb file is used by all Apple system processes that run under the sandbox, including mdworker. If you modify this file (which is located in /System/Library/Sandbox/Profiles) to include:
(allow mach-lookup (global-name "com.apple.ls.boxd"))

(allow mach-lookup (local-name "com.apple.ls.boxd"))

This will stop all the lsbox related mdworker issues.

A: If Spotlight never finishes building the index, it can be because the indexing always stops on certain files. I made a clean installation a few years ago because of that issue, but it returned after I restored my old files. I ended up narrowing down the files that caused it by just adding folders to the privacy tab in System Preferences.
Someone at Super User ran opensnoop to find what files mdworker stopped on:
sudo opensnoop -n mdworker

From a suggested edit by user37651:

I ran the opensnoop command above and it showed a problem with files in ~/Library/Developer that were put there from a previous Time Machine restore. (I currently don't have XCode installed.) I deleted the folder, and Spotlight indexing finished in only 30 minutes. My Time Machine backup now seems to be working.

A: The OS X Lion 10.7.5 Supplemental Update released October 04, 2012 includes:

Resolves an issue that may cause Time Machine backups to take a very long time to complete

and, after testing, this seems to have completely resolved the issue.
Note that for me, the first backup after installing this update still took unexpectedly long, and included many com.apple.backupd[423]: Waiting for index to be ready (100) messages, so maybe Spotlight hadn't yet properly re-indexed the drive.  Now, a couple hours later, small backups complete at their usual brisk pace and all is well.

A: I posted this workaround in that topic. Here it is (it is not a solution, only a temporary workaround to let my backup and Spotlight work until a fix is released).
Using Terminal:

*

*I disabled Spotlight indexing:
sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.metadata.mds.plist

*I deleted Spotlight index in all my drives (including the backup drives):
sudo rm -rf /.Spotlight-V100/Store-V1 /.Spotlight-V100/Store-V2  /.Spotlight-V100/VolumeConfiguration.plist

sudo rm -rf /TimeMachineDrive/.Spotlight-V100/Store-V1 /TimeMachineDrive/.Spotlight-V100/Store-V2  /TimeMachineDrive/.Spotlight-V100/VolumeConfiguration.plist

(rm -rf /.Spotlight-V100/* did not work for me.) (This can also be done by excluding the whole drive using privacy setting of Spotlight and then reincluding it.)

*

*I deleted /var/folders content (see this topic to know why):
sudo rm -rf /var/folders/*

*I deleted the .inProgress files from my Backups.backupdb subfolders (put to trash then empty the trash is the only way to do this).
It may be necessary to reformat your backup drive instead of only deleting .inProgress files.

*

*I rebooted and then I restarted Spotlight:
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.metadata.mds.plist

sudo mdutil -i on -E /

*I waited until Spotlight finished indexing process

*I launched a new backup using TimeMachine

*I opened a bugreport to Apple with the title: "TimeMachine hangs when Spotlight is in use under Mac OS X 10.7" praying that many other people will do the same to make this bug a priority.
Some steps may be useless, but I took all what I learn by reading different topic about slow TM and Spotlight.

A: It is possible to delete the Spotlight index and then force Mac OS X to create a fresh Index from scratch. This is usually worth trying in a situation like yours.
I'm afraid I don't know the Terminal commands for doing this. When I need to do it, I use the commercial program MacPilot, from Koingo Software, which costs US $20. They have a fully-functional trial version that you can use for 15 days. If you find it useful, you can decide to pay for it.
I suppose there are other utilities for doing this also.
Of course, once you delete the existing Spotlight index, you need to wait for Spotlight to create a new index. You should let your Mac run uninterrupted for as long as it takes to generate a new one completely.

A: Damn! Got faster boot times too
I am writing a different answer just to summarize the specific steps I took (I must keep clear that they are part of what is ALREADY written here, not my contribution), because after I took those steps, not only Time Machine is working faster, but my boot time decreased from 1min10secs to 40secs! My boot time always intrigued me as I constantly saw people reporting much lower boot time for the same specs and, somehow, those steps cut 30 seconds off my boot time (Yeah, I tested more than once and, yeah, caches were ok and I took many steps before taking those ones here, including repairing permissions, repairing disk, even defragging with iDefrag2, all to no results). Until now :P
1
sudo mkdir ~/trash_backup
sudo mv /var/folders ~/trash_backup/ # backup just in case

2
After that, editing
/usr/share/sandbox/mdworker.sb and /usr/share/sandbox/mdworker-bundle.sb, adding
(allow mach-lookup (global-name "com.apple.ls.boxd")) below the line (allow mach-lookup (global-name "com.apple.ocspd")) on both files.
3
Finally,
sudo mdutil -i on -E /; sudo reboot

Thanks lauhub and Old Pro. Can anyone explain the decrease on boot time and what the mach-lookup on boxd thing does and possible security issues? Thanks all :)

A: So I've suffered the same as everyone else but unfortunately didn't read all the multitude of threads in the correct order so basically lost my original TM backup, then my Spotlight db in a failed effort to fix it.
A thread somewhere which I can't find again (I think it was more about slow Spotlight index) had a post from a guy who simply reinstalled 10.7.5 and everything was back to normal. So I did that, and it worked.
After completion of the reinstall I left TM off and allowed Spotlight to index. I went out for a ride and when I came back it was done - 149GB in something less than 90 min. And it works, I've searched for stuff on my HD.
I then turned TM on and it took 2hrs 9min to complete.
So if you are considering spending the time and bandwidth downgrading to 10.7.4 you may wish to consider a reinstall of 10.7.5.

A: All, I had the same issue, TM anticipated to take days for a brand new backup on a new disk, and indeed it took hours for some 200MB to be completed.
I disabled spotlight with the command indicated above, and - behold - 40GB loaded within 10min and the TM updated is running as smoothly as one would expect.
This is quite an important bug and its disappointing that Apple sends out an "update" that causes problems like this.

A: According to https://discussions.apple.com/thread/4324046?start=60&tstart=0 disabling Spotlight with $ sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.metadata.mds.plist improves the Time Machine backup speed.

A: A simple rebooting into SAFEMODE and then rebooting back to NORMAL MODE appears to have cleared this use up for me.  Went from 3 weeks to 1 hour for back up.


text:
Q: Implementing CDC in Amazon S3 I am fairly new to cloud space. As part of our current project, we are trying to create a data lake in Amazon S3 buckets. There would be another S3 layer which would contain CDC happened in previous layer. Talend or Streamsets is what the architecture team is proposing to use. Is there any other way by which CDC can be implemented from S3 to another S3 bucket?

A: Implementing CDC or Patching CDC is always an important task when pulling data from transactional sources. While objects in S3 are immutable, so S3 doesn't provide anything of its own to merge the change data captured (CDC). There are few ways using which CDC patching can be achieved in S3 or AWS-Data-Lakes.
First, you need to make sure that your pipeline of ETL tool (Stream-sets/NiFi/Sqoop) should be able to fetch the updated transactions/records from the source system(either by using last_modified_date column, etc or by transaction logs) and place it in same s3 diff path or different s3 bucket (CDC-delta).
Now to merge this delta(CDC) into the base-table, you can use either of the approaches mentioned below :

*

*If you are using AWS EMR, or Spark in your environment, I would recommend to use Apache-hudi. Open source now, but this was designed by Uber earlier for providing the facility of the transactional tables in data-lakes. It has power to merge the CDC patch in base data even in real-time scenarios, which later might save your efforts to implement lambda-architecture in your data-lake.
Refer this link - https://aws.amazon.com/blogs/aws/new-insert-update-delete-data-on-s3-with-amazon-emr-and-apache-hudi/

*Recently one amazing feature launched by data bricks is Delta Lakes. This approach of using delta lakes is really great and give you an out of the box performance. Delta lakes provide the functionality of ACID transactions to your data-lake and give better performance in both streaming and batch scenarios. Please refer these links, where the delta-lake has been implemented with AWS DMS and S3.
https://databricks.com/blog/2019/07/15/migrating-transactional-data-to-a-delta-lake-using-aws-dms.html
https://databricks.com/blog/2019/03/19/efficient-upserts-into-data-lakes-databricks-delta.html

*One another way is, you can write your own custom spark-jobs to do this functionality like explained in the below link, but this is a slow and costly operation if your dataset is large, and you might need some other technique in case of real-time CDC patching. Refer the link - change data capture in spark

A: You have to use a ETL/ELT tool to capture CDC. There is no way (as per my knowledge) S3 can handle that on its own.
However, you could also consider AWS Glue or Matillion as they are native to AWS and hence compatibility might be better than Talend (P.S. I haven't used Talend)


text:
Q: Removing values less than the median If I know the median of an array, say the median is d, how can i remove all the values that are not greater than or equal to that value? I know you could binarize the image to a certain threshold but I want to still have a gradient so that I can see which pixels are more active than others. Thanks

A: Indexing with a boolean mask is good at this:
d = median(img);
img(img < d) = 0;


text:
Q: Individually modulate two lasers diodes using sound - while using the same power suppy and preventing signal "bleed over" I'm trying to individually modulate two lasers diodes using the same power supply.  The modulation for each laser module is created by the left and right audio channels.  Is there a way to do this using one power supply? Here's a little circuit idea I came up with but I notice that the left and right channels (signals) may "bleed over" into each other is there a way to prevent this "bleed over" so each laser is modulated by just one of the audio channels but still have the ability to use the same power supply?
See circuit idea along with website I got it from

Website I got the idea from http://scitoys.com/laser_communicator.html


text:
Q: Запрос на стороннее апи из nodejs Необходимо получить данные с https://forkdelta.io c помощью апи https://github.com/forkdelta/backend-replacement/tree/master/docs/api
Вот код:
var http = require("http");

http.createServer(function(request, response) {
   const io = require('socket.io-client');
   socket = io.connect('https://api.forkdelta.com', { transports:
   ['websocket'] });

socket.on('connect', function() {
    console.log('socket connected');
    socket.emit('getMarket', {
        token: "0x6fff3806bbac52a20e0d79bc538d527f6a22c96b",
        user: "" });

});
  socket.on('market', function(payload) {
    console.log(payload.orders.buys);

    const json = JSON.stringify(payload.orders.buys);
    response.setHeader('Content-Type', 'application/json');
    response.end(json);
});

}).listen(3000);

console.log("Server has started.");

Сохраняю его в server.js и исполняю команду node server.js
клиент отдельно в index.html
 <script src="/socket.io/socket.io.js"></script>
 <script>
   var socket = io('http://localhost:3000');
   socket.on('connect', function(){});
   socket.on('market', function(data){
      console.log(data);
   });
   socket.on('disconnect', function(){});
</script>

Запускаю код по ссылке http://localhost:3000 с локального сервера - виснет
Запускаю код отсюда https://repl.it/repls/DeafeningBlushingAddons - успешно
Помогите, пожалуйста, разобраться как правильно запустить код из браузера, Далее предполагается разобрать массив данных и преобразовать в таблицу

A: Кратко
Приняв запрос (от браузера, по http://localhost:3000) и сделав всё что нужно (т.е.
 выполнив запрос к указанному API) верните браузеру ответ.
socket.on('market', function(payload) {
  console.log(payload.orders.buys);

  const json = JSON.stringify(payload.orders.buys);
  response.setHeader('Content-Type', 'application/json');
  response.end(json);
});

Развёрнуто
Сервер "виснет" потому что вы не используете аргументы, которые вы принимаете в callback функции, которую вы передаёте в метод http.createServer. В указанной callback-функции вы принимаете, и почему-то игнорируете, аргументы request и response. Сервер, на самом деле не "виснет", а не может дождаться, когда вы воспользуетесь вторым аргументом response для того, что бы вернуть ответ на запрос браузера.


text:
Q: Node Not being Deleted from Binary Search Tree C++ I keep trying to get the 25 to be deleted from the tree and i cannot get it to be deleted.
I have tried debugging and creating breakpoints and everything, nothing is working. I havent coded like this in over a year and its proving to be very daunting.
Please Help!
![output] (https://i.gyazo.com/8e953ebe14d9d33a2a0ffa233ccfacb1.png)
#ifndef BSTREE_H
#define BSTREE_H
#include <iostream>
#include <iomanip>
using namespace std;

// class must be templated
template <class DataType>
class BSTree
{
private:
// You may NOT add any data members
struct node;
typedef node* nodePtr;

struct node
{
    DataType element;
    nodePtr right;
    nodePtr left;
};
int count;
nodePtr root;

// You may add any private member functions here
bool isEmpty() // helper funtion for determining if the tree is empty
{
    return root == NULL;
}

void inOrderPrint(nodePtr x, ostream& out)
{
    if (root != NULL)
    {
        inOrderPrint(x->left, out);
        out << x->element << " ";
        inOrderPrint(x->right, out);
    }
}

void preOrderPrint(nodePtr x, ostream& out)
{
    if (root != NULL)
    {
        out << x->element << " ";
        preOrderPrint(x->left, out);
        preOrderPrint(x->right, out);
    }
}

bool search(DataType x) // helper function to check if item is in tree already
{
    bool found = false;
    if (isEmpty())
    {
        cout << "Nothing in the Tree!" << std::endl;
        return false;
    }
    nodePtr current;
    nodePtr parent;
    current = root;
    parent = NULL;
    while (current != NULL)
    {
        if (current->element == x)
        {
            found = true;
            break;
        }
        else
        {
            //parent = current;
            if (x > current->element)
            {
                current = current->right;
            }
            else
            {
                current = current->left;
            }
        }
    }
    if (!found)
    {
        found = false;
    }
    else
    {
        found = true;
    }
    return found;

}

/*
nodePtr findNode(nodePtr x)
{
    bool found = false;
    if (isEmpty())
    {
        cout << "Nothing in the Tree!" << std::endl;
        return;
    }
    nodePtr current;
    nodePtr parent;
    current = root;
    parent = NULL;
    while (current != NULL)
    {
        if (current->element == x->element)
        {
            found = true;
            return x;
            break;
        }
        else
        {
            parent = current;
            if (x->element > current->element)
            {
                current = current->right;
            }
            else
            {
                current = current->left;
            }
        }
    }
    if (!found)
    {
        found = false;
        return;
    }
    else
    {
        found = true;
    }
    return x;

}
*/

void destroyTree(nodePtr x)
{
    if (x != NULL)
    {
        destroyTree(x->left);
        destroyTree(x->right);
        delete x;
    }
}

// This method is given – it is called by printTree
void printTreeHelper(int depth, nodePtr cur) const
{
    const int spacing = 4;
    if (cur != NULL)
    {
        if (depth == 0)
            cout << cur->element;
        else
            cout << setw(spacing * depth) << " " << cur->element;
        cout << endl;
        printTreeHelper(depth + 1, cur->right);
        printTreeHelper(depth + 1, cur->left);
    }
    else
        cout << setw(spacing * depth) << " " << "****" << endl;

}

void copyTreeHelper(nodePtr x)
{
    if (x != NULL)
    {
        insert(x->element);
        copyTreeHelper(x->left);
        copyTreeHelper(x->right);
    }
}

nodePtr minNodeFinder(nodePtr min)
{
    nodePtr curr = min;
    while ((curr != NULL) && (curr->left != NULL))
    {
        curr = curr->left;
    }
    return curr;
}

public:
// Default constructor
BSTree()
{
    root = NULL;
}

// Copy constructor
BSTree(const BSTree<DataType>& copyTree)
{
    root = NULL;
    copyTreeHelper(copyTree.root);
}

// Equal overload
const BSTree& operator =(const BSTree& rhs)
{
    if (this == &rhs)
    {
        return *this;
    }
    else
    {
        copyTreeHelper(rhs.root);
        deleteTree();
        return *this;
    }
}

// Destructor
~BSTree()
{
    deleteTree();
}

// Inserts element into the tree
// If value is already in the tree do NOt add it
// a second time
void insert(DataType x)
{
    if (search(x))
    {
        cout << "item already in tree" << std::endl;

    }
    else
    {
        nodePtr temp = new node();
        nodePtr parent;
        temp->element = x;
        temp->left = NULL;
        temp->right = NULL;
        parent = NULL;
        if (isEmpty())
        {
            root = temp;
        }
        else
        {
            nodePtr current;
            current = root;
            while (current)
            {
                parent = current;
                if (temp->element > current->element)
                {
                    current = current->right;
                }
                else
                {
                    current = current->left;
                }
            }
            if (temp->element < parent->element)
            {
                parent->left = temp;
            }
            else
            {
                parent->right = temp;
            }
        }
    }
}

//Print the tree as a tree
// This (and its helper function) is given to you
// See sample output and understand how the tree is displayed
// because it can help when testing the code
bool printTree() const
{
    if (root == NULL)
        return false;
    else
    {
        printTreeHelper(0, root);
        return true;
    }
}

// Prints tree in order to the screen
// call printInOrder with  cout passed in
// This function is done for you
void printInOrder()
{
    printInOrder(cout);
}

// Prints the tree in order to
// the ostream passed into it
void printInOrder(ostream& out)
{
    inOrderPrint(root, out);
    out << std::endl;
}

// Prints tree in preorder to the screen
// call printPreOrder with  cout passed in
// This function is done for you
void printPreOrder()
{
    printPreOrder(cout);
}
// Prints the tree in preorder to
// the ostream passed into it
void printPreOrder(ostream& out)
{
    preOrderPrint(root, out);
    out << std::endl;
}

// Deletes the item passed in from the tree
// It returns a true if it finds it and deletes it, otherwise
// It returns a false
bool  deleteNode(DataType x)
{

    if (!search(x))
    {
        cout << "Item not found" << std::endl;
        return false;
    }
    nodePtr current;
    nodePtr parent;
    current = root;
    parent = NULL;
    //Node is a single node with one child
    if((current->left == NULL && current->right != NULL) ||
       (current->left != NULL && current->right == NULL))
    {
        if(current->left == NULL && current->right != NULL) // right child is present
        {
            if(parent->left == current)
            {
                parent->left = current->right;
                delete current;
            }
            else
            {
                parent->right = current->right;
                delete current;
            }
        }
        else // left child is present
        {
            if (parent->left == current)
            {
                parent->left = current->left;
                delete current;
            }
            else
            {
                parent->right = current->left;
                delete current;
            }
        }
        return true;
    }
    // node is a leaf node
    if (current->left == NULL && current->right == NULL)
    {
        if(parent == NULL)
        {
            delete current;
        }
        else
        {
            if(parent->left == current)
            {
                parent->left = NULL;
            }
            else
            {
                parent->right = NULL;
            }
            delete current;
            return true;
        }
    }
    // node has two children i.e parent node
    if (current->left != NULL && current->right != NULL)
    {
        nodePtr checker;
        checker = current->right;
        if ((checker->left == NULL) && (current->right == NULL))
        {
            current = checker;
            delete current;
            current->right = NULL;
        }
        else // right child has children
        {
            //nodes right child has a left child
            if ((current->right)->left != NULL)
            {
                nodePtr left_current;
                nodePtr left_current_parent;
                left_current_parent = current->right;
                left_current = (current->right)->left;
                while (left_current->left != NULL)
                {
                    left_current_parent = left_current;
                    left_current = left_current->left;
                }
                current->element = left_current->element;
                delete left_current;
                left_current_parent->left = NULL;
            }
            else
            {
                nodePtr temp;
                temp = current->right;
                current->element = temp->element;
                current->right = temp->right;
                delete temp;
            }
        }
    }
    return true;
}

// Deletes the item passed in from the tree
// It also passes back the item to the calling function
// It returns a true if it finds it and deletes it, otherwise
// It returns a false
bool  deleteNodePassBackData(DataType x, DataType& temp)
{
    if (search(x))
    {
        nodePtr itemToDelete = findNode(x);
        temp = itemToDelete->element;
        deleteNode(x);
        return true;
    }
    else
    {
        return false;
    }
}

// Deletes the whole tree
void deleteTree()
{
    destroyTree(root);
}
};

#endif

     BSTree<int> t1;
  t1.insert(50);
  t1.insert(75);
  t1.insert(25);
  t1.insert(22);
  t1.insert(5);
  t1.insert(85);
  t1.insert(95);
  t1.insert(82);
  t1.insert(76);
  t1.printTree();

  BSTree<int> t2(t1);
  t2.deleteNode(25);
  t2.deleteNode(75);
  t2.deleteNode(50);

  cout << "After copy constructor and deletes" << endl;
  cout << "T1" << endl;
  t1.printTree();
  cout << "T2" << endl;
  t2.printTree();

A: First of all, you should always post full code for someone else to debug. If I cannot run your code, how on the earth could I debug it at all?
But beside that, deleteNode(DataType x) from your code has serious issue.
current NEVER TRAVERSE the tree at all.
deleteNode() function will always delete root of the tree if item is exist in tree.
You should traverse the tree like you did in search() function within the deleteNode() function.
By the way what is the point of below code in search()?
if (!found)
{
    found = false;
}
else
{
    found = true;
}


text:
Q: cursor plsql using select i want to get one value from table1(etudiant) in order to use this value in table2(employee) using slect
i use cursor , but i didn't get the result; can u help me thanks
    declare
           cle employee.id%type;
           cursor cur_test is select id from etudiant where name ='Hichem';
           no_data_found exception;
    begin

      open cur_test;

      loop
           fetch cur_test into cle;
           exit when cur_test%notfound;
      end loop;

      --dbms_output.put_line('ID IS ' ||cle);
      select * from employee where id=cle;

      if cur_test%rowcount=0 then
        close cur_test;
        raise no_data_found;
      end if;
      close cur_test;

exception
      when no_data_found then
        dbms_output.put_line('no data found');

end;
/

A: Looks like you've overcomplicated it. Why wouldn't you directly join etudiant and employee tables? Something like this:
begin
  for cur_r in (select e.name
                from employee e join etudiant t on t.id = e.id
                where t.name = 'Hichem'
               )
  loop
    dbms_output.put_line(cur_r.name);
  end loop;
end;
/

Perhaps you don't even need a loop; or, you do if there is more than one person with the name you're looking for (Hichem in this case).

As of your code:

*

*generally speaking, it is simpler to use a cursor FOR loop than doing everything manually (declaring cursor variable, opening cursor, fetching, exiting the loop, closing cursor) - if you use cursor FOR loop, Oracle does all that for you

*no need to explicitly declare no_data_found; it is a predefined exception

*select * from employees is wrong as - in PL/SQL - you have to select the result INTO something. If you expect more than a single row, consider using a collection with bulk collect


text:
Q: How to move a Page title but not a Post title for a Genesis child theme I asked Studio Press support how to move the page title to a different section of the Genesis framework. They replied with code:
remove_action( 'genesis_entry_header', 'genesis_entry_header_markup_open', 5 );
remove_action( 'genesis_entry_header', 'genesis_do_post_title' );
remove_action( 'genesis_entry_header', 'genesis_entry_header_markup_close', 15 );
add_action( 'genesis_after_header', 'genesis_entry_header_markup_open', 11 );
add_action( 'genesis_after_header', 'genesis_do_post_title', 12 );
add_action( 'genesis_after_header', 'genesis_entry_header_markup_close', 13 );

There's a problem with this, in that it moves both Page titles and Post titles. This means on the Blog page, the Post title is moved into the position of the Page title, and the Post title has the Page title e.g. "News".
My question is: how do I move just the Page title, and not the Post title, using remove_action / add_action...?
Help appreciated.

A: You have 2 choices:

*

*You can use the code in functions.php with a conditional tag like is_singular('page') See this tutorial

*Or add the code to a page.php template file with a opening PHP tag like this:

remove_action( 'genesis_entry_header', 'genesis_entry_header_markup_open', 5 );
remove_action( 'genesis_entry_header', 'genesis_do_post_title' );
remove_action( 'genesis_entry_header', 'genesis_entry_header_markup_close', 15 );
add_action( 'genesis_after_header', 'genesis_entry_header_markup_open', 11 );
add_action( 'genesis_after_header', 'genesis_do_post_title', 12 );
add_action( 'genesis_after_header', 'genesis_entry_header_markup_close', 13 );

genesis();


text:
Q: Casting error in my form I have a ComboBox in a DataGridView.  However I get an error when I run it:

Unable to cast object of type 'System.Windows.Forms.DataGridView' to type 'System.Windows.Forms.ComboBox'.

What can I do to resolve this error?
 ComboBox comboBox;
    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (e.Control is ComboBox)
        {
            comboBox = e.Control as ComboBox;

            if (dataGridView1.CurrentCell.ColumnIndex >= 0)
            {
                System.Diagnostics.Debug.WriteLine("Edit Control Showing");
                comboBox.SelectedIndexChanged -= new EventHandler(comboBoxItems_SelectedIndexChanged);
                comboBox.SelectedIndexChanged += new EventHandler(comboBoxItems_SelectedIndexChanged);

            }
        }
    }

    void comboBoxItems_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {

            int comboBoxSelectedIndex = ((ComboBox)sender).SelectedIndex;
            string comboboxSelectedValue = ((ComboBox)sender).SelectedText;
            int gridViewSelectedRow = dataGridView1.CurrentRow.Index;
            if (comboBoxSelectedIndex >= 0 && gridViewSelectedRow >= 0)
            {
                System.Diagnostics.Debug.WriteLine("ComboBox Index - " + comboBoxSelectedIndex);
                System.Diagnostics.Debug.WriteLine("GridView Index - " + gridViewSelectedRow);
                if (comboBox != null)
                {
                    comboBox.SelectedIndexChanged -= new EventHandler(comboBoxItems_SelectedIndexChanged);

                }
            }
        }
        catch(Exception E)
        {

        }
    }

A: Looks like this method is also registered to an event of type DataGridView. That is why when you try to cast it (sender) to ComboBox, it throws an exception. Because, in that case, sender is of type DataGridView.

A: I would also recommend checking the sender object before attempting to cast it (would confirm what decyclone mentioned in his answer in addition to preventing casting errors):
if(sender is ComboxBox) {
      //cast
}

A: I think somehow you have set the comboBoxItems_SelectedIndexChanged event handler to the DataGridView itself. Check the properties window of DataGridView and if it's there, remove it.
Also I recommend using "as" keyword for casting and checking it for "null".


text:
Q: Reusable table component
Есть некий reusble table component, но не могу понять какие данные туда нужно передать, можете отправить варианты?

import { useState } from 'react'
import { Checkbox, styled } from '@mui/material'
import Table from '@mui/material/Table'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableContainer from '@mui/material/TableContainer'
import TableHead from '@mui/material/TableHead'
import TableRow from '@mui/material/TableRow'

function TableList({ columns, data, width, checkbox }) {
   const [checked, setChecked] = useState(0)
   const countChecked = (event) => {
      if (event.target.checked === true) {
         setChecked((prevState) => prevState + 1)
      } else {
         setChecked((prevState) => prevState - 1)
      }
   }
   return (
      <TableContainer>
         <MuiTable width={width}>
            <TableHead>
               <TableRow>
                  <DivHead>
                     {checkbox && (
                        <HeadCell>

                              {checked}

                        </HeadCell>
                     )}
                     {columns.map((col) => {
                        if (col.headerCell) {
                           return (
                              <HeadCell width={col.width} key={col.key}>
                                 {col.headerCell()}
                              </HeadCell>
                           )
                        }
                        return (
                           <HeadCell width={col.width} key={col.key}>
                              {col.header}
                           </HeadCell>
                        )
                     })}
                  </DivHead>
               </TableRow>
            </TableHead>
            <TableBody>
               {data.map((row) => {
                  return (
                     <Row key={row.id}>

                           {checkbox && (
                              <BodyCell>
                                 <Checkbox onChange={countChecked} />
                              </BodyCell>
                           )}
                           {columns.map((col) => {
                              if (col.cell) {
                                 return (
                                    <BodyCell width={col.width} key={col.key}>
                                       {col.cell(row)}
                                    </BodyCell>
                                 )
                              }
                              return (
                                 <BodyCell width={col.width} key={col.key}>
                                    {row[col.key]}
                                 </BodyCell>
                              )
                           })}

                     </Row>
                  )
               })}
            </TableBody>
         </MuiTable>
      </TableContainer>
   )
}

export default TableList

const MuiTable = styled(Table)`
   table-layout: fixed;
   width: width;
`

const HeadCell = styled(TableCell)`
   border: none;
   height: 40px;
   display: flex;
   align-items: center;
   text-align: left;
   color: white;
`

const BodyCell = styled(TableCell)`
   border-collapse: collapse;
   border: none;
   width: width;
   height: 74px;
   max-height: 74px;
   text-align: left;
`

const Div = styled('div')`
   border: 1px solid #d5d8de;
   border-radius: 6px;
   margin-top: 8px;
   &:hover {
      background-color: rgba(213, 216, 222, 0.5);
   }
`
const DivHead = styled('div')`
   height: 40px;
   display: flex;
   background: rgba(56, 66, 85, 0.9);
`
const Row = styled(TableRow)`
   font-size: 16px;
`


text:
Q: Oracle SQL: How to convert one column of Select to rows I am new to Oracle and am looking for a way to convert 1 column in a Select to rows.
My first approach was using Listagg which does exactly what I want but the character limit for this is not enough for my case.
As an alternative I would like to do the following.
SELECT
   t.col1
   , t.col2
   , t.col3
   , t.col4
   , t.col5
FROM
   my table t

Instead of the standard output of t.col1 t.col2 t.col3 t.col4 t.col5 I would like t.col2 to appear in rows (i.e. below each other) instead of in columns (next to each other). Col2 always contains a value and each of them should appear in a separate row.
When searching for a solution to this I came across Unpivot and Decode but am not sure if and how this could be applied here.
Can someone tell me how this can be achieved ?
Many thanks in advance for any help,
Mike

A: A simple method -- if your data is not too large -- is just to use union all.  Your description makes it sound like you want this:
select col1, col2, col5
from t
where col2 is not null
union all
select col1, col3, col5
from t
where col2 is not null
union all
select col1, col4, col5
from t
where col2 is not null;

Hmmm, or if you just want the distinct values in col2:
select distinct col2
from t;

A: You are looking for the UNPIVOT function
SELECT col
FROM my table t
UNPIVOT INCLUDE NULLS (col FOR source_column_name IN (col1, col2, col3, col4, col5)

COL
----
Value 1
Value 2
Value 3
Value 4
Value 5

The result contains five rows with one column COL each that contains the value from the columns COL1 to COL5. The (unused) column SOURCE_COLUMN_NAME contains the name of the column where the data is coming from. You can remove the INCLUDING NULLS if you are only interested in rows the COL IS NOT NULL.
See the ORACLE-BASE article on PIVOT and UNPIVOT operators for more details.


text:
Q: Can device sleep before foreground service? I know that previously we needed to use WakefulBroadcastReceiver to ensure that between receiver onReceive and service onHandleIntent the device doesn't fall back asleep.
Now Google seems to have deprecated WakefulBroadcastReceiver because it's not "correct" to start a service from a receiver anymore.
One thing I'm doing is to start a foreground service from a high priority FCM notification. This is completely valid under the new background execution rules. But since WakefulBroadcastReceiver is deprecated, does that mean startForegroundService guarantees that device stays awake long enough between onReceive and onHandleIntent's wakelock? Or should I just hold a wakelock manually in the receiver and send it to the service to release?

A:
Does that mean startForegroundService guarantees that device stays
  awake long enough between onReceive and onHandleIntent's wakelock?

No.

Or should I just hold a wakelock manually in the receiver and send it
  to the service to release?

You can request partial wakelock in onCreate() of your service as follows:
private PowerManager.WakeLock wakeLock;
@Override
public void onCreate() {
    super.onCreate();
    final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PARTIAL_WAKE_LOCK_TAG);
    ...
}

Remember to release the wakelock after usage or in onDestroy() as follows:
@Override
public void onDestroy() {
    super.onDestroy();
    if (wakeLock.isHeld()) {
        wakeLock.release();
    }
}

Google recommends to avoid usage of wakelock since it could drain user's battery. There are several APIs available for variety of use-cases. Based on the documentation, you can consider following alternatives:

*

*If your app is performing long-running HTTP downloads, consider using DownloadManager.

*If your app is synchronizing data from an external server, consider creating a sync adapter.

*If your app needs to execute background tasks at regular intervals, consider using JobScheduler or Firebase JobDispatcher. For information
  on triggering tasks at specific intervals, see Intelligent
  Job-Scheduling.


text:
Q: Greensock, jquery, code does not fire in chrome? I  have no idea why, but for some reason my code does not fire in chrome. Any idea why? I read the entire documentation of Greensock but nothing that adresses my issue.
http://jsfiddle.net/w0otqcw8/6/
var t = TweenLite.to(".menu-button", 4, {left:'0', opacity:'0.9', ease:Bounce.easeOut, paused:true, reversed:true});

$(".menu-button").on("click", function() {
  if (t.reversed()) {
    t.play();
  } else {
    t.reverse();
  }
});

A: Your code adds right and left css properties at the same time. Animate x,y,xPercent and yPercent instead.


text:
Q: List all keys added to keychain using `security add-generic-password` Is there a command in security that lists the names of all keys that have been added to the keychain through add-generic-password?
I've tried, but it find-generic-password only ever returns one result as far as I know.

A: As of 2021-11-25, there is no flag in security to output only the keys so you have to get the whole list and then look for the relevant value:
security dump-keychain | awk -F'=' '/0x00000007/ { print $2 }'

Learn more about awk pattern matching.


text:
Q: Which exception type to use for a sanity check? I'm writing software in .NET which requires runtime sanity checks, even in release mode, which means Debug.Assert and Trace.Assert are inappropriate (as Debug.Assert only works when the DEBUG symbol is defined, and Trace.Assert doesn't cause program termination). The runtime sanity check is necessary because there is a non-zero probability of invalid incoming data.
An immediate solution is to use Environment.FailFast with an explanatory message, but I'd prefer to throw some kind of exception - and I'd really not like to throw my own custom exception because my code could be called by other code which does not have a reference to my assembly, so they would be unable to catch it without catching System.Exception.
Surprisingly, the standard .NET Framework does not ship with any kind of RuntimeAssertException, ThisShouldNeverHappenException or UnacceptableUnexpectedDataException - granted, that's what System.Exception is meant to represent ("exceptional" circumstances) - except Best Practices prohibit throwing System.Exception directly. Furthermore ApplicationException is effectively deprecated and is only meant for use in non-fatal situations:
https://msdn.microsoft.com/en-us/library/system.applicationexception(v=vs.71).aspx

ApplicationException Class - The exception that is thrown when a non-fatal application error occurs.

Using InvalidOperationException is a cop-out, but it isn't entirely appropriate because my particular scenario relates to incoming data.
Here's an example:
public void ProcessData() {

    // Input:
    MyDataType incomingData = this.dataSource.ReadFromExternalSource();

    // Sanity check:
    if( incomingData.Foo != 1 ) throw ...;
    if( incomingData.Bar != "baz" ) throw ...;
    if( incomingData.Items.Count <= 123 ) throw ...;

    // Do work:
    this.turboEncabulator.ApplyCapacitativeDiractance( incomingData.Bar, ref incomingData.Foo );

    // Output:
    this.dataSink.Output( incomingData );
}

*

*Using ArgumentException is inappropriate because the incomingData is not actually an argument.

*

*While there is ArgumentOutOfRangeException there is no LocalVariableOutOfRangeException which might be more appropriate.

*In this contrived example, InvalidOperationException would be valid as it concerns to the state of incomingData, but in my example the interaction between objects is more complex.

*As the TurboEncabulator just processes raw numbers, it's the responsibility of the ProcessData method to ensure the data is within the correct domain bounds, which is why ApplyCapacitativeDiractance won't throw any ArgumentException values.

Updates:
Regarding this comment by Alireza:

It's a bit strange that a caller can call (or execute) your application and yet it doesn't have access to its assembly! Can you elaborate how this call is done?

Assemblies can be loaded at runtime and code can call into them without ever making a reference to that assembly at build-time, for example this code might exist in third-party code:
Assembly externalAssembly = Assembly.LoadFile("MyAssembly.dll");
Type externalType = externalAssembly.GetType("Foo.Bar.DataProcessor");
Object dataProcessorInstance = Activator.CreateInstance();
MethodInfo method = externalType.GetMethod("ProcessData");
try {
    method.Invoke( dataProcessorInstance, null ); // <-- throws
} catch(...) { // <-- no reference exists, so this code cannot be specific about the exception it catches if the type is defiend in MyAssembly.dll
    // handle error gracefully
}

A: I don't think there's a single absolute answer to this question, I think it's a matter of opinion. That said, in my opinion, I believe you should create a new custom exception type that derives from System.Exception. The issue you've described about the caller not having access to your types is a separate problem. If you didn't have this scenario, the solution would be clear, you'd create a custom exception. I argue this is still the case. With the unique situation you have, where the caller is using Assembly.Load and therefore doesn't have direct access to your types at compile time, I'd suggest they can still catch the exception as System.Exception in this case (remember this isn't as bad now that this no longer catches everything by default, see the HandleProcessCorruptedStateExceptions attribute). They can then use reflection to load information on your exception type in the same way they must have to call your method in the first place, or use the type name, and can re-throw the exception if it isn't the one they wanted to catch. If you're using C# 6, you can also use an exception filter to make this cleaner.
EDIT: Based on your added code snippet, here's how I suggest this could be done:
Assembly externalAssembly = Assembly.LoadFile("MyAssembly.dll");
Type externalType = externalAssembly.GetType("Foo.Bar.DataProcessor");
Type exceptionType = externalAssembly.GetType("Foo.Bar.MyCustomException");
Object dataProcessorInstance = Activator.CreateInstance();
MethodInfo method = externalType.GetMethod("ProcessData");
try
{
    method.Invoke( dataProcessorInstance, null ); // <-- throws
}
catch(System.Exception ex)
{
    if(!exceptionType.IsAssignableFrom(ex.GetType()))
    {
        throw;
    }
    // handle error gracefully
}

And if you have C# 6 support (VS2015+), the better way to do it is with exception filters, as follows:
Assembly externalAssembly = Assembly.LoadFile("MyAssembly.dll");
Type externalType = externalAssembly.GetType("Foo.Bar.DataProcessor");
Type exceptionType = externalAssembly.GetType("Foo.Bar.MyCustomException");
Object dataProcessorInstance = Activator.CreateInstance();
MethodInfo method = externalType.GetMethod("ProcessData");
try
{
    method.Invoke( dataProcessorInstance, null ); // <-- throws
}
catch(System.Exception ex) when (exceptionType.IsAssignableFrom(ex.GetType()))
{
    // handle error gracefully
}


text:
Q: C++ FILE pointer to stdout? I'm writing a program and I want the user to be able to specify whether the output is written to a file or to stdout.  Until this point, my program has been using printf commands, so I was hoping to simply change the commands to fprintf commands, but my compiler is shouting at me because obviously, they are not the same object classes.
For example:
FILE *fp;
bool print_to_file;
.
.
.
if(print_to_file){
  fp = fopen("something.txt", "w");
}
else{
  fp = &stdout;
}
fprintf(fp,"%s\t%s\t%s\n",string1 . c_str(), string2 . c_str(), string3 . c_str());

I'd prefer to stick with fprintf and find a FILE pointer to stdout, does anyone know if that's possible?  If the answer is no, can I open my files as fstreams, and then use fprintf?

A: Just drop the ampersand: fp = stdout;.

A: stdout is a FILE*, so you can simply use:
FILE* fp = stdout;


text:
Q: Begginer doubt in Ring of p-adic integers I am studying $p$-adic Rings and let me explain my understanding and doubt here. As I understood, Let $p$ be a rational prime and $Z$ denotes ring of integers, then form cartesian product
$$P=Z/pZ \times Z/p^2Z......Z/p^nZ \times ...$$ ($n=0,1,2,3.......$) . and let for $r \ge  s$ and
$$\phi^r_s: Z/p^{r+1}Z \to Z/p^{s+1}Z$$ be the natural mapping, Then consider subring $Z_p$ of $P$ defined as
$$Z_p=\left\{\alpha =(\alpha_0,\alpha_1,...,\alpha_n,....)\right\}$$ for which $\phi^{n+1}_{n}(\alpha_{n+1})=\alpha_n$ for every $n \ge 0$.
$\textbf{1)-  }$Up untill it is clear to me. But the next line in my book says- this means that if $\alpha_i$ is the residue class mod $p^{i+1}$ of the integer $a_i$, then $$a_{n+1} \equiv a_n \pmod{p^{n+1}}\;,\;\; n \ge 0$$
Now $\alpha_i$ is some element of the ring $Z/p^{i+1}Z$ so it is of the form $b_i(p^{i+1}Z)$ for some rational integer $b_i$, so this $a_i$ mentioned above is some integer s.t. $a_i \equiv b_i \hspace{.1cm} mod(p^{i+1}Z)$ ? Does residue class means this? Why calling $\alpha_i$ a residue class, residue class is a set of elements but I guess this is the meaning here, as I interpret it (i.e. calling some representative as the whole class).
$\textbf{2)-}$  Now if let $\alpha=(\alpha_1,\alpha_2,\alpha_3,......)$ such that $\alpha_n=0$, that means $\alpha_n=a_n(p^{n+1}Z)$ where $a_n$ is a multiple of $p^{n+1}$. But why does it imply that $a_n,a_{n+1},...$ are all divisible by $p^{n+1}$  s.t. $\alpha_i$ is the residue class mod $p^i$ of $a_i$. (As used in one of the proofs I was going through).
By our $\phi$, we should have that $\phi^{n}_{n-1}(\alpha_n)=\alpha_{n-1}$ and $\alpha_n$ being zero, should imply that $\alpha_{n-1}=0$ being homomorphic image of $0$ and {$\alpha_0,\alpha_1,....\alpha_n$} these all must be zero.
Please explain my these two doubts, and especially second one.

A: I think everything becomes clearer if you look at your elements in a $p$-base. Take an $\alpha_n\in \mathbb{Z}/p^n\mathbb{Z}$. Then $\alpha_n$ in $p$ base is some number of the form $a_0 + a_1p+\ldots+ a_{n-1}p^{n-1}$, where the $a_i\in\{0,\ldots,p-1\}$. Note that by extending we can interpret the elements of $\mathbb{Z}_p$ as power series in $p$.
Next, the obvious map to $\mathbb{Z}/p^m\mathbb{Z}$ you talk about (for $m<n$) is $\alpha_n (\mod p^n)\mapsto \alpha_n(\mod p^m)$, or
\begin{equation}
a_0 + a_1p+\ldots+ a_{n-1}p^{n-1}\stackrel{\phi^{n}_{m}}{\mapsto} a_0 + a_1p+\ldots+ a_{m-1}p^{m-1}.
\end{equation}
Therefore $a_n = a_m (\mod p^m)$, which answers question 1. I think that with this interpretation you should be able to solve number 2?


text:
Q: Loading contents of a Google Sheets cell into a php variable I'm attempting to load the contents of a single cell of Google Sheet into a PHP variable. From there I intend to make an image change on a website when the cell contents are changed to different values. I can't get the cell contents to load into a PHP variable to get this ball rolling though.
Google Sheets API gives the following PHP code to do this:
$result = $service->spreadsheets_values->get($spreadsheetId, $range);

When I use this code after substituting my spreadsheetId and range, I echo $result and get nothing. I'm sure thre's something I'm missing in the code or that the variables $result or $service need to be defined, but Google dropped the ball on the PHP side aparently. Any help would be appreciated.

A: download the V1 master (not master) from:
https://github.com/google/google-api-php-client-services/issues?utf8=%E2%9C%93&q=spreadsheets_values
copy on server, verify path of requires
put your code in an exemple, with the class declared for $service and variables $range, $spreadsheetId and $api_key (from explorer api of google, to auhenticate:
https://console.developers.google.com/apis/credentials
)
run the modified exemple
PS: I look for multi-range in case you find the method with :
$range[]= 'Sheet1!A:C'; // I try to have all sheets in once
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();


text:
Q: How to install pylab in Ubuntu16.04?
(GWAVA) wangshx@wangshx-KVM:~/GWAVA_v1.0/src$ python gwava_paper.py
Traceback (most recent call last):
  File "gwava_paper.py", line 19, in <module>
    from gwava import *
  File "/home/wangshx/GWAVA_v1.0/src/gwava.py", line 21, in <module>
    import pylab as pl
ImportError: No module named pylab

How can I install pylab module, I search it and find that it is a part of matplotlib, but I don't know which version of matplotlib I should install. I try to install the newest version, it reminds me to update many module version. But I need to control the version of modules.
When I run a python scripts written by others, I controlled module version by creating a new environment using Anaconda.
This is the scripts documentation.
The software requires the following python libraries (and their
associated dependencies) to be installed. The version numbers used
are identified, other versions may also work, but results may be
slightly different.

- numpy (1.7.0)
- scipy (0.11.0)
- pandas (0.12.0)
- scikit-learn (0.14.1)
- pybedtools (0.6.4)
- tabix (0.2.5)

I installed all module in the README.
(GWAVA) wangshx@wangshx-KVM:~/GWAVA_v1.0/src$ conda list
dateutil                  2.4.1                    py27_0    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
libgfortran               1.0                           0    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
mkl                       2017.0.1                      0    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
nose                      1.3.7                    py27_1    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
numpy                     1.7.0                    py27_0    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
openssl                   1.0.2l                        0    defaults
pandas                    0.12.0               np17py27_0    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
pip                       9.0.1                    py27_1    defaults
pybedtools                0.6.4                     <pip>
python                    2.7.13                        0    defaults
python-dateutil           2.6.0                    py27_0    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
pytz                      2017.2                   py27_0    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
readline                  6.2                           2    defaults
scikit-learn              0.14.1               np17py27_1    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
scipy                     0.11.0               np17py27_3    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
setuptools                27.2.0                   py27_0    defaults
six                       1.10.0                   py27_0    https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
sqlite                    3.13.0                        0    defaults
tabix                     1.0                       <pip>
tk                        8.5.18                        0    defaults
wheel                     0.29.0                   py27_0    defaults
zlib                      1.2.8                         3    defaults

Any help?

A: virtualenv is the usual way to avoid the library versioning problem with Python.
From the documentation:

virtualenv is a tool to create isolated Python environments.
The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform's standard location is), it's easy to end up in a situation where you unintentionally upgrade an application that shouldn't be upgraded.
Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.

A: I use conda search matplotlib to find all the version of matplotlib.
          1.2.1                np17py33_0  defaults
                         1.2.1                np16py26_1  defaults
                         1.2.1                np16py27_1  defaults
                         1.2.1                np17py26_1  defaults
                         1.2.1                np17py27_1  defaults
                         1.2.1                np17py33_1  defaults
                         1.3.0                np16py26_0  defaults
                         1.3.0                np16py27_0  defaults
                         1.3.0                np17py26_0  defaults
                         1.3.0                np17py27_0  defaults
                         1.3.0                np17py33_0  defaults
                         1.3.1                np16py26_0  defaults
                         1.3.1                np16py27_0  defaults
                         1.3.1                np17py26_0  defaults
                         1.3.1                np17py27_0  defaults
                         1.3.1                np17py33_0  defaults

And choose one version (such as 1.3.0) that seems support the numpy17.  It works after installing 1.3.0 version of matplotlib!


text:
Q: Convert Numpy array in python to C++ mat (opencv) using ctypes I have to create a (openCV) image processing function in C++ and have to call that function from python using ctypes.
so how can i pass a numpy array as an input to c++ function, than convert that array to Mat(opencv) in c++ and do the operations in c++ and return that Mat back to python script.
python file
import numpy
import cypes

libmatmult = ctypes.CDLL("./cpp_function.so")

def opencv_mat(a,b):
    # inits for cpp multiplications
    ND_POINTER_1 = numpy.ctypeslib.ndpointer(dtype=numpy.float64,
                                        ndim=2,
                                        flags="C")
    ND_POINTER_2 = numpy.ctypeslib.ndpointer(dtype=numpy.float64,
                                        ndim=2,
                                        flags="C")
    libmatmult.opencv_dot.argtypes = [ND_POINTER_1, ND_POINTER_2, ctypes.c_size_t, ctypes.c_size_t]
    libmatmult.opencv_dot.restype = None #Needed numpy array
    np_array = libmatmult.opencv_dot(a, b, *a.shape, *b.shape , a.shape[0] * a.shape[1])
    return np_array

opencv_mat(numpy.random.uniform(1,255,(5,5)), numpy.random.uniform(1,255,(5,5)))

C++ file
Compile using :g++ -shared -fPIC cpp_function.cpp -o cpp_function.so -I /usr/include/opencv4/ -L /usr/lib -lopencv_core -lopencv_imgproc
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace cv;

extern "C" {

    void opencv_dot(...){
        // 1) convert to np to cv::mat
        // 2) do any operations
        // 3) convert mat back to numpy compatible format
        // 4) return to python file
    }
}


text:
Q: CSS fluid center positioning issue in IE I'm having an issue in IE (11 & earlier) with a fluid layout. Basically the images spread out to the far sides rather than centering as they should.  This works fine in other browsers.
I am using the following code:
HTML:

Little Recipes

Shabby Chic

3 Colour Options, 5 Outfit Choices
    Price Range £15.95-£18.95

Classic Vintage

3 Colour Options, 5 Outfit Choices
    Price Range £15.95-£18.95

Memo

2 Colour Options, 5 Outfit Choices
    Price Range £15.95-£18.95

Newborn Welcome

Footprints

3 Colour Options, 2 Outfit Choices
    Price Range £15.95-£16.95

Delivery Stork

3 Colour Options, 2 Outfit Choices
    Price Range £15.95-£16.95

Summer Range

Classic Vintage

Yellow/Purple
    Orange/Green
    Blue/Red

CSS:
.newRange
{
 width:100%;
}

.rangeWrapper {
       text-align: center;
    -ms-text-justify: distribute-all-lines;
    text-justify: distribute-all-lines;
}

.rangeModern {
  width:200px;
  height:480px;
  margin:10px;
   vertical-align: top;
    display: inline-block;
    *display: inline;

}

.stretch {
    width: 100%;
    display: inline-block;
    font-size: 0;
    line-height: 0
}

Please see this JSFiddle:
https://jsfiddle.net/afnguyen/qzzrkc4w/1/
Any help would be much apreciated.

A: ok stumbled across the solution while inspecting element in IE and editing the css.  By removing the following:
.rangeWrapper {
       text-align: center;
    /*-ms-text-justify: distribute-all-lines;  REMOVED THESE TWO LINES
    text-justify: distribute-all-lines;*/
}

It now works across browsers including IE and across devices


text:
Q: Delay in logwatch sending results as an email I have set up a dual server email system using Debian. One server is active, the other just syncs all the email data in case of a server failure. Everything is working very well, but I notice a very strange behavior.
The backup server has a logwatch cronjob set up to run at 06:25 AM and send its results to the default user on the active server as an email.
This works, BUT logging on to the active server with a thunderbird email client, I see that it can be as late at 04:30 PM before the email (timestamped 06:25 AM) is received. "Get Messages" selected on the thunderbird client does not seem to get the missing email to the default user's Inbox any quicker. I just have to wait for it to show up.
Any ideas why this might be happening?


text:
Q: Postgres reporting "window function call requires an OVER clause" in a query that has an OVER clause I've got a table, me, that's got an e_id column, a first_name, and a last_name. (A few other columns too but I'm just trying to figure out the window function stuff.)  When I try to do a query and pick out the first name values in the table for a given e_id value:
SELECT e_id, first_value(first_name), first_value(last_name)
  OVER (PARTITION BY e_id)
  FROM me

I get the "window function call requires an OVER clause" error. Now, like I said, I don't know what I'm doing yet, but I'm pretty sure there's at least an attempt at an OVER clause in that query. OK, so when I try it without the functions:
SELECT e_id, first_name, last_name
  OVER (PARTITION BY e_id)
  FROM me

I get a syntax error at OVER.  I'm running psql version 9.4.4 against a 9.1.13 server. I'm staring at the documentation for 9.1 and it looks to me like OVER is documented there. Am I just missing something basic here?

A: Each window function must have its own OVER clause. The problem with your first query is that the first_value(first_name) window function does not have an OVER clause.
And the problem with your second query is that you have an OVER clause that is not preceded by a window function.
Try this
SELECT e_id,
  first_value(first_name) OVER (PARTITION BY e_id),
  first_value(last_name) OVER (PARTITION BY e_id)
FROM me


text:
Q: Adaptive HLS Streaming - Flutter video_player I am developing a new native App. I have chosen Flutter for it (over React Native). In this app, there will be a section for video streaming. These videos will have HLS streaming.
I am using video_player package in Flutter for it. I am able to play the video successfully but there is no option to change the quality (1080p, 720p etc.). How can I implement video quality selection in video_player package? Also, does video_player have adaptive bitrate streaming for HLS?

A: You can use stack widget adding there video player and button. After pressing button you change url of video from 1080 p to 720 p.

A: There's a package which you can use to change the quality from 1080p to 720p, here's the package's link: yoyo_player

A: For those that might come here looking for a solution. It is a pretty trivial solution using the default video_player or even yoyo player. In front of the url, just add the file format type that you desire. For example for HLS just add ".m3u8" and for dash add ".mpd" and the video will work and still be adaptive.
So your full url should be something like this:
For HLS
https://itvnnowoptimised-sano1.streaming.media.azure.net/3c0ecaef-002f-461f-854a-2397449d351f/thestoryofjoseph.ism/manifest(format=m3u8-aapl).m3u8
For dash
https://itvnnowoptimised-sano1.streaming.media.azure.net/3c0ecaef-002f-461f-854a-2397449d351f/thestoryofjoseph.ism/manifest(format=mpd-time-cmaf).mpd
This was using azure Media Services.


text:
Q: Simplify $\Bigg(\frac{x^3}{6} + \frac{1}{2x}\Bigg)\sqrt{1+\Bigg(\frac{x^2}{2} - \frac{1}{2x^2}\Bigg)^2}$ How is this integral simplified as shown?
\begin{align}
S &=2\pi \int^3_\frac{1}{2} \Bigg(\frac{x^3}{6} + \frac{1}{2x}\Bigg)\sqrt{1+\Bigg(\frac{x^2}{2} - \frac{1}{2x^2}\Bigg)^2} \mathop{\mathrm{d}x}\\
&= 2\pi\int^3_\frac{1}{2} \Bigg(\frac{x^5}{12}+\frac{x}{3} + \frac{1}{4x^3}\Bigg)\mathop{\mathrm{d}x}
\end{align}

A: Note that
$$\left(\frac{x^2}{2}-\frac{1}{2x^2}\right)^2=\left(\frac{x^2}{2}\right)^2-2\cdot\frac{x^2}{2}\cdot\frac{1}{2x^2}+\left(\frac{1}{2x^2}\right)^2=\left(\frac{x^2}{2}\right)^2-\frac{1}{2}+\left(\frac{1}{2x^2}\right)^2.$$
So when you add $1$, the middle term becomes $+\frac{1}{2}$. Thus
$$1+\left(\frac{x^2}{2}-\frac{1}{2x^2}\right)^2=\left(\frac{x^2}{2}+\frac{1}{2x^2}\right)^2.$$

A: $1+(\frac{x^2}{2}-\frac{1}{2x^2})=(\frac{x^2}{2}+\frac{1}{2x^2})^2$. Now you can do it

A: Hint: Expand the term under the square root. It is a square, namely $(x^8 + 2x^4 + 1)/(4x^4)$. Do you see why ?


text:
Q: How to call Activity method from outside library in Android In my main activity I am having a method that I need to call from a secondary java class. I used the constructor of the secondary java class to receive reference to the main Activity. I then tried to use this reference to invoke that method from the body of the secondary java class. But java doesn't recognize that method through the passed reference?
My main Activity is as below:
public class MainActivity extends Activity{

    public void onCreate(){

        TestClass mTestClass = new TestClass(this);
    }

   public testMethod(){
       // do some work here
   }
}

now, in my TestClass.java I receive reference to the MainActivity:
public class TestClass{

    public TestClass(Activity mActivity){
        //Android/Java doesn't recoginze testMethod here????
        mActivity.testMethod();
    }
}

I've been trying to solve this issue for a few days with no success. I urgently need your help and would appreciate any suggestion!
P.S. The TestClass will act as a library that everyone can call it from their android application. In other words, I provide the TestClass as the library. The user then implements the content of a method that will be executed whenver certain conditions are met. Thus, I need to call that specific method (which will be defined by the user in their own Activity) through a reference which is passed by the user to my library class

A: In your application:
public class MainActivity extends Activity implements Testeable {

    public void onCreate(){

        TestClass mTestClass = new TestClass(this);
    }

   public testMethod(){
       // do some work here
   }
}

In your library:
public interface Testeable {
   public void testMethod();
}

public class TestClass{

    public TestClass(Testeable mActivity){
        //Android/Java doesn't recoginze testMethod here????
        mActivity.testMethod();
    }
}

A: If you pass the Activity class in the constructor of the TestClass the testMethod will not be visible because it is contained in your MainActivity class and not the Activity. So change
public TestClass(Activity mActivity){
...

to
public TestClass(MainActivity mActivity){
...

or cast mActivity or use an interface like Julio Gorgé suggested


text:
Q: On differentiability of continuous square root Let $U\subset\mathbb{C}-\{0\}$.  Can we find a continuous function $f:U\longrightarrow{\mathbb{C}}$ such that $(f(z))^2 = z$ for all $z\in{U}$, and such that it isn't differentiable at some $z_0$ in $U$?
I think it's not possible, but I am not sure.

A: Notice that for all $z\in U$, $f(z)\ne0$ and therefore, by continuity of $f$, $$\lim_{h\to0}\frac{f(z+h)-f(z)}h=\lim_{h\to 0}\frac{(f(z+h))^2-(f(z))^2}{h(f(z+h)+f(z))}=\frac1{2f(z)}$$


text:
Q: concatenating columns in dataframe and generate new ID I have a dataframe
City  hits
A     10
B     1
C     22
D     122
E     1
F     165

I want to make a dataframe with a single column called Hit_ID, whose rows are
A_1
A_2
etc.
A_10
B_1
C_1
C_2
etc.
D_124
D_125
E_1

I tried
df['Hit_ID'] = df[['City','hits']].apply(lambda x:'_'.join(x.astype(str)),axis=1) but this just concatenates the columns. How can I modify the apply function to get the desired op?

A: You need:
#repeat index values by column hits
df = df.loc[df.index.repeat(df['hits'])].reset_index(drop=True)
#create counts
df['hits'] = df.groupby('City').cumcount() + 1
#concatenate columns
df['Hit_ID'] = df['City'] + '_' + df['hits'].astype(str)
print (df.head(20))
   City  hits Hit_ID
0     A     1    A_1
1     A     2    A_2
2     A     3    A_3
3     A     4    A_4
4     A     5    A_5
5     A     6    A_6
6     A     7    A_7
7     A     8    A_8
8     A     9    A_9
9     A    10   A_10
10    B     1    B_1
11    C     1    C_1
12    C     2    C_2
13    C     3    C_3
14    C     4    C_4
15    C     5    C_5
16    C     6    C_6
17    C     7    C_7
18    C     8    C_8
19    C     9    C_9

A: Try this:
df['hits'] = df.hits.transform(lambda x: range(1, x))
s = df.apply(lambda x: pd.Series(x['hits']),axis=1).stack().reset_index(level=1, drop=True)
s.name = 'hits'
df = pd.concat([df.City, s], axis=1)
df['hit_id'] = df.City + '_' + df.hits.astype(str)

*

*Change the df.hits from a column of integers to a column of lists, ranging from 1 to the original value.

*Use the technique discussed here by @RomanPekar to expand the column of lists into a series of rows.

*Concatenate that new column with the original df.City column.

*Join the two columns together with an _.