How can I use Jackson mapper for java.io.Serializable type fields?

Question: I have a situation where POJOs extend an abstract super class, which defines methods like getId() and setId() using java.io.Serializable type (code shown below). Whenever I am deserializing a JSON string to my concrete POJOs, I get following exception:
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.io.Serializable, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
 at [Source: java.io.StringReader@6fd90825; line: 1, column: 2] (through reference chain: com.demo.jackson.AClass["id"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
    at com.fasterxml.jackson.databind.DeserializationContext.instantiationException(DeserializationContext.java:716)
    at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:140)
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:525)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:99)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:242)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:118)
    at com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1270)
    at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:897)

The Java codes:
Abstract Super Class
public abstract class AbstractClass {
  protected abstract void setId(final Serializable id);
  protected abstract Serializable getId();
}

Implementation Class: AClass
public class AClass extends AbstractClass {
  private Long id;
  private String name;

  public Long getId() {
    return id;
  }
  public void setId(Serializable id) {
    this.id = (Long) id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
}

Implementation Class: BClass
public class BClass extends AbstractClass {
  private String id;
  private String name;

  public String getId() {
    return id;
  }
    public void setId(Serializable id) {
    this.id = (String) id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
}

The testing class
public class JsonSerializerTest {
  public static void main(String[] args) throws Exception {
    final ObjectMapper objectMapper = new ObjectMapper();
    serialize(objectMapper);
  }

  private static void serialize(final ObjectMapper objectMapper) throws Exception {
    final String jsonString = "{\"id\":123,\"name\":\"AClass\"}";
    final ObjectReader objectReader = objectMapper.reader(AClass.class);
    final AClass a = objectReader.readValue(jsonString);
    System.out.println(a);
  }
}

Could someone provide some pointers?
~ NN
Comment: i dont think serializable is a type, its an interface. also your abstract getid is of type serializable but your concrete method is of type long
Comment: Yes, I am aware of this and this is something by design. Our framework team provides such interfaces and abstract classes whereas the implementations are provided by the app development team.
Answer: We had same situation, we have to use java.io.Serializable as ID in entities. With Serialization we have no problem, but in Deserialization we have the issue. In our application we use String in JOSN objects, so Stdandard StringDeserializer and it is working - in theory you can use it with any implementation of a Serializable. (Apache CXF and Jackson 2.4.1 is used):
Initialize Jackson provider:
    // Jackson JSON Provider
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new IdentifiableDeserializableModule());

    JacksonJaxbJsonProvider jp = new JacksonJaxbJsonProvider(mapper, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS);
    jp.configure(SerializationFeature.INDENT_OUTPUT, indentJson);

And the module:
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.Serializable;

/**
 * Jackson module to deserialize java.io.Serializable class.
 */
public class IdentifiableDeserializableModule extends SimpleModule {
    public IdentifiableDeserializableModule() {
        addDeserializer(Serializable.class, new StringDeserializer());
    }
}

Answer: The solution that worked for us is shown below.
Abstract Class: Use Object instead of Serializable. I know Serializable suits better for IDs, but this issue was a kind of blocker for our app and we opted this solution.
public abstract class AbstractClass {
  protected abstract void setId(final Object id);
  protected abstract Object getId();
}

Implementation: AClass
public class AClass extends AbstractClass {
  private Long id;
  private String name;

  public Long getId() {
    return id;
  }
  public void setId(Object id) {
    // We need this inverted way to get a Long from a String, but we didn't have any other option!
    this.id = Long.valueOf(Objects.toString(id));
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
}

Implementation: BClass
public class BClass extends AbstractClass {
  private String id;
  private String name;

  public String getId() {
    return id;
  }
    public void setId(Object id) {
    this.id = Objects.toString(id);
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
}

I do not know if this is an elegant solution or not (compromising(?) Serializable for Objects), but please feel free to post a better one.
Thanks.
~ NN
Comment: This is not compromising at all. The implementation is very good. My only concern is related if we are are not free to change the json structure. For example in the Serializable object, we can have String or Long and not only nested objects. If there is such a restriction, this cannot be implemented with this way, I suppose.
Answer: I recently ran into this situation.  The solution I went with approaches the problem similar to the Answer posted above by Niranjan in using Object in lieu of Serializable. However, instead of using get/set methods with Object  or attempting to create a separate custom de-serializer I leveraged the constructor to keep the field type as Serializable while allowing Jackson to provide an instance of Object.
I used the @JsonCreator annotation on the constructor and then individual @JsonProperty annotations on the parameters (this isn't required in Java 8 using the Parameter Names Module making this an even cleaner solution).
This answer also contains extensive information regarding @JsonCreator.
For the purpose of brevity in the answer the class defined below is immutable (all fields final and no setters).
public class PersonLocation {
    private final Serializable id;
    private final String name;
    private final Location location;

    /**
     * Constructor leveraged by Jackson to de-serialize an incoming
     * PersonLocation instance represented in JSON.
     *
     * @param id The instance identity.
     * @param name The name of the person.
     * @param location The location of the person.
     **/
    @JsonCreator
    public PersonLocation (
        @JsonProperty("id") Object id,
        @JsonProperty("name") String name,
        @JsonProperty("location") Location location)
    {
        //This safety check and cast should be a static utility method.
        if (!id instanceof Serializable) {
            throw new IllegalArgumentException("Id must be a serializable type.");
        }
        this.id = (Serializable)id;
        this.name = name;
        this.location = location;
    }

    public Serializable getId () {
        return id;
    }

    public String getName () {
        return name;
    }

    public Location getLocation () {
        return location;
    }
}

Answer: I don't know what options you have, but what about overloading the setId methods in the subclasses then make Jackson to ignore those which accept Serializable?
So, ClassA would look like this:
public class AClass extends AbstractClass {
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }
    @JsonIgnore
    public void setId(Serializable id) {
        this.id = (Long) id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

This solution is not too elegant but it may be acceptable for you. If not then I suggest to check Jackson's custom serialization and/or polymorphic serialization support.
Comment: Thanks for this, but I am afraid this will not work because `@JsonIgnore` is to ignore the property. So, with this approach my ID value won't be populated during deserialization. Let me glance at the links you provided. I had seen these custom and polymorphic serializations, but somehow I didn't find a good example similar to my problem.
Comment: Ok, but have a look on this question regarding the overloaded methods with JsonIgnore: http://stackoverflow.com/questions/6346018/deserializing-json-into-object-with-overloaded-methods-using-jackson


Evaluating an infinite sum with the term $x^{\rho^i}$

Question: When calculating asset prices with lognormal productivity, I ran into the follow expression for asset price:
$$
\sum_{i=1}^\infty \beta^i \exp\left(\frac{1}{2}\frac{1-\rho^{2i}}{1-\rho^2}\sigma^2\right) x^{\rho^i},
$$
where $x$ is the current productivity level. This does not look like it can be solved directly, so I tried to differentiate w.r.t. to $x$, but the results is not very satisfactory. I guess the difficulty lies in the term involving $x$. Could someone tell me whether this sum has explicit solution? Thanks very much!
Answer: When $\rho > 1$ it is an example of what they call a lacunary series.
Not even the case $\sigma = 0, \beta=1, \rho=2$ has a known (to Maple) closed form:
$$
\sum_{i=0}^\infty x^{2^i}
$$
Comment: In this case $\rho <1$, but I guess the answer is still no?


Trocar Long por BigInteger ou BigDecimal?

Question: Estou tentando ler do teclado um numero inteiro muito grande, vi que existem os tipo BigInteger ou Bigdecimal, não sei se eles são maiores que o Long.
estava querendo ler do teclado numeros com 10 ou 14 algarismos mas o Long não esta suportando,
poderia estar usando um desses dois tipos para fazer isso? como?
 import java.util.Scanner; import java.math.BigDecimal;

 /**
  *
  * @author Mateus
  */
 public class Fatorial {

     /**
      * @param args the command line arguments
      */
     public static void main(String[] args) {
       long a=1,num,fat,res;
         String aa;
         Scanner ler = new Scanner (System.in);

         while (a == 1){
          res=1;

                 System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------");
                 System.out.println("");

                     System.out.println("Digite o numero que vc queira descobrir seu fatorial:");
         num = ler.nextLong();

         for (fat=1;fat<100000;fat++){
             res=fat*res;

             if(res==num)
                 break;
         }

         aa = String.valueOf(fat);

          if (fat == 100000){
             aa = "Não existe numero para esse resultado";
          }
             System.out.println("O numero do fatorial é: "+aa);

             System.out.println("");
             System.out.println("");

                     System.out.println("Digite 1 para calcular novamente ou 0 para sair");
                     a = ler.nextInt();

         }

     }

 }

A ideia do programa é fazer o inverso do fatorial, em vez de se digitar um numero e ter o resultado o fatorial, se digita o resultado do fatorial, e tem-se o numero que chegaria a esta fatorial.
PS. O programa funciona com numero de até  9 algarismos.
Answer: Nesse seu exemplo, substitua a variável res por uma BigInteger, assim:
BigInteger num = BigInteger.ONE;

E no laço for faz assim:
for(fat=1;fat<=100000;fat++){
    num = num.multiply(BigInteger.valueOf(fat));
}

Preste atenção para não abusar e usar valores muito altos.
Answer: O long suporta até o valor de -9,223,372,036,854,775,808 até +9,223,372,036,854,775,807, ou seja, o long dá conta dos 14 algarismos, suportando até 19 algarismos.
Exemplo
public static void main(String[] args) {
    long teste = Long.MAX_VALUE;
    System.out.println(teste);
    System.out.println("Algarismos suportados: " + String.valueOf(teste).length());
}

Saída:
9223372036854775807
Algarismos suportados: 19

Exemplo com BigInteger
public static void main(String[] args) {
    BigInteger teste = new BigInteger("9");
    BigInteger teste2 = new BigInteger("9");
    System.out.println(teste.add(teste2));
}

Saída:
18


The general solution to the differential equation

Question: I am having problems in classifying the differential equation $y''=y(x^2)$ in categories like homogeneous, exact, bernoulli, separable and non-exact so I could have the general solution.
Or would someone help me find the solution
Comment: Almost never do such equations have closed-form solutions. If you can even prove a solution exists.
Comment: @Chappers,Do solved you mean it can not be solved?
Comment: is it $y(x^2)$ or $y(x)^2$?
Comment: @Dr. Sonnhard Graubner ,Square of x is multiplying y
Comment: Oh, so you mean $y''=x^2y$?
Comment: @Chappers, yes it is as you stated in the comment above
Comment: Ah, well, that's different. Using brackets after a function name are ambiguous: $y(x^2)$ normally means $y$ applied to $x^2$.
Comment: I get it. Thanks for noticing the error in my typing
Comment: Is there no solution to this differential equation?
Answer: The General solution to this differential equation would be an infinite series:
$$y(x) = \sum^\infty_{n=0} a_nx^n $$
In this case, the coefficents are pretty odd.  Since $ a_2 = 0, a_3 = 0 $, and the recurrence is every 4 terms.  In this case we have:
$$ a_4 = a_0/12, a_5 = a_1/20, a_8 = a_4/56, a_9 = a_5/72 $$
To find the exact relationship requires some art.  I would go with:
$$ a_{4k} = \frac{a_0}{(4^k)k!(4k-1)(4k-5)...etc)} , a_{4k+1} = \frac{a_1}{4^kk!(4k+1)(4k-3)...etc} $$
The etc. can be rewritten as factorials if needed.
Comment: Completely lost here
Comment: would you provide some literature
Comment: Here is the [wikipedia entry](https://en.wikipedia.org/wiki/Power_series_solution_of_differential_equations) on this method.
Answer: the solution containes the Bessel-function
$$y \left( x \right) =C_1 \,\sqrt {x} \, {{I}_{1/4}\left(1/2\,{x}^
{2}\right)}+ C_2 \,\sqrt {x} \, {{K}_{1/4}\left(1/2\,{x}^{2}
\right)}
$$


General solutions for trigonometry equations

Question: I'm taught that how to find the general solution for example $\cos 5\theta=\frac{\sqrt{3}}{2}$.
But the exercise given by the book is much more complex than the example.
For example, $\sin^2 3\theta+\cos 3\theta+1=0$, $\tan \theta=2\csc2\theta$
I've no idea where to start. Can anyone provide me some resource or guide me for this topic? Thanks
Answer: For the first one, use the Pythagorean identity: $\sin^2 x+ \cos^2 x = 1$ on the sine term, and for the second, re-write it as $\sin \theta \cdot \sin 2\theta = 2 \cos \theta$ and use the double angle formula for sine.
A possible flowchart for these problems might be the following:

Express in terms of sines and cosines
Factorise where possible.

Then to solve each "factor",

Use the appropriate formulae in order for all the trigonometric arguments to be the same (usually double or half)
Apply the Pythagorean identity to bring everything into sines (or cosines).
Answer: In order to solve the given questions, it might be helpful to use certain trigonometric identities. For example if I am going to solve:
$tan\theta=2csc2\theta$, I will first note that $csc2\theta=\frac{1}{sin2\theta}=\frac{1}{2sin\theta cos\theta}$.
In effect we have:
$tan\theta=\frac{1}{sin\theta cos\theta}$ which means
$sin^2\theta=1$, by invoking the identity $tan\theta=\frac{sin\theta}{cos\theta}$ and multiplying.
I leave the last step for you to solve or answer.
Again the idea is that you can use identities in simplifying the given equations.


jQuery in external file not working

Question: I have an external file being loaded via template.php using the following code:
function digital_dots_preprocess_views_view(&$vars) {
  $view = $vars['view'];
  if($view->name == 'work') {
    drupal_add_js(drupal_get_path('theme', 'digital_dots') . '/assets/scripts/fx.js');
  }
}

The JS file is being loaded with the following code:
(function ($) {
    $(".image-overlay").hide();
    //alert('It works!');
})( jQuery );

Un-commenting the alert will trigger the alert however the hide effect doesn't?
Very confused!
Comment: Hi, this is a general problem with your jQuery code, nothing to do with Drupal. It's already been addressed a number of times on this site so there's no point in keeping another version of the same question around. Read up on jQuery.ready and you'll have the answer :)
Answer: If you are getting alert from the JS file than it means your JS file is loading properly, and the problem of hide seems to be causing because hide to be called in the document.ready as following:
// Jquery wrapper for drupal to avoid conflicts between libraries.
(function ($) {
  // Jquery onload function.
  $(document).ready(function() {
    $(".image-overlay").hide();
  });
})(jQuery);

jQuery in external file not working


Converting normal attoparsec parser code to conduit/pipe based

Question: I have written a following parsing code using attoparsec:
data Test = Test {
  a :: Int,
  b :: Int
  } deriving (Show)

testParser :: Parser Test
testParser = do
  a <- decimal
  tab
  b <- decimal
  return $ Test a b

tParser :: Parser [Test]
tParser =  many' $ testParser <* endOfLine

This works fine for small sized files, I execute it like this:
main :: IO ()
main = do
  text <- TL.readFile "./testFile"
  let (Right a) = parseOnly (manyTill anyChar endOfLine *> tParser) text
  print a

But when the size of the file is greater than 70MB, it consumes tons of memory. As a solution, I thought I would use attoparsec-conduit. After going through their API, I'm not sure how to make them work together. My parser has the type Parser Test but it's sinkParser actually accepts parser of type Parser a b. I'm interested in how to execute this parser in constant memory ? (A pipes based solution is also acceptable, but I'm not used to the Pipes API.)
Answer: The first type parameter to Parser is just the data type of the input (either Text or ByteString). You can provide your testParser function as the argument to sinkParser and it will work fine. Here's a short example:
{-# LANGUAGE OverloadedStrings #-}
import           Conduit                 (liftIO, mapM_C, runResourceT,
                                          sourceFile, ($$), (=$))
import           Data.Attoparsec.Text    (Parser, decimal, endOfLine, space)
import           Data.Conduit.Attoparsec (conduitParser)

data Test = Test {
  a :: Int,
  b :: Int
  } deriving (Show)

testParser :: Parser Test
testParser = do
  a <- decimal
  space
  b <- decimal
  endOfLine
  return $ Test a b

main :: IO ()
main = runResourceT
     $ sourceFile "foo.txt"
    $$ conduitParser testParser
    =$ mapM_C (liftIO . print)

Answer: Here is the pipes solution (assuming that you are using a Text-based parser):
import Pipes
import Pipes.Text.IO (fromHandle)
import Pipes.Attoparsec (parsed)
import qualified System.IO as IO

main = IO.withFile "./testfile" IO.ReadMode $ \handle -> runEffect $
    for (parsed (testParser <* endOfLine) (fromHandle handle)) (lift . print)


accessing json data in python and fast api

Question: <code>test_data = {
        "transactions": [{
                "id": 5494,
                "specific_wallet_id": 2079,
                "evaluation_process_transaction_id": 5229,
                "transaction_type": "Earn",
                "points": 9,
                "created_at": "2022-09-20T16:14:19.000+05:30",
                "updated_at": "2022-09-20T16:14:19.000+05:30",
                "custom_wallet_transaction_id": "null",
                "order_meta_data": {},
                "points_validity": "2023-09-20T00:00:00.000+05:30",
                "points_status": "Active",
                "transaction_amount": 450.0,
                "transaction_at": "2022-09-20T16:14:18.000+05:30",
                "tnx_status": "Successful",
                "current_points": 9,
                "programme_id": 4,
                "customer_id": 1,
                "reason_code": "Earn",
                "channel": "app",
                "order_id": "1",
                "transaction_references": "null",
                "points_value": 9.0,
                "issuer": {
                    "id": 1,
                    "name": "oo",
                    "code": "oo",
                    "image_url": "null"
                },
                "partner": null

            },
            {
                "id": 5486,
                "specific_wallet_id": 2079,
                "evaluation_process_transaction_id": 5221,
                "transaction_type": "Earn",
                "points": 9,
                "created_at": "2022-09-20T15:46:15.000+05:30",
                "updated_at": "2022-09-20T15:46:15.000+05:30",
                "custom_wallet_transaction_id": "null",
                "order_meta_data": {},
                "points_validity": "2023-09-20T00:00:00.000+05:30",
                "points_status": "Active",
                "transaction_amount": 450.0,
                "transaction_at": "2022-09-20T15:46:14.000+05:30",
                "tnx_status": "Successful",
                "current_points": 9,
                "programme_id": 4,
                "customer_id": 2189,
                "reason_code": "Earn",
                "channel": "app",
                "order_id": "uuu",
                "transaction_references": "null",
                "points_value": 9.0,
                "issuer": {
                    "id": 1,
                    "name": "oo",
                    "code": "ooo",
                    "image_url": "null"
                },
                "partner": {
                    "id": 1,
                    "name": "qq",
                    "code": "qq",
                    "image_url": "https://d157777v0iph40..net///offers/avis.jpg"
                }
            }
        ],
        "success": "true",
        "error": "null"
    }

results=[]
results.extend(
    [

        AllTransaction(
            issuer_id=Config.evaluation_issuer_id,
            issuer_name="",
            issuer_logo="",
            wallet_id=o["specific_wallet_id"],
            partner=o["partner"],
            points=o["points"],
            points_value_in_currency=(
                o["points"] * 1
            ),
            transaction_at=o["transaction_at"],
            transaction_id=o["id"],
            transaction_type=o["transaction_type"],
            transaction_meta={
                "order_id": o["order_id"],
                "channel": o["channel"],
                "order_meta_data": o["order_meta_data"],
            },
            transaction_name=o["transaction_type"],
        )
        for o in test_data["transactions"]
    ]
)
return TransactionResponse(results=results)
</code>
model code
<code>   class TransactionDetailsPartner(BaseModel):
            partner: Optional[dict] =None
class TransactionDetails(BaseModel):
    points: int
    points_value_in_currency: float
    transaction_id: int
    transaction_at: datetime
    transaction_type: str
    transaction_meta: Optional[dict]
    transaction_name: Optional[TransactionType]
class TransactionDetailsIssuer(BaseModel):
    issuer_id: int
    issuer_name: str
    issuer_logo: str
    wallet_id: int
class AllTransaction(TransactionDetails, TransactionDetailsIssuer, TransactionDetailsPartner):
    pass
</code>
**this is my main method and here my partnerdata is null in one entry at test_data
and in pydantic model i made as optional but still it throwing error if i pass null data how to resolve this                        **
how to access this partner key even it is null and at model or api level is ok.
thanks in advance
Answer: The code that you gave is not valid Python, null is a valid JSON value but in Python it has to be None.
Try to load the string as JSON and then parse it to a Pydantic model.
Comment: i understand but i am calling external api here and i need to loop through json for some reason(i need to append some data) while doing so partner object may have or not data it will give null(from response) if partner data is there i am receiving response if it is null  error is coming.
Comment: I understand that the JSON is coming from somewhere, but as long as you provide `null` rather than `None` to a `BaseModel` that has an optional field, it won't work. It would help if you could create a Minimal Reproducible Example.
Comment: its worked     transaction_meta=o["partner] after reading like this


How to change the line style of ECharts custom graph from solid to dashed or dotted

Question: I created a custom graph using Apache ECharts to draw a vertical line from the input data. Following ECharts documentation and some online examples, I was able to draw the line and custom it with color or width as per the MWE below.
My question is how to configure the line style as dotted or dashed. I searched extensively but could not find any options or documentation on that.

const chart = echarts.init(document.getElementById("chart"));

const render = (_, api) => {
  const start1 = api.coord([api.value(0), api.value(1)]);
  const end1 = api.coord([api.value(0), api.value(2)]);
  const x1 = start1[0];
  const y1 = start1[1];
  const x2 = end1[0];
  const y2 = end1[1];
  const line = {
    type: "line",
    shape: {
      x1,
      y1,
      x2,
      y2
    },
    style: {
      stroke: "blue",
      lineWidth: 3
    }
  };

  return {
    type: "group",
    children: [line]
  };
};

const options = {
  xAxis: {
    min: 0,
    max: 2,
    interval: 1
  },
  yAxis: {
    min: 0,
    max: 4,
    interval: 1
  },
  series: [{
    type: "custom",
    data: [
      [1, 1, 3]
    ],
    renderItem: render
  }]
};
chart.setOption(options);
<!DOCTYPE html>

  <title>ECharts custom line</title>
  <meta charset="UTF-8" />

MWE: https://codesandbox.io/s/echarts-custom-vertical-line-442cv
Comment: You want todo something like [this](https://stackoverflow.com/a/56633946/11629088)
Comment: @kamleshparmar Many thanks, but the `markLine` way is not suitable in this case. I don't want extra lines because I already created my own render to draw the lines. The only configuration that I might have missed is to set the line style to `dashed` or `dotted`. I looked into `markLine` perhaps as the last resort.
Answer: You can easily make custom dashed line in echarts. You need to pass lineDash to the graphic element object.
lineDash is stroke-dasharray attribute of line defining the pattern of dashes and gaps. Pass the values of dashes and gaps in form of an number array.
const render = (_, api) => {
  const start1 = api.coord([api.value(0), api.value(1)]);
  const end1 = api.coord([api.value(0), api.value(2)]);
  const x1 = start1[0];
  const y1 = start1[1];
  const x2 = end1[0];
  const y2 = end1[1];
  const line = {
    type: "line",
    shape: { x1, y1, x2, y2 },
    style: {
      stroke: "blue",
      lineWidth: 4,
      lineDash: [2] // put dash, gap values here
    }
  };

  return {
    type: "group",
    children: [line]
  };
};


Use AJAX with form button to clear checkboxes in separate forms

Question: I have a case where I need to have a Clear button on a form that not only clears out the form it's on, but also clears out checkboxes in other forms and clears data from ctools_object_cache.
The page is a custom search page created by the apachesolr module.  In the sidebar I have multiple blocks that are just 'checkboxes' form elements of taxonomy terms (each block is a separate vocabulary).  The checkboxes are used to select terms, which are written to ctools_object_cache using #ajax in the form when selected.  What I need is to have a Clear button (or link) on the search form that does a few things:

Clears the search field
Deletes items from ctools_object_cache
Deselects the checkboxes in the sidebar forms
Selects a specific checkbox in another sidebar block (labeled "All")

Is it possible to do this using a #ajax button with Forms API?  Or do I need to just write it as a separate Drupal behavior in jQuery?  I know Drupal forms can be handled in jQuery, but I haven't used it before, so I'm not sure where to start.
Thanks.
Answer: In talking to Randy Fay, this will not work for a number of reasons, of which security is a big one.  Form API was written to avoid one form modifying other forms (among other things), so I re-architected the form elements to be all in one form instead of separate forms.


What is the longest PCIe card that can fit in a Dell R310

Question: I have a full height 4" full length 13" PCIe Card that I need to fit into a R310 or other low end rack-mountable server.  Will this card fit? clearing the processor fan, memory, etc.
I've poured over the R310 Technical Reference but still have not found an answer.
http://i.dell.com/sites/content/shared-content/data-sheets/en/Documents/PowerEdge-R310-Tech-Guide-rev1.pdf
Comment: Link doesnt appear to work.
Comment: Don't forget to mark the correct answer.
Answer: You will not be able to fit a full-length 13" card in the R310. The usable depth of the slot is less than 7 inches.
The server has a riser with a PCIe slot on either side. The length of the card is limited by the processor cage and the memory bank.
Comment: Thanks you!, after reading a little more I confirmed the same thing on Page 10 of the Technical Guide, it supports full height half length.

After looking throught the models it looks like the R510 will support one full height full length PCIe card at x4 speed in slot 2.
Answer: Servers use half-length cards for everything. The slot is much shorter so any full length card simply will not fit. most are pci-e. Larry
Comment: In addition to containing (questionable) generalsations, this answer adds nothing to the existing (excellent) answer, as far as I can see.


Esquema de ROTA .htaccess

Question: Tenho a seguinte URL:
http://localhost/devops/json/index.php

e eu desejo que fique assim o acesso ao index dessa página:
http://localhost/devops/json/

Desejo que a exibição do index.php seja oculto
Answer: Todas as modificações de redirecionamento e extensões de url são alteradas no arquivo .htaccess!
Abaixo segue o código!
RewriteEngineOn
RewriteCond%{REQUEST_FILENAME}!-f
RewriteCond%{REQUEST_FILENAME}!-d
RewriteRule^(.*)$/index.php?/$1[L]

Esquema de ROTA .htaccess


C# dll that can be pinvoked?

Question: Question: Is it possible to write a C# dll that can be pinvoked ?
I want to write a replacement library for the WinAPI calls WritePrivateProfileString etc. for reading and writing ini files.
Is it possible to export a function, e.g. 'WritePrivateProfileString', implemented in C# so one can pinvoke the dll with DllImport ?
I want to replace the native dll with a managed dll, so the managed dll gets called by the pinvoke call (instead of the native dll, when the managed dll is in the bin directory).
Answer: Contrary to popular belief, this is possible. (note that you'll need to modify the calling application to import from your DLL)
See here.
However, in your case, it's not necessarily a good idea.
Why don't you change the extern declarations to normal methods that call your replacements?
Comment: Doesn't have to be as dumb as it may read like. It could be that he wants to change the way another app reads INI files. And maybe he doesn't want to use a native language to do just that.
Comment: @Robert: The question is talking about C#.  He'll need to modify the calling application no matter what.
Comment: Perhaps not, would this make it possible? http://msdn.microsoft.com/en-us/library/ms682586%28VS.85%29.aspx
Comment: @Ani: Are you sure that applies to system DLLs (which are already loaded)?
Comment: @SLaks: I'm not sure either way, to be honest.
Comment: @Robert Giesecke: Exactly, I want to replace that kernel32.dll functionality on Linux, for a program where I don't have the source to. I want to write it in C#, because that way I don't get a native dependency (e.g. different versions of Linux/Unic/Mac). On Windows, it doesn't matter which dll is called. Of course, if that's not possible I can always write a native dll, but then I get that native libc + version dependency.
Comment: @Quandary: I don't know if that's possible.  For one thing, your DLL would need to implement _every_ function in `kernel32.dll`.
Comment: @SLaks: No, only those used by the program's pInvokes, which is WritePrivateProfileString, etc., and not every function in kernel32.dll...
Comment: @Quandary: And those used by .Net's P/Invokes (which may be fewer on Mono, but would be a very large number in Microsoft's CLR)
Answer: This is not easy, but it can be done with the use of a few "hacks"
However COM may be a better option for you, as it is easy to export a com object from C# and to use com objects from VB6.  Then change the extern declarations to normal methods that call you're your com objects.
Comment: Read the question.  He's not talking about VB6.
Comment: The question was originally tagged with VB.net, not sure why though. I removed that tag.
Comment: Little offtopic but which part was not easy?
Comment: That's not necessary and beside the point. I need it to add windows API functionality to Linux, and COM doesn't work on Linux.
Answer: Try using Mono Cecil to change the third-party program's extern methods to methods that call your DLL (without P/Invoke).
Reflector will help here.

C# dll that can be pinvoked?


Is it possible to subscribe to a newsletter without first having to register?

Question: I am using the Simplenews module, but from what I've been able to conclude, is not possible to subscribe to a newsletter without first having to register.  Is that correct?
Is there a different newsletter module which will enable me to do this: offer a newsletter subscription to users without having to first become a registered user?
Answer: It is supposed to be possible, but the anonymous user is still required to confirm their email address. Check this issue in the Simplenews issue queue.
Answer: Yes, it is possible. You do not need to register to subscribe to a simple news list. It is the default way to use the module.


How to activate component in loop angular?

Question: I have a template:

       <app-dropdown-reglaments *ngIf="showReglamentList" [depid]="order.depId"></app-dropdown-reglaments>

When user clicks over row it toggles showReglamentList, so component app-dropdown-reglaments is activated.
But now it activates all components in each row (loop) with server request.
I can solve this like this:
    let rowComponentVisibility = {};
    orders.foreach((item, index) => rowComponentsVisibility[index] = false);

Then use:
*ngIf="rowComponentsVisibility[index]"
Problem is I try to cache it, and dont initialize the component again, just hide/show if it was initilized before.
How to solve it?
Comment: Could you explain more, what do you mean?
Comment: If I understand correctly : you have a list of order and when you click on an order it should request some kind of details and display them ? And the problem is when you click on one every orders are loaded ? If the problem is only to cache component you should use css visibility (use ngIf with rowComponentsLoaded for example and set visibility with ngClass on rowComponentSVisibility)
Comment: Yes, but atfirst time component should be loaded (request send), second time I need just/ show/hide it
Comment: May be to use ViewChild?
Answer: You want component to be loaded on click, ngIf is a good option. Below I use rowComponentsLoad array to keep a track of what component to load. To display / hide you can use ngClass and toggle a "hide" class. You keep track of what is displayed in a second array rowComponentsVisibility.

    <app-dropdown-reglaments *ngIf="rowComponentsLoad[index]" ngClass="{ 'hide': rowComponentsVisibility[i] }></app-dropdown-reglaments>

component
loadOrder(index) {
    this.rowComponentsLoad[index] = true;
    this.rowComponentsVisibility[index] = true;
    hideVisibilityBut(index);
}
hideVisibilityBut(index) {
    for(for i=0;i<this.rowComponentsVisibility.length;i++) {
        if(i!==index) {
            this.rowComponentsVisibility[index] = false;
        }
    }
}

css
.hide {
    display: none;
}

Comment: right, if you have access to the app-dropdown-reglaments then you can choose to display it or not using css https://stackoverflow.com/questions/50458920/angular-6-show-hide-component-programmatically-using-contentchildren-and-ho
Comment: Maybe to use ViewChild?
Comment: Could you explain ` hideVisibilityBut(index);`?
Comment: ViewChildren as you have a list, yes it should work as well. You also may deal with visibility inside the loaded component itself (maybe the simplest way actually)
Comment: How to combine `this.rowComponentsVisibility` and  `this.rowComponentsLoad`?
Comment: Could you explain how to use `ViewChildren ` and changes inner state of dropdown?
Comment: hideVisibilityBut is to hide every element but the one clicked
Comment: app-dropdown-reglaments is not a component you wrote ?
Comment: It is compoenent, if to use `ViewChildren` should I wrap component HTML in ng-container?
Comment: https://stackoverflow.com/questions/53016596/angular-5-access-divs-list-using-viewchildren
Comment: Problem is that using ViewChildren it initializes ngInit of components, where I make server request


Why EKS can't issue certificate to kubelet after nodepool creation?

Question: When I'm creating EKS cluster with single nodepool using terraform, I'm facing the kubelet certificate problem, i.e. csr's are stuck in pending state like this:
NAME        AGE     SIGNERNAME                      REQUESTOR          REQUESTEDDURATION   CONDITION
csr-8qmz5   4m57s   kubernetes.io/kubelet-serving   kubernetes-admin   <none>              Pending
csr-mq9rx   5m      kubernetes.io/kubelet-serving   kubernetes-admin   <none>              Pending

As we can see REQUESTOR here is kubernetes-admin, and I'm really not sure why.
My terrafrom code for cluster itself:
resource "aws_eks_cluster" "eks" {
  name     = var.eks_cluster_name
  role_arn = var.eks_role_arn
  version = var.k8s_version
  vpc_config {
    endpoint_private_access = "true"
    endpoint_public_access  = "true"
    subnet_ids  = var.eks_public_network_ids
    security_group_ids  = var.eks_security_group_ids
  }
  kubernetes_network_config {
    ip_family = "ipv4"
    service_ipv4_cidr = "10.100.0.0/16"
  }
}

Terraform code for nodegroup:
resource "aws_eks_node_group" "aks-NG" {
  depends_on = [aws_ec2_tag.eks-subnet-cluster-tag, aws_key_pair.eks-deployer]
  cluster_name  = aws_eks_cluster.eks.name
  node_group_name = "aks-dev-NG"
  ami_type  = "AL2_x86_64"
  node_role_arn = var.eks_role_arn
  subnet_ids    = var.eks_public_network_ids
  capacity_type = "ON_DEMAND"
  instance_types = var.eks_nodepool_instance_types
  disk_size = "50"
  scaling_config {
    desired_size = 2
    max_size     = 2
    min_size     = 2
  }
  tags = {
    Name  = "${var.eks_cluster_name}-node"
    "kubernetes.io/cluster/${var.eks_cluster_name}" = "owned"
  }
  remote_access {
    ec2_ssh_key = "eks-deployer-key"
  }
}

Per my understanding it's very basic configuration.
Now, when I'm creating cluster and nodegroup via AWS management console with exactly SAME parameters, i.e. cluster IAM role and nodegroup IAM roles are same as for Terraform, everything is fine:
NAME        AGE     SIGNERNAME                      REQUESTOR                                    REQUESTEDDURATION   CONDITION
csr-86qtg   6m20s   kubernetes.io/kubelet-serving   system:node:ip-172-31-201-140.ec2.internal   <none>              Approved,Issued
csr-np42b   6m43s   kubernetes.io/kubelet-serving   system:node:ip-172-31-200-199.ec2.internal   <none>              Approved,Issued

But here, certificate requestor it's node itself (per my understanding). So I would like to know what's the problem is here? Why requestor is different in this case, what's the difference between creating of these resources from AWS management console and using terraform, and how do I manage this issue? Please help.
UPD.
I found that this problem appears when I'm creating cluster using terraform via assumed role created for terraform.
When i'm creating the cluster using terraform with regular IAM user credentials, with same permissions set everything is fine.
It doesn't gives any answer regarding the root casue, but still, it's something to consider.
Right now it seems like weird EKS bug.
Comment: Unrelated to your issue, but I would highly recommend not putting your nodes in a public subnet.
Comment: It's testing environment, so i believe it's safe for now. Thank you for advice.
Answer: I had a similar issue to this, I created a cluster using an assumed role that I created separately and I was getting errors tls errors in the pod.
My resolution was that the role I created that was being used to assume to create the cluster did not have eks as a trusted entity. Once I modified the roles trust relationships to add in the eks service it was able to issue the certs.


Parse Query with array include not always returning every array object

Question: I'm running into some strange behavior when using Parse.Query.find() and am hoping someone can show me my errors.  My scenario is that I'm including an array field in my query and sometimes, at a random record, some of the included array elements are null.  I've verified that the array elements are indeed NOT null.  Additionally, if I use each() instead of find(), I don't see this problem.  Also, if I reduce the # of records I read at a time (CHUNK_SIZE) from Parse's 1000 maximum to 500, things work, so I'm not sure what's going on.
Here's the code I'm using.
/**
 Iterates over a query using find(), which is very fast, compared to each().
 Works up to 10,000 records maximum.

 @param query  Parse.Query to iterate.
 @param callback  Called for each batch of records.

 @return  Promise, fulfilled when iteration is done.
 */
function findAll(query, callback) {
    var queryCount = 0;
    var startTime = new Date();
    var CHUNK_SIZE=1000;
    query.limit(CHUNK_SIZE);

    var queryFind = function() {
        query.skip(CHUNK_SIZE * queryCount);
        queryCount++;

        return query.find().then(function(rows) {
            callback(rows);

            if (rows.length == CHUNK_SIZE) {
                return queryFind();
            }
        });
    }

    return queryFind();
}

// Example of how to use findAll.
function fetchTree() {
    var records = 0;
    var query = new Parse.Query('TreeNode');
    query.include('scores');

    return findAll(query, function(nodes) {
        nodes.forEach(function(node) {
            records++;
            node.get('scores').forEach(function(score, scoreIndex) {
                if (!score) {
                    throw "Null score at row " + node.id + "/" + records + " index " + scoreIndex;
                }
            });
        });
    }, true);
}

fetchTree();

Thanks in advance.
Answer: Parse limits rows returned per query to a default of 50 with a max of 1000.
This limit includes related records, so if you get 10 records that each have on average 50 pointers in their array and you include() them you are using 500/1000 max records for your query.


Opening a new window scrolled to extreme right

Question: I have a chrome extension which opens a small window. I'm trying to scroll the window to the right once loaded. I have tried scrollLeft property but I guess the problem is the code runs in the active window and not the popup.
let smallInterval = setInterval(()=>{

    let emailAddress = document.querySelector("body > workspace-layout > workspace")
    ?.shadowRoot.querySelector("input");
    if(emailAddress !== undefined && emailAddress !== null){

        let obj = {
        email: emailAddress.value,
        };
        console.log(obj.email);

        const MyUrl ="https://test.com"

        let newWindow2 = window.open(MyUrl , "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=50,left=3000,width=50,height=200");

        clearInterval(smallInterval);
    }else{
    }

},1000);

Comment: _" have tried scrollright property"_ - what are you talking about? Where would any `scrollright` property exist? The property to determine scroll position on the x axis is `scrollLeft`. https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft, https://stackoverflow.com/a/8906007/1427878
Comment: that was a typo.. I updated the question.
Comment: Still don't see what you actually tried with it. _Show_ what you are talking about, instead of _just_ talking about it.
Comment: Never mind.. I will figure it out on my own.
Answer: newWindow.onload = function() {
newWindow.scrollTo(800,500);
};

I got it to work. Hope this helps someone in future.
Answer: Try with window.outerWidth property.
If window is small than 150px in width you'll have to tune the diff offset.
window.open(MyUrl, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=50,left=" + (window.outerWidth - 150) + ",width=150,height=200")


Disabled button when textInputField is invalid on change text Flutter

Question: I'm new on Flutter.
I'm trying to disabled button while I compile textFormField and it is invalid.
My problem is that it works only if I click on "confirm" on keyboard and not while I compile my input.
So would like disable button while I write the input.
I've done a pastebin for example:
https://pastebin.com/q5WuwrCm
class AddCartButton extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return AddCartButtonState();
  }
}
class AddCartButtonState extends State<AddCartButton>{
  TextEditingController myController = TextEditingController();
  bool isValid = false;
  @override
  Widget build(BuildContext context) {
    void _addToCart(){
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("QUANTITY"),
            content: Column(
              children: <Widget>[
                TextFormField(
                    controller: myController,
                    decoration: new InputDecoration(labelText: "quantity"),
                    keyboardType: TextInputType.numberWithOptions(decimal: true),
                    inputFormatters: <TextInputFormatter>[],
                    autovalidate: true,
                    validator: (value) {
                      if (value.isEmpty) {
                        isValid  = false;
                        return "the quantity cannot be empty";
                      } else if (double.tryParse(value) == null) {
                        isValid = false;
                        return "the quantity must be valid number";
                      } else {
                        isValid = true;
                        return null;
                      }
                    }
                )
              ],
            ),
            actions: <Widget>[
              FlatButton(
                  disabledTextColor: Colors.grey,
                  child: Text("add"),
                  onPressed: isValid ? () { print("is valid"); }: null
              )
            ],
          );
        },
      );
    }
  }
}

Comment: You can do this with the onChange method of the TextFormField, but it's a bit confusing what you want to achieve. You want the button to be disabled while you type, and then after a second of not typing you want the button to be enabled again?
Comment: No, I want only disable button while I'm typing on input, but only if the input is invalid. Instead if the input become valid the button should be enabled. OnChange in theory is useless because textInput has validator that catch when input change.
Answer: You can use addListener() function on your TextEditingController myController.
myController.addListener((){
    //With this, you can "listen" all the changes on your text while
    //you are typing on input
    print("value: ${myController.text}");
    //use setState to rebuild the widget
    setState(() {
        //you can check here if your text is valid or no
        //_isValidText() is just an invented function that returns
        //a boolean representing if the text is valid or not
        if(_isValidText(myController.text)) isValid = true;
        else isValid = false;
    });
});

Comment: thank you but doesn't work, same problem. The button is disabled not while I'm typing but when I "confirm" on keyboard
Comment: Did your app print the `value: ${myController.text}` from the listener function? And, can you remove the `autovalidate` property to false?
Answer: If I understood what you want to achieve the following code works for you. The conditions I set are the same as your validation rules:
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  TextEditingController _textEditingController = TextEditingController();
  Function _submitFunction;
  // We need a reusable timer and it needs to not be null so that we can cancel it from th start.
  Timer _timer = Timer(Duration(milliseconds: 1), () => print('initialTimer'));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Auto disable button'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextFormField(
                controller: _textEditingController,
                onChanged: (text) {
                  setState(() {
                    _submitFunction = null;
                  });
                  restartTimer();
                },
              ),
              RaisedButton(
                child: Text('Submit'),
                onPressed: _submitFunction,
              ),
            ],
          ),
        ),
      )
    );
  }

  void submitForm(){
    print(_textEditingController.text);
  }

  void enableButton(){
    if(_textEditingController.text != ''){
      setState(() {
        _submitFunction = submitForm;
      });
    }
  }

  void restartTimer(){
    _timer.cancel();
    _timer = Timer(Duration(milliseconds: 1500), enableButton);
  }
}

Answer: You can use this method .
  bool isEnable = false;
void validateButton() {
    bool isValid = true;

    isValid = userEmail.isNotEmpty &&
        userPassword.isNotEmpty &&
        validateEmail(userEmail) &&
        userPassword.length >= 8;

    setState(() {
      isEnable = isValid;
    });
  }

now in your Textfield onChanged method you have to call this function
like This
onChanged: (email) {
                        userEmail = email;
                        setState(() {});
                        validateButton();
                      },

and in your Login Button
isEnable?ActiveButton():DisableButton()


How many times has a cricket player got ten wickets and a fifty in a test match?

Question: After seeing this video I wondered: how many times has a bowler scored fifty runs and also had a ten-wicket haul in the same test match?
Comment: I presume you mean fifty runs in a single innings, rather than fifty runs in the match - you may wish to edit your question to make this clearer.
Answer: As of 19 October 2016, there have been 25 instances of a player taking 10 wickets in a match and scoring fifty or more runs in an innings. Sir Richard Hadlee is currently the only player to have done so more than once: he achieved the feat in three Tests.
Comment: Nice one - I spent a couple of hours playing with the Statsguru interface but couldn't figure out how to make it accept the two restrictions for the same match, not separate ones. How did you manage that?
Comment: @TrueDub Under "Advanced filter", enter a condition under "Result qualifications". Pressing "Add to query" will then log the condition and return you to the same page, allowing you to go through the process again to add another condition. Repeat as desired!
Comment: Got it, thanks. I was doing 2 things wrong - I used the "10 wickets in a match" filter, which was incorrect, and I failed to use Match Total as the ordering factor. Thanks for your help.
Answer: At least four other players have achieved and surpassed this, by scoring  100 runs and taking 10 wickets in a match. Of course to score 100 runs in a match, you need to score at least one half-century.

Alan Davidson for Australia (scores 44 and 80)
Ian Botham for England (score 114, batted once)
Imran Khan for Pakistan (score 117, batted once)
Shakib al Hasan for Bangladesh (scores 137 and 6)

http://stats.espncricinfo.com/ci/content/records/287370.html
So the number of players achieving the feat of scoring a half-century in one innings and taking 10 wickets in a match will probably be considerably larger than these four and Steyn (mentioned in question).


SocketIO com Typescript

Question: Estou tentando fazer uma aplicação realtime com express (^4.17.1"), node (10.12.0) usando typescript.
Só que só no socket que está dando problema de cors

Access to XMLHttpRequest at
  'http://localhost:3000/socket.io/?EIO=3&transport=polling&t=Mo_nwPh'
  from origin 'http://localhost:4200' has been blocked by CORS policy:
  The value of the 'Access-Control-Allow-Origin' header in the response
  must not be the wildcard '*' when the request's credentials mode is
  'include'. The credentials mode of requests initiated by the
  XMLHttpRequest is controlled by the withCredentials attribute.

Minha classe de configuração é essa aqui
class Aplicaccao {
    app: express.Application
    port = 3000
    private io: SocketIO.Server
    private server: Server;
    constructor(){
        this.app = express()
        this.server = createServer(this.app);
        this.io = socketIo(this.server);
    }
    listen(){

        this.middleware()
        this.realtime()
        this.routes()

        this.app.listen(this.port, ()=>{
            console.log(`System is listening on port ${this.port}`);
        })
    }

    middleware(){
        this.enableCors()
        this.app.use( bodyParser.json() )
        this.app.use( bodyParser.urlencoded( {extended: true} ) )
    }
    enableCors(){
        const options: cors.CorsOptions = {
                            "origin": "*",
                            "methods": "*",
                            "preflightContinue": false,
                            "optionsSuccessStatus": 200
                        }
        this.app.use(cors(options))
    }
    realtime(){
        this.io.on('connect', socket =>{
            console.log('socket',socket);

            socket.on('read', msg =>{
                socket.broadcast.emit('read', msg)
            })
        })
    }

    routes(){
        this.app.get('/', (req, res)=>{
            res.send({obs: 'Bem vindo a api do Sistema de Notificações'})
        })
        this.app.use('/api', ...routes)
    }
}

export const server = new Aplicaccao()

A chamada no angular está assim:
this.socket = io( 'http:localhost:3000' )

E no javascript assim:
var socket = io('http://localhost:3000')

Como pode ser problema CORS se os outros módulos da API funcionam: Consulta, insert, update?
Onde posso estar errando?
Answer: Amigo, para dar este erro você deve estar utilizando XMLHttpRequest.withCredentials como TRUE (geralmente utiliza essa propriedade como true quando precisa enviar cookie).
Para resolver seu problema você pode passar essa propriedade como FALSE, caso não precise enviar cookies.
Agora, se realmente precisa utilizar XMLHttpRequest.withCredentials como TRUE, você deve adicionar o domínio de origem que quer permitir, e não passar * pois isso fica muito permissivo e da este erro.
Altere este seu pedaço de código para:
const options: cors.CorsOptions = {
  //Ou altere o http://localhost:3000 para o protocolo+dominio+porta de onde esta vindo as requisições.
  "origin": "http://localhost:3000",
  "methods": "*",
  "preflightContinue": false,
  "optionsSuccessStatus": 200
}

Comment: Bom eu mudei pro restify, e funcionou sem burocracia
Comment: @adventistaam, desculpe não ter conseguido lhe ajudar antes, mas que bom que você conseguiu!
Comment: Valeu pela tentativa...

SocketIO com Typescript


Como converter um inteiro para uma string binária no Python 3?

Question: Se eu quero converter entre inteiros e caracteres, uso chr e ord:
>>> chr(10)
'\n'
>>> ord('$')
36

Entretanto eu preciso fazer um teste com strings binárias, algo novo no Python 3, e eu - que só tenho experiência com o Python 2 - não tenho a menor ideia de como fazer:
# O que eu sei
teste(b'\x00')
teste(b'\x01')
teste(b'\x02')
...
teste(b'\xff')

# O que eu quero
for i in range(256)
    teste(???)

Comment: Acho que você está procurando isso: http://pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/
Comment: @AndréRamos Esse artigo só fala da conversão entre strings (texto) e bytes através de um *encoding*. O problema são aquelas sequências de bytes que não representam texto nenhum em *qualquer* encoding (ex.: `b"\xdb"` não é uma string válida em nenhuma codificação Unicode). De todo modo, eu quero trabalhar com bytes "crus", não com texto, qualquer conversão desse tipo seria uma "gambiarra".
Answer: No Stack Overflow em inglês tem uma resposta.
Então seu loop seria (limitei o máximo, mas teste que funciona):
>>> for i in range(20):
...   print(bytes([i]))
...
b'\x00'
b'\x01'
b'\x02'
b'\x03'
b'\x04'
b'\x05'
b'\x06'
b'\x07'
b'\x08'
b'\t'
b'\n'
b'\x0b'
b'\x0c'
b'\r'
b'\x0e'
b'\x0f'
b'\x10'
b'\x11'
b'\x12'
b'\x13'

Não se preocupe com o b'\t', pois são caracteres especiais bem conhecidos.
Comment: Ótimo, valeu! Eu havia dado uma olhada rápida na [documentação do `bytes`](https://docs.python.org/3.3/library/functions.html#func-bytes), mas sem um exemplo não percebi que poderia usá-la desse jeito (com um *iterable* de inteiros).
Comment: Oi, Paulo, comentário temporário e off-topic. Me apareceu [a seguinte edição sua](https://pt.stackoverflow.com/review/suggested-edits/43937) para aprovar e decidi pular pois não é minha praia. Com sorte, os revisores que decidirem conhecem MongoDB, mas pode ser que rejeitem; seria a reação natural dentro deste eco-sistema. O que sugiro é que você faça sua própria resposta (colocando um sumário daqueles links para sites externos).


Call tabelize again after injecting table with ajax and jquery html

Question: I'm using this plugin, tabelizer, it is very simple to use, you just construct your table as specified and on document ready you call tabelizer:
My jquery:
$(document).ready(function(){
    tabilize();
});

My function:
function tabilize(){
    console.log("It's getting called");
    var table1 = $('#table1').tabelize({
        /*onRowClick : function(){
            alert('test');
        }*/
        fullRowClickable : false,
        onReady : function(){

        },
        onBeforeRowClick :  function(){

        },
        onAfterRowClick :  function(){

        },
    });
}

And I get the desired result,
But when I refresh my table with an ajax call:
success: function (response) {
       var resp = response.split('|');
        if (resp[0] == 'ok'){
                $('#table1').html(resp[1]).promise().done(function(){
                   tabilize();
                });
                return false;

I know it is getting called again because when I load my page, I get the the console log and when I click the button I get the console log again.
I know the table its the same plus the new row because the same function creates the table, also, if I just refresh my browser it gets tabelized, but when I called with the refresh table button it doesn't get tabelized.
I noticed the reason for this was that you can only call tabelize once, if I don't call it on document ready, and I click my refresh table button, the table does get tabelized, but if I hit refresh it again, it doesn't get tabelized, I just get the table.
So, what do I need to do to be able to call tabelize again?
Comment: Have you considered using a more appropriate plug-in that can better handle changes to table data?
Comment: I most certainly have not, but when I looked at this one I liked it, it's very simple to use, you have any suggestions?
Answer: Well, if anyone stumbles across this same problem, what I did was modify jquery.tabelizer.min.js and added a function I called retabelize, which just inits itself again and returns the public object.
I know it has something to do with the object created by the plugin itself being persistent, and once initialized it doesn't init itself again, it just updates, so when you call tabelize again, it doesn't init itself again which is what you need.
The plugin is very short itself, so you can read what it does.
What I added to  the script:
e.fn.retabelize = function() {
    return n.caller = this,
    n.init(),
    n.updateData(),
    n.getPublicObj()
}

And my tabelize function:
function tabilize(){

if (table1 == null || table1 == 'undefined'){
    table1 = $('#table1').tabelize({
    /*onRowClick : function(){
        alert('test');
    }*/
    fullRowClickable : false,
    onReady : function(){

    },
    onBeforeRowClick :  function(){

    },
    onAfterRowClick :  function(){

    },
});
}else{
    table1 = $('#table1').retabelize();
}
}

Answer: $.fn.tabelize = function(confProp){
    var existingSelf = this.data('tabelizer');
    if (typeof existingSelf == 'undefined'){
        $.extend(self.conf, confProp);
        self.caller = this;
        self.init();

    }else{
        self = existingSelf;
        $.extend(self.conf, confProp);
        self.caller = this;
        self.init();
    }
    //Store copy of self in data for repeat calls, update it after any repeating call
    self.updateData();

    return self.getPublicObj()
};

My tabilize function
function tabilize(){
            alert("table value"+table1);
            table1 = $('#table1').tabelize({
                /*onRowClick : function(){
                    alert('test');
                }*/
                fullRowClickable : true,
                onReady : function(){
                    console.log('ready');
                },
                onBeforeRowClick :  function(){
                    console.log('onBeforeRowClick');
                },
                onAfterRowClick :  function(){
                    console.log('onAfterRowClick');
                },
            });
    }

then call given method to any where    tabilize();
Comment: Dear, Pierre, What u do not get ?


Shiny - hide actionButton created dynamically when renderUI value is null

Question: I have the app below (simplified example). Basically I would like that, when I turn on the app, if the reactive value is equal to "" than I do not want that the activeButton appears on the UI. At the moment is appearing but without label. How can I do in this case? Thank you for your help!
library(shiny)
runApp(list(ui=
    shinyUI(fluidPage(

        mainPanel(
            textInput("text", label = ""),
            uiOutput("wordOneButton")
        )
    ))
,

server=shinyServer(function(session, input, output) {
    reval <- reactive(sample(c("a", "b", ""), 1))

    # Fill the buttons with the random letter
    output$wordOneButton <- renderUI({
        actionButton("action", label = reval()[1])
        })

    # Include predicted word in the text after click event on button
    observeEvent(input$action, {
        name <- paste0(input$text, reval()[1], sep = " ")
        updateTextInput(session = session, "text", value = name)
    })

})
))

Answer: You need to add shinyjs::toggle():
library(shiny)

runApp(list(ui=
    shinyUI(fluidPage(
        shinyjs::useShinyjs(), #NEW
        mainPanel(
            textInput("text", label = ""),
            uiOutput("wordOneButton")
        )
    ))
,

server=shinyServer(function(session, input, output) {
    reval <- reactive(sample(c("a", "b", ""), 1))

    # Fill the buttons with the random letter
    output$wordOneButton <- renderUI({
        actionButton("action", label = reval()[1])
        })

    observe(shinyjs::toggle("wordOneButton", condition = reval() != "")) #NEW

    # Include predicted word in the text after click event on button
    observeEvent(input$action, {
        name <- paste0(input$text, reval()[1], sep = " ")
        updateTextInput(session = session, "text", value = name)
    })

})
))

Comment: This works, but do you think there is a way to do it with the 'shinyjs' package?
Comment: because currently I am having problems deploying the app in the shinyapps.io server: Attaching package: 'shinyjs'

The following object is masked from 'package:shiny':

    runExample

The following objects are masked from 'package:methods':

    removeClass, show (and I already specified the package with shinyjs::toggle())
Comment: I updated my answer above to remove the library call for `shinyjs` and explicitly calling the package in the two lines where I'm using its functions.
Comment: Hi! This works, I forgot to remove the library call! Thanks
Answer: This is absolutely possible without calling an additional library. Two functions you are looking for are validate() and need(). Just add a couple of lines validating that the reactive reval() is different than the empty string "":
library(shiny)
runApp(list(ui=
              shinyUI(fluidPage(

                mainPanel(
                  textInput("text", label = ""),
                  uiOutput("wordOneButton")
                )
              ))
            ,

            server=shinyServer(function(session, input, output) {
              reval <- reactive(sample(c("a", "b", ""), 1))

              # Fill the buttons with the random letter
              output$wordOneButton <- renderUI({

                # Validate that reval() is distinct than ""
                shiny::validate(
                  shiny::need(reval() != "", message = "")
                )

                actionButton("action", label = reval()[1])
              })

              # Include predicted word in the text after click event on button
              observeEvent(input$action, {
                name <- paste0(input$text, reval()[1], sep = " ")
                updateTextInput(session = session, "text", value = name)
              })

            })
))

I'm using the shiny:: calls to explicitly use these functions from the shiny library and avoid errors in case you use other libraries such as jsonlite that share functions with the same name. If you don't use this library, feel free to erase the shiny:: calls.
Also, you can add a message in case reval() does equal the empty string "". Just change the message parameter inside the need() function.


Why SQL Server generates two statements for only one foreign key?

Question: I'm using SQL Server 2012.
Let's say I have two tables:

Foo (Id int, BarId int)
Bar (id int, BarName varchar(50))

In the database diagram, I created a relationship between Foo and Bar and save changes.
The question: when I script the created key, I found there are two SQL statements generated:
ALTER TABLE [dbo].[Foo] WITH CHECK
    ADD CONSTRAINT [FK_Foo_Bar]
        FOREIGN KEY([BarId]) REFERENCES [dbo].[Bar] ([BarId])
GO

ALTER TABLE [dbo].[Foo] CHECK CONSTRAINT [FK_Foo_Bar]
GO

I wonder what the need of second statement is - isn't the first one enough?
Answer:
I wonder what the need of second statement is - isn't the first one
  enough?

You are right, first one is enough for enabling the foreign key constraint. Second statement is definitely is redundant in this case.
SSMS might be using some generic templates for generating the script.
The main reason I feel behind this generation is to first create the constraint and enable it separately.


Extract the stream from a Silverlight image control

Question: Is it possible to extract the steam (or something similar) from a silverlight image control?
I figured you could get the stream from the Image.Source property, but so far that has been a dead end option.
Thanks.
Answer: In general, the answer is no. The reason being that the image element is not constrained by the same cross-domain limitations that most other network traffic is subjected to in Silverlight (i.e. you can display an image accessed cross-domain, but your application can never access the image data).
In order to get access to the underlying bits of an Image, you can get the image's source URI and then use WebClient to request the stream (assuming that your app has the appropriate access to that server).
Comment: Thanks. I should have mentioned that I am setting the Image.Source via streams I generate, but I guess a viable solution will be to simply hold on to a copy of the stream in a local variable.


Printer: Is it possible to show print PDF and ePub url link for each node on Views?

Question: I have Printer module installed on Drupal 7. Let's say I have a view that lists all the articles in table format. I would like to have the PDF and ePub url link next to each article as a field. Is it possible?
Answer: Yes, add a global text field and under Rewrite Results select output this field as link and give the path eg. for PDF it should be printpdf/[nid].
similarly you can create one more  field for EPUB using printepub/[nid].
Note [nid] is a replacement pattern, you should add nid before these fields and exclude it from display.
Comment: You have to add `Content:nid` field before the global fields and exclude it from display if you want. But it should come before the global fields.
Comment: I cant upvote this whole thread enough, haha.
Comment: Ty @wolverine. The link go to page "Page not found". I believe I didn't enable one of the functions. What am i missing? I'm using wkhtmltopdf from https://github.com/wkhtmltopdf/wkhtmltopdf and PHPePub from https://github.com/Grandt/PHPePub.
Comment: the url printpdf/[nid] on output this field as link is pointing to /printepub/%5Bnid%5D. am i using the right code?
Comment: ty @wolverine :)


Rails 3.0.9 Model attributes are lost on database query

Question: If i open the console and type in the following code, my model looses attributes. In all cases only the first attribute after the id is accessable. I had this problem on one server. My old server is working fine with the same code and same versions. Here the output:
<code>irb(main):001:0> User.new
=> #<User id: nil, encrypted_uid: nil, encrypted_access_token: nil, created_at: nil, updated_at: nil>
irb(main):002:0> User.first
=> #<User id: 1, encrypted_uid: "I7lPHOYoGMNWki3cZtb5oA==\n">

ActiveModel::MissingAttributeError (missing attribute: encrypted_access_token):
</code>
Has anyone an idea to get it working? Thanks in advance.
Answer: I had to recreate the application and copy the model into hte new application. after that everything worked fine. No clue what was wrong.


Monitorar alterações no aplicativo

Question: Preciso de uma classe que fique escutando por alguma alteração na aplicação (ou alteração externa).
Fiz uma classe que estendeu da classe Service, porém percebo que entra no método onStartCommand apenas uma vez.
Estou fazendo algo errado?
@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e("--> ", "onStartCommand");
      return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
}

Answer: Minha sugestão é criar "estados" possíveis de conclusão (ok, erro, etc.), ou qualquer outra alteração que você queira monitorar, que um serviço externo possa gerar na execução e fazer o serviço armazenar esses valores numa chave de SharedPreferences de acordo com o estado desejado, pois ela poderá ser acessada na Activity.
Na aplicação você implementa na sua Activity um SharedPreferences.OnSharedPreferenceChangeListener e passa a "escutar" as alterações na chave de preferência especificada acima dentro do método onSharedPreferenceChanged() dessa interface.
Maiores detalhes de como implementar na documentação oficial:
https://developer.android.com/guide/topics/data/data-storage.html#pref
https://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListener.html

Monitorar alterações no aplicativo


CNAME, htaccess and ERR_NAME_NOT_RESOLVED

Question: I have the following code to make sure that api.example.com will call example.com/api.php. It works on my localhost, but not on my website.
RewriteEngine On

 # Handle Front Controller...
RewriteCond %{HTTP_HOST} ^api\.(.*)
RewriteRule ^ api.php [L]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ website.php [L]

The browser returns the eror ERR_NAME_NOT_RESOLVED. Whats the problem and how do I fix this?
Comment: Show your DNS record(s)..
Comment: Have you tried clearing dns cache of the PC you are testing from? Try `ipconfig /flushdns` and also check your dns address.
Answer: Try from another machine on another network. What does host return? Do you get the proper IP?
host api.example.com

Answer: The ERR_NAME_NOT_RESOLVED means that the problem has nothing to do with the server. It means that the bowser didn't even send any requests as it didn't find any api.example.com in the name records.
You have to open the account from which you purchased the domain name and find the settings where you can manage DNS records. And then you can either:

Point anything.example.com to your example.com. by adding wilcards to the name field of your type A record, such as *.example.com or:
Point only api.example.com to your example.com by a CNAME record api to api.example.com

And please note that changes in DNS records can sometimes take more than 24 hours to propagate. But usually it takes less than that.


Strip a list item for extracting a specific value in python

Question: I have a list, which was produced as output of a python script in the following format:
[' (* 100.856 UnitA', ') [ 98.0%]',
 ' (* 100.598 UnitB', ') [ 98.0%]',
 ' (*  98.193 UnitC', ') [ 25.6%]']

Now, I am interested to put the floating point values in every list item to a new list for further processing in a python script. Is there a way (an in-built python function maybe) I can strip the floating point content alone to a new list? In the above example my desired output would be like :
[100.856,98.0,100.598,98.0,98.193,25.6]

If not an in-built function, any other alternate way I can achieve this?
Comment: This could be done simply in a loop or a list comprehension. What have you tried so far?
Comment: I tried using extend. Realized won't work. New to python. So, wanted to explore the options.
Answer: Using a regex pattern from here will extract the floats and cast to float as desired:
In [153]:
l=[' (* 100.856 UnitA', ') [ 98.0%]',
 ' (* 100.598 UnitB', ') [ 98.0%]',
 ' (*  98.193 UnitC', ') [ 25.6%]']
import re
[float(re.findall(r'(-?\d+\.\d+)',x)[0]) for x in l]

Out[153]:
[100.856, 98.0, 100.598, 98.0, 98.193, 25.6]

So the tricky thing here is that you need to search for digits \d but also search for the decimal point and trailing digits


Invalidate single block cache in D7

Question: I have a custom site-wide block that shows on all pages, which I would like to be heavily cached for anon users but able to be invalidated when I modify its settings, or en/disable it (both drupal variables set in an admin page).
I've managed to achieve this pretty nicely in D8 with Cache::invalidateTags(), as well as some custom Acquia stuff to invalidate the varnish cache. However in trying to port this same functionality to a D7 site I've not managed to find any good method of doing it.
Any help much appreciated, thanks in advance!
Answer: You may have a look at Block Refresh, and implement your custom logic on top of it whenever you want to send a Cache-Control: max-age=0 :
//Override external cache max age if set
  if (isset($settings[$block_id]['bypass_external_cache']) && $settings[$block_id]['bypass_external_cache'] != '') {
    drupal_add_http_header('Cache-Control', 'public, max-age=' . intval($settings[$block_id]['bypass_external_cache']));
  }

Invalidate single block cache in D7


qt47-webkit-devel installation conflicts?

Question: I'm receiving several conflicts while trying to install qt47-webkit-devel on a CentOS 6.4 server, the meat of the conflicts is here:
--> Processing Conflict: 1:qt47-x11-4.7.2-1_18.el6.x86_64 conflicts qt-x11 < 1:4.7.2-1_18.el6
--> Processing Conflict: 1:qt47-x11-4.7.2-1_18.el6.x86_64 conflicts qt4-x11 < 1:4.7.2-1_18.el6
--> Processing Conflict: 1:qt47-x11-4.7.2-1_18.el6.x86_64 conflicts phonon < 4.3.80-1
--> Processing Conflict: 1:qt47-devel-4.7.2-1_18.el6.x86_64 conflicts qt4-devel < 1:4.7.2-1_18.el6
--> Processing Conflict: 1:qt47-devel-4.7.2-1_18.el6.x86_64 conflicts phonon-devel < 4.3.80-1
--> Finished Dependency Resolution
Error: qt47-devel conflicts with 1:qt-devel-4.6.2-26.el6_4.x86_64
Error: qt47-x11 conflicts with 1:qt-x11-4.6.2-26.el6_4.x86_64

And a pastebin is here: http://pastebin.com/YwF6gvfx
If someone could help me resolve this I'd be much appreciated
Comment: Where did you get these packages?
Comment: @MichaelHampton I answered my own question after thinking on it a minute. Plus one for the problematic package question ;)
Answer: Answer was
yum remove qt-x11 qt qt4 qt4-x11 phonon
yum install qt47 qt47-x11 qt47-webkit qt47-webkit-devel --enablerepo=atrpms-testing

ATRPMS.repo
[atrpms]
name=CentOS #releasever – #basearch – ATrpms
baseurl=http://dl.atrpms.net/el$releasever-$basearch/atrpms/stable
gpgkey=http://ATrpms.net/RPM-GPG-KEY.atrpms
gpgcheck=1
enabled=1

[atrpms-testing]
name=CentOS #releasever – #basearch – ATrpms testing
baseurl=http://dl.atrpms.net/el$releasever-$basearch/atrpms/testing
gpgkey=http://ATrpms.net/RPM-GPG-KEY.atrpms
gpgcheck=1
enabled=1


error: value toList is not a member of (Object, Object) - Spark Shell

Question:   val cooccurrences = orders.map(order =>
  (
    order._1,
    order._2.productIterator.toList.combinations(2).map(order_pair =>
        (
            if (order_pair(0)._2 < order_pair(1)._2)
                (order_pair(0)._2, order_pair(1)._2)
            else
                (order_pair(1)._2, order_pair(0)._2),
            order_pair(0)._1 * order_pair(1)._1
        )
    )
  )
)

When I submit the last method I'm getting the following error:
 <console>:46: error: value _2 is not a member of Any
                   if (order_pair(0)._2 < order_pair(1)._2)
                                     ^
<console>:47: error: value _2 is not a member of Any
                       (order_pair(0)._2, order_pair(1)._2)
                                      ^
<console>:47: error: value _2 is not a member of Any
                       (order_pair(0)._2, order_pair(1)._2)
                                                        ^
<console>:49: error: value _2 is not a member of Any
                       (order_pair(1)._2, order_pair(0)._2),
                                      ^
<console>:49: error: value _2 is not a member of Any
                       (order_pair(1)._2, order_pair(0)._2),
                                                        ^
<console>:50: error: value _1 is not a member of Any
                   order_pair(0)._1 * order_pair(1)._1
                                 ^

Anyone knows why I'm getting this errors? Do I need to declare order before the method?
Many thanks!
Answer: It looks like you are trying to apply toList to an Object in the order._2.toList call. order is of type (Object, Object), hence order._2 is of type Object which does not have a toList method.
I assume you had in mind to apply it to the sequence of (Order, Order) objects.
Generally, I would advise to explicitly annotate type annotations for more or less complex types.
Answer: The value order._2 is a tuple, and the toList method does not apply to tuples directly. You could use order._2.productIterator.toList to get a list
Comment: Thanks for your help Samar :) I'm trying to use the new sentence to get the list but it still gives me error. I've updated the code and error above
Comment: From the orders mapping `(x.get("cat"), x.get("quantity"))` It seems that your order._2 will always be a 2 element tuple. Is that right? If so, then I don't see the point of the `combinations(2)` step. Also, the order_pair in the map function expects a two element list of tuples. I am not sure how its expecting that from the previous code.
Comment: with combination(2) I am trying to know how many products combinations I've in the dataset
Answer: Here:
val orders = transactions.map { x => (
    x.get("id"),
    (x.get("cat"), x.get("quantity")))
}

You map transactions which yields in orders that is an RDD where each element has form of (valueOfId, valueOfCat, valueofQuantity). When you call order._2.toList you invoke it on an object valueOfCatthat does not have such method (it's not a collection).
Comment: Hi sebszyller,

It still gives me an error :(

:44: error: value toList is not a member of (Object, Object)
           order._2.toList.combinations(2).map(order_pair =>
                    ^
Comment: This is not a copy paste code that will solve your problem; it's an explanation what the problem is. Read the whole post.
Comment: Sorry I'm very new at Scala programming... I'm try to know which products combination I have (If product A is "connected" to B). If I understand when I create the cooccurrences I need to invoke order.2_toList to call 3 objects (id,cat,quantity), right? I don't know how to do it :(


xmlrpc() error: (-1001) unable to parse URL during Drush command

Question: I have an odd error coming from Drush when I perform module updates and other commands (it's most consistently comes from module updates). Near the end of the command execution this message pops up:

xmlrpc() error: (-1001) unable to parse URL

Some cursory Googling produces that its likely an error popping up in drupal_http_request. I'm not sure where however since I'm not too familiar with the Drush code base.
I ran drush with the --debug switch for more information but that didn't tell me much other than this message typically pops up after the drush_cache_command_clear() being executed.
What is causing this error?
Answer: Turns out the issue was the APC module. After some testing I was able to isolate the issue during cache clear.
[shawnconn@host www]$ drush cc all
'all' cache was cleared.                                                                                [success]
xmlrpc() error: (-1001) unable to parse URL                                                                                [error]
[shawnconn@host www]$ drush dis apc
The following extensions will be disabled: apc
Do you really want to continue? (y/n): y
apc was disabled successfully.                                                                                [ok]
You need to enable the APC module for remote cache clearing to work. Run drush pm-enable apc.                                                                                [error]
[shawnconn@host www]$ drush cc all
'all' cache was cleared.                                                                                [success]
[shawnconn@host www]$

Answer: It seems likely that you have not correctly specified the URI for your site.  You can do this in one of several ways:

--uri=http://example.com on the commandline.
'uri' => 'http://example.com' in a site alias.
$options['uri'] = 'http://example.com' in a drushrc.php file.

For the purpose of most Drush commands, it is sufficient to use the name of the folder that contains the settings.php file as your uri -- or you do not need to specify the uri at all if the sites folder is 'default'.  However, some modules will need the full URI, including the http:// protocol, or you will experience problems similar to what you describe above.
Comment: Thanks for reply Greg (and all for all the awesome work with Drush!). I tried all those options and I still wasn't able to get rid of the problem. Turns out the cause was the APC module.


How do I generate mipmap images in OpenGL ES?

Question: What is the equivalent function of gluBuild2DMipmaps() in OpenGL ES on an iPhone?
Answer: glGenerateMipmapOES(GL_TEXTURE_2D);
document
http://www.khronos.org/opengles/sdk/docs/man/glGenerateMipmap.xml


Social Science Trade Book

Question: I am looking for a book (not textbook) to use in an undergraduate statistics course. I would like to find a book with a clear central thesis relying largely on statistical reasoning and evidence to support the thesis. I would use the book to motivate discussions on measurement, research design, validity, reliability, sampling, statistics etc. In the past, I've used Putnam's Bowling Alone and Gilbert's Stumbling on Happiness. I've considered Sunstein & Thaler's Nudge, various Malcom Gladwell books, Kahneman's Thinking Fast and Slow. Ideally, I find a book with broad appeal and plenty of social science (perhaps conflicting) to draw upon. A bonus would be a book with supporting, publicly available data set. Ideas?
Comment: In my opinion, under no circumstances should you use a Malcom Gladwell book for anything in undergrad as a cautionary tale of how NOT to think. (And maybe setting a bonfire.) None of the books that you listed strike me as stats books at all. To get more precise answer, I think you should be more specific with your question. What level undergrad are you referring to? What background/pre-requisites do these students have? What is the goal of the course, i.e. general information or as a pre-requisite for other courses?
Comment: I am not looking for a stats book, as I note in my original post. I want a social science book to serve as a supplement to a traditional stats textbook. The students are 2nd and 3rd year. I assume no background in quantitative methods. For some students, this may be their last class as undergraduates in quantitative methods. For others, it is a prereq to a more advanced statistics course. The overall course goals are statistical literacy and applied statistical analysis.
Answer: You might consider "The Bell Curve" by Herrnstein and Murray. They used the NLSY data, which is publicly available. The main book argues their thesis, while there are a couple of hundred pages of statistical analysis in the appendix. http://en.wikipedia.org/wiki/The_Bell_Curve
It starts off fairly sensibly, they talk about 'cognitive segregation', that you tend to associate with people who are of similar intelligence to yours. Then it starts to get more, errrmmm..., interesting, until the final chapter where they suggest that people with low IQs should live on reservations.
There's a lot more learning done when you pick holes in a book that you disagree with than find one where you nod along the whole time. The book can be critiqued on several levels - you can discuss their conclusions with no knowledge of statistics, for example from a sociological perspective, or you can delve into the models.
It's a little old, and I don't know how much it costs. There were at least two books that came out as direct responses to it as well.
Comment: Nice suggestion. I agree that students may learn more if a critical posture is easier to get to. Do you remember the "response" book titles?
Comment: @DBK Thanks. One was The Bell Curve Wars: http://www.amazon.com/The-Bell-Curve-Wars-Intelligence/dp/0465006930. Edit: Just found another: http://www.springer.com/statistics/social+sciences+%26+law/book/978-0-387-94986-4
Answer: It seems that your interest is in qualitative analysis rather than quantitative, because terms such as reliability and validity are from qualitative analysis domain. That's why I'd suggest you to look at texts in psychometrics, for instance Michell, Joel. "Quantitative science and the definition of measurement in psychology." British Journal of Psychology 88.3 (1997): 355-383.. He also has book "Measurement in Psychology".
There's an easier reading book on the measurement in soft subjects: DeVellis, Robert F (2003). Scale Development: Theory and Applications (2nd ed.). He covers validity and reliability, latent variables and such.
Comment: I've never heard of reliability and validity as being purely qualitative domains (but maybe we're meaning different things by qualitative). I find Michell's work to be possibly interesting, but very hard to read, and short on suggestions about what we should be doing.
Comment: It's not my field, but that's how I got introduced to these things in the course on qualitative analysis, along with things like factor analysis (CFA). I guess the qualitativeness comes from the domain. Measuring *happiness* is very different from measuring income. So, they came up with these quantitative techniques and math to do it, but it really is very different kind of measurement compared to physics or even economics. So, psychometrics is really the field that does this stuff.
Comment: @JeremyMiles, I added another ref. On *qualitativeness*: my background is in quantitative area, so I figured this was all *qualitative*, touchy-feely stuff, but you might be right that it should be treated as quantitative treatment of the subject. Maybe I should edit my response.
Comment: Thanks for getting back to me, that's interesting. (I've just edited a book called "Quantitative research in psychology" and it has a lot on things like CFA and reliability, there's a companion called "Qualitative research in psychology" which has nothing on these things. Here, in case you're interested: http://smile.amazon.com/Quantitative-Research-Psychology-SAGE-Benchmarks/dp/1446282678/ref=sr_1_1?ie=UTF8&qid=1419360536&sr=8-1
Comment: I don't think you need to edit your response, I think it's OK to cover different perspectives. I like DeVellis's book too.
Comment: I am interested in quantitative research. Validity and reliability, as applied to measurement, are important concepts in both qualitative and quantitative research. See [here](http://www.socialresearchmethods.net/kb/measure.php) for one explanation.

Social Science Trade Book


Base 64 encoding, Java or JavaScript?

Question: i've a particular js function that encrypts some form inputs into base64, but I need to run it in my Java app. So my question is, how can i call that function inside a java class? Otherwise I'll have to translate it but I think will be more complicated. Here's some of js code:
function encode64(input)
{
      //alert(input);
      //alert(input);
      input = escape(input);
      var output = "";
      var chr1, chr2, chr3 = "";
      var enc1, enc2, enc3, enc4 = "";
      var i = 0;

      var nMod =( input.length) % 3;
      //alert(nMod);
      //alert(input.length);
      do
      {
         chr1 = input.charCodeAt(i++);
         chr2 = input.charCodeAt(i++);
         chr3 = input.charCodeAt(i++);

         enc1 = chr1 >> 2;
         enc2 = (((chr1  << 4) | (chr2 >> 4))& 0x3f);
         enc3 = (((chr2  << 2) | (chr3 >> 6))& 0x3f);
         enc4 = chr3 & 0x3f;

         output = output +
            keyStr.charAt(enc1) +
            keyStr.charAt(enc2) +
            keyStr.charAt(enc3) +
            keyStr.charAt(enc4);
         chr1 = chr2 = chr3 = "";
         enc1 = enc2 = enc3 = enc4 = "";
      } while (i < input.length);

    if(nMod == 1)
    {
        chr1 = input.charCodeAt(i++);
        enc1 = ((chr1 & 192)>>2);
        enc2 = ((chr1 & 3) <<4);
        enc3 = "=";
        enc4 = "=";
        output = output + keyStr.charAt(enc1)
                + keyStr.charAt(enc2)
                + keyStr.charAt(enc3)
                + keyStr.charAt(enc4);
    }
    if(nMod == 2)
    {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        enc1 = ((chr1 & 192)>>2);
        enc2 = ((chr1 & 3) << 4 )|((chr2 & 0xf0) >> 4);
        enc3 = ((chr2 & 15) <<2);
        enc4 = "=";

        output = output + keyStr.charAt(enc1)
                + keyStr.charAt(enc2)
                + keyStr.charAt(enc3)
                + keyStr.charAt(enc4);
    }

      return output;
}

Thanks so much!
Comment: So you have a javascript function that you want to call from Java?  If thats the case, not likely to happen.  What exactly are you trying to do?
Comment: I've to get output string from this js in order to login
Answer: Or better use commons-codec 's Base64 class
P.S. You do not "encrypt" into Base64 - you "encode"
Comment: sorry, english is not my native language
Comment: the native language doesn't matter - these are different terms.
Answer:
but I think will be more complicated.

Why would it be more complicated? You can perfectly do that in Java. If your actual problem is already the first line
input = escape(input);

then it's good to know that the Java equivalent is the URLEncoder#encode(). As to the remnant of the coding, it's ultimately straightforward. Just replace var by String or char here and there, align the methods according java.lang.String API and you'll be fine.
Edit: for some downvoting nitpickers out here: I did NOT say that URLEncoder#encode() does the Base64 encoding. It just does URL encoding the same way as Javascript's escape() function does. That was just the first line of his to-be-translated Javascript code. Please read answers, do not scan answers.
Comment: So you insinuates that you thought that Javascript's `escape()` function equals to `Base64` thing? Reread it all dude.
Comment: it doesn't, of course.. but never mind.. I removed my downvote, to 'end the war'.. now you can perhaps remove yours from all my recent posts :P
Comment: (the point was that it is redundant to write all that code, and messing with URLEncode, while simply base64 was needed)
Comment: URLEncode.encode actually works as expected, I'm finishing the translation, worked ok with char and Strings, only have to be catch IndexOutOfBounds Exceptions when accesing charCodeAt(i++), thanks again BalusC!
Comment: You're welcome. The `ArrayIndexOutOfBoundsException`s can be avoided by checking lengths properly.
Answer: You could do that using a javascript engine written in Java, but I think it's better to simply translate it into java.
Answer: I have used http://iharder.sourceforge.net/current/java/base64/ and it works.
Answer: Translate the code into Java - it will be quicker. (Or search for an existing example in Java!)
Comment: Indeed I found some examples but not getting the same outputs :(
Comment: sscalzadona: could the different outputs be because your js implementation calls escape on the input? Why are you doing that, anyway?
Comment: Js code is implemented in an embedded device, I'd love to change that implementation, but I can't!

Base 64 encoding, Java or JavaScript?


Prove $\lim\limits_{n \to \infty }\sqrt[n]{a}=1$, if $a>0$

Question: I tried solving by using $\log$ and got $\log(a)/n = \log (1)$ which after applying limit (of $n \to \infty$) gives $0= \log(1)$. Is this right?
Comment: Certainly $\log1$ is $0$.
Comment: Also: https://math.stackexchange.com/q/2506582/42969
Comment: @RuRu Ly Hii!! Welcome to MSE . Kindly write statement of question in question also ( apart from title) . Also  you should add context of problem , that is  source(if textbook)  . Also see on site tour , How to ask a good question .
Answer: Write , $a^{\frac{1}{n}} = e^{\ln(a^{\frac{1}{n}} )}= e^{\frac{1}{n} \cdot \ln(a) } $
Now , just apply the limit.