Instagram JSON TypeError: Cannot read property "text" from undefined

Question: I'm trying to build analytics with Google Sheet for Instagram, but I keep getting errors when I want to return the caption text from an image url.
I've tried different variations of my code, but it's always the same issue. Either my result comes back (in the output) as "undefined", or it just throws errors.
    function MultipleHashtags() {
  //Set up multiple sheets and instagram accounts
var hashtagArray = ["fitness", "fashion"];

  for(var i = 0; i < hashtagArray.length; i++) { grabData( hashtagArray[i]); };
//Grab data from TOP 9 posts
  function grabData(tag) {

  var url = "https://www.instagram.com/explore/tags/"+tag+"/?__a=1";
  var response = UrlFetchApp.fetch(url).getContentText();

    for(var i = 0; i < 9; i++) {
      var hashtag = JSON.parse(response).graphql.hashtag.name;
      var postOwner = JSON.parse(response).graphql.hashtag.edge_hashtag_to_top_posts.edges[i].node.owner.id;
      var shortCode = JSON.parse(response).graphql.hashtag.edge_hashtag_to_top_posts.edges[i].node.shortcode;
      var URL = "https://www.instagram.com/p/"+shortCode;
      var isVideo = JSON.parse(response).graphql.hashtag.edge_hashtag_to_top_posts.edges[i].node.is_video;
      var PostComments = JSON.parse(response).graphql.hashtag.edge_hashtag_to_top_posts.edges[i].node.edge_media_to_comment.count;
      var PostLikes = JSON.parse(response).graphql.hashtag.edge_hashtag_to_top_posts.edges[i].node.edge_liked_by.count;
      var caption = JSON.parse(response).graphql.hashtag.edge_hashtag_to_top_posts.edges[i].node.edge_media_to_caption.edges.node.text;
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getSheetByName("Sheet2");
      sheet.appendRow([Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd"), hashtag, postOwner, shortCode, URL, isVideo, PostComments, PostLikes, caption])
      var range = sheet.getRange("A2:H")
      range.sort([{column: 1, ascending: false}]);
      Utilities.sleep(200);;
    }
  }
};

Might not be the best code yet, but i'm still learning :). Any help would be appreciated.
What this script does is read the dump that's behind this URL:
https://www.instagram.com/explore/tags/fashion/?__a=1
for instance:
"graphql":{"hashtag":{"name":"fashion","is_top_media_only":false,"profile_pic_url":"https://scontent-bru2-1.cdninstagram.com/vp/3919f4813f1759cd589c9e256fafa05b/5B584579/t51.2885-15/s150x150/e35/c0.135.1080.1080/29717343_617997658538341_2606017788199829504_n.jpg","edge_hashtag_to_media":{"count":494984995,"page_info":{"has_next_page":true,"end_cursor":"AQBYZqz6Bc4vBlwhzRuhZm1NQSk7HQmHsJ9ZdMzanB-4UAH9rfDCjuWq-iqx5iEEaT0pPeJ_2aydWn_ZToa_aR5wt2ww743GTMbvIfx1lEAlpQ"},"edges":[{"node":{"comments_disabled":false,"id":"1750034539685082052","edge_media_to_caption":{"edges":[{"node":{"text":"NEW | Our new webshop is online!\n\nwww.ivan-online.nl\nFrom now on you can order your shawl easily online. A special gift for yourself, or for someone else. A warm shawl with a warm story.\n\nLet us know what you think about it \ud83d\ude4f \u2014\n\u2014\n#webshop #fashion #shawl #sjaal #cashmere #kasjmir #internetfashion #fashionable #handmade #nepal #fairtrade #springfashion #2018\n#photo"}}]},"shortcode":"BhJXyRKl_PE","edge_media_to_comment":{"count":0},"taken_at_timestamp":1522840395,"dimensions":{"height":720,"width":1080},"display_url":"https://scontent-bru2-1.cdninstagram.com/vp/cbf53cb645805430051bc7b056fb1dbf/5B643AD8/t51.2885-15/e35/29414609_430637507388196_1941728523811028992_n.jpg","edge_liked_by":{"count":0},"edge_media_preview_like":{"count":0},"owner":{"id":"5998662494"},"thumbnail_src":"https://scontent-bru2-1.cdninstagram.com/vp/68d5e9377dee9bfb0165bfa18473b6c6/5B56C8D8/t51.2885-15/s640x640/sh0.08/e35/c180.0.720.720/29414609_430637507388196_1941728523811028992_n.jpg","thumbnail_resources":[{"src":"https://scontent-bru2-1.cdninstagram.com/vp/e8a4b97569e409822c382ddb3231af00/5B62B69B/t51.2885-15/s150x150/e35/c180.0.720.720/29414609_430637507388196_1941728523811028992_n.jpg","config_width":150,"config_height":150},{"src":"https://scontent-bru2-1.cdninstagram.com/vp/fbc573c382379e29a4b321b1b5e423c3/5B5A190D/t51.2885-15/s240x240/e35/c180.0.720.720/29414609_430637507388196_1941728523811028992_n.jpg","config_width":240,"config_height":240},{"src":"https://scontent-bru2-1.cdninstagram.com/vp/a5b50f4711a8ab1774320c912cb70b7c/5B620CE5/t51.2885-15/s320x320/e35/c180.0.720.720/29414609_430637507388196_1941728523811028992_n.jpg","config_width":320,"config_height":320},{"src":"https://scontent-bru2-1.cdninstagram.com/vp/b27613e12796dfb97803acd4e429c20d/5B5C9FCC/t51.2885-15/s480x480/e35/c180.0.720.720/29414609_430637507388196_1941728523811028992_n.jpg","config_width":480,"config_height":480},{"src":"https://scontent-bru2-1.cdninstagram.com/vp/68d5e9377dee9bfb0165bfa18473b6c6/5B56C8D8/t51.2885-15/s640x640/sh0.08/e35/c180.0.720.720/29414609_430637507388196_1941728523811028992_n.jpg","config_width":640,"config_height":640}],"is_video":false}}

In there is the following line that's of interest:
"edge_media_to_caption":{"edges":[{"node":{"text":"NEW | Our new webshop is online!\n\nwww.ivan-online.nl\nFrom now on you can order your shawl easily online. A special gift for yourself, or for someone else. A warm shawl with a warm story.\n\nLet us know what you think about it \ud83d\ude4f \u2014\n\u2014\n#webshop #fashion #shawl #sjaal #cashmere #kasjmir #internetfashion #fashionable #handmade #nepal #fairtrade #springfashion #2018\n#photo"}}]}

Which i'm trying to grab with:
var caption = JSON.parse(response).graphql.hashtag.edge_hashtag_to_top_posts.edges[i].node.edge_media_to_caption.edges.node.text;

And this returns the error:

TypeError: Cannot read property "text" from undefined

From stackdriver:

2018-04-04 14:20:42.316 CEST
  TypeError: Cannot read property "text" from undefined. at grabData(GrabData:21) at MultipleHashtags(GrabData:5)
  Expand all | Collapse all {
   insertId:  "198nrphg1tmmbn6"
   jsonPayload: {…}
   labels: {…}
   logName:  "projects/project-id-1872200188033847311/logs/script.googleapis.com%2Fconsole_logs"
   receiveTimestamp:  "2018-04-04T12:20:43.328274499Z"
   resource: {…}
   severity:  "ERROR"
   timestamp:  "2018-04-04T12:20:42.316Z"
  }
Comment: What errors are you getting? Could you provide the value stored in `response`?
Comment: @Diego added some additional info
Comment: I recommend storing the parsed response: `var r = JSON.parse(response);` and logging its contents so you can see what properties are really there: `console.log(r);` (logs to Stackdriver). My guess is a typo/capitalization issue. In Stackdriver, you can easily explore the structure of the passed data - this is not easy to do in the Apps Script `Logger` window.
Comment: @tehhowch added :)
Comment: @ThomasSt no, you only added the error report from Stackdriver. I'm saying you need to log the object you're working with so you can understand its structure and why your access failed.
Answer: The reason you're getting the errors is because you're trying to access an object property that doesn't exist. Unfortunately, this is heavily nested data, so you'll need to do a lot of checks here. There are multiple ways to do this, but I used this as a guide.
In the code below, I broke out your grabData() function as I'm personally not a fan of nested functions.
function MultipleHashtags() {
  //Set up multiple sheets and instagram accounts
  var hashtagArray = ["fitness", "fashion"];
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet2");
  var range = sheet.getRange("A2:H")
  range.sort([{column: 1, ascending: false}]);
  Utilities.sleep(200);;
  for(var i = 0; i < hashtagArray.length; i++) {
    var data = grabData(hashtagArray[i]);
    sheet.appendRow([Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd"), data.hashtag, data.postOwner, data.shortCode, data.URL, data.isVideo, data.PostComments, data.PostLikes, data.caption]);
  }
}

//Grab data from TOP 9 posts
function grabData(tag) {
  var url = "https://www.instagram.com/explore/tags/"+tag+"/?__a=1";
  var response = UrlFetchApp.fetch(url).getContentText();
  var responseObject = JSON.parse(response);
  var hashtagData = responseObject.graphql.hashtag;
  var data = {};
  for(var i = 0; i < 9; i++) {
    var hashtag = hashtagData.name;
    if (checkNested(hashtagData, "edge_hashtag_to_top_posts", "edges")) {
      var edge = hashtagData.edge_hashtag_to_top_posts.edges[i];
      if (checkNested(edge, "node")) {
        var node = edge.node;
        var postOwner = checkNested(node, "owner", "id") ? node.owner.id : "";
        var shortCode = checkNested(node, "shortcode") ? node.shortcode : "";
        var URL = "https://www.instagram.com/p/"+shortCode;
        var isVideo = checkNested(node, "is_video") ? node.is_video : "";
        var PostComments = checkNested(node, "edge_media_to_comment", "count") ? node.edge_media_to_comment.count : "";
        var PostLikes = checkNested(node, "edge_liked_by", "count") ? node.edge_liked_by.count : "";
        var caption = "";
        if (checkNested(node, "edge_media_to_caption", "edges")) {
          var captions = node.edge_media_to_caption.edges[0];
          caption = checkNested(captions, "node", "text") ? captions.node.text : "";
        }
      }
    }
    data = {
      "hashtag": hashtag,
      "postOwner": postOwner,
      "shortCode": shortCode,
      "URL": URL,
      "isVideo": isVideo,
      "PostComments": PostComments,
      "PostLikes": PostLikes,
      "caption": caption
    };
  }
  return data;
}

/**
 * Test for existence of nested JavaScript object key
 * Copied from https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key
 */
function checkNested(obj /*, level1, level2, ... levelN*/) {
  var args = Array.prototype.slice.call(arguments, 1);

  for (var i = 0; i < args.length; i++) {
    if (!obj || !obj.hasOwnProperty(args[i])) {
      return false;
    }
    obj = obj[args[i]];
  }
  return true;
}

EDIT: Forgot a major point about your original code. When you were accessing the caption, var caption = JSON.parse(response).graphql.hashtag.edge_hashtag_to_top_posts.edges[i].node.edge_media_to_caption.edges.node.text;, the last edges is actually an array. In my code, I only selected the first element of that array. You can update as necessary.


How can I configure Spring Cache to ignore cache serialization errors?

Question: I'm using Spring Cache with Redis / JDK Serialization as cache backend. I have a method whose result is cached and the cache is populated with some values. In an update to my app, I'm changing the class of the cached object in a way that breaks Java deserialization (changing the type of a member from a List to a Set). Now any invokation to my cached method fails with org.springframework.data.redis.serializer.SerializationException.
@Cacheable(cacheNames = "myCache", cacheManager = "myCacheManager)
public SomeObject myCachedMethod(String param) {
    return ...;
}

Stack Trace:
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 java.lang.ClassCastException: cannot assign instance of java.util.ArrayList to field SomeObject.foo of type java.util.Set in instance of SomeObject
    at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.deserialize(JdkSerializationRedisSerializer.java:41) ~[spring-data-redis-1.6.4.RELEASE.jar:na]
    at org.springframework.data.redis.cache.RedisCache$CacheValueAccessor.deserializeIfNecessary(RedisCache.java:378) ~[spring-data-redis-1.6.4.RELEASE.jar:na]
    at org.springframework.data.redis.cache.RedisCache.get(RedisCache.java:144) ~[spring-data-redis-1.6.4.RELEASE.jar:na]
    at org.springframework.data.redis.cache.RedisCache.get(RedisCache.java:94) ~[spring-data-redis-1.6.4.RELEASE.jar:na]
    at org.springframework.cache.interceptor.AbstractCacheInvoker.doGet(AbstractCacheInvoker.java:68) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.cache.interceptor.CacheAspectSupport.findInCaches(CacheAspectSupport.java:466) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.cache.interceptor.CacheAspectSupport.findCachedItem(CacheAspectSupport.java:432) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:336) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:302) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208) ~[spring-aop-4.2.7.RELEASE.jar:4.2.7.RELEASE]
    at com.sun.proxy.$Proxy175.myCachedMethod(Unknown Source) ~[na:na]

Is there a way to configure Spring cache to ignore error when deserializing objects and let the method invokation go through?
Answer: Found a solution after reading through Spring's code.
Cache layer handling happens in an instance of org.springframework.cache.interceptor.CacheErrorHandler. By default, Spring uses org.springframework.cache.interceptor.SimpleCacheErrorHandler which throws back all exceptions. To relax this, one can extend that class and log / ignore cache get exceptions (which causes them to be handled like cache miss):
@Configuration
@EnableCaching
public class CacheConfiguration extends CachingConfigurerSupport {
    @Slf4j
    private static class RelaxedCacheErrorHandler extends SimpleCacheErrorHandler {
        @Override
        public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
            log.error("Error getting from cache.", exception);
        }
    }

    @Override
    public CacheErrorHandler errorHandler() {
        return new RelaxedCacheErrorHandler();
    }

    // More config...
}

Comment: Would be nice if after prevent the error some kind of circuit breaker mechanisc were triggered. Because if there are too many calls to the cached method, all responses would take at least the timeout of Redis connection plus the actual work to get the data. I was trying to find some way to do this but I did not have much success.


When using width:100vw in nuxt.js there is extra white space

Question: I'm building component banner in my nuxt.js.
I tried a lot of way to solved this problem but it still not solved yet, i tried to add margin:0; and padding:0; in my html and body tag but the white space is still there. I tried another solution in this topic about using-100vw-and-vh-creates-extra-space-beyond-viewport-size-how-do-i-get-rid-of but when I try it the result is still the same. I try this topic too about 100vw-causing-horizontal-overflow-but-only-if-more-than-one but there is no luck.
this is my banner component:
<template>

Let's See Where You Fit In

</template>

this is my css:

can someone save me to solve this?
this is what I got right now
Answer: try adding box-sizing

Comment: Thankyou for the response, where I must add it? when I try it there is nothing change
Comment: i have updated my answer add the entire line in your css and check.
Comment: I tried to add `box-sizing:border-box` like you did but still nothing happen
Comment: can you please create the snippet with the same behavior so i can check.
Comment: I add a my component in this fiddle but it is already work but not in my full code https://jsfiddle.net/RFTaurus/qx0ozLw1/
Comment: this means there something else in your code which have issue. you  must have to produce that issue in jsfiddle then and only then we will be able to help you.


Como saber qual classe de link selecionar com php

Question: Estou criando um site que possui informações de vários vendedores acessadas por um administrador. Para exibir os dados dos vendedores, disponho os nomes deles numa tabela, selecionando-os de um banco de dados MySQL.
Pegando os dados:
$db = mysqli_connect($servername, $user_db, $pass_db, $nome_db) or die(mysqli_error());
    mysqli_select_db($db, $nome_db);
    $query_vendor = "SELECT * FROM users WHERE ID != 4";//id temporária do admin
    $result = mysqli_query($db, $query_vendor);
    $vendorData = mysqli_fetch_array($result);

Disposição dos nomes dos vendedores:
<?php
      do{
           echo "
$vendorData[USERNAME]
";
          }while($vendorData = mysqli_fetch_array($result));
 ?>

Na página que encaminho todos os vendedores, a vendorData.php, preciso mostrar o nome do vendedor cujo link foi clicado. Minha dúvida é: como vou saber qual link foi clicado? Sei que posso pegar a classe dos links com o DOM Document (seguindo essa resposta), mas não sei como definir o valor da variável $classname para pegar a classe certa.
Answer: Você irá passar por parâmetro para a outra página, através do protocolo http GET, insira no hrefo seguinte ajuste para passar como parâmetro:
<?php
      do{
           echo "
$vendorData[USERNAME]
";
          }while($vendorData = mysqli_fetch_array($result));
 ?>

Na página vendorData.php capture o id da seguinte maneira:
$id = $_GET['id'];

Esse array irá trazer todos os parâmetros passados através do protocolo http get.
Comment: Obrigada, deu certo!


Injective homomorphism between a finite group $G$ and $GL_n(\mathbb{F}_p)$ where $p$ is prime

Question: I'm looking for a solution to the following problem:
Given a natural number $n$, a prime number $p$ and a  finite group $G$, I need to find an injective homomorphism between $G$ and the group $GL_n(\mathbb{F}_p)$.
thanks.
Comment: Such a homomorphism doesn't exist for all $n$ and $p$. Do you mean that we should choose $n$?
Answer: Hint : From Cayley's theorem, we know that $G$ can be embedded inside $S_{|G|}$. So to embed $G$ inside $GL_n(\Bbb F_p)$, you have to just find an injective homomorphism from $S_{|G|}$ to $GL_n(\Bbb F_p)$. (note that this is not possible for all $n, p$)
Comment: Let $G=S_3$, $n=2$. Then $G$ can't be embedded in $S_n$.
Comment: @MattSamuel Edited.
Comment: cayley's theorem states if G is of order n then it is isomorphic to a subgroup of Sn. but G here is just finite thus its order could be a number which is not n.
Comment: Yes, @nir, in other words, there is a faithful homomorphism from $|G|$ to $S_{|G|}$.
Comment: If $|G| \leq n$, then you can embed $G$ inside $S_n$. Otherwise, it might not be possible.
Comment: i,m thinking about a permutaion as an nxn matrix obtained from the identity matrix by permutations over the rows.


Must all inner-product preserving maps be linear?

Question: Must all inner-product preserving maps be linear?
Answer: For all $x,y,z,\mu,\nu$, you want $\langle f(x),f(\lambda y+\mu z)\rangle=\langle x,\lambda y\rangle+\langle x,\mu z\rangle$ and, so, for all $x'\in\operatorname{im} f$ the map $\langle x',f(\bullet)\rangle$ is linear.
Assume as a contradiction that there are $x,y,\mu,\nu$ such that $w=f(\lambda x+\mu y)-\lambda f(x)-\mu f(y)\ne 0$. Then, \begin{align}0<&\langle w,w\rangle=\langle w,f(\lambda x+\mu y)\rangle-\lambda\langle w,f( x)\rangle-\mu\langle w,f( y)\rangle=\text{(linearity)}\\=&\langle w, f(\lambda x+\mu y-\lambda x-\mu y)\rangle=\langle w,f(0)\rangle=0\end{align}
Absurd.
Comment: thank you. so it means that if domain and codomain have same dimension, then preserving inner product map between them must be linear map. I got it
Comment: @user330235 The requirement on the dimension is not particularly relevant in this. The important ingredient is that $\langle x,x\rangle\ne 0$ for all $x$ or, to scringe for minimality, that there is no vector $u\in\operatorname{im} f$ such that $\langle u,v\rangle=0$ for all $v\in\operatorname{im} f$. All these facts are obvious for the usual positive-definite inner products.


session, DB or cookie in eCommerce site

Question: I am creating my 1st eCommerce website. After searching a lot i am confused about whether to use session, DB or cookie.

Some says session is best because not every user purchases what he have in cart, DB will be very heavy.
Some says that DB should be used so that cart data will persist in different sessions.

What is the best choice? What most sites do?
Note: user must login to buy something.
Edit: what about that, when a user add something in the cart i insert that in DB TempTable which have a foreign key of userID(user must login to buy something). When users checkouts records from that table will be deleted and inserted into a perminent table.

If a user left the pc for few hours, he have to login and all data will be there(session problem solved).
If he uses another pc, he have to login and all data will be there(Cookie problem solved).
If he removed the cookies, Data still there(Cookie problem solved).

Is this a good technique?
Comment: As you already stated, you must face some trade-offs. I would go to DB, then having a daily routine which clean all older unused sessions, then rebuilding the table indexes
Answer: Personally I wouldn't rely on sessions to hold a basket. Customers can quite often spend time on a site, then wander away - perhaps from their desk. should this happen, and they have left their browser and the session expires, then so does their cart...
There are plenty of other reasons too. Maybe they started shopping, closed the browser, went back another time and again would have to start shopping.
What I have a tendency to do is store their cart in a database and the ID to that cart in their cookie. When the user comes back, read the cookie and get their cart. they can continue onwards then. Clear this cookie when the cart has been purchased, so you don't allow them to edit a purchased cart.
I'm sure this has it's downsides too - cookies disabled etc - though I personally try and cater more for the masses, rather than the very rare..
Just my take...
Comment: +1 @syedmohsin There are a lot of different ways the skin the shopping cart cat; this way is probably the best & most scalable.

session, DB or cookie in eCommerce site


Load file of content by weight

Question: Let's suppose I have a simple content type with title, body and file fields, and file field is multi value. I create a piece of content and upload some file in my field. Finally my content is something like
title : my title
body  : somebody text come in body
file  :

file1
file2
file3

My question
I can change the order of files in node edit by drag them up or down, I want to know how I can load a file programmatically by its weight. I mean I want to upload a file that is shown first or second in node edit mode. How can I upload file form node programmatically, ordering by weight?
Comment: It's not clear what you are asking. When you say "load a file programmatically" do you mean UPload a file - ie. changing the node content - or load it in the sense of retrieving it?
Comment: @AlfredArmstrong if we have several field I want load one of them by weight
Answer: When you change the order, the changes are saved as the delta in the database. For example if your field was called file you would access $node->field_file[$node->language][delta]. In your example above, the second file would be $node->field_file[$node->language][1] as the first file would be 0
Comment: lastDay I found my solution by looking at database field table. tnx for you attnetion and answer.

Load file of content by weight


Is it possible to compute geodesic without induced metric

Question: Suppose a manifold embedding $i:M\to N$ into Riemannian manifold $(N,g)$ is given by $f(x)=0$, where $f:M\to R^m$ is a smooth vector-valued function. Now if it is very hard to parameterize the submanifold $M$ with $\text{dim}M$ parameters, can we still compute the geodesic on $M$?
For a very simple example, given an isometry embedding $i:S^n\to R^{n+1}$ using $f(x)=|x|^2-1$, without parameterize the sphere by spherical coordinate, do we know the geodesics of sphere are great circles?
Answer: This is sort of a soft question, so some of this answer may ramble.
Computing the geodesics of a general Riemannian manifold is (as far as I can tell) not an easy problem. (I'm not even sure how to make sense of this problem in general without parameterizing $M$.) However, for specific Riemannian manifolds one can often use tricks to compute geodesics that don't require a parameterization.
For instance, let's show that the geodesics on $S^2$ are great circles. We imagine $S^2$ as embedded in $\mathbb{R}^{3}$. Then take a point $p \in S^2$ and any tangent vector $v \in T_p S^2$. We can think of $v$ as living in $\mathbb{R}^{3}$ in the usual way.
Consider the reflection $R$ of $\mathbb{R}^{3}$ through the plane spanned by $p$ and $v$. This is obviously an isometry of $S^2$ whose fixed-point-set is exactly the great circle through $v$. On the other hand, since $R$ leaves $v$ fixed, it must also fix the geodesic through $v$. Thus the great circle must exactly be this geodesic.
The exact same argument works for $S^n$, of course.
As another example, this method determines geodesics in the hyperbolic plane. We use the model where $\mathbb{H}^2$ is the complex upper half-plane with the metric $\tfrac{1}{y^2} g_{{}_\text{Euclid}}$. By symmetry of the metric, the reflection in the imaginary is an isometry; since this isometry fixes only the imaginary axis, we conclude that the imaginary axis is the geodesic through $i$ in the vertical direction. Now one shows (standard calculation) that $SL(2, \mathbb{R})$ acts by isometries on $\mathbb{H}^2$ (via Mobius transformations), and since this isometry group is transitive on tangent vectors (there is an isometry taking any tangent vector to any other), this allows us to easily compute all the geodesics.
This sort of idea is very useful whenever the isometry group of $M$ is known and relatively large. But even when the isometry group of $M$ is not so large, one might still be able to exploit symmetries to at least determine some of the geodesics, which can still be useful. For instance, consider the case of $M$ a surface obtained by revolving a smooth curve about the $x$-axis in $\mathbb{R}^3$. Again exploiting the fact that reflection through any plane containing the $x$-axis is an isometry, one sees that the curves running along the surface parallel to the $x$-axis are geodesics. This doesn't determine all the geodesics on $M$, but it is a start.


Particular solution error

Question: I'm trying to solve for a particular solution (when $y = -1$ and $x = 1$) but seem to be stuck on the general solution.
<code>$$\frac{dy}{dx} = 1 - 2x - 3x^2$$
</code>
My initial answer was: $$y = x - x^2 - x^3 + C$$ , but the correct answer in my textbook is:$$ y=x - x^2 + 3x^{-1} + 4$$
Thanks :)
EDIT: Realised there was a typo in the question (Question 2b)! Thanks for your help everyone
Comment: You might like to fix typos using [mathjax](https://math.meta.stackexchange.com/q/5020/306553) and include your working. You have two equal signs in the first maths expression.
Answer: The answer in the textbook corresponds to $\frac{dy}{dx} = 1-2x-3x^{-2}$. My guess is that somewhere there is a typo, but whether that's in the original problem in your book, or in the solution (or in the author's notes when he made the solution), or in your notes from writing down the problem for the first time, I cannot tell.
When you're solving differential equations, it's usually a good idea to check your solution. It's often a lot less work than solving the equation, and it is a great help in spotting mistakes. And if you check your solution, and it works, then you most likely have the correct solution (the probability that the exact reverse of an error occurs when checking a solution is positive, but usually rather small).
Comment: Turns out there was a typo in the textbook, thanks!
Answer: Your book solution answer a different question:
$$\frac{dy}{dx}=1-2x-3x^{-2}$$
Your solution to the question that you posted seems fine. Just subtitute those particular value (when $x=1, y=-1$) to solve for $c$.
$$-1 = 1-2(1)-3(1^2)+c$$

Particular solution error


Twitter bootstrap well corner text/image

Question: I have a well div, and I would like to attach a small text/image at the corner, as shown here (http://draw.to/D46BqsC)...and have that element be placed relatively to the well, so that  it changes position as the well does. What is the best approach? Thank you!
Answer: You can use position: absolute to make an element position itself in an absolute location relative to its parent (in this case the well).  The only catch is the parent element has to be something other than static, so your well might need to be contained in something else.
.my-well {
    position: relative;
}

.my-well span {
    position: absolute;
    top: 0;
    right: 0;
}

    xxx

http://jsfiddle.net/YPcLy/


Check Is Internet Connectivity Active Using Javascript & Jquery

Question: I want to create a script using javascript or query to check is internet connection still active on every 1 second ?
So was wrote some codes using PING.JS but I have a problem. My script sends 1 PING request on every 1 second and the server will response within 1 second, but My problem is I want to code if for any reason server's reply will not receive within 60 seconds then it will show me an alert. Also, I want to store data on variable how many PING request was received server's reply successfully? I am providing my script link. Please check and tell me where I was wrong.

https://476606.playcode.io
Comment: Please embed your code in the question :-)
Comment: Does this answer your question? [Detect the Internet connection is offline?](https://stackoverflow.com/questions/189430/detect-the-internet-connection-is-offline)
Answer: As an alternative, there's an experimental browser API called the "Network Information API".
You can use it like this:
<code>var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
var type = connection.effectiveType;

function updateConnectionStatus() {
  console.log("Connection type changed from " + type + " to " + connection.effectiveType);
  type = connection.effectiveType;
}

connection.addEventListener('change', updateConnectionStatus);
</code>
https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API
It's got reasonably good support on mobile browsers, but not so on desktop browsers.
This will show you the currently supported browsers:
https://caniuse.com/#feat=netinfo
Comment: Nice solution, and much better than DDOSing your server with requests every second
Comment: @JashminBezos don't. It's a really bad idea. Why do you feel that you need to do that?
Comment: @RoryMcCrossan Due to some Ads serving requirements I want to check it on every 1 second.
Comment: Ah, so you're trying to rinse ad revenue. Good luck.
Comment: @RoryMcCrossan I don't using Adsence Ads. I want to use my own Ads network. So I really want to check it on every 1 second . **Please give me solution.**
Comment: @JashminBezos are you looking to see if your AD server is online in general or just accessible by the user's browser at the time?


Curious about the meaning of the term '&c' in Legendre's paper

Question: In Legendre's paper "De Nouvelles Méthodes pour la Détermination des Orbites des Comètes", the term $\&c$ is used. I'm not familiar with that terminology, but it seems to me that it represents higher order terms, mostly $O(t^2)$. Can anyone validate or correct my interpretation of that symbol?
Comment: No, it just mean : etc. ("et coetora")...
Comment: If you want to read more about this topic, see https://en.wikipedia.org/wiki/Et_cetera
Comment: Thanks for the reply and clarifying the term Jean Marie, **&c**! It literally means etcetera. From reading that paper, I believe that by this time Taylor's series expansion was well known.
Side question, how does one mark this question as answered?
Comment: @Catriel re. side question: it's allowed here to answer one's own question. If you do that the question gets marked as answered.
Answer: Thank you, Jean Marie, coffemath, &c, for answering my question. (Notice what I did there with &c?)
Comment: [+1] for the parenthezed humor.


Problema com função mcrypt*

Question: Estou usando essas duas funções abaixo para encriptar e decriptar uma string. Deixei o exemplo o mais limpo possível.
Função para encript
$key = '123';
$iv  = md5( md5( 'key' ) );
mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, $iv);

Função para decript
$key = '123';
$iv  = md5( md5( 'key' ) );
mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, $iv);

Não conheco a fundo a função, e estou com problema para usar json encode/decode. Consigo usar encode sem problema, mas o decode não roda a string descriptografada.
Usei como exemplo um array simples array( 123 ) e o output descriptografado é exatamente igual à json_encode( array( 123 ) ), a diferença é o tamanho, mas não aparecem espaços nem antes nem no fim.
Dump
decrypt( $argument )        : string(32) "[123]"
json_encode( array( 123 ) ) : string(5) "[123]"

Achei uma questão que relata o mesmo problema que o meu e a solução proposta foi o uso de rtrim( $decrypted , "\0" ). Funcionou para o autor e para mim, mas a explicação é superficial:

Diz que a função ENCRYPT/DECRYPT adiciona lixo para ficar com o tamanho correto, e deve remover os nulos ao final da string.

Também criei valores nulos no final da string mas não afetaram o tamanho no dump. Não consigo entender de como o tamanho da string não combina.

O uso de \0 no trim abrange quais caracteres?
Gostaria de saber mais sobre as opções cipher e mode, não encontrei na DOC referências mais profundas de cada caso.
É possível combinar cipher e mode de modo que a string não crie valores nulos para satisfazer o tamanho.
Comment: `rtrim( , "\0" )` abrange apenas o caractere "\0" mesmo. É o mesmo que `rtrim( ,chr(0) )`. Esse _padding_ é uma característica do modo escolhido para a criptografia. É usado para que os blocos fiquem do mesmo tamanho para a função criptográfica. http://en.wikipedia.org/wiki/Block_cipher - Pena que não dá tempo de eu elaborar como resposta agora cedo.
Comment: @Bacco, usei `trim( $crypt )` e surtiu o mesmo efeito - há diferença? Vi que diz algo a respeito na **RFC 5652**, vou procurar com calma.
Comment: O problema de `trim` sem especificar o `chr(0)` é que se a string original tem espaços e/ou quebras de linha no começo ou no fim, vc acabou de perdê-los também. Ah, outra coisa, aquele `md5(md5())` me dá frio na barriga de ver. Aproveitando, ja leu isso aqui? http://pt.stackoverflow.com/questions/2402/ não tem uma conexão direta com a sua pergunta, mas é interessante saber.
Comment: Entendi a questão do *trim*. O link tem coisas interessantes, lerei com calma - sua resposta precisa de tempo pra assimilar :). Sobre o *md5*, foi um exemplo que peguei para fins didáticos. Nunca trabalhei com `mcrypt`.
Answer: Para quem vier a encontrar esse tópico no futuro, o que o Bacco disse nesse comentário, basicamente, é remover todo o "lixo" adicionado pelas cifras para que tenham o mesmo tamanho o que, em código, seria isso:
$string = json_encode( array( 123 ) );

$key = '123';
$iv  = md5( md5( 'key' ) );

$encrypted = mcrypt_encrypt(

    MCRYPT_RIJNDAEL_256, md5( $key ),

    $string, MCRYPT_MODE_CBC, $iv
);

$decrypted = rtrim(

    mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5($key), $encrypted, MCRYPT_MODE_CBC, $iv),

    "\x00..\x1F"
);

Basta comparar com um var_dump() e ver que sem aquele rtrim() a string encriptada é bem diferente da não encriptada, porém ambas têm o mesmo comprimento:
string ''!Ù Èžtvûþ×Ij>+|oÙ(Œà¢qŒ)·Î""Æ¡h' (length=32)
string '[123]���������������������������' (length=32)

Mas (e agora vem minha contribuição), não basta remover apenas o byte nulo (\0 ou 0x00) pois cada linguagem pode incluir seu próprio lixinho.
Por isso meu pseudo-código traz um intervalo de caracteres mais amplo \x00..\x1F, isto é, os 31 primeiros caracteres da Tabela ASCII.
A propósito, respondendo a esse seu levantamento, se você considerar a remoção apenas do byte nulo (\0) pode tranquilamente usar rtrim() sem argumentos pois esse caractere já consta na lista de remoção padrão da função.
Comment: Valeu Bruno. Parece que o *decrypt* é meio capenga e esquece de remover o próprio complemento usado. Andei procurando mais sobre a função e encontrei exemplos usando `mcrypt_create_iv` e `mcrypt_get_iv_size`, depois calcula o tamanho do *iv* e subtrai a string.

Problema com função mcrypt*


Blown (?) speaker, or swapped poles?

Question: I've just rewired my 4x12 cab to become two 2x12s to accommodate for a new head. One duo of speakers is playing loud and clear, the other side sounds extremely underpowered. One speaker at maybe 60%, the other at maybe 25% of the expected volume (and compared to the other pair).
I've tried this amp through another cab with two 8 ohm inputs and she works fine.
The amp has two 8 ohm outputs, so I'm going from each into my "new" 2x12s (all the same speakers, celestion 16ohm wired in parallel for 8ohms). The "good" pair of speakers is wired to a regular mono phone jack. The "bad" pair is wired to a two-lead Cliff jack that was original to the cab.
The contacts on the "bad" jack all seem to be tight, nothing visibly wrong. I've re-done the wiring once, cleaned up all the connections and triple-checked which wires go where... my only thinking is that maybe I have the poles wrong on my "bad" jack, since I can't find a schematic telling me which lead is which, I'm just going off of the pictures I took before I re-did the wiring (and maybe I've had the poles wrong for years and didn't know it).
Could having my pos/negative incorrectly connected on my Cliff jack cause this problem? Or would I not be getting any sound at all?
Thanks!
PS attached is a picture of the jack, if anyone can tell me with certainty which lead is which and whether or not this could be my issue]1
Comment: I don't see any wiring there.
Comment: Polarity is important. Wire the two up, and connect a small battery across the terminals of the jack input. Both cones should jump - either in or out. When in phase, they'll both go the same way. Make sure the battery connects the same way for the other cab, so all speakers are in phase.
Answer: On the jack pictured, Positive (the tip of your cable) is the highest of the two connections, and the Negative (Earth - the body of your cable) is the lower.
Connecting speakers in series will increase resistance, and connecting them in parallel will decrease resistance (as in the following diagrams from https://www.hometoys.com/article/2002/06/series--parallel-speaker-wiring/1775/)

Your original 4x12 cab probably had series/parallel wiring, as follows. My recommendation is to check your wiring - I think you have an incorrect connection somewhere.
Comment: Thanks everyone! I'll try switching things around and give it a go!

Blown (?) speaker, or swapped poles?


WPF/C# - Throw away the Content for a Checkbox in a Datagrid

Question: TL;DR How do I make a Checkbox not draw/include the label for the content or the space required for the label?
I'm using Visual Studio in conjunction with C# and WPF.  I have a Checkbox in a DataTemplate inside of a DataGrid. My issue is that I suspect that while the Content is empty, the space for the content is still being taken up.
The end result is that I have a checkbox smashed to the left of the column, and a vast desert of whitespace to it's right
My current UI disaster looks like this:

Right now, my XAML looks like the following.  As you can see, I've tried messing around with the Horizontal and HorizontalContentAlignments with little to no luck.
 <DataGridTemplateColumn Header="Y/N">
   <DataGridTemplateColumn.CellTemplate>
     <DataTemplate>
       <CheckBox IsChecked="{Binding Path=IsSelected, UpdateSourceTrigger=PropertyChanged}"
                                  HorizontalContentAlignment="Center">
         <TextBlock>
         </TextBlock>
       </CheckBox>
     </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
 </DataGridTemplateColumn>

I've tried setting the size of the DataGridTemplateColumn but I don't see it really centering the checkbox even with the Horizontal* attributes set which makes me think it's got the space for the Label in there.
Any help on this is greatly appreciated.
Comment: `` does center the checkboxes in the column. Is it this, what you want?
Comment: @Rekshino There is no HorizontalAlignment property for the Checkbox
Comment: :) [CheckBox Class](https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.checkbox?view=netframework-4.8)
Answer: <DataGridTemplateColumn Header="Y/N" Width="50">
   <DataGridTemplateColumn.CellTemplate>
     <DataTemplate>
       <CheckBox IsChecked="{Binding Path=IsSelected, UpdateSourceTrigger=PropertyChanged}"
                                  HorizontalContentAlignment="Center">
         <TextBlock>
         </TextBlock>
       </CheckBox>
     </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
 </DataGridTemplateColumn>

Insert Width into DataGridTemplateColumn
or
 <DataGridCheckBoxColumn Header="Y/N" Binding="{Binding Path=IsSelected, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                        </DataGridCheckBoxColumn>

You can use this way


Problemas para ordenar código com ShellSort

Question: #include <stdio.h>

typedef struct {
 int id_submissao;
 int tempo;
 int id_equipe;
 int id_problema;
 char status;
} Linha;

void shellSort(Linha *v, int n) {
 int i = (n - 1) / 2;
  int chave, k, aux;

  while(i != 0) {
   do {
     chave = 1;
     for(k = 0; k < n; k++){
        if(v[k] > v[k + i]){
           aux = v[k];
           v[k] = v[k + i];
           v[k + i] = aux;
           chave = 0;
        }
     }
  }while(chave == 0);
      i = i / 2;
  }
}

void imprimeLinhas (Linha* vet, int N) {
int i;

for (i = 0; i < N; i++)
    printf("%d %d %c %d %d\n",
           vet[i].id_equipe,
           vet[i].id_problema,
           vet[i].status,
           vet[i].tempo,
           vet[i].id_submissao);

printf("\n");
}

int main () {

FILE* arq;
Linha vet[105];
int i;

arq = fopen("EDI-1S2018-Aula11-runs.txt", "r");

for (i = 0; !feof(arq); i++)
    fscanf(arq, "%d %d %d %d %c\n",
           &vet[i].id_submissao,
           &vet[i].tempo,
           &vet[i].id_equipe,
           &vet[i].id_problema,
           &vet[i].status);

printf("**********************************\n");
printf("**   Dados antes da ordenacao   **\n");
printf("**********************************\n");
imprimeLinhas (vet, 105);

shellSort(vet, 105);

printf("\n");
printf("**********************************\n");
printf("**    Dados apos a ordenacao    **\n");
printf("**********************************\n");
imprimeLinhas (vet, 105);

return 0;
}

Answer: Depois de ler um pouco sobre shell sort eu encontrei alguns problemas em seu código, como na maioria dos algorítimos de ordenação, os exemplos são dados com vetores de inteiros, mas observe que você tem um vetor de struct, logo, a comparação de v[i] > v[j], como qualquer outra comparação (==, <=, >=, !=) logica não iria funcionar dessa maneira visto que nós so podemos comparar tipos não primitivos em C, então a primeira coisa que eu fiz foi arrumar sua função de ordenar, de modo que ela compare os vetor[k].tempo  dessa forma ele consegue verificar os tempos maiores antes dos menor menores então podendo ordena-los. Perceba também que sua variável auxiliar não pode ser um inteiro uma vez que ela é usado para mover as estruturas dentro do seu vetor, teremos então que usar uma variável auxiliar do tipo Linha
void shellSort(Linha *v, int n) {
 int i = (n - 1) / 2;
 int chave, k;
 Linha aux;

 while(i != 0) {   do {
 chave = 1;
 for(k = 0; k < n; k++){
    if(v[k].tempo > v[k + i].tempo){
       aux = v[k];
       v[k] = v[k + i];
       v[k + i] = aux;
       chave = 0;
    }
 }
  }while(chave == 0);
    i = i / 2;
  }
}

Também Perceba que a sua função imprimeLinhas(Linha vet,int N) esta incorreta, de forma que ela espera receber uma unica struct do tipo Linha como parâmetro, mas você passa um vetor, como sabemos que você quer imprimir o vetor então temos que modificar seu escopo para: imprimeLinhas(Linha *vet,int N) dessa forma você tem a função esperando um vetor.
Perceba as diferenças entre implementação quando você usa um vetor de tipos primitivos, ou uma struc que contem varias informações.
Percebi também que você não trata os arquivos de forma correta, aconselho a você fazer o seguinte para abrir seu arquivo:
arq = fopen("EDI-1S2018-Aula11-runs.txt", "r");
if(arq == NULL) {
    perror("Erro ao abrir arquivo");
    return(-1);
}

Dessa forma você consegue assegurar que o arquivo foi aberto corretamente, caso contrario o seu programa encerra.Também assim que terminar de usar o arquivo é ideal fecha-lo, no seu caso depois de ler todo o arquivo você pode fechar o arquivo, desta forma:
fclose(arq);

Veja que o função feof() retorna um valor não zero se o arquivo não tiver chegado ao fim, e caso contrario, valor zero, perceba que essa não é uma boa maneira de assegurar que você leu seu arquivo todo já que a função percebe isso de acordo com a ultima operação de I/O (Você pode ler mais sobre isso na documentação aqui), e também não faz sentido já que seu vetor tem tamanho limita então a solução mais pratica seria deixar seu for da seguinte forma:
for (i = 0; i<105 i++)


Haskell standard function (or simple composition) for "mjoin"?

Question: This seems a long shot, but recently I've had a need for the following:
mjoin :: (Monoid b, Monad m) => m b -> m b -> m b
mjoin a b = do
  a' <- a
  b' <- b
  return $ mappend a' b'

The example use is this:
> mjoin (Just [1,2,3]) (Just [4, 5, 6])
Just [1,2,3,4,5,6]
> mjoin (Just [1,2,3]) Nothing
Nothing
> mjoin Nothing (Just [4, 5, 6])
Nothing

In other words, if either parameters are Nothing, then return Nothing. Else, return Just and the appended values.
Is there a standard function for this or a simpler formulation, perhaps with >>=?
Comment: A slight simplification would be `liftM2 mappend`.
Comment: @sabauma: Why not write that as an answer?
Answer: Perhaps something like this:
mjoin :: (Monoid b, Monad m) => m b -> m b -> m b
mjoin = liftM2 mappend

Comment: @Ana This also means that you don't really have to define `mjoin` as a function, you can just do `liftA2 mappend (Just [1, 2, 3]) (Just [4, 5, 6])`. (I suggest `liftA2` since you're not really doing monad stuff, you're just doing applicative stuff.)
Comment: Thanks. I knew it was covered somewhere.
Comment: (As long as the types being used are instances of both, which is almost always the case now)


Valor não é adicionado a uma váriavel dentro de uma função

Question: Estou fazendo um simples programa de um quiz com perguntas e respostas, com pontuação. O meu problema é o seguinte: eu fiz uma função para que toda vez que a resposta for certa, +1 será adicionado na variável da pontuação.
public static int pontu1 { get; set; }

    public static int pont(int pontu1)
    {
        pontu1++;
        return pontu1;
    }

Então aparentemente, ela está funcionando, resolvi criar a função "resposta certa", para toda vez que a resposta for certa, essa função será chamada:
public static void rcerta()
    {
        Console.WriteLine("Resposta certa");
        pont(pontu1);
        System.Threading.Thread.Sleep(2000);
        Console.Clear();
    }

O problema é, fui testar o código, mandou a pergunta, botei a resposta certa. Okay, a função rodou normal, deu resposta certa, porem, quando eu fui ver quanto estava minha pontuação, com o seguinte código (ele fica dentro de um switch de um menu que eu fiz) :
case 2:
                    Console.WriteLine("Sua pontuação é: " + pontu1);
                    Console.WriteLine("Pressione ENTER para continuar....");
                    break;

A pontuação aparece como 0, mesmo com a resposta certa. Alguem pode me ajudar? Segue todo o programa e a classe abaixo.
Programa:
class Program
{
    public static int pontu1 { get; set; }

    public static int pont(int pontu1)
    {
        pontu1++;
        return pontu1;
    }

    public static void rcerta()
    {
        Console.WriteLine("Resposta certa");
        pont(pontu1);
        System.Threading.Thread.Sleep(2000);
        Console.Clear();
    }

    public static void rerrada()
    {
        Console.WriteLine("Resposta errada");
        Console.Clear();
    }

    public static void resetar()
    {
        string r;
        Console.WriteLine("Sua pontuação atual é: " + pontu1);
        Console.WriteLine("Deseja reiniciar sua pontuação?      S  / N");
        r = Console.ReadLine();
        if (r == "S")
        {
            pontu1 = 0;
            Console.WriteLine("Pontuação reiniciada.");
            Console.WriteLine("Sua pontuação atual é: " + pontu1);
            Console.WriteLine("Pressione ENTER para voltar ao menu...");
        }
        else
        {
            Console.WriteLine("Pontuação mantida.");
            Console.WriteLine("Sua pontuação atual é: " + pontu1);
            Console.WriteLine("Pressione ENTER para voltar ao menu...");
        }
    }

    public static void QuizIncio()
    {
        int opcao;
        Console.WriteLine("Escolha um assunto!");
        Console.WriteLine("[ 1 ] teste");
        Console.WriteLine("[ 2 ] teste2");
        Console.WriteLine("-------------------------------------");
        Console.Write("Digite uma opção: ");
        opcao = Int32.Parse(Console.ReadLine());
        switch (opcao)
        {
            case 1:
                Class1.teste();
                break;
            case 2:
                break;
            default:
                break;
        }
        Console.ReadKey();
        Console.Clear();
    }
    static void Main(string[] args)
    {
        int opcao;
        do
        {
            Console.WriteLine("[ 1 ] Iniciar");
            Console.WriteLine("[ 2 ] Ver Pontuação");
            Console.WriteLine("[ 3 ] Resetar Pontuação");
            Console.WriteLine("[ 0 ] Sair do Programa");
            Console.WriteLine("-------------------------------------");
            Console.Write("Digite uma opção: ");
            opcao = Int32.Parse(Console.ReadLine());
            switch (opcao)
            {
                case 1:
                    Console.Clear();
                    QuizIncio();
                    break;
                case 2:
                    Console.WriteLine("Sua pontuação é: " + pontu1);
                    Console.WriteLine("Pressione ENTER para continuar....");
                    break;
                case 3:
                    Console.Clear();
                    resetar();
                    break;
                case 0:
                    break;
            }
            Console.ReadKey();
            Console.Clear();
        }
        while (opcao != 0);
    }

}

Classe:
class Class1 : Program
{
    public static void teste()
    {
        string r1, r2, r3, r4, r5;
        Console.WriteLine("Quanto é 2 + 2?");
        Console.WriteLine("a) 4");
        Console.WriteLine("b) 3");
        r1 = Console.ReadLine();
        if (r1 == "a")
        {
            rcerta();
        }
        else
        {
            rerrada();
        }
    }
}

Answer: Este código está bem confuso e cheio de problemas. Nem vou tentar consertar porque daria muito trabalho e o foco da pergunta é apenas um. Se o código fosse mais organizado o erro não ocorreria. Está usando o mesmo nome para a propriedade da classe e para o parâmetro local do método que tem prioridade, então está adicionando no variável local que desaparece ao final da execução do método, e não mexe na propriedade. troquei o nome da propriedade, que inclusive está mais de acordo com o estilo do C# e o problema foi resolvido.
using static System.Console;
using System.Threading.Tasks;

public class Program {
    public static int Pontu1 { get; set; }

    public static int IncrementaPontos(int pontu1) {
        Pontu1++;
        return pontu1;
    }

    public static void RespostaCerta() {
        WriteLine("Resposta certa");
        IncrementaPontos(Pontu1);
        Task.Delay(2000);
//        Console.Clear();
    }

    public static void RespostaErrada() {
        WriteLine("Resposta errada");
        Clear();
    }

    public static void Resetar() {
        WriteLine("Sua pontuação atual é: " + Pontu1);
        WriteLine("Deseja reiniciar sua pontuação?      S  / N");
        string r = ReadLine();
        if (r == "S")  {
            Pontu1 = 0;
            WriteLine("Pontuação reiniciada.");
        } else WriteLine("Pontuação mantida.");
        WriteLine("Sua pontuação atual é: " + Pontu1);
        WriteLine("Pressione ENTER para voltar ao menu...");
    }

    public static void QuizIncio() {
        WriteLine("Escolha um assunto!");
        WriteLine("[ 1 ] teste");
        WriteLine("[ 2 ] teste2");
        WriteLine("-------------------------------------");
        Write("Digite uma opção: ");
        if (!int.TryParse(ReadLine(), out int opcao)) return;
        switch (opcao) {
            case 1:
                Class1.Teste();
                break;
            case 2:
                break;
        }
 //       Console.Clear();
    }

    public static void Main(string[] args) {
        int opcao;
        do
        {
            WriteLine("[ 1 ] Iniciar");
            WriteLine("[ 2 ] Ver Pontuação");
            WriteLine("[ 3 ] Resetar Pontuação");
            WriteLine("[ 0 ] Sair do Programa");
            WriteLine("-------------------------------------");
            Write("Digite uma opção: ");
            if (!int.TryParse(ReadLine(), out opcao)) continue;
            switch (opcao) {
                case 1:
 //                   Console.Clear();
                    QuizIncio();
                    break;
                case 2:
                    WriteLine("Sua pontuação é: " + Pontu1);
                    WriteLine("Pressione ENTER para continuar....");
                    break;
                case 3:
//                    Clear();
                    Resetar();
                    break;
                case 0:
                    break;
            }
//            Console.Clear();
        } while (opcao != 0);
    }
}

class Class1 : Program {
    public static void Teste() {
        WriteLine("Quanto é 2 + 2?");
        WriteLine("a) 4");
        WriteLine("b) 3");
        string r1 = ReadLine();
        if (r1 == "a") RespostaCerta();
        else RespostaErrada();
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Dei uma boa melhorada, mas ainda dá para fazer mais.


Roboelectric 3.0 with Android Studio android.view.InflateException

Question: I recently moved to Roboelectric 3.0 and I cant get past a simple step to run a test which runs the following command:
@Config(sdk = 18, constants = BuildConfig.class)
@RunWith(RobolectricGradleTestRunner.class)
public class LegDetailActivityTest {
    @Test public void testThatLegDetailActivityCanBeInjected() {

        LegDetailsActivity activity =
            Robolectric.buildActivity(LegDetailsActivity.class).create(bundle).get();

        graph.inject(activity);
    }
}

I receive the following error:
android.view.InflateException: XML file build/intermediates/res/merged/debug/layout/abc_screen_toolbar.xml line #-1 (sorry, not yet implemented): Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:633)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:743)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:299)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:246)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:106)

My activity class is extended with AppCompatActivity.
My build.gradle has these dependencies:
  testCompile 'junit:junit:4.12'
  testCompile 'org.easytesting:fest:1.0.16'
  testCompile 'com.squareup:fest-android:1.0.8'
  testCompile 'org.mockito:mockito-all:1.9.5'
  testCompile('org.robolectric:robolectric:3.0') {
    exclude group: 'commons-logging', module: 'commons-logging'
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
  }
  testCompile('org.robolectric:shadows-support-v4:3.0')

Has anyone experienced this issue?
Comment: Where do you get this error, in Android Studio, or on command line. Simple examples can be found at https://github.com/nenick/AndroidStudioAndRobolectric
Answer: The problem was somewhere with the v4 library. I solved it by excluding v4 in my build.gradle.
 testCompile('org.robolectric:robolectric:3.0') {
    exclude group: 'commons-logging', module: 'commons-logging'
    exclude group: 'org.apache.httpcomponents', module: 'httpclient'
    exclude group: 'com.android.support', module: 'appcompat'
    exclude group: 'com.android.support', module: 'support-v4'
    exclude group: 'com.android.support', module: 'recyclerview-v7'
  }


Algorithm to find the probability of a number given the probability of another number?

Question: Let me preface that I'm not sure if this is even possible and I'm unsure of what math principals would apply but I'm trying to build an algorithm for a sports betting project that can find the probability of a number given the following assumptions:

A QB has a 53% chance of going over 282.5 passing yards (I'm getting this line and odds from the sports book's implied odds)

In their previous games they had the following passing yards:
[262, 308, 282, 309, 249, 466]

The team they are playing has given up the following passing yards to QBs in previous games:
[316, 364, 146, 290, 222, 186]

Are there any math principles that could estimate the probability of the QB going over 249.5 yards?
I've thought maybe calculating the z score for the QB's previous yards might be it:
z = (x − μ) / σ

μ = 312.67
σ = 72
z = (249.5 - 312.67) / 72
P(x>Z) = 0.81 or ~81% chance of going over

But that doesn't really factor in the assumption that they have 53% chance of going over 282.5 yards or the opponent's previous yards allowed.
So with that I'm not sure if this is possible, or if more information / data is needed or if there's a completely different math principle used to solve something like this.
Comment: There are many issues lurking here, so let me just ask about the first one that crops up: *how do you know that* "A QB has a 53% chance of going over 282.5 passing yards"?  That kind of assertion appears in some textbooks and exam questions, but it's never true of the real world, so it must be code for some kind of information.  What is that information?
Comment: Will you change "principal" to "principle", and round the numbers to two or three digits after the decimal point? That would make the question more inviting of a serious answer.
Comment: @whuber that's correct, I should've explained in the question, I'll go back and edit. But those are the implied odds that I get from sportsbooks
Comment: Do you have access to more than 6 data points? And do you know how the score of the QB (first vector of data) are related to the score of the QBs in the team (second vector of data)?
Comment: @CamilleGontier I could probably go back further seasons for more data points, although I'm not sure if they would be as relevant since rosters / defenses etc. change year to year. So right now both vectors are just reflecting the current NFL season.

The 2nd vector is just based on how the defense he's playing has done vs previous QB's they've gone againse, so I was thinking if they've given up more yards than the league average (I probably need the league average now to factor that in maybe?) then that might factor in to how well the QB might do
Comment: A major issue here is the distinction between a true underlying probability and an estimate from data (which of course may not be very reliable if there isn't much data). You seem to treat the 53% as some true underlying probability, at least you don't know what the data basis of it is. Then you try to estimate something from the data that you have, but there is no guarantee that this is compatible with the 53%, and I don't think there is enough information to bring these together in a principled way.
Comment: @ChristianHennig Thanks for the reply, yeah I understand these are all estimated probabilities, the 53% is based off of sharp sportsbooks so I'm treating that as the basis and then trying to deduce a probability for a different line using that.
Comment: @MattF. updated the OP, sorry about that, I appreciate the formatting tips and spelling correction!
Answer: Your question is primarily concerned with $P(Y|A)$ where Y is allowed yards for your QB of interest and you condition that probability on the opposing team's historic allowed yards.
The comments on your question are correct that there is a lot of unknown variables or model decisions here, but if you are comfortable either assuming things for convenience of calculation or with being representative of the uncertainty, then you can probably still get a model for it with varying certainty.
If you know this QB gets >= 282.5 yards 53% of time unconditional on opposing team (averaged), then a question is what is the distrib of passing yards for a player?
It may be fine to assume Gaussian for Y if they always perform similarly each time independent (enough) of the opposing team and other external factors.
Given the (very small amount of) data, the assumed model, and an accepted 53% prob at that point, you can construct a Gaussian for Y that satisfies the data and probability constraint. Fit a Gaussian whose 53% of cumulative prob is at the 282.5 yards and hold that as true as you find the sample standard deviation given that constraint. The result can serve as Y.
The same Gaussian assumption could then apply to A for the opposing team. Similarly fit it the best you can with the data available and fill in any variables with best guesses or use em as parameters to explore possibilities.
You then may think of that as two opposing forces Y vs A and so you can think of how they would interact to one another. With our assumption of Gaussians, you could take the convolution and get a resulting Gussian that would indicate the probability of passing yards Y given team's allowed yards A. Y * A
Then you could do your z score test and it at least incorporates all the information at the cost of what may be a naive model.


Problem in undertsanding the definition of Neighborhood (and it's followed corollaries) in Metric Space Topology

Question: Mtric Sets : (Topology)

(1) Definition : Let $(M,d)$ be any metric set. Let $p$ be a fixed
point in M, and let ϵ be any positive real number. We define a
'neighborhhod $N(p,ϵ)$ of $p$, with radius $ϵ$ as follows :
$N(p,ϵ) = \{q \in M : d(p,q) < ϵ\}$.

(2) Let $A$ be any set with metric defined by $d(p,q) = 0$ if $p=q$, and
$d(p,q)=1$ if $p \neq q$. Then $N(p,ϵ) = p$ if $ϵ \leq 1$ and $N(p,ϵ) = A$.
(3) A 'deleted neighborhood $N^{′}(p,ϵ)$ is defined as follows :
$N^{′}(p,ϵ) = {q, 0,d(p,q)<ϵ}$. Note that, $N^{′}(p,ϵ)$ has precisely
one point less than $N(p,ϵ)$ that is, $N^{′}(p,ϵ) = N(p,ϵ) - {p}$.

I'm unable to undertsand these 3 points in terms of Metric Space topology, I want logical (with Cantors) explanation of these 3 points.
Edit :
(1) I did undertsnad the first definitons more or less, since it's the key point I want some detailed (geometrical wise) explanation of this definiton along with the rest 2 points.
Yes, I tried to think about it, but I'm not convinced enough by my way of thinking, I'm missing the core understanding of it.
(2) Yes, I thought in terms of $\mathbb{R}^2$. $N(p,ϵ)$ is the set of points insde a circel with center $p=(a,b)$  and radius $ϵ$, described as : $\{x,y : (x-a)^2+(y-b)^2 < ϵ^2\}$.
(3) So, the point (1) I undertsnad in the sense of given meaning but I can't undertsand when I use the same key definition to understand the points (2) and (3).
Comment: What don't you understand?
Comment: In the definition, try using set notation: $N(p,\epsilon) = \{q \in M : d(p,q) < \epsilon\}.$ What does this mean geometrically? Think of what happens in $\mathbb{R}^2.$
Comment: have you tried to think about it yet? like, write down points with neighborhoods or something?
Comment: Formatting tip:  use `\{` to get `{` in MathJax
Answer: For (1), maybe instead of thinking of an arbitrary metric space, just think of $\mathbb{R}^2$ with the usual Euclidean metric, i.e. just the 'distance' that you're used to in everyday life. More intuitively, think about an infinitely large sheet of paper where you can measure distance with a ruler. First thing you do now is draw any point on this paper and call it $p$. For convenience, let's fix $\epsilon = 1$ but note that any positive radius would be possible. So with that analogy in mind, what is now $N(p,1)$? We have that
$$N(p,1) = \{x \in \mathbb{R}^2 | d(p,x) < 1\},$$
so all points $x$ on your sheet of paper that are less than the distance 1 away from your initial point $p$. If you actually draw this on a piece of paper it should be clear to you that with the distance we are used to this leads to a circle of radius 1 around $p$, just without the border at the outside (these points would be exactly at the distance 1 from $p$.)
The thing now is, we can actually use this definition for other metrics, or 'distance functions' than the one we are used to in everyday life. For instance we can try to see what happens if you apply this reasoning to the metric you have defined in (2). Be aware that this doesn't work like a normal 'infinite sheet of paper' anymore, so you might have to adapt your intuition a bit.


jquery cookie not working

Question: hey people i'm using a jquery plugin for creating cookies which seems to be working perfect when i run it on localhost but when I tested in the server it's not working as i expected.
below is my file testcookie.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<link rel="shortcut icon" href="3.ico">

hello there

result= no alert
here's the demo
http://namadda.com/demo/testcookie.php
onething i noticed just now is that click view source and all the script link is working but jquery.cookie.js isn't showing up, instead i'm getting error 406 when i clicked jquery cooke link on view source page. But it's present on server like other plugins.
Comment: What is not working? The value of the cookie is not being shown?
Comment: can you create jsfiddle use case to demonstrate it doesn't work?
Comment: And what are you expectations? Do you use an IE or a different browser? As concerned as IE this explorer has different page zones with different security options. Check these first if cookies are allowed in your zone, when the page was on the server.
Comment: Unless you are looking for cross site usage I'd look into HTML5 localStorage and sessionStorage as a more long term solution. Especially as some countries will in the future require websites to ask explicit permission to store cookies on someone's computer. Check out [Amplify.js](http://amplifyjs.com/) for an easy JQuery implementation.
Comment: it gives you undefined???? or do you have a error report for us
Comment: i solved this problem by renaming the file jquery.cookie.js
Answer: The best solution is renaming jquery.cookie.js file to something like jquery_cookie.js
It was the best solution for me, because I don't have permission to modify mod_security
Comment: What does mod_security have to do with this? Can you explain why renaming the file all of the sudden works?
Comment: Works for me in Magento2 I just renamed my file from jquery.cookie.js to jquery-cookie.js
Answer:
Make sure that the JQuery and js/jquery.cookie.js js files exist at the server.[1]
Set the expiry date, so that the cookie doesn't get destroyed after the session.
Set a path, so that your cookie is accessible from your whole site (optional).

Combining 2 and 3: $.cookie("example", "foo", {expires:7, path:"/"}) - Life time of 7 days
[1] A common novice mistake.
Comment: I forgot the expires setting which made firefox/safari destroy the cookie when the browser was closed, thanks :)
Answer: Renaming the file jquery.cookie.js to something else should succeed.
Answer: When I visit http://namadda.com/demo/js/jquery.cookie.js I get a 406 Not Acceptable HTTP error.

An appropriate representation of the requested resource
  /demo/js/jquery.cookie.js could not be found on this server.
Additionally, a 404 Not Found error was encountered while trying to
  use an ErrorDocument to handle the request.

Something is not configured properly on your server.

jquery cookie not working


How to work with GMSMapViewDelegate in view

Question: GMSMapViewDelegate how to work in view where I can access infwindow maker function Swiftui
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: I don't get the question, but I think you need to access the UIWindow instance.
I made a simple ViewModifier that allows you to access the window your view is being displayed in.
Usage:
Text("Hello World")
  .onWindow { window in
    // ...
  }

Implementation
extension View {
    public func onWindow(_ foo: @escaping (UIWindow) -> Void) -> some View {
        self.background(WindowGrabber(onWindow: foo))
    }
}

private struct WindowGrabber: UIViewRepresentable {
    let onWindow: (UIWindow) -> Void

    func makeUIView(context: Context) -> UIView {
        let view = UIView()
        view.backgroundColor = .clear
        DispatchQueue.main.async {
            if let window = view.window {
                self.onWindow(window)
            }
        }
        return view
    }

    func updateUIView(_ uiView: UIView, context: Context) {
        // ...
    }
}

Comment: struct GoogleMapsView: UIViewRepresentable { I have markers at map now I want to show custom info window according to mine requirements I am very confused how I will use GMSMapViewDelegate here in this structure to use this function mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView { } I need help how to access GMSMapViewDelegate to use

}


How do I reliably check if an attribute is defined for an object?

Question: Sometimes I create Objects with the x attribute defined, sometimes I don't.
class Object(models.Model):
    x = models.IntegerField(blank=True, null=True)

I want to create a subset of my Objects for which x is not defined at a point in my app:
[o for o in os if not hasattr(o,'x')]

I've being playing around in the shell, and I don't get the results I want.
>>> o = Object()
>>> o.save()
>>> o.id
1L
>>> hasattr(o,'x')
True

Is checking x == None sufficient?
Answer: Yes, checking x is None is sufficient.
Any instance of Object will always have the attribute x, regardless of whether you set it - it'll just be None if you didn't set it.
Comment: It should be done with ``x is None``, see (PEP 8)[http://www.python.org/dev/peps/pep-0008/#id37]


Cannot change Drush version from 6.1.0 to 7.0

Question: I am trying to update my version of Drush to include the Omega commands. For this I think I need 7.0. I have run composer global require drush/drush:7.0.0-alpha5 and this installs the package but when I check drush version it still says Drush Version   :  6.1.0 How do I change my version of Drush to 7.0?
Comment: I found a way to do this using 'brew install --HEAD drush' followed by 'brew switch drush HEAD'
Answer: I found a way to do this using brew install --HEAD drush followed by brew switch drush HEAD The full article where I found this is here, under Installing Drush 7.x dev


camera crashes when not taking picture

Question: I have a simple activity that when clicking a button, the picture is set to the ImageView.
When I open the camera and take the picture, it is fine and the picture is loaded to the ImageView.
But if I open the camera app via the button, and cancel(press the back button), then the application crashes.
I'd to know how to fix it. Thanks in advance.
Activity
    import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SituationStatusActivity extends AppCompatActivity {
ImageView imVCature_pic_first;

private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
static final int REQUEST_IMAGE_CAPTURE = 1;
String imageFilePath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_situation_status);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    overridePendingTransition(R.anim.fadein, R.anim.fadeout);

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
     imageFilePath = Environment.getExternalStorageDirectory().toString()+"/Android/data/com.my.app/Image-"+timeStamp+".png";

    imVCature_pic_first = (ImageView) findViewById(R.id.nirPic);

    Button uploadPic = (Button) findViewById(R.id.picUploadButton);
    uploadPic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {    /*************************** Camera Intent Start ************************/
            File imageFile = new File(imageFilePath);
            Uri imageFileUri = Uri.fromFile(imageFile); // convert path to Uri
            // Standard Intent action that can be sent to have the camera
            // application capture an image and return it.
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);   // set the image file name
            startActivityForResult(intent, 1);
            /*************************** Camera Intent End ************************/
        }
    });

}

public void onActivityResult( int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 1) {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = false;

        //imageFilePath image path which you pass with intent
        Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

        //rotate image by 90 degrees
        Matrix rotateMatrix = new Matrix();
        rotateMatrix.postRotate(270);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
        imVCature_pic_first.setImageBitmap(getRoundedCornerBitmap(rotatedBitmap,500));
        imVCature_pic_first.setScaleType(ImageView.ScaleType.FIT_XY);
    } else {
        Toast.makeText(getApplicationContext(),"not taken", Toast.LENGTH_LONG).show();
    }

}

public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
            .getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    final RectF rectF = new RectF(rect);
    final float roundPx = pixels;

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);

    return output;
}
}

LogCat error
            java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=0, data=null} to activity {fastner.israel.nir_zabari.onelove/fastner.israel.nir_zabari.onelove.SituationStatusActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3688)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3731)
                                                                                at android.app.ActivityThread.access$1300(ActivityThread.java:162)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1398)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5430)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
                                                                                at fastner.israel.nir_zabari.onelove.SituationStatusActivity.onActivityResult(SituationStatusActivity.java:83)
                                                                                at android.app.Activity.dispatchActivityResult(Activity.java:6299)
                                                                                at android.app.ActivityThread.deliverResults(ActivityThread.java:3684)
                                                                                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3731)
                                                                                at android.app.ActivityThread.access$1300(ActivityThread.java:162)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1398)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5430)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:706)

Comment: Since when did stackoverflow become fix-my-code.com? you should be asking a specific question to understand your problem, not ask us to fix the code for you. It doesn't look like you did any work to try to understand your problem. Show some due diligence, won't ever learn that way.
Comment: You are right. I did not expressed myself clearly. My intent was to understand what is the problem, but in order to fix it.
I emphasized on making the code work, and not understanding the problem. I did searched in google, went to developer.android, checked other StackOverFlow threads, but did not manage to understand how to fix it (understand the problem, and fix it after understand what is wrong).  @JoxTraex
Answer: You need to check resultCode along with requestCode as for cancelling the camera, you will get null intent data in your onActivityResult
Change your code to as below:
public void onActivityResult( int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 1 && resultCode == RESULT_OK) {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = false;

        //imageFilePath image path which you pass with intent
        Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

        //rotate image by 90 degrees
        Matrix rotateMatrix = new Matrix();
        rotateMatrix.postRotate(270);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
        imVCature_pic_first.setImageBitmap(getRoundedCornerBitmap(rotatedBitmap,500));
        imVCature_pic_first.setScaleType(ImageView.ScaleType.FIT_XY);
    } else {
        Toast.makeText(getApplicationContext(),"not taken", Toast.LENGTH_LONG).show();
    }

}

PS: try to avoid using hardcoded value for requestCode, declare it as constant variable.
Comment: For better programming practices, hardcoded values should be avoided. For ex, you are using a hardcoded key value for a bundle that is used in multiple places. Now if you want to change that key name, you need to change it to all places where it was using. If you declare it as constant, you just need to change the value of that constant on a single place.
Comment: Thank you for the comment!
Why to avoid using hardcoded value for the requestCode? @Gagan singh
Answer: In your onActivityResult method, after checking for requestCode check for resultCode. resultCode returns RESULT_OK if you accepted the image from camera and RESULT_CANCEL if you didn't accept the image from camera. In your case your not accepting any image from camera and coming back to the activity so resultCode will be RESULT_CANCEL. If you wont check condition for resultCode then app will crash.
public void onActivityResult( int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 1) {
      if (resultCode == RESULT_OK) {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = false;

        //imageFilePath image path which you pass with intent
        Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);

        //rotate image by 90 degrees
        Matrix rotateMatrix = new Matrix();
        rotateMatrix.postRotate(270);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
        imVCature_pic_first.setImageBitmap(getRoundedCornerBitmap(rotatedBitmap,500));
        imVCature_pic_first.setScaleType(ImageView.ScaleType.FIT_XY);
       }
       else{
            // your code in cancel condition
       }
    } else {
        Toast.makeText(getApplicationContext(),"not taken", Toast.LENGTH_LONG).show();
    }

}

Comment: Hi.
I'm getting the same issue.
Mainly, I wanted to know how to handle the RESULT_CANCEL part.

camera crashes when not taking picture


Image Recognition Intro: Identifying obects on googlemaps

Question: I know, already so many 'how to compare 2 images' question out there.
I have looked at many and could not find anything relevant to my particular need - I apologize if I have missed something I should not have !
So,
Firstly, I am familiar with c#, completely unfamiliar with image processing and recognition.
Secondly, I am not looking for someone to hand me a complete answer, simply seeking to point myself in the right direction to tackle the job in hand.
Objective:
I am seeking to identify the location of certain physical structures on images taken from google maps.
Unfortunately I cannot tell or show what those structures are, but we can use an example, let's say it's a round swimming pool.
Key point maybe, I'm looking to find a small object 'within' a large image.
Considering I've never tackled image processing before, I appear to be completely over whelmed with options of libraries available, names and terminology of functions and capabilities... and I seem to be spending hours going down dead end avenues.
A lot of reading seems to be comparing 1 image with another, rather than an image 'within' an image.
So far AForge & Open CV are the obvious names that have been seen a lot .. but I really can't work out which of them will do this specific job.
Simply, could someone be kind enough to point me in the right direction to get started?
I'm really trying to narrow reading down to subject matter that is relevant to my case.

Basic Principles
Libraries with the required capability.

Any guidance much appreciated.
Many Thanks
Simon
Comment: take a look at "opencv" and its C# wrapper "opencvsharp"
Answer: If you want to detect shapes for example, you can use opencv.
Unfortunately opencv is written in c++ and you would have to write your wrapper.
Instead you can use EmguCV. Try to look at this: link


Detect process that is doing an outbound DDoS attack

Question: My web host has informed me that my Fedora server is the source of an outbound DDoS attack on somebody. The web host didn't give any other information. How can I find out what process is doing the attack so that I can stop it? I realize this is vague but I think if I can view outbound traffic in some way I might be able to find the process that is sending it.
I appreciate I will need to find the point of entry once I have stopped the attack, and likely will need to re-image the server with updates.
Thanks in advance.
Comment: That doesn't sound like a very good hosting company if they didn't provide you with any information about the nature of the DDOS and how they made their determination.
Comment: http://nethogs.sourceforge.net/
Comment: @quanta thanks, I will try that. @ joewerty - yes you're right about the host!
Comment: Are you running a DNS server?  It could be a DMS reflection attack.
Comment: @Zoredache no not running a DNS server.
Comment: The first 'D' in DDoS stands for Distributed, which involves more then just one server-- if it's really a DDoS it's not just your one server. Another reason to get more information from your provider.
Answer: You could use something like iptraf (available in a repo near you). This will tell you which ports are being used on your system and at what rate. Once you know which ports are being used you can then use netstat to find the process attached to each port. So if for example you identify that your port 6666 is active you can use
<code>netstat -tunp | grep 6666
tcp   0  77352 192.168.254.188:56405  192.168.254.181:6666   ESTABLISHED 30072/nc
</code>
As you can see in this demo pid 30072 is using the port.
Answer: Please note that you may find nothing at all. There is a chance that your system has been compromised and the tools you are using don't give the correct answers they should. Even using the system for further analysis could lead to more problems if there's a backdoor and you are entering your passwords for example.
The only solution is to shut down the server and consider it being compromised. If you want to find the source in a safe way you'd had to examine the system in an isolated environment.
Comment: Good points, unfortunately it is hosted by a web host, the only way I can access it is via the Internet (no physical access), and I really want to eventually find the entry point if I can so that I can prevent it happening again.


Domain or range?

Question: I am doing some questions on contraction mapping and the first part of the question is:

I am not sure what the question is asking for and how to do it.
Any help is hugely appreciated! thank you
Comment: The question is asking you to find explicitly the set $\{f(x):x\in[0,3]\}$. What level of calculus can you use?
Answer: You want to find the range of $f(x)$ on the domain $[0,3]$; that is, the set $I=\{f(x)\,|\,x\in[0,3]\}$. Since the function is continuous on $[0,3]$, the set will be equal to
$$I=[\min_{x\in[0,3]} f(x),\max_{x\in[0,3]} f(x)].$$
To find the minimum and the maximum of the function, take a look at the sign of its derivative:
$$\frac{\mathrm{d}}{\mathrm{d}x}\left(\frac{x^2-2x}{2x+1}\right)=\frac{2(x^2+x-1)}{(2x+1)^2}$$
We see that the sign is determined by the sign of $x^2+x-1$, which is negative on $\left[0,\frac{\sqrt{5}-1}{2}\right]$, zero at $\frac{\sqrt{5}-1}{2}$, and positive on $\left[\frac{\sqrt{5}-1}{2},3\right]$.
Hence $$\min_{x\in[0,3]} f(x)=f\left(\frac{\sqrt{5}-1}{2}\right)=\frac{-3+\sqrt{5}}{2}$$ and $$\max_{x\in[0,3]} f(x)=\max\left\{f(0),f(3)\right\}=f(3)=\frac{3}{7},$$ so $I=\left[\frac{-3+\sqrt{5}}{2},\frac{3}{7}\right]$.
Answer: The question is asking you to find the set of all numbers of the form $f(x)$, where $x$ ranges over all numbers $0\le x\le 3$. A hint at how to do it: Start by computing a few such values (e.g., $f(0)$, $f(3)$, and perhaps a few more) to get a general feel for what is going on. Next try to sketch the graph of the function based on what you have found. That will at least get you started. Then, depending on how rigorous your arguments need to be, you'll need to refer to some theorems in order to establish your result.
Answer: You are being asked to find the set of all numbers $f(x)$ for $0\le x\le 3$, where $f$ is the function
$$f(x)=\frac{x^2-2x}{2x+1}\;.$$
For example, $f(0)=0$, $f(1)=-\frac13$, $f(2)=0$, and $f(3)=\frac37$, so $-\frac13$, $0$, and $\frac37$ are all in the set that you're asked to find. Of course $[0,3]$ is an infinite set, so looking at specific values of $f(x)$ for $x\in[0,3]$ isn't going to help much.
The function $f$ is continuous on its domain, which includes every real number except $-\frac12$ (why?), and $[0,3]$ is a closed interval in the domain of $f$, so you can use the extreme value and intermediate value theorems to answer the question. By the extreme value theorem you know that $f$ attains a minimum value on $[0,3]$ at some point $a\in[0,3]$ and a maximum value on $[0,3]$ at some point $b\in[0,3]$. By the intermediate value theorem you know that if $f(a)<y<f(b)$, there is some $x$ between $a$ and $b$ such that $f(x)=y$. Thus, the values of $f(x)$ for $x\in[0,3]$ are precisely the real numbers between $f(a)$ and $f(b)$, inclusive, i.e., the closed interval $[f(a),f(b)]$. That interval is what you're asked to find.

Domain or range?


Is there any way to use the Electronic Drum Kits as regular midi drum kits (instead of as summing stacks) in Logic Pro X?

Question: I have created a MIDI script that I use for the standard drum kits that come from Logic Pro X, eg. "Blue Ridge" or "Bluebird".

However, I cannot use this script against the electronic drum kits (e.g. "808 Flex" or "Above and Beyond") as those are showing up as "DMD" and do not have the option to add MIDI controls.

Is there any way to use the MIDI controls, such as Scripter, Modifier, Modulator, etc, on an Electronic Drum Kit like I can on the regular Drum Kits?
Answer: What is Drum Machine Designer (DMD)?
Drum Machine Designer (DMD) is basically a Summing Stack with a grid/pad interface, with each pad mapped to a track in the track stack which gets triggered by a note (C1, C#1, D1...) designated on respective pads.

So for 808 Flex :
key C1 is mapped to Kick 1 which is a sample named Kick_1_808Flex.aif loaded in the first pad as a One Shot Sampler instrument.
If DMD is record enabled and key C1 is pressed on a MIDI keyboard then the corresponding track hosting Sampler (Kick 1) gets activated and a particular note, which you can define as the Root Key in the bottom left corner of the sampler interface, gets played.
Is there any way to use the MIDI FX
As the MIDI FX slot for DMD is unavailable so it's fairly obvious that as of ver 10.7.2 it is not (directly) possible to use MIDI FX on a DMD.
Side note : DMD is controlling multiple instruments and each grid/pad is a software instrument track, with a dedicated channel strip in the mixer, which takes MIDI input and hence can be manipulated individually by MIDI FX.

Is there any workaround?
Yes.

Load an External Instrument in another track

Choose 'IAC Driver Bus' from the MIDI Destination dropdown

Leave every other option as it is

Make sure the MIDI In Port of DMD is set to 'All'

Record Enable the External Instrument track and record your MIDI.
After you're done, 'Record Enable' DMD and play recorded MIDI region from the start, DMD will playback the MIDI.
As 'External Instrument' has MIDI FX slot, you can put any MIDI FX on it and DMD will play it back

Caveat : Only recorded MIDI will work, you cannot live-record it.

Reference Logic Pro ver : 10.7.2
Comment: The workaround looks awesome, I will try it. THANK YOU!
Comment: I don't know bout v10.7.2, but in 10.5.1 there's an easy workaround. You assign one of the sampled drummer kits that allows MIDI scripts to the channel, turn on patch merging and set it to merge only the instruments, and then select one of the DMD kits.


Exchange Server 2010 ActiveSync SSL Certificate Problem

Question: We have a problem related Exchange Server 2010 Activesync.My problem is;When I connecting to activesync from outside, I am receiving the following error.
<code>ExRCA is testing Exchange ActiveSync.
The Exchange ActiveSync test failed.

Test Steps

Attempting to resolve the host name mail.xxxxx.com in DNS.
The host name resolved successfully.

Additional Details
IP addresses returned: xx.0.x3.4
Testing TCP port 443 on host mail.x.com to
ensure it's listening and open.
The port was opened successfully.
Testing the SSL certificate to make sure it's valid.
The SSL certificate failed one or more certificate validation checks.

Test Steps

Validating the certificate name.
Certificate name validation failed.
Tell me more about this issue and how to resolve it

Additional Details
Host name mail.x.com doesn't match any name found
on the server certificate CN=xxxxxx.
</code>
Thanks in advance all your help.
Comment: What are the EXACT names in your cert? Is it a standard SSL, wildcard, UC, self signed?
Comment: Do you have a SSL certificate running? is that self signed or actually bought with one of the major SSL companies?
And is webmail working from an external address ?
Answer: If the DNS name you're connecting to externally (eg mail.x.com) is not one of the names on the SSL cert configured for Exchange (andr for ISA/TMG if thats how you're publishing Exchange) then you'll see that error.
Exchange installs with a self-signed SSL cert but you need to replace that with a proper SAN cert for external access scenarios like this, or you face a nightmare of configuration and support issues.
Here is some guidance for setting up an SSL certificate for Exchange 2010.
http://exchangeserverpro.com/configure-an-ssl-certificate-for-exchange-server-2010


hyn multi-tenant v5.2 - how to create the website, hostname and associate

Question: I created a class 'CreateTenant' in 'App\Console\Commands' and I can even create the website:
<code>    $website = new Website();
    app(WebsiteRepository::class)->create($website);
</code>
But I am not able to create a hostname and perform the association between them.
I would like to create subdomains, something like sub1.domain.local, sub2.domain.local, etc
I imagine I should use something like this...
<code>    $hostname = new Hostname();

    app(HostnameRepository::class)->attach($hostname, $website);

    $hostname->website()->associate($website)->save();
</code>
... but I'm not succeeding. And I'm also not sure how to tell the FQDN I'd like
Answer: So easy that I can not even believe it took me 2 days to find the answer, but really their documentation leaves a lot to be desired...
<code>$website = new Website();
$website->managed_by_database_connection = env('DB_CONNECTION','system');

app(WebsiteRepository::class)->create($website);

$hostname = new Hostname();
$hostname->fqdn = 'sub1.domain.local';
app(HostnameRepository::class)->attach($hostname, $website);

app(Environment::class)->tenant($website);
</code>


How to overwrite Paragraphs Item on subpages?

Question: I am using a couple of Drupal Paragraphs Items in full-size edge-to-edge view with Bootrap's container class. It's working great.
I've applied a container class to paragraphs-item--service.tpl.php
However how can I overwrite the paragraph item on a subpage that uses a 2 column layout?
Answer: Instead of putting it into the template, a better solution would be to use the hook_entity_view_alter to add the classes based on some conditions.