text:
Q: Can't visit many websites except a few(google, wikipedia, yahoo) My internet hasn't worked normally since yesterday.
I can't visit a lot of websites, such as amazon.com, nba.com & my school website. I can visit Google, Gmail, Facebook, Wikipedia, Yahoo etc & it seems that those are the only website I can visit.
So the modem should be fine. The problem exist across more than one device, on any web browser(I cleared the browser cache as well), different operating system(my cellphone(iOS), OSX, Ubuntu).
So the problem should not be in computer or cellphone. Plus these device works well under other wifi network.
I've tried resetting my modem many times. It worked for a short period of time, several minutes to a couple of hours, but then the same problem occurred again. I've called Comcast several times and they checked that the modem they provide is fine, and no firewall issues.
My operating system is Ubuntu 14.04. I tried pinging websites that I can't visit, data loss was 100%, while pinging google.com or Wikipedia.com is normal.
I've no idea how I should even start tackling this problem. Can anyone help me ?
Update: I tried the suggestion from the top answer of this thread(same as @Agu V suggested below, changing DNS to 8.8.4.4 and 8.8.8.8), but it doesn't work for me. The problem stays the same.
Update2: I forgot to mention that Comcast gave me a new modem for replacement but the problem still persist. And also, if I use vpn connecting to my school, then I can access the internet normally.
What else can I try? Thanks again

A: You can try changing the dns from the router.
Example:  Google DNS service
Use the IP addresses 8.8.8.8
and 8.8.4.4 as your DNS servers.


text:
Q: autocomplete textbox in asp.net webservice I use master page and a script to open a popup window. This popup window has one textbox. I add an ajax autocomplete extender in the textbox. It runs and gets the values and I check the breakpoint, but it doesn't display the autovalues in the textbox. How can I solve this problem?
My code:
<ajaxToolkit:autocompleteextender ID="aceSearch" runat="server" TargetControlID="itemnametext" BehaviorID="AutoCompleteEx" MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="5" CompletionInterval="100" ServiceMethod="GetCompletionList" ServicePath="CloudlistService.asmx">

</ajaxToolkit:autocompleteextender>

A: I think that this is related to the z-index of the popup and the autocomplete.
the autocomplete must have a heigher z-index
you can achieve that by the property CompletionListCssClass of the autocomplete

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to assign command output in expect script I want to execute the below command in an expect script.
`netstat -nr | while read line;do flag=$(echo $line | cut -d' ' -f4); if [[ $flag == "UG" ]];then gateway=$(echo $line | cut -d' ' -f2);echo $gateway;fi;done`

The aim of the script is to login to a host and get the gateway of the hots to create another ip ( eth0 ) with ifcong eth0:0 <ip> and add a IP route thereafter with-- ip route add <ip> via <gateway ip>.
i have tried the below possibilities:
1)
`expect -c '
   spawn bash -c "ssh user@host"
   expect {
     // password provided
          }
   expect "*?$*"
   send "\$cmd"
expect EOF
    '`

For this i get the error: missing )
    while executing
"set cmd "netstat -nr | while read line;do flag=$(echo $line | cut -d"
couldn't read file " -f4); if [[ $flag == "UG" ]];then gateway=$(echo $line | cut -d": no such file or directory
2)
`expect -c
   spawn bash -c "ssh user@host"
   expect {
     // password provided
          }
   expect "*?$*"
   send "netstat -nr | while read line;do flag=\$(echo \$line | cut -d' ' -f4); if [[ \$flag == "UG" ]];then gateway=\$(echo \$line | cut -d' ' -f2);echo \$gateway;fi;done\r"
expect EOF
   '`

For this i get error as: couldn't read file " -f4); if [[ $flag == "UG" ]];then gateway=$(echo $line | cut -d": no such file or directory
Is there no way to execute bash commands inside an expect script and register the out to a variable so that it can be used subsequently in the expect script.
I have tried out the way of set output $expect_out(buffer) but it does not register the output at all.

A: foreach {whole gw f} [regexp -all -inline {\S+\s+(\S+)\s+\S+\s+(\S+)} [exec netstat -nr]] {
        if {$f eq "UG"} {
                puts "Gateway : $gw"
        }
}

Output :
Gateway : 192.xx.xx.1


text:
Q: How can I compare answer of current iteration with previous one in Mathematica for example: computing f[f[f[x]]], I want to compare  answer of f[f[f[x]]] with the answer of f[f[x]].
I want to keep  iterating and comparing until answer of current iteration matches with answer of previous one. How Can I do that in Mathematica?
Basically I want to write Generic code for Fixed Point Iteration method for any function given by the user. How can I compare Iterations in this case?


text:
Q: (LINX-IPC protocol) How to find out if a process with a PID is running in C++? I have a PID of a LINX process (obtained through 'linxstat' command) that I want to send a LINX signal (http://linx.sourceforge.net/linxdoc/doc/html/linx.7.html) to:
Cmn::Ipc<ASig> sig(A_SIG);
sig->a = 10;
sig->b = 20;
sig.send(PID);

Now, before I send the LINX signal to the PID, I want to make sure that the PID exists and is still running (making sure the process hasn't crashed). If the PID does not exist, then I'll send it to another common process which has a PID of 0 and this process can handle any type of signal. Is there a way to check if the PID exists in C++? If yes, what is the LINX API for it?
I want to be able to do this without having to know the process name and with just the PID of the process.

A: Anywhere between the code that gets the PID, performs the PID check and sends a signal target process can exit and the new unrelated process with the same PID can spawn as range of PID numbers is limited and they are reused over time. So I think it is not possible to achieve what you want with just PID.

A: You can send signal 0 first:
kill(2):

If sig is 0, then no signal is sent, but error checking is still
  performed; this can be used to check for the existence  of
         a process ID or process group ID.

But it's probably pointless. Moreover, this kind of pid-based access is rather race-condition prone unless you're the parent of the process (in which case you always know whether or not it ended and whether or not you've reaped it).

A: No matter what you do to check that it is currently running, there's no guarantee that it won't crash between the time you check and the time you send the signal - or, between the time you send the signal and the time it arrives. So, just send the signal and find a way to deal with the fact that the process may not be there when it arrives. In extreme cases the process may even die and its PID be re-used before the signal arrives - have fun dealing with that..


text:
Q: markup language with formulae and html + LaTeX output I'd like to create a software manual with some kind of markup language. I need HTML and LaTeX output. The markup language must support math formulae (basic ones, including fractions). Which markup language do you suggest? I have tried asciidoc (no forumlae except for the LaTeX filter, but the output is extremely bad with LaTeX output) and textile,markdown. (no formulae?).
The input should be easy, so inserting a MathML formula is not a good option IMO.

A: What about doxygen it does support formuals?


text:
Q: Can't make an absolutely positioned element take the whole height of the container I am trying to make the .info pane take the whole height of its container which is .card, I was able to make this work by giving .card { position: absolute; }, but I can't have the .card be absolute because I am going to have a list of these cards and with position:absolute; they just stack on top of each other. Here is the code:
HTML

Project Title

        Lorem ipsum dolor sit amet consectetur, adipisicing elit. Cupiditate ut perspiciatis est sit architecto molestiae illo debitis accusantium laboriosam labore!

      Technologies used:

ReactJs

Express

Redux

MongoDB

Github Url: www.github.com

Click to Open Demo

CSS
* {
  box-sizing: border-box;
}

.card {
  width: 100%;
  height: auto;
  background-color: #ccc;
  margin: auto;
  position: absolute;
  z-index: 0;
}

.card .info {
  position: absolute;
  width: 200px;
  background-color: #ff729f;
  z-index: -1;
  color: #000;
  padding: 10px;
  overflow-y: scroll;
  top: 0;
  bottom: 0;
}

.info::-webkit-scrollbar {
  width: 4px;
}

.info::-webkit-scrollbar-thumb {
  background: #888;
}

.info::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.card:hover .info,
.card:active .info {
  z-index: 2;
  box-shadow: 10px 0 10px -1px rgba(40, 40, 40, 0.75);
}

.card:hover .img-container {
  opacity: 0.6;
}

.card:hover .img-container img {
  box-shadow: unset;
}

.card .info .info-section {
  border-bottom: 0.8px solid rgba(100, 100, 100, 0.8);
  margin-bottom: 10px;
}

.card .info .info-section:last-child {
  border-bottom: none;
}

.card .info .info-section .demo {
  margin: 10px 0;
  padding: 10px 5px;
  background-color: red;
  color: white;
  border-radius: 4px;
  border-top-right-radius: 100%;
  border-bottom-right-radius: 100%;
  cursor: pointer;
}

.card .img-container {
  width: calc(100% - 100px);
  height: 100%;
  transition: 100ms ease-in;
  background-color: #blue;
  float: right;
}

.card .img-container img {
  width: 100%;
  height: auto;
  float: right;
  box-shadow: -10px 0 8px -1px rgba(40, 40, 40, 0.75);
}

I can't give .card a static height because it has to be fully responsive.

A: One way you could solve this is by changing the position in .card to relative. The disadvantage to this is needing to declare a height. I see you said no static height, but a percentage would also work and help to keep your page somewhat responsive.
.card {
    width: 100%;
    background-color: #ccc;
    margin: auto;
    position: relative;
    height: 50%;
    z-index: 0;
    overflow: hidden;
}


text:
Q: Case convention- Why the variation between languages? Coming from a Java background, I'm very used to camelCase.  When writing C, using the underscore wasn't a big adjustment, since it was only used sparingly when writing simple Unix apps.  In the meantime, I stuck with camelCase as my style, as did most of the class.
However, now that I'm teaching myself C# in preparation for my upcoming Usability Design class in the fall, the PascalCase convention of the language is really tripping me up and I'm having to rely on intellisense a great deal in order to make sure the correct API method is being used.  To be honest, switching to the PascalCase layout hasn't quite sunk in the muscle memory just yet, and that is frustrating from my point of view.
Since C# and Java are considered to be brother languages, as both are descended from C++, why the variation in the language conventions?  Was it a personal decision by the creators based on their comfort level, or was it just to play mindgames with new introductees to the language?

A: The culture difference originated long before C# or Java.
All three conventions have coexisted since the late 60s or early 70s, and have been popular in different groups.  (As well as other conventions, including the unlamented Hungarian notation that Microsoft inflicted on so many for so long.)
In particular the inventors of Java were at Sun, and many were involved with StrongTalk, which is a form of Smalltalk.  The Smalltalk community has used camelCase for a very, very long time.
The inventors of C# came from Microsoft.  StudlyCaps was one of the major conventions at Microsoft, and is heavily seen in places like Visual C++.
Those originator styles appear in all of the core documentation, which influences groups who pick up the language, and therefore has caused the split in capitalization conventions between two very similar languages.

A: YOU FORGET FORTRAN, THE FIRST HIGHER LEVEL COMPUTER LANGUAGE. BACK IN THOSE DAYS THERE WERE NO LOWER CASE LETTERS, AND SO EVERYTHING WAS IN UPPER CASE. LATER WE HAD EBCDIC BUT STILL THE KEYPUNCHES DID NOT SUPPORT LOWER CASE LETTERS SO ALL PROGRAMS WERE STILL KEYPUNCHED IN CAPITAL LETTERS. COBOL SAME AS FORTRAN; AFAIK SAME FOR ALGOL BACK THEN.
Then along came ASCII and terminals and suddenly lower case letters were all over the place.
When you want to name something "next serial number" it is natural to want to break it into three words. But with one disasterous exception, no language I've ever used allows blanks in names. So you can write next_serial_number or NextSerialNumber or nextSerialNumber or anything similar depending on your taste.
Personally I see no reason why the first word should be lower case and the rest of the words capitalized: "nextSerialNumber" makes no sense to me at all.
AND YOU CAN STILL TYPE IN CAPS IF YOU WISH.

A: Naming convention, as I learned in Software Engineering course, is to make code consistent and self documenting.
The naming conventions of languages could more have to do with the timeline a language was being used the most and the naming conventions that were prominent at the time. Hence those naming conventions that were being used at the time of a particular language was famous got stuck together.
There are no restrictions what naming conventions you use as long as your code is consistent and self documenting for the sake of maintainability.

A: To the best of my knowledge, none of the languages you mentioned enforces any naming convention.
As to the naming convention of the standard libraries - you have to remember that C came first, C++ wanted to be backward compatible to C while improving some, and Java and C# were developed to compete against each other (while learning lessons from C and C++, both). Sometimes migrating from one language to another is not in the best interest of the language developers.
In your own code - you can use whatever naming convention you want, there's no restriction.

A: Anders Hejlsberg is the lead architect of C#.  He comes from a Pascal background, and this has influenced C# in various ways.


text:
Q: How do I use the route package to push a new URL and trigger its handler? Here's my attempt:
https://github.com/DaveNotik/dart-stack/commit/99f877491dbd7163aa1bd8d5844c489bdab05eeb
My aim was to make it so when /welcome is detected (which I set the Facebook callback URL to) a window.alert is triggered. But right now it triggers on every page load, so it doesn't seem the router is working appropriately? Is my approach correct?

A: Most likely you problem is this:
addHandler(Routes.sayWelcome, MainController.sayWelcome(app))

The second argument should be a function to call; but you are calling the function immediately such that its return value is being used as the handler. You need to make this a function so that it will be invoked only when the route is navigated to. For example:
addHandler(Routes.sayWelcome, (_) => MainController.sayWelcome(app))


text:
Q: Cucumber-JVM 3 - Convert DataTable to single object using asMap() In cucumber-jvm 3.x.x, I want to convert a datatable with only 2 columns to a single object. This used to be automatic in 2.x.x but has since been removed with the new major version.
Code:
// Feature
Scenario: Scan Barcode
    Given I Am At The Login Page
    When I Log In As Valid User
        | group    | gpao     |
        | username | svgpao1  |
        | password | REDACTED |

// Stepdef
@When("I Log In As Valid User")
public void I_Log_In_As_Valid_User(User user) throws Throwable {
    Selenium.enterText(driver, user.getUsername(), "username");
    Selenium.enterText(driver, user.getPassword(), "password");
    Selenium.clickElement(driver, "sign.in");
    LOGGER.debug("User Group=" + user.getGroup());
}

// Configurer
registry.defineDataTableType(new DataTableType(User.class, new TableTransformer<User>() {
    @Override
    public User transform(DataTable dataTable) throws Throwable {
        Map<String, String> map = dataTable.asMap(String.class, String.class);
        return new User(map);
    }
}));

// User - constructor
public User(Map<String, String> map) {
    this.group = map.get("group");
    this.username = map.get("username");
    this.password = map.get("password");
}

Stacktrace:
cucumber.runtime.CucumberException: Could not convert arguments for step [I Log In As Valid User] defined at 'jcucumberng.project.stepdefs.EnterPacketDetailsSteps.I_Log_In_As_Valid_User(User) in file:/Z:/workspace/java/jcucumberng-framework/target/test-classes/'.
The details are in the stacktrace below.
        at cucumber.runtime.PickleStepDefinitionMatch.couldNotConvertArguments(PickleStepDefinitionMatch.java:69)
        at cucumber.runtime.PickleStepDefinitionMatch.runStep(PickleStepDefinitionMatch.java:46)
        at cucumber.runner.TestStep.executeStep(TestStep.java:55)
        at cucumber.runner.TestStep.run(TestStep.java:42)
        at cucumber.runner.PickleStepTestStep.run(PickleStepTestStep.java:53)
        at cucumber.runner.TestCase.run(TestCase.java:47)
        at cucumber.runner.Runner.runPickle(Runner.java:44)
        at cucumber.runtime.junit.PickleRunners$NoStepDescriptions.run(PickleRunners.java:140)
        at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:68)
        at cucumber.runtime.junit.FeatureRunner.runChild(FeatureRunner.java:23)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at cucumber.runtime.junit.FeatureRunner.run(FeatureRunner.java:73)
        at cucumber.api.junit.Cucumber.runChild(Cucumber.java:98)
        at cucumber.api.junit.Cucumber.runChild(Cucumber.java:55)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at cucumber.api.junit.Cucumber$1.evaluate(Cucumber.java:107)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:273)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:159)
        at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:383)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:344)
        at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:125)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:417)
Caused by: io.cucumber.datatable.CucumberDataTableException: 'jcucumberng.project.domain.User' could not transform
      | group    | gpao     |
      | username | svgpao1  |
      | password | REDACTED |

A: You need to also modify the transform method in addition to @Transpose.
public User transform(DataTable dataTable) throws Throwable {
    return new User(dataTable.asMaps().get(0));
}

@When("I Log In As Valid User")
public void I_Log_In_As_Valid_User(@Transpose SilverUser user) throws Throwable {
    System.out.println(user);
}


text:
Q: Is there a general pattern for all integrals of the form $\sin^{k/2}x$ where $k$ is an integer? Though a CS student, my main hobby is mathematics, and was wondering about the primitives of rational powers of $\sin x$.
I solved and found the primitive of the square root of $\sin x$ via a series and proceeded to use the same method for $3/2$, then $5/2$ and mostly gave the same results differing in a few key aspects regarding the powers of $\sin x$ in the series.

A: In all cases of positive integer $k$, your integral is equivalent to
$$I_k(x)=\int_0^x\sin^{k/2}(t)dt$$
So let's focus on a different integral for a second:
$$G(x,a,b)=\int_0^x\sin^a(t)\cos^b(t)dt$$
To evaluate this, we make the substitution $u=\sin^2(t)$, giving $dt=\frac12u^{-1/2}(1-u)^{-1/2}du$, which gives
$$G(x,a,b)=\int_0^{\sin^2(x)}u^{a/2}(1-u)^{b/2}\frac12u^{-1/2}(1-u)^{-1/2}du$$
$$G(x,a,b)=\frac12\int_0^{\sin^2(x)}u^{\frac{a-1}2}(1-u)^{\frac{b-1}2}du$$
$$G(x,a,b)=\frac12\int_0^{\sin^2(x)}u^{\frac{a+1}2-1}(1-u)^{\frac{b+1}2-1}du$$
Next we recall the definition of the incomplete beta function:
$$B(x;a,b)=\int_0^xt^{a-1}(1-t)^{b-1}dt$$
Which gives our generalized integral:
$$G(x,a,b)=\frac12 B\bigg(\sin^2(x);\frac{a+1}2,\frac{b+1}2\bigg)$$
Then back to the integral in question:
$$I_k(x)=G\bigg(x,\frac k2,0\bigg)$$
$$I_k(x)=\frac12 B\bigg(\sin^2(x);\frac{k+2}4,\frac12\bigg)$$
A Special Value:
Note that
$$B(1;a,b)=\frac{\Gamma(a)\Gamma(b)}{\Gamma(a+b)}$$
Where $\Gamma(s)$ is the Gamma function.
Therefore,
$$I_k\bigg(\frac\pi2\bigg)=\frac12 B\bigg(1;\frac{k+2}4,\frac12\bigg)$$
$$I_k\bigg(\frac\pi2\bigg)=\frac{\Gamma(\frac{k+2}4)\Gamma(\frac12)}{2\Gamma(\frac{k+4}4)}$$
And from $\Gamma(\frac12)=\sqrt{\pi}$,
$$I_k\bigg(\frac\pi2\bigg)=\frac{\sqrt{\pi}\,\Gamma(\frac{k+2}4)}{2\Gamma(\frac{k+4}4)}$$
Which doesn't really get anymore simplified than that.


text:
Q: back button on webview exits app instead of displaying previous listview results I am developing an application which initially loads a listview of items within onPostExecute. There was no problem opening fuller details on webview (still within the onPostExeceute) after item is selected. However, hitting the goback button within the webview just exits the whole application.
Can someone please help.
The scheme of events is thus
Activity Create establish network broadcast --> onStart --> AsyncTask --> retrieves data --> onPostExecute --> setContentView (ListView) --> onClickListener --> WebView --> goback button at this stage then exits the entire application.
I'm sure someone can help me on this and I would really appreciate any effort.
Regards

A: This behavior is normal. onBackPressed() event call finish() method in your activity and throw you back to where you just start from.
You still have the possibility to catch this event and tell your app what to do at next

A: The default behavior of the back key in Android is to return the previous Activity, or if you are already at the root Activity, to exit the app. It sounds like your WebView is located within the same Activity as your ListView, so when you are clicking the "Back" key the app is exiting because there is no previous Activity to return to.
One solution would be to create a new Activity for displaying the WebView and pass in the data that you want to be displayed. With the WebView being loaded in a separate Activity, pressing the "Back" button will finish the WebView Activity bring you back to the list. You also get the added benefit of having screen transitions this way.
Another solution is to override the onKeyUp method in the ListView Activity and handle the pressing of the back key manually. (I personally recommend onKeyUp instead of onKeyDown because it makes it easier to handle long press that way) Capture the event and just undo whatever you are doing when an item in the list is clicked.


text:
Q: Pattern matching over Data.Map I did a search but, surprisingly, didn't find anything that would help me to perform pattern matching over it. I need to make sure that in my Map "variable" exactly 3 keys. That's it. Instead of "if ... then ... else", I want to go with pattern matching as it is easier to read and seems to be more haskell way. So:
myFunction :: Map String String
--.......................

main = do
  let var1 = myFunction
  -- how do I ensure it has exactly 3 keys in it and if not raise an error?

A: You could pattern match on M.toList:
import qualified Data.Map as M
-- ...
main = do
  case (M.toList myFunction) of
    [a,b,c] -> ... -- exactly 3 arguments
    _       -> ... -- more or less than 3 arguments

A: You cannot pattern match on abstract data types, as you don't have access to their constructors¹, so you will have to work with the functions provided by the `Data.Map´ module.
But note that there is a size :: Map k a -> Int function you can use. And if you don't like if .. then .. else .. (which is in no way wrong or unhaskellish), you can use pattern guards:
foo m | size m == 3 = ...
      | otherwise = error "Not three element"

¹ Disregarding view patterns and pattern synonyms here, but these are just syntactic surgar.


text:
Q: How to encode categorical features in Apache Spark I have a set of data based on which I want to create a classification model. Each row has the following form:
user1,class1,product1
user1,class1,product2
user1,class1,product5
user2,class1,product2
user2,class1,product5
user3,class2,product1

There are about 1M users, 2 classes, and 1M products. What I would like to do next is create the sparse vectors (something already supported by MLlib) BUT in order to apply that function I have to create the dense vectors (with the 0s), first. In other words, I have to binarize my data. What's the easiest (or most elegant) way of doing that?
Given that I am a newbie in regards to MLlib, may I ask you to provide a concrete example? I am using MLlib 1.2.
EDIT
I have ended up with the following piece of code but is turns out to be really slow... Any other ideas provided that I can only use MLlib 1.2?
val data = test11.map(x=> ((x(0) , x(1)) , x(2))).groupByKey().map(x=> (x._1 , x._2.toArray)).map{x=>
  var lt : Array[Double] = new Array[Double](test12.size)
  val id = x._1._1
  val cl = x._1._2
  val dt = x._2
  var i = -1
  test12.foreach{y => i += 1; lt(i) = if(dt contains y) 1.0 else 0.0}
  val vs = Vectors.dense(lt)
  (id , cl , vs)
}

A: You can use spark.ml's OneHotEncoder.
You first use:
OneHotEncoder.categories(rdd, categoricalFields)

Where categoricalField is the sequence of indexes at which your RDD contains categorical data. categories, given a dataset and the index of columns which are categorical variables, returns a structure that, for each field, describes the values that are present for in the dataset. That map is meant to be used as input to the encode method:
OneHotEncoder.encode(rdd, categories)

Which returns your vectorized RDD[Array[T]].

A: If using built-in OneHotEncoder is not an option and you have only a single variable implementing poor man's one-hot is more or less straightforward. First lets create an example data:
import org.apache.spark.mllib.linalg.{Vector, Vectors}

val rdd = sc.parallelize(List(
    Array("user1", "class1", "product1"),
    Array("user1", "class1", "product2"),
    Array("user1", "class1", "product5"),
    Array("user2", "class1", "product2"),
    Array("user2", "class1", "product5"),
    Array("user3", "class2", "product1")))

Next we have to create a mapping from a value to the index:
val prodMap = sc.broadcast(rdd.map(_(2)).distinct.zipWithIndex.collectAsMap)

and a simple encoding function:
def encodeProducts(products: Iterable[String]): Vector =  {
    Vectors.sparse(
        prodMap.value.size,
        products.map(product => (prodMap.value(product).toInt, 1.0)).toSeq
    )
}

Finally we can apply it to the dataset:
rdd.map(x => ((x(0), x(1)), x(2))).groupByKey.mapValues(encodeProducts)

It is relatively easy to extend above to handle multiple variables.
Edit:
If number of products is to large to make broadcasting useful it should be possible to use join instead. First we can create similar mapping from product to index but keep it as a RDD:
import org.apache.spark.HashPartitioner

val nPartitions = ???

val prodMapRDD = rdd
     .map(_(2))
     .distinct
     .zipWithIndex
     .partitionBy(new HashPartitioner(nPartitions))
     .cache

val nProducts = prodMapRDD.count // Should be < Int.MaxValue

Next we reshape input RDD to get PairRDD indexed by product:
val pairs = rdd
    .map(rec => (rec(2), (rec(0), rec(1))))
    .partitionBy(new HashPartitioner(nPartitions))

Finally we can join both
def indicesToVec(n: Int)(indices: Iterable[Long]): Vector = {
     Vectors.sparse(n, indices.map(x => (x.toInt, 1.0)).toSeq)
}

pairs.join(prodMapRDD)
   .values
   .groupByKey
   .mapValues(indicesToVec(nProducts.toInt))

A: Original question asks for the easiest way to specify categorical features from non-categorical.
In Spark ML, you can use VectorIndexer's setMaxCategories method, where you do not have to specify the fields - instead, it will understand as categorical those fields with lower or equal cardinality than a given number (in this case, 2).
val indexer = new VectorIndexer()
.setInputCol("features")
.setOutputCol("indexed")
.setMaxCategories(10)

Please see this reply for details.


text:
Q: Obtaining a cmap for color brewer palette How to obtain the cmap version of the palette that comes from sns.color_palette() function? For example, I can ask for the color brewer palette like this:
sns.color_palette('Blues')

but
sns.color_palette('Blues', as_cmap=True)

results in "TypeError: color_palette() got an unexpected keyword argument 'as_cmap'".
I could of course use sns.choose_colorbrewer_palette(), which accepts as_cmap argument, but it only works in interactive mode (I can't ask it for 'Blues' in the python script).

A: If you want to use the colormap in a matplotlib/seaborn function, simply pass the name (e.g., plt.pcolormesh(..., cmap="Blues")) and matplotlib will know what to do.
If you want the colormap object for some reason, it lives in the matplotlib.cm namespace.

A: Just want to add something that was confusing for me.
For palettes that support it, if you set as_cmap=True, seaborn creates a color palette with 256 colors and then asks mpl.ListedColorMap to make an mpl.ColorMap (which will simply interpolate between the neighboring colors, treating them as if they split [0, 1] interval into equal parts). It makes sense that seaborn doesn't use the n_colors argument in this case because a mpl.ColorMap represents a function from [0, 1] into colors, and the more colors are used to create this with mpl.ListedColorMap the more precise the function is. (Presumably no need to go above 256 colors due for most applications?)
So converting a seaborn color palette to mpl.ColorMap can be done by generating 256 colors of the palette (assuming the palette is generated algorithmically of course, so it produces that many distinct colors) and then calling mpl.ListedColorMap. Of course, as @mwaskom pointed out one can simply use the mpl.ColorMap object from mpl.cm namespace.


text:
Q: StyleCop CA0055 issue when target DOES exist As with another, similar question, I am getting two StyleCop errors on build:
CA0052: No targets were selected.
CA0055: Could not load [path to main exe...]
But, unlike the other question, reformatting and reinstalling everything on my dev machine did NOT fix it.  We are running Visual Studio 2010, with SP1, and targeting Dotnet 4.0.
Here's another detail that may help someone out there figure out what's wrong, though:
I also tried building the solution under Visual Studio 2012 RTM, and I got a more detailed version of the second error message -
CA0055  Error Running Code Analysis

CA0055 : Could not load C:\Users\UserName\SourceCode\ProjectName\Debug\xxx.exe.
The following error was encountered while reading module 'System.Windows.Forms':
Could not resolve type reference: [System.Drawing, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a]System.Drawing.BitmapSuffixInSatelliteAssemblyAttribute.

[Errors and Warnings]

(Global)

Anyone out there have any clues?  No one else is getting this error, so it is undoubtedly something odd in my own setup, and which I inadvertantly replicated when I repaved my machine.  But...what?

A: I found two ways to fix this, with no help whatsoever from any of Microsoft's documentation.  The clue was in VS 2012's additional error reportage - StyleCop could not locate the System.Drawing assembly.
Fix #1: remove the HintPath element from the .csproj file telling the project where to find the Windows.Forms assembly:
<Reference Include="System.Windows.Forms">
    <!--<HintPath>..\..\..\..\..\..\..\..\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll</HintPath>-->
</Reference>

Fix #2: add a HintPath element for the System.Drawing include in the .csproj file:
<Reference Include="System.Drawing">
    <HintPath>..\..\..\..\..\..\..\..\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll</HintPath>
</Reference>

The first option worked better for me, because there is no particular reason for the hint.  MSBuild is able to find the assembly without it, and it's redundant, since the target type is set the 4.0 version of the framework.


text:
Q: Why does float argument fit to int function parameter? Please, look at this code:
#include <iostream>
class A {
  public:
    int my;
    A(int a=0) : my(a) { }
};

int main() {
  A x = 7; // 1
  A y = 6.7; // 2
  std::cout << x.my << " " << y.my << "\n";
}

It actually compiles although there is no A(double a); constructor.
When exactly compiler is allowed to convert one argument type to another to call corresponding constructor?

A: cppreference has a list of standard conversions.  Of interest to you is the Floating - integral conversions section which can also be found in N4140 4.9/1

A prvalue of floating-point type can be converted to prvalue of any integer type. The fractional part is truncated, that is, the fractional part is discarded.

Finding A(int) to be callable with a standard conversion, the compiler inserts the necessary step to make the code work.  It's the same rule that allows int x = 1.1 to compile
If this behavior is undesirable you can forbid it with an =delete
class A {
  public:
    //...
    A(int a);
    A(double) =delete;
};


text:
Q: Problems with building a project in CodeNameOne Suddenly I can't build any projects in Netbeans with CN1.
The message on the console:
Created dir: C:\Users\ruben\Documents\ProyectosCodenameOne\Tempus\build
Updating property file: C:\Users\ruben\Documents\ProyectosCodenameOne\Tempus\build\built-clean.properties
Deleting directory C:\Users\ruben\Documents\ProyectosCodenameOne\Tempus\build
C:\Users\ruben\Documents\ProyectosCodenameOne\Tempus\nbproject\build-impl.xml:1387: Unable to delete file C:\Users\ruben\Documents\ProyectosCodenameOne\Tempus\dist\README.TXT
BUILD FAILED (total time: 0 seconds)

A: The error is: Unable to delete file C:\Users\ruben\Documents\ProyectosCodenameOne\Tempus\dist\README.TXT
Try deleting it. Make sure permissions for the directory are set so the build script can delete/create files there.


text:
Q: Are amenable groups topologizable? I've learned about the notion of topologizability from  "On topologizable and non-topologizable groups" by Klyachko, Olshanskii and Osin (http://arxiv.org/abs/1210.7895) - a discrete group $G$ is topologizable iff there exists a topology on $G$ which makes it into a Hausdorff non-discrete topological group.

Main question: Is every infinite amenable group topologizable?

Main motivation for this question is that perhaps naively non-topologizability seemed to me such a strange property that I hoped it could be used to show existence of non-sofic groups.

Question: Is there an infinite non-topologizable sofic group?

After failing to prove that sofic groups are topologizable I thought it would be still interesting to prove that infinite "elementary sofic" groups are topologizable. Elementary sofic groups are for the purpose of this discussion the class of "groups which are provably sofic by current methods", i.e. it contains all amenable groups, is closed under taking free products amalgamated over amenable groups, extensions with sofic kernel and amenable quotient, /any other results which are in the literature/, and with the property that if G is residually elementary sofic then G is elementary sofic.

Question: Is there an infinite non-topologizable elementary sofic group?

Unfortunately my plan to answer the above question negatively failed at step 1, and hence the Main question.


text:
Q: Как узнать о вызове метода? Допустим есть следующий класс
class Example
{
    public static void Main()
    {
        SayHello();
        Console.ReadLine();
    }
    public static void SayHello() => Console.WriteLine("Hello");
}

Как другой класс может быть осведомлен о вызове метода SayHello без внесения изменений в этот?
Наверное рефлексией можно добиться этого? Но поиск по msdn ничего похожего не выдал

A: Я думаю, что рефлексией добиться этого нельзя.
Рефлексия не панацея от всех болезней.
Нет, конечно вы можете вызвать метод, а потом рефлексией поставить метку в поле класса, но тем самым вы нарушите внутреннее состояние.
Не понимаю, зачем вам это могло понадобится...
Вы можете сделать обертку для класса-посредника и через него дергать свой класс, а сам посредник будет делать отметки, что метод вызывался.

A: Если ваш класс не закрытый, и от него можно наследоваться, то поступим так, наследуемся от этого класса, переопределим настоящий метод SayHello указав компилятору ключевое слово new в методе SayHello класса-наследника. Напишем простой delegate (можно использовать Action) и event, а так же метод который будет производить вызов делегата (подробнее читайте о коллбэках c#). Далее, подпишемся на созданный ивент, и будем передавать сообщение в консоль которое будет приходить от класса наследника (В данном примере используется Trace в тестовых классах).
Результат работы: https://ideone.com/PiWlQU
public class Example
{
    public void SayHello() => Console.WriteLine("Hello");
}

public class DeviredExample : Example
{
    public delegate void MethodCall(object sender, string message);

    public event MethodCall CallMethod;
    protected virtual void OnCallMethod(string message, Action callback)
    {
        callback?.Invoke();
        CallMethod?.Invoke(this, message);
    }

    public new void SayHello()
    {
        OnCallMethod("Say hello called", () => base.SayHello());
    }
}

[TestMethod]
public void Test()
{
    DeviredExample d = new DeviredExample();

    int i = 0;

    d.CallMethod += (sender, message) =>
    {
        Trace.WriteLine(message);
        i = 1;
    };

    d.SayHello();
    if (i != 0)
    {
        Assert.IsTrue(true);
        return;
    }

    Assert.Fail();
}

Результат теста:
Tests (1 test) [0:00.989] Success
 yami.ui.tests (1 test) [0:00.989] Success
  yami.ui.tests.Services (1 test) [0:00.989] Success
   SettingsModelTest (1 test) [0:00.989] Success
    Test [0:00.989] Success

Трассировка отладки:
Hello
Say hello called


text:
Q: SQL profiler not showing RPC calls When I am running SQL profiler to trace the sql queries being executed, the trace is showing only Audit logs, not the sql commands being executed.
Can somebody tell me how to get the sql commands also?
Thanks

A: In the "Events Selection" tab of the trace definition, make sure that the TextData column is checked for RPC:Completed events.
(This is unchecked in the default trace definition)


text:
Q: How to fix problem with editing e.g. menu or list items I work on APEX 19.1, and i have a problem with editing e.g. lists. Problem concerns only items with "polish" characters..
For example i have list, which i use for menu. I have entry for example "Ą". When i create it and save it it save it as "A??". when I would like to edit via the form, error occurs
Session state protection violation: This may be caused by manual alteration of protected page item P4052_N. If you are unsure what caused this error, please contact the application administrator for assistance.

But i can edit it through "Grid Edit".
P4052_N it's an item used on administrating page 4052. This page is for editing List Entry.

I used inspect via Google Chrome and i found that it keeps the value with name of entry list. There is a problem only with entries that contains "polish" characters.

A: The problem was caused by CAS filters.
I resolved it in this question:
Encoding problem with APEX app builder caused by CAS


text:
Q: Sys Routing Table Router: Destination IP, Gateway IP and Public IP are different, something unusual? I am currently studying my home network router Sys Routing Table and attempting to resolve WHY my Public IP (assigned by my ISP), Gateway IP (WAN) and Destination Network (WAN) are all different.
I assume the Gateway IP would be identical to my Public IP as I believe the Destination Network IP is an internal network at my ISP.
For example, this is what I am seeing:
Destination Network (WAN): 205.211.222.192
Gateway IP (WAN): 205.211.222.254
Public IP: 205.211.222.208
It appears the ISP has a different Gateway IP assigned to my router as the Public IP is obviously not a match.
From what I can tell, the Destination Network is an internal network at the ISP.
The Gateway IP is a secondary IP, assigned to my router. Public IP is another IP, assigned to my router?
The latter two points is where I am confused.
I did some pretty intense research on this and getting mixed results and answers as to why this is happening.
I am not running any independent Firewalls or otherwise. Just a standard TP-Link Archer C9 with default settings.
This was another article I read on this exchange, but seemed to be a variant issue (different setup):
https://networkengineering.stackexchange.com/questions/20063/why-is-my-routers-wan-ip-different-from-public-ip
I did some further research and received some data about the fact that this could be related to a subnet requirement of the ISP, but it's still not clear.

A: This looks completely normal to me.
205.211.222.192/26 (The 26 is derived form the fact that 192 is the lowest address in that subnet and 255 is the highest making for a 64 address subnet) is the subnet at your ISP into which your router connects its WAN port.
The default gateway on that subnet is 205.211.222.254, which your router is to use as its WAN gateway to reach the rest of the internet.
Your router gets 205.211.222.208 as its own WAN ip-address in that subnet and which is also its public IP.
205.211.222.192/26 is NOT an internal network. It is a public network which according to the WHOIS registration belongs to "Honduras Tegucigalpa Amnet Cable Tegucigalpa" which is an ISP in Honduras. (They can have rented out this range to another ISP though. This sometimes happens.)
It is quite possible other addresses in this subnet are allocated to other customers of your ISP. It is very unlikely you got that whole 64 address subnet to yourself.


text:
Q: Mongoose: Using objectModel.schema doesn't work for parameter in other schema? With mongoose, if you define two Schemas:
const mongoose = require("mongoose");

const objectAModel = require("/pathTo/objectAModel");

const Schema = mongoose.Schema;

const objectBSchema = new Schema({
  _id: Schema.Types.ObjectId,
  objectAArray: [objectAModel.Schema]
});

module.exports = mongoose.model("objectB", objectBSchema);

const mongoose = require("mongoose");

const objectBModel = require("/pathTo/objectBModel");

const Schema = mongoose.Schema;

const objectASchema = new Schema({
  _id: Schema.Types.ObjectId,
  objectBArray: [objectBModel.Schema]
});

module.exports = mongoose.model("objectB", objectBSchema);

The first code works fine, but the second one throws an error:
TypeError: Invalid value for schema Array path `ObjectBArray`

So, I can't identify the problem, since both of the code snippets are the same, and if I delete the .schema from the objectBArray in the second snippet, everythin works. What's the problem?

A: The problem is you have circular dependencies. The way to solve it would be to create a reference from one model to the other as follows:
// the schema in objectB.js
const objectBSchema = new Schema({
  _id: Schema.Types.ObjectId,
  objectAArray: [{
     type: Schema.Types.ObjectId,
     ref: "objectA"
  }]
});

module.exports = mongoose.model("objectB", objectBSchema);

// the schema in objectA.js
const objectASchema = new Schema({
  _id: Schema.Types.ObjectId,
  objectBArray: [{
     type: Schema.Types.ObjectId,
     ref: "objectB"
  }]
});

module.exports = mongoose.model("objectA", objectASchema);

Note that now you don't need to import the models in to other model files at all. Also the ref name must match exactly to what you name your model in mongoose.model. Lastly you would be storing the _id of the related models in this array, and you can use .populate to fetch the related documents when running a find query


text:
Q: Drupal or Umbraco: which is easiest for a junior dev/designer to come to terms with? Out of Drupal and Umbraco, in your opinion which CMS would be easiest for a junior dev / designer to come to terms with?
Initial configuration will be by an experienced developer, with handover to an in-house junior. I'm not a programmer, so forgive my terminology - but is one built using a more common language than the other, for instance? Are there particular traps / benefits of each one? Also, which one has a more active developer community?
I realise it's really hard to do this if you haven't worked in both, but I'd really appreciate any thoughts to help with choosing between these two systems - both of which meet our stated business requirements.
Thanks so much for your help,
V

A: As I said in my comment, ideally you should leave this decision up to the developer in question. As choosing a CMS based on their choice of language will cut down development time considerably.
The strongest trait Drupal brings onto the table, is the fact that it has been around for quite some time and has a huge community supporting it. Its choices/options of modules are also very extensive as this would be a good point to factor into your decision. The documentation and guides that are available freely on the net may also aid your junior developer.
Just my 2 cents.


text:
Q: Escaping @ sign in a link in Razor I have a link with an @ sign inside my razor view.
like so: example.com/@problem
I tryed the following:

*

*Escaping @ using @@

*Putting my string in myString block

*Verbatim string

*Encoding @ as &#64 and %40

*Putting my string in Html.Raw(myString)

and various combinations of the above. But i keep getting the following Parser error:
Parserfehlermeldung: "problem" is not valid at the start of a code block.  Only identifiers, keywords, comments, "(" and "{" are valid.
I checked various other answers but nothing worked for me.

A: this works fine for me @Html.Raw("example.com.@tt") and so does this @Html.Raw("<text>example.com.@tt</text>")


text:
Q: TypeError: _this._transport.sendEvent is not a function I have successfully provisioned Device, I am using X509 certs for provisioning and its working fine. Now I want to send device messages to IoT hub, so I have created a separate class DeviceHelper, but I am getting this error. Can somebody please help?
TypeError: _this._transport.sendEvent is not a function
Code for Device Provisioning

var fs = require('fs');
var DeviceHelper = require('./device-helper');
var Transport = require('azure-iot-provisioning-device-http').Http;
var X509Security = require('azure-iot-security-x509').X509Security;
var ProvisioningDeviceClient = require('azure-iot-provisioning-
device').ProvisioningDeviceClient;
// Register the device.  Do not force a re-registration.
        deviceClient.register(function (err, result) {
           if (err) {
               that.setProvisionStatus(PROVISION_STATUS.ERROR);
            console.log(err);
        } else {
            console.log('registration succeeded');
            that.assignedHub = result.assignedHub;
            console.log('assigned hub=' + result.assignedHub);
            console.log('deviceId=' + result.deviceId);
            var deviceHelper = new DeviceHelper(that.deviceId, that.assignedHub, deviceCert, Transport);
            deviceHelper.sendEvent();
        }
    });

DeviceHelper code:

var Device = require('azure-iot-device');
    var Client = Device.Client;
    var X509AuthenticationProvider = Device.X509AuthenticationProvider;
    var Message = Device.Message;
    var Http = Device.Http;

    var client = {};
    class DeviceHelper {

      constructor(deviceId, hubName, security, transport) {
        client = Client.fromAuthenticationProvider(X509AuthenticationProvider.fromX509Options(
          deviceId, hubName, security
        ),transport);
      }

      print(err, res) {
        if (err) console.log(err.toString());
        if (res) console.log(res.statusCode + ' ' + res.statusMessage);
      }

      sendEvent() {
    // Error on this line
        client.sendEvent(new Message('hello world'), this.print);
      }
    }

    module.exports = DeviceHelper;

Console log of the issue:
TypeError: _this._transport.sendEvent is not a function
index.js:23
message:"_this._transport.sendEvent is not a function"
stack:"TypeError: _this._transport.sendEvent is not a function\n at D:\Working\Brahma\web-communicator\server\iot-agent\node_modules\azure-iot-device\lib\client.js:216:30\n at retryOperation (D:\Working\Brahma\web-communicator\server\iot-agent\node_modules\azure-iot-device\node_modules\azure-iot-common\lib\retry_operation.js:31:13)\n at RetryOperation.retry (D:\Working\Brahma\web-communicator\server\iot-agent\node_modules\azure-iot-device\node_modules\azure-iot-common\lib\retry_operation.js:57:9)\n at Client.sendEvent (server\iot-agent\node_modules\azure-iot-device\lib\client.js:214:17)\n at DeviceHelper.sendEvent (\device-helper.js:22:12)\n at \iot-device.js:99:30\n at D:\Working\Brahma\web-communicator\server\iot-agent\node_modules\azure-iot-provisioning-device\lib\x509_registration.js:50:33\n at constructor._onEnter (D:\Working\Brahma\web-communicator\server\iot...
proto:Error {constructor: , name: "TypeError", message: "", …}

A: I suggest you take a look at azure-iot-sdk-node/device/samples/simple_sample_device.js, it provides a nice example on how to send a message using the SDK.
Hope it helps!

A: The transport that you are sending to your deviceHelper constructor appears to be a provisioning transport.  I think you want to send a device client transport.  Your code snippet for the deviceHelper module does a require on a device transport.  That is the kind of transport that has a send.


text:
Q: The build_absolute_uri function always generates url with the http protocol The build_absolute_uri function of the request object generates a url with the http protocol, although the url with the https protocol is obviously. Is it possible to somehow force the generation of a security protocol?

A: That sounds strange. The docs say, that the method HttpRequest.build_absolute_uri() always uses the protocol of the current request:

Mixing HTTP and HTTPS on the same site is discouraged, therefore build_absolute_uri() will always generate an absolute URI with the same scheme the current request has [...]

Are you sure that you are using https in the current request?


text:
Q: CKEditor works - but get error "Uncaught ReferenceError: CKEDITOR is not defined" I have an inline CKeditor on my page and it works fine. It posts AJAX after its been updated, all works great.
However, in the console I get the error "Uncaught ReferenceError: CKEDITOR is not defined"
I discovered this when I was trying to modify the toolbar in the javascript, but the toolbar wasn't changing.
Any ideas what is going on here?
<div id="editor<?php echo $sub_category['id'] ?>" contenteditable="true" class="contentz ckeditor" typeID="<?php echo $sub_category['id'] ?>">
<?php if($sub_category['content']==""){ echo "Click here to add some content"; }else{ echo $sub_category['content']; } ?>
</div>
<script>

    // Turn off automatic editor creation first.
    CKEDITOR.disableAutoInline = true;
    CKEDITOR.inline('editor<?php echo $sub_category['id'] ?>');

</script>

This is called just before the body tag...
<script src="assets/js/ckeditor/ckeditor.js"></script>
<script src="assets/js/ckeditor/adapters/jquery.js"></script>

A: Move
<script>
    CKEDITOR.disableAutoInline = true;
    CKEDITOR.inline('editor<?php echo $sub_category['id'] ?>');
</script>

after
<script src="assets/js/ckeditor/adapters/jquery.js"></script>

because you must load ckeditor.js library first and then configure it with CKEDITOR methods/properties


text:
Q: Converting color struct to tensor for input into an onnx model In Unity, I'm working to feed input from the computer's webcam into a model I've already trained to recognize faces. I already have the webcam streaming frames into my code and my model loaded and ready to take input. But having never worked with C# until this project, I'm struggling to turn the webcam's texture into a tensor.
Here's my code so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System.Runtime.InteropServices;
using UnityEngine.UI;
using Unity.Barracuda;

public class EmotionModel : MonoBehaviour
{
    public RawImage rawImage;
    public NNModel dummyModel;

    private WebCamTexture camTexture;

    // Start is called before the first frame update
    void Start()
    {
        // Use cam_devices to allow a person to select their desired camera
        // For debugging purposes, prints available devices to the console
        WebCamDevice[] cam_devices = WebCamTexture.devices;
        for (int i = 0; i < cam_devices.Length; i++)
            Debug.Log($"Webcam available: {cam_devices[i].name}");

        // Assuming the first available WebCam is desired
        camTexture = new WebCamTexture(cam_devices[0].name);
        rawImage.texture = camTexture;
        rawImage.material.mainTexture = camTexture;
        if (camTexture != null)
            Debug.Log($"Streaming [{cam_devices[0].name}]");
            camTexture.Play();
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("");
        Debug.Log("");
        Debug.Log("EmotionModel Update Called");

        // Create worker for the model
        IWorker worker = dummyModel.CreateWorker();

        // Get current frame
        // They're float values of 0 to 1. Which is what we want; our
        // input needs to be normalized to be 0 to 1 values anyways.
        Color[] frameColors = camTexture.GetPixels();
        Debug.Log($"Red: {frameColors[0].r}");
        Debug.Log($"Green: {frameColors[0].g}");
        Debug.Log($"Blue: {frameColors[0].b}");
        /* SOMEHOW convert this stupid thing into the tensor down there ↓ */

        // Execute neural network with specific input and get results back
        //Tensor inputImage = new Tensor(1, frameColors[0], frameColors[1], frameColors[2], 3);
        Tensor inputImage = new Tensor(1, 224, 224, 3);
        var outputPreds = worker.Execute(inputImage).PeekOutput();

        // Access values of the output tensor causing the main thread to block until neural network execution is done
        var predIndex = outputPreds.ArgMax()[0];

        Debug.Log($"Predicted Index: {predIndex}");
        Debug.Log($"Prediction Confidence: {outputPreds[predIndex]}");

        // Disposes
        try {
            worker.Dispose();
        } catch (NullReferenceException e) {
            Debug.Log("Failed to dispose of worker (does worker exist?).");
        }
        try {
            inputImage.Dispose();
        } catch (NullReferenceException e) {
            Debug.Log("Failed to dispose of inputImage tensor (does inputImage exist?).");
        }
    }
}

As you can see in this line:
Color[] frameColors = camTexture.GetPixels();

I've converted the texture into a Color structure. That lets me access the pixel values; you can me printing out the rgb values of the first pixel right below it. But I can't figure out where to go from there.

A: I think you simply want to use another constructor.
There is Tensor(UnityEngine.Texture srcTexture, int channels = 3, string n = "") which looks exactly like what you are trying to achieve.
So probably simply
var inputImage = new Tensor(camTexture);


text:
Q: How to get large number in Amazon Redshift? I am trying to get epochtime (13 digits) after subtracting from task_end_time column using something like
((task_end_time - to_date ('01 Jan 1970 00:00:00', 'DD Mon YYYY HH24:MI:SS')) * 24 * 3600* 1000)::bigint AS "log_datetime"

This gives me below exception
ERROR: XX000: Integer data overflow (multiplication)

A: seems like all you actually need to do is
extract('epoch' from task_end_time) AS "log_datetime"


text:
Q: Running workflow from failed session
Possible Duplicate:
How to run only failed sessions in a workflow

This is a question which is already asked...
In a workflow there are sessions connected in parallel and in sequence. Suppose some sessions which are in parallel and in sequential mode are failed, How do I restart the workflow with only failed sessions. How can I design this in Informatica?
...
i saw the answer that we wil update database with status and then when we start workflow, before each session we will check the status and run if it is failed. How we will check this from session? How this is acheived?

A: You will have to write custom shell scripts for this and before each session include a command task that will connect to the database and check for the success records.
You can find the information in Informatica's Repository tables REP_WFLOW_RUN and REP_SESS_LOG tables for the latest runs. IF you need more controlled logging, you can write custom code to implement these.
You can look at some of the template code in the links mentioned below. However, the scripts I have written are to check event waits . You'll have to modify them, but this should give you a general idea.
http://www.etl-developer.com/2011/04/workflow-dependency-in-informatica-part-2-load-status-entries/
http://www.etl-developer.com/2011/12/extending-functionality-using-command-tasks-informatica/


text:
Q: DataGridView column names not accessable after adding new column I'm trying to add a column to an existing data grid view and I'm getting an error after adding a column. Referencing the column by it's name throws a null reference exception and after some debugging I noticed, the names of the columns have disappeared after adding a column.
Before I add a new column you can see in the first image, that each column has a name. After I add a column, the second image shows the names of each column as being empty. No code was changed and the column being added to the data grid view was the only change.
DGV_List.Columns("Vendor").Visible = CB_Vendor.Checked

I've found one or two ways to get around this, such as directly referencing the column like Me.Vendor.Visible. But I'm curious why adding a new column could cause existing working code to fail.
Edit adding code
The code is really long so I'm linking it on pastebin. Also note the column was added manually and not with code. Nothing besides the form designer code changed when the error started.
Code that has null reference error after adding column
https://pastebin.com/inZCT27A
Form designer before adding column
https://pastebin.com/2nv33pA3
Form design after adding column
https://pastebin.com/7ULHpNwE

A: I am pretty sure that the problem lies in "WHEN" the CheckBoxs CheckedChanged event is fired.
If the check box is set to True in the designer, then, its CheckedChanged event will get fired "once" in the InitializeComponent method.
If the check box is set to False in the designer, then its CheckedChanged event will NOT be fired in the InitializeComponent method.
Because the check box is set to true in the designer, then "sometime" in the InitializeComponent method the CheckChanged event is going to get fired and when it does... you can NOT guarantee that the grid has been fully initialized.
Checking "anything" relating to the grid "before" it has been fully initialized is risky. This would easily explain some of the inconsistencies I and I am sure you have seen.
The main point would be that, because you DO want to reference the grid in the CheckChanged event of the check boxes, AND you DO want to have the check box initially checked, then you need to make sure the grid is fully initialized "before" you set the check box to True/False (checked/unchecked).
One way to do this is from the "designer", UNCHECK the check boxes that reference the grid. This will prevent the CheckedChanged event from firing in the InitializeComponent method when the grid may not be fully initialized.
Then in the forms Load event, where we can pretty much guarantee the grid is initialized fully, set the check boxes state to checked. Then the CheckedChanged event can fire without errors. …
Private Sub MCRI_Checker_Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  CB_Description.Checked = True
  CB_Drawing.Checked = True
  CB_FilePath.Checked = True
  CB_Quantity.Checked = True
  CB_ReqType.Checked = True
  CB_Vendor.Checked = True
  CB_WhereUsed.Checked = True
End Sub

I hope this helps and makes sense.


text:
Q: flex 3 cancel tooltip event I am trying to cancel a tooltip event (I only want it to display when the mouse is hovered over a certain area), and can't seem to figure it out. I tried stopPropagation, preventDefault, and stopImmediatePropagation, but none of them seem to work.
Here the code I am using:
        private function toolTipCreateHandler(event:ToolTipEvent):void {
            if(event.currentTarget.mouseX < 130) {
                var tooltip:PhotoToolTip = new PhotoToolTip();
                tooltip.src = event.currentTarget.toolTip;
                event.toolTip = tooltip;
            }
            else {
                event.stopImmediatePropagation();
            }
        }

Any ideas?
Thanks

A: Step one, add an event listener to detect when the mouse leaves the area you want the tooltip, run a function and title it something like "toolTipDestroyer"
Step two, You need to call the destroy method of the tooltip manager
private function toolTipDestroyer():void {
    if (myToolTip) {
        ToolTipManager.destroyToolTip(myToolTip);
        myToolTip= null;
    }
}

Also, just for readability, give your tooltip some other name than "tooltip", you'll find it easier to follow up on your code later. My example names it "myToolTip"


text:
Q: Borwein's algorithm for the calculation of Pi in Fortran is converging too fast The following implementation of Borwein's algorithm with quartic convergence in Fortran admittedly calculates Pi, but converges simply too fast. In theory, a converges quartically to 1/π. On each iteration, the number of correct digits is therefore quadrupled.
! pi.f90
program main
    use, intrinsic :: iso_fortran_env, only: real128
    implicit none
    real(kind=real128), parameter :: CONST_PI = acos(-1._real128)
    real(kind=real128)            :: pi
    integer                       :: i

    do i = 1, 10
        pi = borwein(i)
        print '("Pi (n = ", i3, "): ", f0.100)', i, pi
    end do

    print '("Pi:", 11x, f0.100)', CONST_PI
contains
    function borwein(n) result(pi)
        integer, intent(in) :: n
        real(kind=real128)  :: pi
        real(kind=real128)  :: a, y
        integer             :: i

        y = sqrt(2._real128) - 1
        a = 2 * (sqrt(2._real128) - 1)**2

        do i = 1, n
            y = (1 - (1 - y**4)**.25_real128) / (1 + (1 - y**4)**.25_real128)
            a = a * (1 + y)**4 - 2**(2 * (i - 1) + 3) * y * (1 + y + y**2)
        end do

        pi = 1 / a
    end function borwein
end program main

But after the second iteration, the value of Pi does not change anymore, as one can see for the first 100 digits:
$ gfortran -o pi pi.f90
$ ./pi
Pi (n =   1): 3.1415926462135422821493444319826910539597974491424025615960346875056357837663334464650688460096716881
Pi (n =   2): 3.1415926535897932384626433832795024122930792206901249618089158148888330110426458929850923595950007439
Pi (n =   3): 3.1415926535897932384626433832795024122930792206901249618089158148888330110426458929850923595950007439
Pi (n =   4): 3.1415926535897932384626433832795024122930792206901249618089158148888330110426458929850923595950007439
Pi (n =   5): 3.1415926535897932384626433832795024122930792206901249618089158148888330110426458929850923595950007439
Pi (n =   6): 3.1415926535897932384626433832795024122930792206901249618089158148888330110426458929850923595950007439
Pi (n =   7): 3.1415926535897932384626433832795024122930792206901249618089158148888330110426458929850923595950007439
Pi (n =   8): 3.1415926535897932384626433832795024122930792206901249618089158148888330110426458929850923595950007439
Pi (n =   9): 3.1415926535897932384626433832795024122930792206901249618089158148888330110426458929850923595950007439
Pi (n =  10): 3.1415926535897932384626433832795024122930792206901249618089158148888330110426458929850923595950007439
Pi:           3.1415926535897932384626433832795027974790680981372955730045043318742967186629755360627314075827598572

(The last output is the correct value of Pi for comparison.)
Is there an error in the implementation? I'm not sure, if real128 precision is always kept.

A: At the second iteration you have converged to as many digits as real128 can support:
ian@eris:~/work/stack$ cat pi2.f90
Program pi2

  Use, intrinsic :: iso_fortran_env, only: real128

  Implicit None

  Real( real128 ) :: pi

  pi = 3.1415926535897932384626433832795024122930792206901249618089158148888330110426458929850923595950007439_real128

  Write( *, '( f0.100 )' ) pi
  Write( *, '( f0.100 )' ) Nearest( pi, +1.0_real128 )
  Write( *, '( f0.100 )' ) Abs( acos(-1._real128) - Nearest( pi, +1.0_real128 ) )

End Program pi2
ian@eris:~/work/stack$ gfortran -std=f2008 -Wall -Wextra -fcheck=all pi2.f90
ian@eris:~/work/stack$ ./a.out
3.1415926535897932384626433832795024122930792206901249618089158148888330110426458929850923595950007439
3.1415926535897932384626433832795027974790680981372955730045043318742967186629755360627314075827598572
.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
ian@eris:~/work/stack$

Thus the further iterations show no change as it is already as accurate as it can be


text:
Q: Using dynamic id's or name's to change text of a label I have a flex app I'm working on and want to be able to loop thru a series of labels and assign the text for them
kinda like
var labelnum:String = "1013";
var elem:Label = this["label" + labelnum];
elem.text = "this one";

example of the grid items... I have both name and id set
<mx:GridItem width="100%" height="100%">
    <mx:Label text="1005" id="label1005" name="label1005" />
</mx:GridItem>
<mx:GridItem width="100%" height="100%">
    <mx:Label text="1006" id="label1006" name="label1006" />
</mx:GridItem>
<mx:GridItem width="100%" height="100%">
    <mx:Label text="1007" id="label1007" name="label1007" />
</mx:GridItem>
<mx:GridItem width="100%" height="100%">
    <mx:Label text="1008" id="label1008" name="label1008" />
</mx:GridItem>

What is the proper way to access these labels and change the text?


text:
Q: Behavior of delete different for a pointer and array I stumbled on this problem while tinkering with old school arrays. An interesting one though:
a[] = {1,2,3,4,5};
a[][] = {{1,2,3,4}, {4,5,6,7}, {8,9,10,11}, {12,13,14,15}}

Consider 2 scenarios:
1.)
void func(int *a) { //passing a 1D array
   a[1] = 100; //modified an element here
   delete a;  //This would have no effect on the array outside this function.
}

2.)
void func(int (*a)[4]) { //passing a 2D array
   a[1][2] = 100; //modified an element here of 2D array
   delete a;  //Would have an effect on the outside. Would delete a[0][0]'s memory outside.
}

Question is why?
In 1.) pointer shall point to an array variable memory hence, the delete signature won't clear the memory a[0]?
In 2.) the signature of parameter and passed variable match exactly hence the delete would indeed delete the memory held by local variable?
Any pointers here?

A: You're invoking undefined behavior on multiple levels.  Calling delete on an array rather than delete[]...and calling any form of delete on an object not allocated with new.
Your program can do anything it wants.


text:
Q: Edit info.plist file using applescript/terminal How can I add
<key>NSUIElement</key>
<string>1</string>

to an info.plist file using applescript or terminal? Or is there another way to automatically make an application into a daemon?

A: plutil -convert text /Info.plist/file/location will convert the file from binary format to text in-place, from which you can then add your new key and value. The command has other options, but I couldn't figure out how to get -insert or -replace working on Mavericks. If someone does, feel free to edit this answer or leave a comment and I'll edit it.


text:
Q: Linear regression with interaction fails in the rms-package I'm playing around with interaction in the formula. I wondered if it's possible to do a regression with interaction for one of the two dummy variables. This seems to work in regular linear regression using the lm() function but with the ols() function in the rms package the same formula fails. Anyone know why?
Here's my example
data(mtcars)

mtcars$gear <- factor(mtcars$gear)
regular_lm <- lm(mpg ~ wt + cyl + gear + cyl:gear, data=mtcars)
summary(regular_lm)

regular_lm <- lm(mpg ~ wt + cyl + gear + cyl:I(gear == "4"), data=mtcars)
summary(regular_lm)

And now the rms example
library(rms)

dd <- datadist(mtcars)
options(datadist = "dd")

regular_ols <- ols(mpg ~ wt + cyl + gear + cyl:gear, data=mtcars)
regular_ols

# Fails with:
#     Error in if (!length(fname) || !any(fname == zname)) { :
#         missing value where TRUE/FALSE needed
regular_ols <- ols(mpg ~ wt + cyl + gear + cyl:I(gear == "4"), data=mtcars)

This experiment might not be the wisest statistic to do as it seems that the estimates change significantly but I'm a little curious to why ols() fails since it should do the "same fitting routines used by lm"

A: I don't know exactly, but it has to do with the way the formula is evaluated rather than with the way the fit is done once the model has been translated. Using traceback() shows that the problem occurs within Design(eval.parent(m)); using options(error=recover) gets you to the point where you can see that
Browse[1]> fname
[1] "wt"   "cyl"  "gear"
Browse[1]> zname
[1] NA

in other words, zname is some internal variable that hasn't been set right because the Design function can't quite handle defining the interaction between cylinders and the (gear==4) dummy on the fly.
This works though:
mtcars$cylgr <- with(mtcars,interaction(cyl,gear == "4"))
regular_ols <- ols(mpg ~ wt + cyl + gear + cylgr, data=mtcars)


text:
Q: Can I use the Windows boot.ini /3GB switch with less than 4 GB physical memory? I ran into this issue while creating an application that needs to allocate large contiguous amounts of memory and must run on 32-bit Windows XP computers with 2 GB of physical memory.
Initially I ran into out-of-memory problems. Setting the /3GB switch in boot.ini and LARGE_ADDRESS_AWARE in the executable solved the problem on my computer with 4 GB of physical memory.
The question is: can I use the same strategy on a computer with less than 4 GB of physical memory, e.g. 2 GB? I.e., are these options all about the virtual address space, or do they have some relation to physical memory as well?

A: The /3GB switch does apply to virtual memory, so you can use it on a machine with less memory.  It is discussed here.  That's not to say that you will get great performance using that option in that situation.  But if it is simply a matter of "making things work", then it may be a reasonable solution.


text:
Q: How to install Mono 2.6 on Ubuntu 9.10? I need urgently to install Mono 2.6 on Ubuntu 9.10 but in Synaptic the version 2.6 doesn't appear :-(
Is there an other repository I can use to install it ?

A: It looks like the latest version in the official repos is 2.4.  So you've got a couple of options.  If you're just using it temporarily you can download a virtual machine or live CD which has the latest build on it from the Mono download page.  However, if a VM or live CD will not do, you may have to compile Mono from source.

A: You can install mono from source.

A: Short answer... You can't
Long answer... you can compile it from source but this requires you to be a quite advanced user. The mono project is produced by Novell, Novell has a linux distro called opensuse which competes with Ubuntu. Novell therefore has no incentive to package mono for ubuntu.
I have asked this same question on the mono mailing list the answer was that it is up to the ubuntu devs to package mono for ubuntu.  Seeing as ubuntu only packages stuff for its 6 monthly releases this means that they will not provide packaging for mono releases which happen after the feature freeze.
You will probably notice that the mono project provides packaging for all other major operation systems including: windows and mac osx. But not for ubuntu even though it has the largest mono user base.

A: I just installed mono 2.6 from source using the script/instructions from http://patrick.qmtech.net/blog/?p=14
It's not quite as easy as the default install, but pretty well automated for a source install. The only additional step I needed to get my build server working was updating the path and pkg-config path so that 2.6 is found before 2.4.

A: The mono-cli team hasn't packaged it yet. So there are no packages to install. Further bad news is it's not coming in 10.04 (Lucid) either. So you will have to install from source, or package it yourself. Do not attempt the later... so install a parallel version of mono and you will not break your distro supplied mono. You can pick and choose which mono to use to run/build your apps. Get the script from my blog...
wget http://patrick.qmtech.net/downloads/mono_parallel.sh
chmod +x mono_parallel.sh
./mono_parallel.sh

Then...
mono-2.6 banshee-1
mono-2.6 mono -V
mono-2.6 your-app

Newer version of MonoDevelop will find your parallel version of mono and allow you to compile against either. Cool huh?


text:
Q: How to pause Media Player of a specific app? I need to pause a player of a specific application - for example Spotify. But if some other player plays I would like to keep it playing and only pause the Spotify.
Is there any function how I can do it?
I ended up with possibility to pause all apps, but not the specific one.
Or other help would be if I could identify what app is currently playing a Media Player and if it is Spotify then I can pause all apps, but I will know that I stop only Spotify.
Cheers

A: There is no way to way extensively to stop particular app player audio
If they implement music api which is directly implemented with hardware
then if you play music in your app then its automatically stop
with AudioManager. You can also get callback if other application play audio.
 private OnAudioFocusChangeListener focusChangeListener =
     new OnAudioFocusChangeListener() {
         public void onAudioFocusChange(int focusChange) {
                             AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
                    switch (focusChange) {

                           case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
                           // Lower the volume while ducking.
                           mediaPlayer.setVolume(0.2f, 0.2f);
                           break;
                           case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
                           pause();
                           break;

                           case (AudioManager.AUDIOFOCUS_LOSS) :
                           stop();
                           ComponentName component =new ComponentName(AudioPlayerActivity.this,MediaControlReceiver.class);
                           am.unregisterMediaButtonEventReceiver(component);
                           break;

                           case (AudioManager.AUDIOFOCUS_GAIN) :
                           // Return the volume to normal and resume if paused.
                           mediaPlayer.setVolume(1f, 1f);
                           mediaPlayer.start();
                           break;
                           default: break;
        }
    }
};


text:
Q: Disambiguate package name from local var in Go Is there a good way to disambiguate between a package name and a local variable? I'd rather not refactor the import name or variable name if I don't have to. Take for example...
import "path"

func foo() {
    path := "/some/path"
    // Disambiguate here
    path.Join(path, "/some/other/path")
}

A: There are two additional options I can think of:

*

*store path.Join in a variable

*make path a type that implements Join
The first is simple. Instead of path.Join you store path.Join in a variable before declaring path and call it instead (play):
join := path.Join

path := "/some/path"
path = join("/some/other/path")

The second is a bit more complicated and I don't think you should actually do that but it is a possibility
(play):
type Path string

func (p Path) Join(elem ...string) string {
    return path.Join(append([]string{string(p)}, elem...)...)
}

fmt.Println("Hello, playground")

path := "/some/path"

path = Path(path).Join("/some/other/path")

A: The local variable always overrides (shadows) the package here. Pick another variable name, or alias the package as something else:
http://play.golang.org/p/9ZaJa5Joca
or
http://play.golang.org/p/U6hvtQU8dx
See nemo's alternatives in the other answer. I think the most maintainable way is to pick a variable name that won't overlap with the package name.


text:
Q: Cartesian to geodetic conversion of 3D bounding box - How to calculate latitude and longitude from an axis aligned bounding box I have a geometry with its vertices in cartesian coordinates. These cartesian coordinates are the ECEF(Earth centred earth fixed) coordinates. This geometry is actually present on an ellipsoidal model of the earth using wgs84 corrdinates.The cartesian coordinates were actually obtained by converting the set of latitudes and longitudes along which the geomtries lie but i no longer have access to them. What i have is an axis aligned bounding box with xmax, ymax, zmax and xmin,ymin,zmin obtained by parsing the cartesian coordinates (There is no obviously no cartesian point of the geometry at xmax,ymax,zmax or xmin,ymin,zmin. The bounding box is just a cuboid enclosing the geometry). Is there any way to get at least an approximate extents (min, max) of latitude and longitude using this bounding box?
The other idea is to reconvert all the cartesian points to latitude and longitude individually and then find the min, max from that but it is computationally too heavy.


text:
Q: Como usar MBDootstrap Angular Scroll animation? Estado realizando prácticas con MDBootstrap para angular. (Instalado desde npm).
En su documentación tienen tutoriales de como utilizar las animaciones de css.
Probe las animaciones y todo bien, el problema es cuando trato de implementar las animaciones con Scroll, la cual debes utilizar la clase .wow y agregar el script correspondiente (El cual no se si estoy agregando realmente el adecuado), alguien sabe como implementarlo?
Ejemplo: En mi app.component tengo un
 con la clase wow y el efecto de animacion fadeInUp
>
Why is it so great?

luego en mi index.html , antes de del cierre de la etiqueta  tengo el script:


text:
Q: Datagrid detailed view of selected rows visibility I am having a Datagrid with some set of values.
I need to display it in another grid when a row of the Data grid is selected.I have binded that grid with datagrid. Its all working fine.
I need to display that detailed view only when any row in the datagrid is selected. Otherwise it should be hidden.
How can i acheive it?
Since am a beginner i couldn't figure out how to acheive this.
I ll be glad if i get some responses.

A: Try to change visibility of grid object with datatrigger e.g. where Datagrid has name LISTNAME
    <Grid>
        <Grid.Style>
            <Style TargetType="{x:Type Grid}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=LISTNAME, Path=SelectedIndex}" Value="-1">
                        <Setter Property="Visibility" Value="Collapsed"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Grid.Style>


text:
Q: How to determine End Of Life for Eclipse versions How do I determine the end of life date for Eclipse versions?
I have googled for Eclipse end of life and found this discussion:
https://www.eclipse.org/forums/index.php/t/160291/
But there was nothing in the conversation about the actual dates for EOL.

A: Eclipse doesn't really seem to use the term 'End of Life' at all. The Eclipse Project Archive site contains every release of Eclipse back to version 1.0 in 2001.
However only the current release is actively maintained with bug fixes and then only until the second fix release. Since Eclipse 3.0 the main product release has been annually in June followed by a fix release in September and another in the following February. So at the time of writing (March 2016) the second fix release of Eclipse 4.5 Mars (4.5.2) was released recently.
Bugs reported after the second fix release are included in the next major release (currently Eclipse 4.6 Neon).


text:
Q: mysql large query issue Hey guys, i had posted this question in another question but i didnt get a helpful response. Partly because i dont think i explained myself properly. So im going to try again.
I've been programming a back end server in vb.net and its been using a mysql database to store information. I was up until a couple of days ago using a webhost's mysql server to do this.
I did not care to renew my webhost so ive moved everything to a home server to continue work on my program. I've got mysql 5.5 installed (which is a newer version then the one on my previous webhost) and everything is working perfectly except for one thing so far.
This program when starting up for the first time sends a query about a million table inserts large. the query looks something like "INSERT into blah VALUES(1,1,1,1,1);INSERT into...." and so on. This used to take about 5-10 mins or so on my webhost (which i had my server program running on my home server machine and it was sending the info via the net to the webhost's mysql.)
Now doing everything locally i was hoping for this to be faster, but it didnt really matter i just needed it to work. So when i send this query it just locks up for a minute or so and then returns a timeout. When i check the table in the database it has loaded exactly 1000 items everytime i try this.
Now im assuming this is some sort of setting issue, however i've played with my "my.ini" to see if it would help, it didnt. I had tried switching to some of the pre-packaged my-huge or my-innodb etc and those did not help either. I would assume that if anything it would just take longer or something, not just timeout immediately after 1000 inserts.
And just for some background info the server machine im using has a quad core core i7, 8gb ram, and a 1tb hd in it running windows 7.
Any help would be great thank you.

A: Probably your query is too large, you can tune MySQL behavior via max_allowed_packet option.
You can also save some bytes by combining several insert queries into one, like this: INSERT INTO blah VALUES(1,1,1,1,1),VALUES(2,2,2,2,2),VALUES(3,3,3,3,3). But if this large combined query fails, then data in that insert will fail too.
But in my opinion it's not the smartest way to do it. If your application should import huge sql dump on start, it can possible use mysql executable like this mysql -uroot -ppassword db_name < dump.sql and you're done. It will be possibly the most effective way to accomplish this task.


text:
Q: How to use VBA to show/hide a sheet using option buttons (Worksheet_Change not triggered by option values) I am trying to show or hide a worksheet based on a cell value.
I used to achieve this through a dropdown list, but I am now trying to use option buttons instead. Since changing the approach, my code no longer works.
In my example, the dropdown (JobType) had options Empty, "Type1" and "Type2" as possible values.
Instead of the dropdown, I now have two option buttons, one for "Type1" and "Type2".
These are linked to cell G10.
Cell H10 is named JobType and contains the following formula:
=IF(G10=1, "Type1", IF(G10=2, "Type2", ""))

I want MyWorksheet to be visible when the "Type1" or "Type2" buttons are selected, and not visible when they are both cleared.
I am using the following code:
    Private Sub Worksheet_Change(ByVal Target As Range)
        If Not Intersect(Range("JobType"), Target) Is Nothing Then

            Application.ScreenUpdating = False
            Worksheets("ThisWorksheet").Visible = False

            Select Case Range("JobType").Value
                Case "Type1"
                    Worksheets("ThisWorksheet").Visible = True
                Case "Type2"
                    Worksheets("ThisWorksheet").Visible = True

            End Select
            Application.ScreenUpdating = True

        End If

End Sub

This worked with the dropdown, but not with the approach I am using now.
I am guessing it has something to do with replacing the direct value in the cell with the formula? Any guidance would be appreciated.

A: A Worksheet_Change is not triggered on a formula's calculation change so Target will never be H10. You need to work with G10 where the values are being set by the option buttons.
You can stack multiple possible results in a Select Case.
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Range("G10"), Target) Is Nothing Then

        on error goto safe_exit

        Select Case clng(target.Value)
            Case 1, 2
                Worksheets("ThisWorksheet").Visible = True
            Case else
                Worksheets("ThisWorksheet").Visible = false
        End Select

    End If

safe_exit:

End Sub

A: If using Option buttons I would add form control options buttons and associate them with the same macro optionButtons. I am not sure however, how you are getting both cleared unless you have another option button(s) i.e. at least an additional one for empty.
Then in a standard module put:
Option Explicit
Public Sub optionButtons()
    Application.EnableEvents = False
    Select Case Application.caller

    Case "Option Button 1", "Option Button 2"
         MsgBox "Unhiding sheet" ' < Do stuff
         ThisWorkbook.Worksheets("Sheet1").Visible = True
    Case "Option Button 3" '<==Empty option
         Msgbox "Hiding sheet"   ' .Visible = False
         ThisWorkbook.Worksheets("Sheet1").Visible  = False
    End Select

    Application.EnableEvents = True
End Sub


text:
Q: css content goes out of div Hi I have page http://rygol.cz/qlife/ and when Iam zooming out the content goes out of his div. If i you height: auto; or height: 100% its ok but leftcolumn is smaller then right, clear doesnt help me.
Have anybody some idea how to fix it?
#leftcolumn {
 color: #333;
 background: #fff;
 background-image:url("./images/corner.png");
 background-repeat:no-repeat;
 padding: 10px;
 height: 800px;
 width: 244px;
 float: left;
}
#rightcolumn {
 float: right;
 color: #333;
 background: #fff;
 padding: 10px;
 height: 800px;
 width: 638px;
 display: inline;
 margin-bottom: 10px;
}

A: If you need that extra space between header and the content you should just go ahead and place the #leftcolumn and #rightcolumn in an additional wrapper container with the background-color set and have the #container without the background-color set.
HTML structure:

And CSS:
#container {
margin: 0 auto;
width: 922px;
}

#header {
color: #333;
background: #fff;
width: 902px;
padding: 10px;
margin-bottom: 10px;
height: 200px;
}

#content-wrapper {
background-color: #fff;
min-height: 1px;
overflow: hidden; /* clear hack :) */
}

#leftcolumn {
color: #333;
background: #fff;
background-image: url("./images/corner.png");
background-repeat: no-repeat;
padding: 10px;
width: 244px;
float: left;
}

#rightcolumn {
float: right;
color: #333;
background: #fff;
padding: 10px;
width: 638px;
margin-bottom: 10px;
}

A: Remove the height declarations in the columns. You could also use overflow-y: scroll though I would stick to removing the heights. Another thing to consider is that people generally don't zoom out that far anyway: the text becomes impossible to read at the zoom level it breaks at (chrome v24).
If you want equal height columns have the shorter column floated to one side then set position: relative and top: 0; bottom: 0; then set the other column to have overflow: hidden; to 'clear' the float. Note: the floated column should come first in the markup for this to work.


text:
Q: Why is my Fraction object returns bad values as new object in C++? I'm trying to make Fraction object and overload a few operators. The problem is at the moment I want to multiply two fractions, because it returns fraction with numerator equals to -858993460 as well as denominator.
Fraction::Fraction(int numerator, int denominator)
{
    if (denominator == 0)
        throw std::overflow_error("Denominator can't be 0");
    else {
        this->numerator = numerator;
        this->denominator = denominator;

        if (this->numerator < 0 && this->denominator < 0) {
            this->numerator = -this->numerator;
            this->denominator = -this->denominator;
        }
    }
}

Fraction::Fraction(const Fraction & scndFraction)
{
    if (scndFraction.denominator == 0)
        throw std::overflow_error("Denominator can't be 0");
    else {
        this->numerator = scndFraction.numerator;
        this->denominator = scndFraction.denominator;
    }
}

Fraction & Fraction::operator*(const Fraction& scndFraction)
{
    // TODO: Sem vložte návratový příkaz.
    Fraction newFraction(this->numerator*scndFraction.getNumerator(),
        this->denominator*scndFraction.getDenominator());

    return newFraction;
}

And main.cpp
#include "Fraction.h"
#include <Windows.h>

int main() {
    //HANDLE hnd = GetStdHandle(STD_OUTPUT_HANDLE);
    //SetConsoleTextAttribute(hnd, FOREGROUND_BLUE);

    Fraction first(1, 2);
    std::cout << first.getFraction() << std::endl;

    Fraction second(1, 2);
    std::cout << second.getFraction() << std::endl;

    Fraction third = second * first;
    std::cout << third.getFraction() << std::endl;

    getchar();

    return 0;
}


text:
Q: How to solve the following system of differential equations?
If $x(t)$ and $y(t)$ are the general solution of the system of the differential equations: $$\frac{dx}{dt}+\frac{dy}{dt}+2y=\sin t $$ $$\frac{dx}{dt}+\frac{dy}{dt}-x-y=0$$ Then which of the following conditions holds for $x(t)$ and $y(t)$? ($a$ is any arbitrary constant)
(a) $x(t)+y(t)=ae^t$
(b) $x(t)+y(t)=a\sin t$
(c) $x(t)-y(t)=ae^{-t}$
(d) $x(t)-y(t)=ae^t+\sin t$

We can write the above system of equations as: $$Dx+(D+2)y=\sin t \label{eq:1}$$ and $$(D-1)x+(D-1)y=0$$
Now, how to solve for $x$ and $y$ ?
The solution says solving above equation for $x$ and $y$ to get:

 $(D-1)x=-\frac{\cos t - \sin t}{2}$ and $(D-1)y=\frac{\cos t - \sin t}{2}$

How to solve please let me know. Thanks.

A: The second equation is
$$\dot x+\dot y=x+y$$ and $x+y=ce^t$.
Then the first says
$$ce^t+2y=\sin t.$$
Done.

A: Multiplying the $1$st equation by $(D-1)$ and the $2$nd one by $D$ and then subtracting, we get
\begin{align}
\{(D-1)(D+2)-D(D-1)\}y&=\sin t\\
\implies (D-1)y&=\dfrac12\sin t\\
\end{align}
So the auxiliary equation is
$m-1=0\implies m=1$
So C.F is $y_c=ce^t$
For P.I, \begin{align}
y_p&=\dfrac{1}{D-1}\dfrac12 \sin t\\
&=-\dfrac14 \sin t\\
\end{align}
So the general solution is $y=ce^t-\dfrac14 \sin t$
Now $Dy=ce^t-\dfrac14 \cos t$
So from the $2$nd equation, we get
\begin{align}
&(D-1)x+ce^t-\dfrac14 \cos t-ce^t+\dfrac14 \sin t=0\\
\implies &(D-1)x=\dfrac14(\cos t-\sin t)\\
\end{align}
The auxiliary equation is
$m-1=0\implies m=1$
So C.F is $x_c=de^t$
For P.I, \begin{align}
x_p&=\dfrac{1}{D-1}\dfrac14(\cos t-\sin t)\\
&=\dfrac18 (\sin t-\cos t)\\
\end{align}
So the general solution is $x=de^t+\dfrac18 (\sin t-\cos t)$

A: Are you sure you copied correectly the system ? Maybe it's a minus sign instead of a positive one in one of the differential equation ?
Because if you substract both DE you get:
$$x+3y=\sin t $$
Use this to solve the seond differential equation:
$$x'+y'=x+y$$


text:
Q: suppress shell output while using python subprocess I am Running a python script to run download commands using shell script and subprocess
import subprocess

script = download.sh
log = open(logfile.txt,"a")
subprocess.run(script,shell=True,stdout=log)
log.close()

I want to supress the downloading indicatior part which is visible when you run when the download starts
I want to supress that part.

A: you need to capture the stderr as well:
subprocess.run(script,shell=True,stdout=log,stderr=log)


text:
Q: Autohotkey ... modifying the mouse/touchpad pointer speed? Is there any way (using autohotkey or not) to create a shortcut (two, actually) for modifying the mouse/touchpad pointer speed ?
I have two mices, and one touchpad, which I use alternatively ... and every one of them somehow differently sets its pointer speed. In any case, very annoying.
I also, sometimes would like to have touchpad at a greater speed, depending on what I'm doing at the moment.
So, does anyone know how that could be accomplished ? All ideas on the subject welcomed.

A: The registry key is loated in HKEY_CURRENT_USER\Control Panel\Mouse\MouseSensitivity but modifying this through AutoHotkey alone usually doesn't work. The best way is to use a DLL call:
^+u::DllCall("SystemParametersInfo", Int,113, Int,0, UInt,20, Int,2) ;high sensitivity
^+d::DllCall("SystemParametersInfo", Int,113, Int,0, UInt,5, Int,2) ;low sensitivity
^+n::DllCall("SystemParametersInfo", Int,113, Int,0, UInt,10, Int,2) ;normal sensisivity

Ctrl + Shift + u sets sensitivity to high, Ctrl + Shift + d sets it low, and Ctrl + Shift + n sets it back to default. Edit this script to your hearts content.
But, what you could use the registry for is querying the current value, so you can increment the speed by 1 like so:
^+u::
RegRead, MyVar, HKEY_CURRENT_USER, Control Panel\Mouse,MouseSensitivity
if (MyVar == 20)
{
    MsgBox Value is already at max
    Exit, 0
}
DllCall("SystemParametersInfo", Int,113, Int,0, UInt,%MyVar%+1, Int,2)
return

A: See if this AutoHotKey forum thread helps you: Adjusting Mouse Sensitivity via hotkey

A: For me Eithermouse works the best.
It automatically switches settings when using a specific device. This way the speed settings get automatically adjusted.
You also get a tray icon in the bottom of the screen where you can fine-tune the speed of the device currently in use.
http://www.eithermouse.com/
From their website
Multiple mice, individual settings!

Instantly changes settings when any mouse is used:
    swap buttons
    mirror cursor
    adjust speeds
    and more...

Leave multiple mice on a pc and automatically swap buttons on each mouse
Have a left-handed and a right-handed mouse always connected and ready to use
Great for multi-user/public workstations to accomodate both left and right handed users.
Possibly helps with RSI/injury issues by allowing switching between left and right hand.
Easily swap mouse buttons from system tray if only one mouse is used
Tray icon points to active mouse
Freeware! no ads, no nags, free software, suggestions appreciated!

Also see my answer here:
https://superuser.com/a/738986/313841