text:
Q: How do I display a webpage body text only in a web browser control? I'm trying to open a webbrowser control that points to a sharepoint page, but I need to strip out the masterpage and all the visual garbage and just display the body text. I'm kind of inexperienced with winforms, and I'm wondering how to do this. Is there a way to just display the body DOM element in the browser control
UPDATE:
I attempted to downloaded the full body text (with hopes of just substringing the body section), but I'm getting server errors "401 Unauthorized". I did set the credentials of the WebClient object to the appropriate username and password but still same error.
I also tried to snag the raw HTML from the WebBrowser control, but despite the fact that it WILL .navigate() successfully, if I try to access any of the control's properties, it says the WebBrowser control is not set to an instance of an object.

A: I think it cannot be done by using standard webbrouser control. You need manually parse html document and create a page that you want to see. Alternative option is to request necessary information from sharepoint web services and display it in a proper way.
Please look at SharePoint 2010 Web Services and Using the SharePoint Foundation 2010 Managed Client Object Model with the Open XML SDK 2.0. Second option is preferable.


text:
Q: How do i add music to my game? I have written a small game in 'c' that has 15 Levels. I am done with that work. But the thing I want is to add music to it. I am playing a song when the game starts using the
system("cmd /c start /min level1.mp3")

That is with the help of dos command.
It's working fine, but it's playing the file in its default player example like WMplayer or VLC player.But i want a separate player something like that plays music, something like that is hidden from user view but he should hear the sounds I wonder how the big games like EA sports and some Prince of Persia play the sounds . I believe they have their own sound drivers installed. Because their sounds wont be started in WMplayer or some other player.
I am satisfied to 90%. Now I'm more confident about me because writing a game in c and running music in the background. with some techniques i made it.But the drawback is, its played in the default player.So guys can anyone tell me how do i make it through? How do i play some music without the media player of computer? I mean how the sounds are added to games like some PS2 games.Thank you.I Just want to know the thing they do.

A: I'd suggest building the music player into the C program itself.
SDL_mixer is a good and fairly simple library for doing this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: i want to cache my webview content to load it faster SWIFT3 So far I tried this but I getting connection time out error. How to load a web view faster with caching can anyone help?(swift3)
here is my code
import UIKit

class test:UIViewController, NSURLConnectionDelegate{
var response: URLResponse?
var error: NSError?
var NSURLRequestReturnCacheDataElseLoad = 2
var sesson:URLSession!
var progressView:UIProgressView!
var urlData: Data?
var baseURLString: String = "https://google.com"

@IBOutlet weak var SubscribeWeb: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    var urlString: String = URL(fileURLWithPath: baseURLString).appendingPathComponent("/").absoluteString

    print("connection urlString = \(urlString)")
    let request = URLRequest(url: URL(string : urlString)!,
                             cachePolicy:NSURLRequest.CachePolicy.returnCacheDataElseLoad,
                             timeoutInterval: 100.0)
    print("connection request = \(request)")
    // var request = URLRequest(url: URL(string: urlString), cachePolicy: URLRequestReturnCacheDataElseLoad, timeoutInterval: 10.0)
    var connection = NSURLConnection(request: request, delegate: nil)
    print("connection = \(connection)")
    if (connection != nil) {

        do
        {

            try self.urlData = NSURLConnection.sendSynchronousRequest(request, returning: &response)//
            print("self.urlData = \(self.urlData)")
        }
        catch (let e) {
            print("error = \(e)")
        }

        let htmlString = String(data: urlData!, encoding: String.Encoding.utf8)
        //String(urlData,encode(with: String.Encoding.utf8))
        //  var htmlString = String(urlData, encoding: String.Encoding.utf8)

        let fileUrl = Foundation.URL(string: baseURLString)

        SubscribeWeb.loadHTMLString(htmlString!, baseURL: fileUrl)
        //SubscribeWeb.loadHTMLString(<#T##string: String##String#>, baseURL: <#T##URL?#>)
    }
    //ara test
    //        let url = NSURL (string: "https://google.com/")
    //        let requestObj = URLRequest(url: url! as URL,
    //                                         cachePolicy:NSURLRequest.CachePolicy.returnCacheDataElseLoad,
    //                                         timeoutInterval: 10.0)
    //       // let requestObj = URLRequest(url: url! as URL)
    //        SubscribeWeb.loadRequest(requestObj)
    // Do any additional setup after loading the view, typically from a nib.
}    //ara test

A: Not Sure but you have create .html file in local and write data in this file via URL . may be it is work .


text:
Q: Get the proper ordering or results from mysql query I'm using C#.
I'm trying to run a query to get the last 20 results in the database, but it returns them like this right now and says the last entry is number "1211".
1211
1210
1209 .. etc

If the last entry is "1211" I need it to start at "1191" and increment up!
I'm using this right now:
string query = string.Format("
    SELECT mesgnumber, targetid, targettype, data, timestamp, sendingid, contenttype
    FROM history
    WHERE targetid='{0}'
    AND targettype='{1}'
    ORDER BY mesgnumber DESC
    LIMIT 20",
    target, IsGroupToInt);

I have tried numerous methods, to no avail. I thought the following would work, yet it didn't:
string query = string.Format("
    SELECT mesgnumber, targetid, targettype, data, timestamp, sendingid, contenttype
    FROM history
    WHERE targetid='{0}'
    AND targettype='{1}'
    ORDER BY mesgnumber DESC
    LIMIT 20,
    mesgnumber ASC", target, IsGroupToInt);

I hope someone can help.

A: Order in one direction in a subquery, then reverse the order in the main query:
SELECT *
FROM (SELECT ... ORDER BY mesgnumber DESC LIMIT 20) AS subquery
ORDER BY mesgnumber ASC


text:
Q: compare nullable param to non-nullable column I have a non-nullable bit column and in my Select statement I would like to only compare it with a nullable param if that nullable param is not null. What's the best way of doing this? There are other conditions in the where clause though I would still like to execute.

A: This sounds like a typical "kitchen sink" kind of query. It would help your question if you provided some details other than a vague explanation. I think you are looking for something like this.
and (@YourParam is null OR [YourBit] = @YourParam)


text:
Q: How to combine JSON objects with equal values within Backbone.js I am trying to display multiple "unread" alerts, but need to attach the organizations label to it if the organizations id is equal to the unread domainId.
How can I acheive this while displaying the results in a handlebars #each function?
JSON
"alerts" : {
    "organizations" : [ {
      "id" : 165,
      "label" : "Label #1"
    }, {
      "id" : 170,
      "label" : "Label #2"
    }],
    "unread" : [ {
      "id" : 20022,
      "domainId" : 170,
      "created" : "2015-10-13T16:48:08Z",
    }, {
      "id" : 20022,
      "domainId" : 165,
      "created" : "2015-10-13T16:48:08Z",
    }]
};

Backbone.js:
context: function() {
  var d = this.options.data

  return {
    welcomeAlerts: d.alerts,
    welcomeOrg: d.alerts.organizations.label
    }
},

Handlebars//HTMl
{{#each welcomeAlerts.unread}}

{{welcomeOrg}}

{{created}}

{{/each}}

A: Simply transform the data beforehand
var data = {
 "alerts" : {
    "organizations" : [ {
      "id" : 165,
      "label" : "Label #1"
    }, {
      "id" : 170,
      "label" : "Label #2"
    }],
    "unread" : [ {
      "id" : 20022,
      "domainId" : 170,
      "created" : "2015-10-13T16:48:08Z",
    }, {
      "id" : 20022,
      "domainId" : 165,
      "created" : "2015-10-13T16:48:08Z",
    }]
 }
};

var organizationDict = _.groupBy(data.alerts.organizations, 'id');

var unreadWithOrganizations = _(data.alerts.unread)
  .map((message) => {
    return {
      ...message,
      organization: organizationDict[message.domainId]
    }
  })
  .value();

and display your data
{{#each unreadWithOrganizations}}

{{organization.label}}

{{created}}

{{/each}}

Demo: http://jsbin.com/sadoluhepu/edit?js,console
I've made an example using lodash library and es6. You might want to stick with ES6 and underscore, which implementation might differ.


text:
Q: language learning on ubuntu tablet I have a linux computer, but i use an android tablet. On my tablet i have a series of apps for learning french and spanish. My favorites are the "fun easy learn" apps which lets you memorize words. But i also use apps to help with verb conjugation. My question is this: will there be more language learning apps in the ubutnu app store for tablets?
My other uses for the tablet are listening to podcasts and radio, and watching netflix. I dot not write longer texts on the tablet.
For the phone, my favorite feature is the hotspot function which lets me use the phone as a router. Call blocking and recording conversations are essential because of the many telemarketers.

A: For language learning, I have found Anki very useful, which works on a variety of platforms, including Ubuntu. It is based on a technique called spaced repetition and, although not the best exponent of "fun" it is definitely "easy learn".
It works for many other fields, not just languages.


text:
Q: PLANE TYPE COLUMN BASED QUESTION
My approach is as follow
$D = \left| {\begin{array}{*{20}{c}}
{2\left( {a + b} \right)}&{3\left( {b + c} \right)}&{4\left( {a + c} \right)}\\
{2\left( {b + c} \right)}&{3\left( {a + c} \right)}&{4\left( {a + b} \right)}\\
{2\left( {a + c} \right)}&{3\left( {a + b} \right)}&{4\left( {b + c} \right)}
\end{array}} \right|$
$\alpha  = a + b;\beta  = b + c,\gamma  = a + c$
$D = \left| {\begin{array}{*{20}{c}}
{2\alpha }&{3\beta }&{4\gamma }\\
{2\beta }&{3\gamma }&{4\alpha }\\
{2\gamma }&{3\alpha }&{4\beta }
\end{array}} \right| \Rightarrow D = 2 \times 3 \times 4\left| {\begin{array}{*{20}{c}}
\alpha &\beta &\gamma \\
\beta &\gamma &\alpha \\
\gamma &\alpha &\beta
\end{array}} \right| \Rightarrow D = 24\left| {\begin{array}{*{20}{c}}
\alpha &\beta &\gamma \\
\beta &\gamma &\alpha \\
\gamma &\alpha &\beta
\end{array}} \right|$
$ \Rightarrow D = 24\left[ {\alpha \left( {\beta \gamma  - {\alpha ^2}} \right) - \beta \left( {{\beta ^2} - \alpha \gamma } \right) + \gamma \left( {\alpha \beta  - {\gamma ^2}} \right)} \right] = 24\left[ {3\alpha \beta \gamma  - \left( {{\alpha ^3} + {\beta ^3} + {\gamma ^3}} \right)} \right] = 24T$
${\left( {\alpha  + \beta  + \gamma } \right)^3} = \left( {{\alpha ^3} + {\beta ^3} + {\gamma ^3}} \right) + 3\left[ {\left( {\alpha  + \beta  + \gamma } \right)\left( {\alpha \beta  + \beta \gamma  + \alpha \gamma } \right) - \alpha \beta \gamma } \right]$
$ \Rightarrow T = 3\alpha \beta \gamma  - \left( {{\alpha ^3} + {\beta ^3} + {\gamma ^3}} \right) = 3\left( {\alpha  + \beta  + \gamma } \right)\left( {\alpha \beta  + \beta \gamma  + \alpha \gamma } \right) - {\left( {\alpha  + \beta  + \gamma } \right)^3}$
$ \Rightarrow T = \left( {\alpha  + \beta  + \gamma } \right)\left( {3\left( {\alpha \beta  + \beta \gamma  + \alpha \gamma } \right) - {{\left( {\alpha  + \beta  + \gamma } \right)}^2}} \right)$
$ \Rightarrow T = \left( {\alpha  + \beta  + \gamma } \right)\left( {3\left( {\alpha \beta  + \beta \gamma  + \alpha \gamma } \right) - {{\left( {{\alpha ^2} + {\beta ^2} + {\gamma ^2} + 2\left( {\alpha \beta  + \beta \gamma  + \alpha \gamma } \right)} \right)}^2}} \right)$
$ \Rightarrow T = \left( {\alpha  + \beta  + \gamma } \right)\left( {\left( {\alpha \beta  + \beta \gamma  + \alpha \gamma } \right) - \left( {{\alpha ^2} + {\beta ^2} + {\gamma ^2}} \right)} \right)$
$ \Rightarrow T =  - \frac{{\left( {\alpha  + \beta  + \gamma } \right)}}{2}\left( {2\left( {{\alpha ^2} + {\beta ^2} + {\gamma ^2}} \right) - 2\left( {\alpha \beta  + \beta \gamma  + \alpha \gamma } \right)} \right)$
$ \Rightarrow T =  - \frac{{\left( {\alpha  + \beta  + \gamma } \right)}}{2}\left( {{{\left( {\alpha  - \beta } \right)}^2} + {{\left( {\beta  - \gamma } \right)}^2} + {{\left( {\gamma  - \alpha } \right)}^2}} \right)$
$ \Rightarrow T =  - \left( {a + b + c} \right)\left( {{{\left( {a - c} \right)}^2} + {{\left( {b - a} \right)}^2} + {{\left( {c - b} \right)}^2}} \right)$
$ \Rightarrow T =  - 2\left( {a + b + c} \right)\left( {{a^2} + {b^2} + {c^2} - \left( {ac + ba + cb} \right)} \right)$
$D \ne 0;a + b + c \ne 0;{a^2} + {b^2} + {c^2} \ne ab + bc + ca$, hence $P \to 3$
Using this how do we find the other options?

A: $\bullet$ If $a+b+c=0$ and $ a^2 + b^2 + c^2 \neq ac + ba + cb $ $\implies $ $T=0$ so the equations have infinitely many solutions
$\bullet$ If $a+b+c\neq0$ and $ a^2 + b^2 + c^2 = ac + ba + cb $ $\implies $ $T=0$ and $a=b=c\neq0$ so the equations represent identical planes
$\bullet$ If $a+b+c\neq0$ and $ a^2 + b^2 + c^2 \neq ac + ba + cb $ $\implies $ $T\neq0$  so the equations represent planes meeting only at a single point
$\bullet$ If $a+b+c=0$ and $ a^2 + b^2 + c^2 = ac + ba + cb $ $\implies $ $T=0$ and $a=b=c=0$ so the equations represent the whole of $\mathbb{R^3}$


text:
Q: How to set the diagonal of a geom_raster plot to a different measure in R? I created a plot (and set the diagonals = 0) that looks like this:

But what I'm trying to achieve is something like this (which I made in powerpoint):

So, basically what Im wondering is if it's possible to have 2 separate measurements on the one plot and if so, how would I try and achieve this?
Any suggestions?
Thanks

A: It is generally a bad idea to combine to different types of data in the same plot. If you are going to do it, it is best if they are visually distinct. So, here is one approach to get what you want.
First, some sample data:
temp_data <-
  tibble(
    A = paste0("x", 1:5)
    , B = paste0("x", 1:5)
  ) %>%
  complete(A, B) %>%
  mutate(interaction = runif(n(), 0, 10)
         , Other = runif(n(), 0, 100))

Then, the plot, note that I am using two different geometries and filtering to only display the one I want for each (you could also do this from completely separate data frames if, for example, your secondary measure was stored somewhere else).
ggplot() +
  geom_raster(
    aes(x = A
        , y = B
        , fill = interaction)
    , temp_data %>%
      filter(A != B)
  ) +
  geom_point(
    aes(x = A
        , y = B
        , color = Other)
    , temp_data %>%
      filter(A == B)
    , size = 5
  ) +
  scale_fill_distiller(palette = "Blues") +
  scale_color_distiller(palette = "Reds")

Results in:


text:
Q: SSL Error When Making New Rails Project When I make a new rails project (on Windows) with rails new projectname -d mysql, it creates all the files and then returns this when it tries to perform bundle install:
C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/vendor/net/http/pe
rsistent/ssl_reuse.rb:70:in `connect': SSL_connect returned=1 errno=0 state=SSLv
3 read server certificate B: certificate verify failed (OpenSSL::SSL::SSLError)
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/vendo
r/net/http/persistent/ssl_reuse.rb:70:in `block in connect'
        from C:/Ruby193/lib/ruby/1.9.1/timeout.rb:54:in `timeout'
        from C:/Ruby193/lib/ruby/1.9.1/timeout.rb:99:in `timeout'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/vendo
r/net/http/persistent/ssl_reuse.rb:70:in `connect'
        from C:/Ruby193/lib/ruby/1.9.1/net/http.rb:755:in `do_start'
        from C:/Ruby193/lib/ruby/1.9.1/net/http.rb:750:in `start'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/vendo
r/net/http/persistent.rb:628:in `start'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/vendo
r/net/http/persistent.rb:570:in `connection_for'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/vendo
r/net/http/persistent.rb:930:in `request'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/fetch
er.rb:195:in `fetch'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/fetch
er.rb:169:in `use_api'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/sourc
e/rubygems.rb:223:in `block in remote_specs'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/sourc
e/rubygems.rb:223:in `select'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/sourc
e/rubygems.rb:223:in `remote_specs'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/sourc
e/rubygems.rb:162:in `fetch_specs'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/sourc
e/rubygems.rb:66:in `specs'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/defin
ition.rb:192:in `block (2 levels) in index'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/defin
ition.rb:189:in `each'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/defin
ition.rb:189:in `block in index'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/index
.rb:9:in `build'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/defin
ition.rb:185:in `index'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/defin
ition.rb:179:in `resolve'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/defin
ition.rb:114:in `specs'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/defin
ition.rb:109:in `resolve_remotely!'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/insta
ller.rb:83:in `run'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/insta
ller.rb:14:in `install'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/cli.r
b:247:in `install'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/vendo
r/thor/task.rb:27:in `run'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/vendo
r/thor/invocation.rb:120:in `invoke_task'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/vendo
r/thor.rb:344:in `dispatch'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/vendo
r/thor/base.rb:434:in `start'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/bin/bundle:20:in
`block in <main>'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/frien
dly_errors.rb:4:in `with_friendly_errors'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/bin/bundle:20:in
`<main>'
        Unfortunately, a fatal error has occurred. Please see the Bundler
        troubleshooting documentation at http://bit.ly/bundler-issues. Thanks!

I got the same error with Ruby 2.0 and thought that might be the problem but the same thing happened with Ruby 1.9.3 (the version I used for this).

A: After a bit of Googling, I came across a guide which shows you how to add the right SSL Cert file (which turned out to be the problem):
https://gist.github.com/fnichol/867550

A: I had the problem.I changed the gem source, then the problem has been solved.
First, check the gem sources with the following command:

gem sources -l

It should be 'https://rubygems.org/'.
Second, remove the gem sources with the following command:

gem sources --remove https://rubygems.org/

Third, add a new gem sources with the following command:

gem sources -a http://rubygems.org/

If you are in China, you also use the Taobao gem sources:

gem sources -a http://ruby.taobao.org/

Finally, it is OK.

When you created a new project,If you met this problem. You can change gem sources in th Gemfile file.
Change the gem sources
from

source 'https://rubygems.org/'

to

source 'http://rubygems.org/'

If you are in China, you also use the Taobao gem sources:

source 'http://ruby.taobao.org/'

then you should run the following command:

bundle install

Good Luck!

I'm not good at English.So, I am sorry.

A: If on linux, try installing libssl-dev and then recompile openssl from source.
sudo apt-get install libssl-dev
If you compiled ruby from source, navigate to your ruby source and go into the ext/openssl directory.
Within there, do ./configure && make && make install
See if you're able to create your new rails app.


text:
Q: How do I apply a style to multiple selections in Word using VBA? I created a macro that will apply a particular style to whatever is selected in the document. However, when in draft view, when the user clicks in the style area pane to select a paragraph and then Ctrl + clicks on an additional paragraph, this additional selection is not applied when this macro is run:
Sub BodyTextApply()
    Selection.Style = ActiveDocument.Styles("Body Text,bt")
End Sub

What do I need to add to this? Note: The workflow cannot change so that the user selects that actual text in the document; they are set on using the style area pane...
The workflow is as follows:
alt text http://img6.imageshack.us/img6/1994/91231840.png
The (undesired) output is as follows:
alt text http://img34.imageshack.us/img34/1239/outputt.png

A: Looks like your style "Body Text,bt" is a pure paragraph style. That means it will only be applied to a complete paragraph.
However, in your screenshot there is only part of the second paragraph selected. Make sure the complete paragraph is selected or, if the style should only be applied to part of the paragraph, make your style "Body Text,bt" a linked (paragraph and character) style.
Programmatic access to discontiguous selections is very limited, and such selections can only be created using the Word UI. The MSDN article Limited programmatic access to Word discontiguous selections gives some more details.
If applying the style only to part of the paragraph (by making it a linked style) is not what you want you probably have to come up with a hack like this:
Sub BodyTextApply()

    Dim oRange As Range

    ' create a temporary character style
    ActiveDocument.Styles.Add "_TEMP_STYLE_", wdStyleTypeCharacter

    ' apply the temporary style to the discontiguous selection
    Selection.Style = ActiveDocument.Styles("_TEMP_STYLE_")

    Set oRange = ActiveDocument.Range

    With oRange.Find
        .ClearAllFuzzyOptions
        .ClearFormatting
        .ClearHitHighlight
        .Style = ActiveDocument.Styles("_TEMP_STYLE_")
        .Text = ""
        .Wrap = wdFindStop

        ' search for all occurences of the temporary style and format the
        ' complete paraphraph with the desired style
        Do While .Execute
            oRange.Paragraphs(1).Style = ActiveDocument.Styles("Body Text,bt")
        Loop

    End With

    ' cleanup
    ActiveDocument.Styles("_TEMP_STYLE_").Delete

End Sub

You probably want to add some error handling as well to make sure that the temporary style used is finally removed from the document.


text:
Q: Mysql slow query log always include "# Time:" I am trying to parse the mysql slow log with logstash so it's important that the format is consistent. I have noticed that if statements execute at the same time, the line # Time: yymmdd is only logged once (see example below). I looked at the setting mysqld_log-long-format however this setting is deprecated and supposedily the default. I have not enabled the log-short-format option.
Is there any setting that can enforce the Time field to either always show, or always not show? I don't actually need the information since there is also a timestamp, I just need the output to be consistent.
# Time: 150419  6:00:43
# User@Host: web[web] @ localhost []
# Query_time: 7.730519  Lock_time: 0.000070 Rows_sent: 167620  Rows_examined: 167620
SET timestamp=1429416043;
SELECT /*!40001 SQL_NO_CACHE */ * FROM `messages`;
# Time: 150419  6:00:45
# User@Host: web[web] @ localhost []
# Query_time: 3.480173  Lock_time: 0.000101 Rows_sent: 0  Rows_examined: 0
SET timestamp=1429416045;
INSERT INTO user (lastupdated, fk_id, user_id) ..
# User@Host: web[web] @ localhost []
# Query_time: 3.388204  Lock_time: 0.000133 Rows_sent: 0  Rows_examined: 0
SET timestamp=1429416045;
INSERT INTO user (lastupdated, fk_id, user_id) ..

The logstash config I'm using looks like this - see logstash multiline codec
input {
  file {
     path => "mysql-slow.log"
     codec => multiline {
        pattern => "^# Time"
        negate => true
        what => previous
     }
  }
}

A: A lot of things have changed in the slowlog over the versions.  Discover the inconsistencies and code to them!
# Time (and maybe some other things) are specified only when they change.
In 5.7.2 Time will include microseconds.  This is one of many syntax changes that have happened over the years -- be careful.  Percona and MariaDB also have different things that can show in the SlowLog.
Query time used to be just an integer.

A: Well this answer doesn't make much sense when I can't add a logstash tag, but I've changed the multiline input codec to anchor each pattern to a # User line as the # Time line is not always present.
I can't find any way to change this setting in MySQL but I'll leave this question open for a while in case it is possible and someone knows.


text:
Q: angularjs - How to inject generated javascript I have a angular js page, in which I get a javascript generated dynamically from backend. The content is as follows

My HTML

My Controller
    $scope.init = function () {
        $scope.initForm({
            action: $attrs.action

        }, function (data) {
            $scope.htmlString = "
so Here it is
" + $scope.model.htmlScript + "";
        });
    };

However when the page is rendered, the javascript tags are filtered out and the rest is displayed. Please suggest how I can proceed?

A: Angular.js has a service called $sce (Strict Contextual Escaping) which automatically uses $sanitize on directives like ng-bind-html.  If you wish to override the escaping, you need to hook into the $sce service and explicitly trust your strings.
NOTE
This is generally not a recommended method to handle arbitrary HTML that can come from non-trusted sources, as it can open your site up to exploits.
$scope.htmlString = $sce.trustAsHtml(
     "
so Here it is
" + $scope.model.htmlScript + "");

A: Is there anyway you can inject the JS with a script tag at startup?  I do some similar kinds of things where I create a URL that calls a django view and that views is returned as javascript.  In the html it looks like this:

And I simply return a valid piece of javascript from the server.  Since it comes over as a script tag, the browser has no idea it was generated.  It's how I handle user specific customization.
In my django app, I return the response as content type 'application/javascript'
Given this kind of example, you could simply inject a


text:
Q: Azure Mobile Services and Blob I'm developing an app with both web based admin UI (html5/JS sdk) and iOS app (using iOS Azure sdk)
Now I have a requirement to store gallery images. I know one way of doing is saving base64 in db, but it's not feasible and not a good practice.
So I was experimenting ways to upload images to blob storage and store the url in the mobile service table. As far as I can see there is a C# tutorial but nothing much on html5 apps. Can someone point me to a correct resources.
I tried to implement it using this tutorial, but it just talks about setting the sass url
Any tips or helps appreciated. Thanks for your time in advance.

A: Now that Windows Azure Storage supports CORS, it is certainly possible to interact with blob storage directly from HTML 5 Apps.
First thing you would need to do is enable CORS on your storage account. My company released a free tool (its .Net based) which you can use to manage CORS rules. You can read more about the tool and download from here: http://blog.cynapta.com/2013/12/cynapta-azure-cors-helper-free-tool-to-manage-cors-rules-for-windows-azure-blob-storage/.
Once you do that, you may find these blog posts useful:
http://gauravmantri.com/2013/12/01/windows-azure-storage-and-cors-lets-have-some-fun/ (Scroll down to the section titled Web Application to see the code for uploading files directly into blob storage using HTML 5/JavaScript).
http://gauravmantri.com/2013/02/16/uploading-large-files-in-windows-azure-blob-storage-using-shared-access-signature-html-and-javascript/ (slightly older post, but you can use the source code for uploading ... this one's useful when you're uploading really large files).


text:
Q: Como utilizar o summarise? Tenho um DF com dados de energia e gostaria de agrupar os dados por atividade (pois estão divididos por estado e eu quero fazer o agregado para Brasil) e somar estes dados para cada data. Estava tentando utilizar o group_by com o summarise, porém, não está retornando da forma que eu gostaria.
Código:
library(tidyverse)
library(lubridate)

CCEE <- read_excel("Dados/Consumo de energia.xlsx", sheet = "CCEE")

colnames(CCEE) <- c("data", "classe", "atividade", "submercado", "UF", "unidade", "value")

CCEE <- CCEE %>%
  mutate(atividade = str_to_title(atividade),
         data = as_date(data)) %>%
  filter(classe == "Consumidor Livre") %>%
  select(-c(unidade, submercado, classe)) %>%
  group_by(data, atividade) %>%
  summarise(value = round(sum(value), 2)) %>%
  arrange(atividade, data)

Com o código desta forma, ele retorna o seguinte erro:
# Error in order(atividade, data) : objeto 'atividade' não encontrado

Se eu remover o arrange, retorna o somatório de todos os valores, dessa forma:
#    value
#1 8832167

Eu gostaria que os dados ficassem dessa forma, com a soma por atividade para cada uma das datas:

Os dados são baixados em csv e eu tive que transformá-los em excel, mas já testei com os dados em formato csv e retornou o mesmo erro.
Meu dput:
dput <- structure(list(Data = structure(c(1533081600, 1533081600, 1533081600,
                                          1533081600, 1533081600, 1533081600), tzone = "UTC", class = c("POSIXct", "POSIXt")),
                       Classe = c("Autoprodutor", "Autoprodutor", "Autoprodutor", "Autoprodutor", "Autoprodutor", "Autoprodutor"),
                       `Ramo de atividade` = c("ALIMENTÍCIOS",  "ALIMENTÍCIOS", "ALIMENTÍCIOS", "ALIMENTÍCIOS", "ALIMENTÍCIOS", "COMÉRCIO"),
                       Submercado = c("NORDESTE", "SUDESTE / CENTRO-OESTE", "SUDESTE / CENTRO-OESTE", "SUL", "SUL", "SUDESTE / CENTRO-OESTE"),
                       Estado = c("Pernambuco ", "Minas Gerais", "Mato Grosso", "Santa Catarina", "Rio Grande do Sul", "São Paulo"),
                       `"Consumo (MWm)"` = c("Consumo (MWm)", "Consumo (MWm)", "Consumo (MWm)", "Consumo (MWm)", "Consumo (MWm)", "Consumo (MWm)"),
                       `Consumo (MWm)` = c(0.24033975, 0, 0.908708333, 3.044405, 1.443036542, 0.16408)),
                  .Names = c("Data", "Classe", "Ramo de atividade", "Submercado", "Estado", "\"Consumo (MWm)\"", "Consumo (MWm)"),
                  row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))

A: Teste isto:
# glimpse(CCEE)
CCEE <- CCEE %>%
  dplyr::mutate_if(is.character, as.factor) %>%
  dplyr::mutate(atividade = stringr::str_to_title(atividade),
                data = lubridate::as_date(data),
                value = as.numeric(value)) %>%
  # dplyr::filter(classe == "Consumidor Livre") %>%
  # No df disponibilizado nao ha o fator "Consumidor Livre" para `classe`
  dplyr::select(-c(unidade, submercado, classe)) %>%
  dplyr::arrange(data, atividade) %>%
  dplyr::group_by(data, atividade) %>%
  dplyr::summarise(value = round(sum(value), 2)) %>%
  dplyr::ungroup()

Perceba que você tinha algumas colunas que deveriam ser fatores (as.factor). A função glimpse pode te ajudar para situações como esta, elucidando a classe de suas variáveis.
Também modifiquei um pouco a ordem dos acontecimentos, passando o arrange para uma etapa anterior ao group_by.


text:
Q: Android Marshmallow: new File (...) gives permission denied EDITED to reflect progress.
If this question has been answered already, my apologies.
Currently writing an app where content (in a small zip file) is downloaded from an external location and stored inside /data/data/package_name_removed/files/, to be read later.
I currently have a zip file in that directory "Test.zip".
A try-catch loop containing:
//where filename is Test.zip

Log.d("Target file is", sourceContext.getFilesDir() +"/"+ fileName);
File file = new File(sourceContext.getFilesDir() +"/"+ fileName);
ZipFile loadedFile = new ZipFile(file);

//where sourceContext is passed into this object from the base Activity class

Doesn't seem to work in Marshmallow:
D/Target file is: /data/user/0/package_name_removed/files/Test.zip
W/package_name_removed: type=1400 audit(0.0:11699): avc: denied { open } for name="Test.zip" dev="mmcblk0p29" ino=57426 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:app_data_file:s0 tclass=file permissive=0

This is a Log.d of the IOException getMessage; I think this one's generated from the new File() statement:
D/Log_title_omitted: /data/user/0/package_name_removed/files/Test.zip: open failed: EACCES (Permission denied)

I had this working in Lollipop; was debugging it for pre-lollipop too until I recently upgraded to Marshmallow. I don't think I can safely continue until I sort this out, because it means my app won't support 6.0.
I have managed to write a text file to this directory with no problems  whatsoever with the same app, so I do not understand why attempting to open a zip file from that directory doesn't work.
Edit: I have also attempted to unzip the offending zip file to its own directory but to no avail:
//where file is now a json file "Test.json"
//located in .getFilesDir()/Test/
String loadedName = fileName.substring(0, fileName.length() - 5); //I need to reuse the string later.".json" is 5 char.
Log.d("Target is", sourceContext.getFilesDir() +"/"+ loadedName +"/" + fileName);
File file = new File(sourceContext.getFilesDir() + "/"+ loadedStoryName +"/" + fileName);

And got:
D/DOH: /data/user/0/package_name_removed/files/Test/Test.json: open failed: EACCES (Permission denied)
W/package_name_removed: type=1400 audit(0.0:22152): avc: denied { search } for name="Test" dev="mmcblk0p29" ino=57184 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:object_r:app_data_file:s0 tclass=dir permissive=0

I understand Marshmallow is really enforcing SELinux now, and I have to code for this eventuality - but I haven't been able to figure out how to get the proper permissions in code. Rightfully I should not need a READ_EXTERNAL anywhere as according to the documentation, there is no need to ask for permissions to the app's own files directory in internal storage.
Any help?
Note: package name omitted, not important.

A: From user CommonsWare:

"Rooting does not disable SELinux" -- no, but it does not mean that files that >you create through a root shell somehow get the same permission bits/ACLs/etc. as >do files you create through your application code. adb shell run-as might behave >better in this fashion.

Yep, it was indeed because I copied the file myself rather than have the app do it; having r permissions across the board is not enough to satisfy SELinux, the app must "own" the file by being the one that "creates" it.
I have yet to test this on the external write directory, but it is true for the internal app's own directory.


text:
Q: How to replace a string in every file in a directory I'm trying to replace with python a string: "XXXXXXXXXXX" with a new string: "ILoveStackOverflow" in every file in a particular folder (all the files in the folder are xml).
My code is as follows:
import os, fnmatch

for filename in os.listdir("C:/Users/Francesco.Borri/Desktop/passivo GME"):
if filename.endswith('.xml'):
    with open(os.path.join("C:/Users/Francesco.Borri/Desktop/passivo GME", filename)) as f:
        content = f.read()
        content = content.replace("XXXXXXXXXXX", "ILoveStackOverflow")
    with open(os.path.join("C:/Users/Francesco.Borri/Desktop/passivo GME", filename), mode="w") as f: #Long Pierre-André answer
        f.write(content)

The next step would be to replace a different string: "YYYY" with a number that increases every time. If in my directory there are 10 files and I set the starting number 1, the first file "YYYY" will be replaced with 1, the second file with 2 and so on until 10.

A: with open(os.path.join("C:/Users/Francesco.Borri/Desktop/passivo GME", filename), mode="w") as f:

You must open the file on writing mode.

A: You are close. When you open the file the second time, you have to open it in writeable mode to be able to write the content.
with open(os.path.join("C:/Users/Francesco.Borri/Desktop/passivo GME", filename), 'w') as f:
    f.write(content)

Once you fix this, I think the second part of your question is just maintaining a variable whose value you increment everytime you replace the string. You could do it manually (iterate over the string), or use the replace function in a for loop:
with open(os.path.join("C:/Users/Francesco.Borri/Desktop/passivo GME", filename)) as f:
        content = f.read()
for i in range(content.count("YYYY")):
    content.replace("YYYY", str(i), 1)  # or str(i+1)
with open(os.path.join("C:/Users/Francesco.Borri/Desktop/passivo GME", filename), 'w') as f:
        f.write(content)


text:
Q: Default TCP connection backlog value in Windows Which is the default connection backlog value for TCP in Windows? I have tried to find it but no luck.
Cheers

A: There is no default. It's always specified by the application in the listen (or equivalent) call.


text:
Q: Laravel - Back button close the session This kind of problem only happens in a specific view where I generated reports.
When I generated the report it seems to be okay, but when I tried to return to the previous page where I put the data to generated the report, instead of return to the page, it returns to the login.
Then I log again to try to generate the report, but this time it show me the view of The page has expired due to inactivity. Please refresh and try again.
Honestly I don't know what happened here, because the controller of the report, doesn't have anything to cause this. This is random, sometimes it return to the page to generated the reports, but obviously this is a bit problem.
I think it has to be a problem of the cache, but i'm not pretty sure.
CACHE_DRIVER=array
SESSION_DRIVER=file

A: After generating the report you can forget any specific key of the session or flush everything.
$request->session()->forget('key');

$request->session()->flush();

A: I'm wracking my brains. I'm sure I've seen this before and it was something to do with Session Cookie Domain
'domain' => env('SESSION_DOMAIN', null),

try by changing this peace of code in session.php file


text:
Q: SonarQube doesn't work with Intellij Community 2019.2 I'm using SonarLint 4.1.1.3345 with IntelliJ Community 2019.2 version by binding project to our SonarQube (with SonarJava 5.3 (build 13828)installed) server. However, I got error with below stack trace from SonarLint log:
Java Main Files AST scan
60 source files to be analyzed
Unable to create symbol table for : C:\Users\username\SomeFile.java
java.lang.IllegalArgumentException: Unsupported class file major version 55
    at org.objectweb.asm.ClassReader.<init>(ClassReader.java:166)
    at org.objectweb.asm.ClassReader.<init>(ClassReader.java:148)
    at org.objectweb.asm.ClassReader.<init>(ClassReader.java:136)
    at org.sonar.java.resolve.BytecodeCompleter.loadClass(BytecodeCompleter.java:204)
    at org.sonar.java.resolve.Symbols.<init>(Symbols.java:176)
    at org.sonar.java.resolve.SemanticModel.createFor(SemanticModel.java:59)
    at org.sonar.java.model.VisitorsBridge.visitFile(VisitorsBridge.java:110)
    at org.sonar.java.ast.JavaAstScanner.simpleScan(JavaAstScanner.java:96)
    at org.sonar.java.ast.JavaAstScanner.scan(JavaAstScanner.java:68)
    at org.sonar.java.JavaSquid.scanSources(JavaSquid.java:116)
    at org.sonar.java.JavaSquid.scan(JavaSquid.java:110)
    at org.sonar.plugins.java.JavaSquidSensor.execute(JavaSquidSensor.java:93)
    at org.sonarsource.sonarlint.core.analyzer.sensor.SensorsExecutor.executeSensor(SensorsExecutor.java:81)
    at org.sonarsource.sonarlint.core.analyzer.sensor.SensorsExecutor.execute(SensorsExecutor.java:72)
    at org.sonarsource.sonarlint.core.container.analysis.AnalysisContainer.doAfterStart(AnalysisContainer.java:132)
    at org.sonarsource.sonarlint.core.container.ComponentContainer.startComponents(ComponentContainer.java:125)
    at org.sonarsource.sonarlint.core.container.ComponentContainer.execute(ComponentContainer.java:110)
    at org.sonarsource.sonarlint.core.container.storage.StorageAnalyzer.analyze(StorageAnalyzer.java:75)
    at org.sonarsource.sonarlint.core.container.storage.StorageContainerHandler.analyze(StorageContainerHandler.java:82)
    at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.lambda$analyze$0(ConnectedSonarLintEngineImpl.java:152)
    at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.withReadLock(ConnectedSonarLintEngineImpl.java:344)
    at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.withReadLock(ConnectedSonarLintEngineImpl.java:334)
    at org.sonarsource.sonarlint.core.ConnectedSonarLintEngineImpl.analyze(ConnectedSonarLintEngineImpl.java:149)
    at org.sonarlint.intellij.core.ConnectedSonarLintFacade.analyze(ConnectedSonarLintFacade.java:74)
    at org.sonarlint.intellij.core.SonarLintFacade.startAnalysis(SonarLintFacade.java:63)
    at org.sonarlint.intellij.analysis.SonarLintAnalyzer.analyzeModule(SonarLintAnalyzer.java:97)
    at org.sonarlint.intellij.analysis.SonarLintTask.analyze(SonarLintTask.java:176)
    at org.sonarlint.intellij.analysis.SonarLintTask.run(SonarLintTask.java:100)
    at org.sonarlint.intellij.analysis.SonarLintUserTask.run(SonarLintUserTask.java:39)
    at org.sonarlint.intellij.analysis.SonarLintJobManager.lambda$runTask$1(SonarLintJobManager.java:120)
    at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$2(CoreProgressManager.java:169)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:591)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:537)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:59)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:156)
    at org.sonarlint.intellij.analysis.SonarLintJobManager.lambda$runTask$2(SonarLintJobManager.java:120)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)

"Unsupported class file major version 55" tells me that the class file Sonar used for code analysis is for java 11 version whereas my class was compiled with java 7 (I took the same class and ran it with javap it showed major version 51), and I don't even have java 11 installed on my system.
Because it works for my teammates. The only difference is they have lower version of IntelliJ installed. So I downloaded IntelliJ 2019.1.4 and it started working.
Could someone explain why it doesn't work with later version of IntelliJ and why the above error occurred? Thanks in advance!

A: This is a known limitation about classloaders in the IDE/sonarlint/plugin:
https://community.sonarsource.com/t/sonarlint-analysis-fails-on-intellij-2019-2-with-java-11-runtime/12905/3
https://jira.sonarsource.com/browse/SONARJAVA-3056

Example with SonarLint
In SonarLint IntelliJ running environment, this is more or less the
  classpath hierarchy:
JDK -> IntelliJ classes -> SonarLint (+deps) [child-first] -> Java
  plugin (+packaged deps) [child-first] -> Squid [parent-first]. So
  imagine we analyze a class that is using a class X. If IntelliJ's
  classloader happens to also use class X (same fully qualified name),
  this will be used instead of the X provided in the analysis classpath,
  even if they are to different copies of the class (different versions,
  for example).


text:
Q: Setting the value in a select dropdown using javascript I am having trouble when trying to set a value in a select. I keep seeing NaN as my result (in some browsers - mainly android smartphone / tablet default browsers)
I am running a simply if statement and setting the value if the condition is true:
if (variable1 >= variable2)
{
    $('select[title="title"]').val(variable1);
}

Where a 'typeof' check on both variable1 and variable2 before the if statement show them both as numbers. Despite this the resulting value shown in select in the browser is NaN.
I've even tried wrapping the javascript Number() function around the variables like so:
if (Number(variable1) >= Number(variable2))
{
    $('select[title="myTitle"]').val(Number(variable1));
}

But I still get the same result!
Note: This works fine in desktop / laptop browsers and even Opera Mobile on my Samsung Galaxy S2 but as I'm working towards this being an app to run on any phone I wanted to be complete in my error checking.
edit:
In case it's my select thats the problem (as suggested below) what's wrong with it here?
Is it because it is converted to a string at the point I return it?
var startPoint = this.do_calcTotal(); // typeof startPoint shows as number
var endPoint = startPoint + 12; // typeof endPoint shows as number

var mySelect =   '<select title="myTitle" class="myClass">';

                    for (o=startPoint; o<endPoint; o++)
                    {
                        mySelect += '<option>'+Number(o)+'</option>'; // is this right?? it shows 'o' and 'Number(o)' as typeof number!?
                    }

mySelect += '</select>
';

return mySelect;

Edit: and the code to add the current selected value to the span for display...
function do_changeNumberSpan(value)
{
    $('.mySpan').text(Number(value)); // even tried throwing a Number() round the value here!!
}

A: Ok. Check out this jsfiddle. This should help you understand a little bit of what your goal is... and how you can accomplish it.
http://jsfiddle.net/aaronfrost/yFuyu/


text:
Q: pandas new column if statement I have a data frame for which I would like to add a column value using an if statement. I have been trying a lambda function but have not had luck. I want to add a column that says if threshold< order, then set new column to threshold else set column to order.
df_new

  Order       Threshold
 20,000        100,000
 500,000       50,000
 100,000       75,000

I tried:
 df_new['New Column'].apply(lambda x: df_new['Threshold'] if < df_new['Order'] else df_new['Order Quantity'])

A: Sometimes it is helpful to use an algorithm which avoids if / else constructs. The below solution is likely more efficient and, moreover, adds some intuitive logic.
import pandas as pd, numpy as np

df = pd.DataFrame({'Order': [20000, 500000, 100000],
                   'Threshold': [100000, 50000, 75000]})

df['New'] = np.minimum(df['Threshold'], df['Order'])

#     Order  Threshold    New
# 0   20000     100000  20000
# 1  500000      50000  50000
# 2  100000      75000  75000


text:
Q: which file formats does opc ua server support? i want to receive data from an OPC UA Server in my big data environment through nifi, i want to know which file formats does OPC UA Server support to send data?

A: "Message Formats
OPC-UA supports two message formats: UA Binary and XML."
https://readthedocs.web.cern.ch/display/ICKB/OPC-UA+Summary


text:
Q: How to input a caret trained random forest model into predict() and performance() functions? I want to create a precision recall curve using performance() but I don't know how to input my data. I follow this example.
attach(ROCR.simple)
pred <- prediction(ROCR.simple$predictions, ROCR.simple$labels)
perf <- performance(pred,"prec","rec")
plot(perf)

I am trying to mimic that for my caret trained RF model specifically on training data (I know there are various examples on how to use predict on newdata). I tried this:
pred <- prediction(rf_train_model$pred$case, rf_train_model$pred$pred)
perf <- performance(pred,"prec","rec")
plot(perf)

My model below. I tried the above because that seems to match the ROCR.simple data.
#create model
ctrl <- trainControl(method = "cv",
                     number = 5,
                     savePredictions = TRUE,
                     summaryFunction = twoClassSummary,
                     classProbs = TRUE)
set.seed(3949)
rf_train_model <- train(outcome ~ ., data=df_train,
                  method= "rf",
                  ntree = 1500,
                  tuneGrid = data.frame(mtry = 33),
                  trControl = ctrl,
                  preProc=c("center","scale"),
                  metric="ROC",
                  importance=TRUE)

> head(rf_train_model$pred)
     pred     obs      case   control rowIndex mtry Resample
1 control control 0.3173333 0.6826667        4   33    Fold1
2 control control 0.3666667 0.6333333        7   33    Fold1
3 control control 0.2653333 0.7346667       16   33    Fold1
4 control control 0.1606667 0.8393333       18   33    Fold1
5 control control 0.2840000 0.7160000       20   33    Fold1
6    case    case 0.6206667 0.3793333       25   33    Fold1

This is wrong because my precision recall curve is going the wrong way. I am interested in more than just the PRAUC curve, although this is a good source that shows how to make it so I would like to fix this error. What error am I making?

A: If you read the vignette of performance:

it has to be declared which class label denotes the negative, and
  which the positive class. Ideally, labels should be supplied as
  ordered factor(s), the lower level corresponding to the negative
  class, the upper level to the positive class. If the labels are
  factors (unordered), numeric, logical or characters, ordering of the
  labels is inferred from R's built-in < relation (e.g. 0 < 1, -1 < 1,
  'a' < 'b', FALSE < TRUE).

In your case, when you provide rf_train_model$pred$pred, the upper level is still "control", so the best way is to make it TRUE / FALSE. Also you should provide the actual label, not the predicted label, rf_train_model$obs. see below for an example:
library(caret)
library(ROCR)
set.seed(100)
df = data.frame(matrix(runif(100*100),ncol=100))
df$outcome = ifelse(runif(100)>0.5,"case","control")

df_train = df[1:80,]
df_test = df[81:100,]

rf_train_model <- train(outcome ~ ., data=df_train,
                  method= "rf",
                  ntree = 1500,
                  tuneGrid = data.frame(mtry = 33),
                  trControl = ctrl,
                  preProc=c("center","scale"),
                  metric="ROC",
                  importance=TRUE)

levels(rf_train_model$pred$pred)
[1] "case"    "control"

plotCurve = function(label,positive_class,prob){
pred = prediction(prob,label==positive_class)
perf <- performance(pred,"prec","rec")
plot(perf)
}

plotCurve(rf_train_model$pred$obs,"case",rf_train_model$pred$case)
plotCurve(rf_test$outcome,"case",predict(rf_train,df_test,type="prob")[,2])


text:
Q: ec2 bundling on AWS (Amazon Web Services) I took an existing ec2 image that I had, made some changes and re-bundled it.
However, when I try to launch my new image it only lets me launch it as a Large instance -- not a small image.
What happened?  How can I fix it?
I made sure when calling ec2-bundle-vol to specify -r i386
Thanks!

A: Did you re-bundle it as a 64-bit image? If so, you can't run it as a small image. Small images are 32-bit, while the smallest 64-bit image is m1.large.

A: I was using the EC2 console from Amazon.
Looks like it was just a bug with Amazon.
When I came back this morning it worked fine.


text:
Q: How to express the past tense I have just watch movie in which I think that they should built the digestive system of that toy , after watching the movie how can I express that sentence like I express it as
They should have made intelligent digestive system of Rand

Which Past tense this is and am I expressing it right ?

A: What you are saying in your highlighted part is somewhat correct but it's not past tense.
If you want to say that in past tense, it would be something like this..
"They had made an intelligent digestive system." - It's past perfect tense...

A: It's a strange example, but assuming OP knows what he means by "intelligent digestive system", and thinks the movie would have been better if "Rand" had one, the correct syntax would be...

They should have made an intelligent digestive system for Rand

...or perhaps more idiomatically,...

They should have given Rand an intelligent digestive system

In the context of fictional characters in books/movies, the author/director effectively plays a god-like role, so he can give attributes to characters as he sees fit. Using make more strongly implies the "Creator" deciding and explaining in detail to the audience exactly how the "intelligent digestive system" works, which wouldn't always be considered necessary.

You could call should have [done something] a past irrealis conditional construction. In this link, it's called a "past conditional affirmative" (as opposed to "past conditional negative" you shouldn't have done that).


text:
Q: React native android app Fatal exception on start and I cant trace the problem React Native Android application, compiles fine, installs the APK but on running the application has a Fatal Exception straight away and I cannot trace the problem, I have a logcat view of the error but dont know how to solve it.
I have tried to debug but it closes straight away so I dont have a chance to do that. I have also tried searching for the specific error but have not managed to find something that fits.
07-06 20:09:56.697 27444 27479 E AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
07-06 20:09:56.697 27444 27479 E AndroidRuntime: Process: com.t2capp, PID: 27444
07-06 20:09:56.697 27444 27479 E AndroidRuntime: java.lang.IllegalStateException: closed
07-06 20:09:56.697 27444 27479 E AndroidRuntime:        at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:398)
07-06 20:09:56.697 27444 27479 E AndroidRuntime:        at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:392)
07-06 20:09:56.697 27444 27479 E AndroidRuntime:        at okhttp3.internal.Util.bomAwareCharset(Util.java:412)
07-06 20:09:56.697 27444 27479 E AndroidRuntime:        at okhttp3.ResponseBody.string(ResponseBody.java:173)
07-06 20:09:56.697 27444 27479 E AndroidRuntime:        at com.facebook.react.devsupport.DevServerHelper$8.onResponse(DevServerHelper.java:485)
07-06 20:09:56.697 27444 27479 E AndroidRuntime:        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135)
07-06 20:09:56.697 27444 27479 E AndroidRuntime:        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
07-06 20:09:56.697 27444 27479 E AndroidRuntime:        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
07-06 20:09:56.697 27444 27479 E AndroidRuntime:        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
07-06 20:09:56.697 27444 27479 E AndroidRuntime:        at java.lang.Thread.run(Thread.java:784)
07-06 20:09:56.701  1170  6229 W ActivityManager:   Force finishing activity com.t2capp/.MainActivity
07-06 20:09:56.701 27444 27476 W unknown:ReconnectingWebSocket: Couldn't connect to "ws://localhost:8081/message?device=LLD-L31%20-%208.0.0%20-%20API%2026&app=com.t2capp&clientid=DevSupportManagerImpl", will silently retry
07-06 20:09:56.771  1170  1300 W InputDispatcher: channel '4439e16 com.t2capp/com.t2capp.MainActivity (server)' ~ Consumer closed input channel or an error occurred.  events=0x9
07-06 20:09:56.771  1170  1300 E InputDispatcher: channel '4439e16 com.t2capp/com.t2capp.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!

The app used to work and I have come back to it recently to continue and encountered this, really stuck on whats wrong.  I thought it was initially firebase issue but that doesnt seem to be the case as that connects (I used the firebase test by creating new app package and starting it up)

A: Your log is saying unknown:ReconnectingWebSocket: Couldn't connect to "ws://localhost:8081/ ...
It seems like you have hardcoded the Firebase socket url for your development environment (on your own machine, localhost).
You have to configure firebase for production.
Very basically it can be done like this :
language: javascript
if (process.env.NODE_ENV === 'development') {
    // define here your connection for development
} else {
    // define here your connection for production
}


text:
Q: JSON GET Method request I have developed a iphone application that need to send User name and Password through HTTP authentication request header. can any one guide me or sent the source code for that functionalities.

A: You'll need to implement the NSURLConnection:didReceiveAuthenticationChallenge: method.
- (void)request:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential = [NSURLCredential
                                              credentialWithUser:@"username"
                                              password:@"password"
                                              persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];
    }
    else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
    }
}

Edit: Or you could simply send the credentials in the URL in the format http://username:password@www.example.com/


text:
Q: How to align two items next to each other in Semantic UI? I'm trying to make a Headerelement sit next to an Button icon but I cannot make it happen.
Without attempting any Grids listing them like this
Header text
<Button icon className='transparentButton'>
   <Icon name='add'/>
</Button>

makes it look like this - each item on different line:

If I try to make a Grid with one row and two columns there is a massive space between the two and also the header text is wrapped. At least is vertically aligned I guess...
<Grid>
  <Grid.Row verticalAlign='middle'>
    <Grid.Column>
      Header text
    </Grid.Column>
    <Grid.Column>
      <Button icon className='transparentButton'>
                      <Icon name='add'/>
                    </Button>
    </Grid.Column>
  </Grid.Row>
</Grid>

This looks like that:
I'd really love to hear how suggestions on how to make the two items sit next to each other properly. I want to make it look like this:

Example code https://codesandbox.io/s/semantic-ui-react-example-ttnxc (not sure why the Icon is not rendering there though).

A: Actually I think that Header Component is displaying as block
Just try to edit it's css and make:
display: inline-block;

and it should render successfully
unfortunately your example code didn't load so i couldn't try this but it should work


text:
Q: Why does one of the paths not bind in this scenario? Elements and FirstAttribute bind as I'd expect (if I didn't know it's a method), but Attributes does not, despite being a member of XElement, just like the others. I know about IValueConverter, and I'm using that to get the binding I want on attributes, but I'm curious as to why it works on Elements.
<Window x:Class="WpfApplication6.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
  <StackPanel>
    <TextBlock Text="{Binding Path=FirstAttribute}" />
    <ListBox ItemsSource="{Binding Path=Elements}" />
    <ListBox ItemsSource="{Binding Path=Attributes}" />
  </StackPanel>
</Window>

using System.Linq;
using System.Windows;
using System.Xml.Linq;

namespace WpfApplication6 {
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window {
        public Window1() {
            InitializeComponent();

            XDocument doc = new XDocument(
                new XElement("Parent",
                    new XAttribute("attr1", "val"),
                    new XAttribute("attr2", "val"),
                    new XElement("Child1"),
                    new XElement("Child2")
                    )
                );

            MessageBox.Show("Elements: " + doc.Elements().First().Elements().Count());
            MessageBox.Show("Attributes: " + doc.Elements().First().Attributes().Count());

            DataContext = doc.Elements().First();
        }
    }
}

A: Are you sure Elements works? Because as far as I know, you can't bind directly to a method. Elements and Attributes are both methods, to get around this see this question.

A: Got the answer on MSDN:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/4be39d21-c9d8-4781-9337-2cb1215ec3d1/
Basically, the XAML team added PropertyDescriptors to XLinq specifically for binding, but must have forgotten about Attributes...


text:
Q: Report Server Web Service: Connecting Subscription to schedule I'm currently in the process of developing a front facing ASP application for a client which is wired up to the ReportService2010.asmx web service. We are using SQL Server 2008 R2.
I have figured out how to fetch all schedules and create them on our end through the interface, but I can't figure out how to then create a subscription that is then connected to that schedule so that it runs at the time.
Can someone help me please?

A: In the end I found that unless some custom assemblies are added to the report server, subscriptions do not connect to schedules and are two different things.


text:
Q: Bridging the gap between classical and modern projective geometry The language of projective geometry is quite common in modern mathematics. For this reason I'd like to learn this subject, however, modern treatments are incredibly abstract. Now, I'm vaguely aware of the history of the subject, so I know that there's much more to it than "let's take an equivalence relation on a vector space over an arbitrary field and formally investigate its properties". I want to fully appreciate the beauty of projective geometry and its connection to traditional geometry.
But so far I've found two kinds of books:

*

*Old books which are interesting (except that I've found they rush through notions like cross ratios and fourth harmonics with insufficient motivation), but make no mention of the kinds of ideas I hear about in modern mathematics, like the construction of projective spaces from vector spaces, or the concept of homogeneous coordinates.

*Modern books which are so abstract that I stop caring half way through page 3 (after the brief historical introduction ended on page 2).
It just seems like a bit of a forgotten field, I can't find that many solid resources. What sort of a roadmap, ideally with book recommendations, can I follow, to get a full picture of the field of projective geometry that will allow me to understand both its roots in classical geometry and how it's used in modern mathematics?


text:
Q: Understanding array_udiff() I have the following simple function to try and understand the array_udiff() function
function udiffCompare( $value, $value2 )
{

echo $value . " - " . $value2 . "<br />";

}

$newArray   =   array(

                    'value2' => 2,
                    'value3' => 3,
                    'value4' => 4
                );

$newArray2  =   array(

                    'value2' => 2,
                    'value3' => 3,
                    'value4' => 4
                );

array_udiff( $newArray, $newArray2, 'udiffCompare' );

I would expect this to simply return:
2 - 2
3 - 3
4 - 4

However it returns:
3 - 2
4 - 3
3 - 2
4 - 3
4 - 4
4 - 3
4 - 3
3 - 2

This leads me to believe there is something I am really not understanding here about how array_udiff() works.
Even if I replace the echo statement above with:
if( $value == $value2 ) { return 1; } else { return 0; }
the outputted array is completely empty even though all the values passed to the function are equal.
Could someone shine a light please?

A: array_udiff  computes the difference of the two arrays. That is all entries in $newArray which are not in $newArray2. In this case the result is an empty array because there is no difference.
The output you are seeing is because you are echoing each value that is being compared. The reason this is a larger list is because, in order to find out the difference array_udiff has to compare every value in $newArray with every value in $newArray2.

A: You didn't write proper callback function for array_udiff().

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Moreover mathematical difference of these 2 sample arrays you given is NULL That is why you will get empty result set if you use this function. Check it on array_diff();
The gray area shows the difference of two collections:


text:
Q: Overparametrized Model I am trying to understand the concept of an overparametrized model:
If I am considering a one way model:
$$Y_{jk}=\mu + \alpha_j + \epsilon_{jk}$$
Where $\epsilon_{jk}\sim N(0, \sigma^2)$.
Why is this model considered overparametrized and has no solutions, when estimating the maximum likelihood values.


text:
Q: How to install man pages on an ubuntu docker image? I use the following Dockerfile to build an image and start a container. But once I am in the container, I still can not find manpages. Does anybody know how to solve this problem?
$ cat Dockerfile
FROM ubuntu
RUN apt -y update && apt -y upgrade
RUN apt-get -y install build-essential
RUN apt-get -y install vim
RUN apt-get -y install man
RUN apt-get -y install gawk
RUN apt-get -y install mawk

$ man man
No manual entry for man
See 'man 7 undocumented' for help when manual pages are not available.
$ find /usr/share/man /usr/local/share/man  -type f

A: There is a easier way to enable the MAN command.
In terminal, just execute the command below:

unminimize

It will ask if you like to continue [Y/n]
Just press:

Y

It will take a while to finish all the processing.
After that, test this:

man man

Simple as that
Thanks to @kazushi

A: You need to make a change to your /etc/dpkg/dpkg.cfg.d/excludes within the container. You can do this in your Dockerfile with the following command:
RUN sed -i 's:^path-exclude=/usr/share/man:#path-exclude=/usr/share/man:' \
        /etc/dpkg/dpkg.cfg.d/excludes

Then make another update to your Dockerfile to install the man pages
RUN apt-get update && \
    apt-get install -y \
        man \
        manpages-posix


text:
Q: Twitter, follows function I've created a new model in database:
class UserProfile(models.Model):
    user = models.ForeignKey('auth.user', on_delete=models.CASCADE)
    date_of_birth = models.DateField(blank=True, null=True)
    follows = models.ManyToManyField(User, related_name="followed_by", blank=True)

And try to add 'follow' feature in my app:
class TweetDetailsView(View):
    def get(self, request, tweet_id):
        tweet = Tweet.objects.get(id=tweet_id)
        #likes
        is_liked = False
        if tweet.likes.filter(id=request.user.id).exists():
            is_liked = True
        stuff = get_object_or_404(Tweet, id=self.kwargs['tweet_id'])
        total_likes = stuff.total_likes()
        #follows
        is_followed = False
        if User.followed_by.filter(id=request.user.id).exists():
            is_followed = True
        return render(request, "twitter/tweet.html", locals())

def FollowUser(request, pk):
    user = get_object_or_404(User, id=request.POST.get('user_id'))
    if User.followed_by.filter(id=request.user.id).exists:
        User.followed_by.remove(request.user)
        is_followed = False
    else:
        User.followed_by.add(request.user)
        is_followed = True
    return HttpResponseRedirect(reverse('tweet', args=[str(pk)]), locals())

However, i receive a info that: 'ManyToManyDescriptor' object has no attribute 'filter'
How can i do that?
In case of likes, it worked.
Does anyone has any idea?


text:
Q: React Native - Module not found when installing React native Paper I'm working on a React Native project and trying to add React Native paper to my application. My app is currently working with redux, but when I try and install React Native Paper I get a build error. I'm on Mac working on iOS.
I've followed the steps on the React Native Paper site: https://callstack.github.io/react-native-paper/getting-started.html

*

*yarn add react-native-paper

*yarn add react-native-vector-icons

*react-native link react-native-vector-icons

After these commands, my app is unable to build and I get a "Requiring unknown module "1090".If you are sure the module is there, try restarting Metro Bundler. You may also want to run yarn, or npm install (depending on your environment)."
I've tried yarn/npm cache clean, watchmen del, and rerunning yarn/npm install but haven't been able to get past this.
App.js (I've removed everything to just try and get this to build) -
import React from 'react';
import { View, Text } from 'react-native';
import { Provider } from 'react-redux';
import { Provider as PaperProvider } from 'react-native-paper';

    export default class App extends React.Component {
        render() {
            return (
                <PaperProvider>
                  <View>
                     <Text>Hello world</Text>
                  </View>
                </PaperProvider>
            );
        }
    }

Here is the message in the terminal:
GET /index.bundle?platform=ios&dev=true&minify=false HTTP/1.1" 200 - "-" "native/1 CFNetwork/975.0.3 Darwin/18.2.0"
Error: ENOENT: no such file or directory, open '/Users/peyton/Desktop/Projects/MoviePass/native/node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js'
    at Object.openSync (fs.js:448:3)
    at Object.readFileSync (fs.js:348:35)
    at Object.getSource (/Users/peyton/Desktop/Projects/MoviePass/native/node_modules/metro/src/DeltaBundler/Transformer.js:226:21)
    at getModuleSource (/Users/peyton/Desktop/Projects/MoviePass/native/node_modules/metro/src/DeltaBundler/Serializers/helpers/getSourceMapInfo.js:59:17)
    at getSourceMapInfo (/Users/peyton/Desktop/Projects/MoviePass/native/node_modules/metro/src/DeltaBundler/Serializers/helpers/getSourceMapInfo.js:50:42)
    at _toConsumableArray.concat.filter.filter.map.module (/Users/peyton/Desktop/Projects/MoviePass/native/node_modules/metro/src/DeltaBundler/Serializers/sourceMapObject.js:52:7)
    at Array.map (<anonymous>)
    at fullSourceMapObject (/Users/peyton/Desktop/Projects/MoviePass/native/node_modules/metro/src/DeltaBundler/Serializers/sourceMapObject.js:51:6)
    at /Users/peyton/Desktop/Projects/MoviePass/native/node_modules/metro/src/Server.js:1165:14
    at Generator.next (<anonymous>)
::1 - - [04/Apr/2019:00:39:30 +0000] "POST /symbolicate HTTP/1.1" 500 - "-" "native/1 CFNetwork/975.0.3 Darwin/18.2.0"
Error: ENOENT: no such file or directory, open '/Users/peyton/Desktop/Projects/MoviePass/native/node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js'
    at Object.openSync (fs.js:448:3)
    at Object.readFileSync (fs.js:348:35)
    at Object.getSource (/Users/peyton/Desktop/Projects/MoviePass/native/node_modules/metro/src/DeltaBundler/Transformer.js:226:21)
    at getModuleSource (/Users/peyton/Desktop/Projects/MoviePass/native/node_modules/metro/src/DeltaBundler/Serializers/helpers/getSourceMapInfo.js:59:17)
    at getSourceMapInfo (/Users/peyton/Desktop/Projects/MoviePass/native/node_modules/metro/src/DeltaBundler/Serializers/helpers/getSourceMapInfo.js:50:42)
    at _toConsumableArray.concat.filter.filter.map.module (/Users/peyton/Desktop/Projects/MoviePass/native/node_modules/metro/src/DeltaBundler/Serializers/sourceMapObject.js:52:7)
    at Array.map (<anonymous>)
    at fullSourceMapObject (/Users/peyton/Desktop/Projects/MoviePass/native/node_modules/metro/src/DeltaBundler/Serializers/sourceMapObject.js:51:6)
    at /Users/peyton/Desktop/Projects/MoviePass/native/node_modules/metro/src/Server.js:1165:14
    at Generator.next (<anonymous>)

And in the iPhone preview:
Requiring unknown module "1090".If you are sure the module is there, try restarting Metro Bundler. You may also want to run `yarn`, or `npm install` (depending on your environment).

loadModuleImplementation
    index.bundle?platform=ios&dev=true&minify=false:224:31
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:170340:42
loadModuleImplementation
    index.bundle?platform=ios&dev=true&minify=false:265:14
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:169329:37
loadModuleImplementation
    index.bundle?platform=ios&dev=true&minify=false:265:14
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:163396:36
loadModuleImplementation
    index.bundle?platform=ios&dev=true&minify=false:265:14
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:157171:40
loadModuleImplementation
    index.bundle?platform=ios&dev=true&minify=false:265:14
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:157077:29
loadModuleImplementation
    index.bundle?platform=ios&dev=true&minify=false:265:14
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:88467:38
loadModuleImplementation
    index.bundle?platform=ios&dev=true&minify=false:265:14
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:1367:48
loadModuleImplementation
    index.bundle?platform=ios&dev=true&minify=false:265:14
guardedLoadModule
    index.bundle?platform=ios&dev=true&minify=false:153:47
global code
    index.bundle?platform=ios&dev=true&minify=false:170659:4

Thanks for any help.

A: Maybe you just need to link react-native-paper with your react-native project. So just try out this command and it may fix your problem.
react-native link react-native-paper
    or just
react-native link


text:
Q: So basically I need to take data a user inputs into a Tkinter entry box and store it into my sqlite3 database. I am using Python 3.6 conn = sqlite3.connect('School.db')
c = conn.cursor()
def account_Table(): #Creates the table for user accounts.
    c.execute('CREATE TABLE IF NOT EXISTS accounts(datestamp TEXT, u_id INT, username TEXT, password TEXT, classy TEXT, subject TEXT, forename TEXT, surname TEXT)')

def LoginFrame(Frame): #Builds the login/home screen for the program

        username_holder = Label(text="Username", bg="#b4c4a1", fg="#000000")
        password_holder = Label(text="Password", bg="#b4c4a1", fg="#000000")

        username = Entry()
        password = Entry(show="*")

        username_holder.grid(row=0, column=20)
        password_holder.grid(row=1, column=20)
        username.grid(row=0, column=40)
        password.grid(row=1, column=40)

        checkbox = Checkbutton(text="Keep me logged in", bg="#b4c4a1")
        checkbox.grid(row=3,column=40)

        logbtn = Button(text="Login", bg="#b4c4a1", command = Login_Check)
        logbtn.grid(row=3,column=30)

        sigup = Button(text="New User", bg="#b4c4a1", command = DataEntry)
        sigup.grid(row=3,column=20)

def DataEntry():
    datestamp = datetime.datetime.now() #Shows when the account was made
    u_id = (random.randrange(0,100)) #Gives the user a unique identifier, I don't really need it as the username is a pretty good identifier for this job.

    label_1 = Label(text='Enter A Username', bg="#b4c4a1")
    username = Entry()
    username.grid(row=4, column=40)
    label_1.grid(row=4, column=39)

    label_2 = Label(text='Enter A Password', bg="#b4c4a1")
    password = Entry(show='*')
    label_2.grid(row=5, column=39)
    password.grid(row=5, column=40)

    label_3 = Label(text='Enter Your Class', bg="#b4c4a1")
    classy = Entry()
    classy.grid(row=6, column=40)
    label_3.grid(row=6, column=39)

    subject = Entry()
    label_4=Label(text='Enter Your Subject', bg="#b4c4a1")
    subject.grid(row=7, column=40)
    label_4.grid(row=7, column=39)

    label_5=Label(text='Enter Your First Name', bg="#b4c4a1")
    forename = Entry()
    forename.grid(row=8, column=40)
    label_5.grid(row=8, column=39)

    surname = Entry()
    label_6 = Label(text='Enter Your Second Name', bg="#b4c4a1")
    surname.grid(row=9, column=40)
    label_6.grid(row=9, column=39)

All of the entries in 'DataEntry():' will go into the account table as a new record.
def Login_Check():
    print(".... Doing This Later")

#account_Table()
root = Tk()
root.geometry('630x350')
root.config(bg="#b4c4a1")
root.title("Student Manager")
root.wm_iconbitmap('Icon.png')
LoginFrame(root)
Tk.mainloop

I don't know how to pass the entries from the Tkinter Login Box, as values to an SQL 'INSERT INTO' statement using sqlite3, It did work before using just the console as a method of inputting values, but that defeats the point of having a GUI for the user to use.

A: You can use the get() function of the Entry widgets to get what's typed in them and then use string-formatting to generate your SQL-command.
# Python 2.7

import sqlite3 as sql
import tkinter as tk
import datetime

connection = sql.connect('School.db')
cursor = connecton.cursor()
# Sidenote: your database does not have a PRIMARY KEY
# I made u_id the PRIMARY KEY
cursor.execute('CREATE TABLE IF NOT EXISTS accounts(datestamp TEXT, ' \
    'u_id INT PRIMARY KEY, username TEXT, password TEXT, classy TEXT, ' \
    'subject TEXT, forename TEXT, surname TEXT)')
insert_command = """INSERT OR IGNORE INTO accounts(datestamp, username, """ \
                 """password, classy, subject, forename, surname) VALUES(""" \
                 """'%s', '%s', '%s', '%s', '%s', '%s', '%s');"""

root = tk.Tk()
username_entry = tk.Entry(root)
password_entry = tk.Entry(root)
classy_entry = tk.Entry(root)
subject_entry = tk.Entry(root)
forename_entry = tk.Entry(root)
surname_entry = tk.Entry(root)

def insert_user():
    datestamp = datetime.datetime.now()
    username = username_entry.get()
    password = password_entry.get()
    classy = classy_entry.get()
    subject = subject_entry.get()
    forename = forename_entry.get()
    surname = surname_entry.get()
    cursor.execute(insert_command % (datestamp, username, password,
                                     classy, subject, forename, surname))

insert_button = tk.Button(root, text="Insert my account", command=insert_user)

username_entry.pack()
password_entry.pack()
classy_entry.pack()
subject_entry.pack()
forename_entry.pack()
surname_entry.pack()
insert_button.pack()

root.mainloop()


text:
Q: Ember.js + JQuery-UI Tooltip - Tooltip does not reflect the model / controller changes Context
I have a small Ember app, which, amongst other things, displays a number of connected users and, when hovering an element of the page, their names as a list.
All in all, it works quite well. The applications pulls data from a REST endpoint every two minutes, as the backend didn't allow for pushing data.
The contents of the tooltip are computed in the Controller, with a function that basically concatenate strings in various ways according to the context. Then it's bound to a data attribute of the  the tooltip is created on. When the View is ready and didInsertElement is fired, the tooltip is generated (if needs be) based on this data-bindattr value.
Question
When new data is pulled from the backend, everything is updated accordingly, except the tooltip content. (When browsing the page's DOM, the data-bindattr value is updated too.)
What could cause the tooltip to not refresh? Is it a case of JQuery-UI not calculating it again?
Some code
Refreshing code in the app's controller:
Monitor.ApplicationController = Ember.ArrayController.extend({
  itemController: 'process',
  sortProperties: ['name'],
  sortAscending: true,
  intervalId: undefined,
  startRefreshing: function() {
    var self = this;
    if (self.get('intervalId')) {
      return;
    }
    self.set( 'intervalId', setInterval(function() {
      self.store.find('process');
    }, 120000 ));
  }
});

View: Process.hbs

{{nbUsers}}

View: ProcessView
Monitor.ProcessView = Ember.View.extend({
  // (...) Various stuff.
  didInsertElement: function() {
    this.updateTooltip();
  },
  updateTooltip: function() {
    console.log('Inside updateTooltip!');
    if (!this.$()) {return;}
    if (this.get('controller').get('inactive')) {
        this.$().tooltip({items: '.caption', disabled: true});
        return;
    }
    this.$().tooltip({
        items: '.caption',
        tooltipClass: 'tooltip',
        content: function() {
            return $(this).data('caption');
        },
        position: {
            my: 'left+15px center',
            at: 'right center',
            collision: 'flip'
        },
        show: false,
        hide: false
    });
  }.observes('controller.inactive', 'controller.contentText')
});

Controller: ProcessController
Monitor.ProcessController = Ember.ObjectController.extend({
  contentText: function() {
    var tooltipContent = '';
    this.get('containers').forEach(function(container) {
    // Do a lot of things to tooltipContent involving:
    // container.get('name')
    // container.get('text')
    // container.get('size')
    // container.get('nbUsers')
    // The data-bindattr value refreshes correctly so I cut this out for readability.
    return tooltipContent;
  }.property('name', 'containers.@each')
});

Edit 1:
Replaced 'containers.@each' by 'contentText' in the observer and added logging.

A: Here's what I think is happening:
Your tooltip library isn't observing the data-caption attribute. Meaning, when you update the attribute, you have to explicitly tell the library to update the tooltip as well. So although your attribute is updating just fine, the tooltip library isn't actually watching for those updates.
This can be remedied by calling updateTooltip, which you do, in didInsertElement. However, didInsertElement only fires once, when the element is first inserted. It's not called when the content changes.
Those two things combined are, I think, causing your problem. I think that all you need to do is have updateTooltip also observe the controller.contextText property. Then it should be called when the text updates.

A: So it turns out my codes declares and initialize a tooltip, but once it's done, you can't change the content the same way. Plus it adds unneeded computing anyway.
Thanks to @GJK's answer and that question, I found out what was happening. Turns out you need to set the content of the tooltip to refresh it, not recreate it.
Here is the working code for Ember integration:
Monitor.ProcessView = Ember.View.extend({
  // Other stuff
  didInsertElement: function() {
    this.initTooltip();
  },
  initTooltip: function() {
    if (!this.$()) {return;}
    if (this.get('controller').get('inactive')) {
        this.$().tooltip({items: '.caption', disabled: true});
        return;
    }
    this.$().tooltip({
        items: '.caption',
        tooltipClass: 'tooltip',
        content: function() {
            return $(this).data('caption');
        },
        position: {
            my: 'left+15px center',
            at: 'right center',
            collision: 'flip'
        },
        show: false,
        hide: false
    });
  },
  updateTooltip: function() {
    if (!this.$()) {return;}
    if (this.get('controller').get('inactive')) {
        this.$().tooltip({items: '.caption', disabled: true});
        return;
    }
    content = this.get('controller').get('contentText');
    this.$().tooltip("option", "content", content);
  }.observes('controller.contentText')
});

As an added bonus, you can avoid using the data attribute as a buffer now, although I'm not sure why.


text:
Q: Copy RTF text from Access to word table using VBA Is there a way to copy a RTF text from a memo field in Access Database to Word document using VBA. I have this code at the moment but it produces html text (the text includes tags and not formatted).
' Query the database and get the sales for the specified customer
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Sales WHERE Sales.[ID] ='" & Forms![customers]![id] & "'")

'Check to see if the recordset actually contains rows
    If Not (rs.EOF And rs.BOF) Then
    rs.MoveFirst
    Do Until rs.EOF = True

    ' Create file and add rtf text
    Set ts = fso.CreateTextFile("c:\temp\temp.rtf", True)
    ts.Write rs(3)
    ts.Close

    ' Add a row
    doc.Tables(1).Rows.Add

    ' Get the number of the added row to add data
     i = doc.Tables(1).Rows.Last.Index

    ' Add sale to word table
    doc.Tables(1).Cell(i, 2).Range.InsertFile "C:\temp\temp.rtf", , False

    'Move to the next record. Don't ever forget to do this.
    rs.MoveNext
   Loop
Else
    MsgBox "There are not records in the recordset."
End If

MsgBox "Finished." & i

rs.Close
Set rs = Nothing

Is there any other way to do this?

A: Note that the "Rich Text" option for Memo fields does not store the formatted text as RTF. The formatted text is stored as HTML, which is why you were seeing HTML tags in your text.
The following Access VBA code creates a Word document that contains formatted text and is saved as .rtf. If you're not committed to using RTF then the code could easily be modified to save the document as .doc or .docx.
Sub FormattedTextToWord()
    Dim objWord As Object  ' Word.Application
    Dim fso As Object  ' FileSystemObject
    Dim f As Object  ' TextStream
    Dim myHtml As String, tempFileSpec As String

    ' grab some formatted text from a Memo field
    myHtml = DLookup("Comments", "MyTable", "ID=101")

    Set fso = CreateObject("Scripting.FileSystemObject")  ' New FileSystemObject
    tempFileSpec = fso.GetSpecialFolder(2) & "\" & fso.GetTempName & ".htm"

    ' write to temporary .htm file
    Set f = fso.CreateTextFile(tempFileSpec, True)
    f.Write "<html>" & myHtml & "</html>"
    f.Close
    Set f = Nothing

    Set objWord = CreateObject("Word.Application")  ' New Word.Application
    objWord.Documents.Add
    objWord.Selection.InsertFile tempFileSpec
    fso.DeleteFile tempFileSpec
    ' the Word document now contains formatted text

    objWord.ActiveDocument.SaveAs2 "C:\Users\Public\zzzTest.rtf", 6  ' 6 = wdFormatRTF
    objWord.Quit
    Set objWord = Nothing
    Set fso = Nothing
End Sub


text:
Q: JavaScript upcall to Java within a JavaFX application fails with arguments So this is the code that runs the application:
public class TestJavaFX extends Application {
private Scene scene;

@Override
public void start(Stage stage) throws UnsupportedEncodingException, IOException {
    // create the scene
    stage.setMinWidth(550);
    stage.setMinHeight(400);
    stage.setTitle("Dashboard Loading...");
    WebView browser = new WebView();
    // sets temp title of scene & creates WebView, a JavaFX panel
    // Programmatic capabilities (aka DOM/loading pages) are accessed
    // through the WebEngine (browser.getEngine())

    browser.getEngine().getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
        public void changed(ObservableValue ov, State oldState, State newState) {
            if (newState == State.SUCCEEDED) {
                JSObject win = (JSObject) browser.getEngine().executeScript("window");
                win.setMember("app", new JavaApp());
                HTMLDocument doc = (HTMLDocument) browser.getEngine().getDocument();
                stage.setTitle(doc.getTitle());
            }
        }
    });
    // adds listener to add app object (from java) to the javascript
    // allowing javascript access to java functions
    // and also changes the window title to the HTML title

    browser.getEngine().load(getClass().getResource("html/index.htm").toString());
    // loads the page, resource is configured to run in a jar setting as
    // well as in the IDE

    StackPane layout = new StackPane();
    layout.getChildren().add(browser);
    // creates a layout for the scene and adds the webview

    scene = new Scene(layout, 900, 650);
    new JavaApp().runBatch(5050505);
    // initiates the scene (AKA the inner part of the window) and adds a
    // layout
    // numbers can be changed; they are the size of the window (W,H)

    stage.setScene(scene);
    stage.show();
    // adds scene to stage (window part of window)
    // packs stage and makes stage visible

}

public static void main(String[] args) {
    launch(args);

}

And here is the code for the JavaApp class:
    public class JavaApp{

    public void runBatch(int num) /*throws IOException*/ {
        System.out.println(num);
       }
    }

The HTML file calls runBatch by a button which has an onclick attribute ="app.runBatch(number)" where number could be 0, 1, 2, etc.
Here's the problem: I have no idea why, but whenever runBatch has an argument (e.g. int num) in its definition, it's as if the function doesn't even exist to the webpage and it doesn't run when I click the HTML button. As soon as I remove the argument, it runs fine. Is this a bug or is it something I can fix?


text:
Q: How can I set the default position of a draggable element using Angular Material DragAndDrop? I would like to set draggable elements' default position within a container.
Example: https://material.angular.io/cdk/drag-drop/overview#restricting-movement-within-an-element
How can I position the element e.g. center-center?

A: As of Angular Material version 8, the following input is available:

@Input('cdkDragFreeDragPosition') freeDragPosition: { x: number; y:
number; }
Sets the position of a CdkDrag that is outside of a drop container.
Can be used to restore the element's position for a returning user.
https://material.angular.io/cdk/drag-drop/api#CdkDrag

And an example can be found at the following:
https://angular-tft6n5.stackblitz.io

A: just use normal css to position the elements.   check the stackblitz for the following https://stackblitz.com/angular/ovlyobmkdnk?file=app%2Fcdk-drag-drop-axis-lock-example.css and here is the changed one https://stackblitz.com/edit/angular-54uare?embed=1&file=app/cdk-drag-drop-axis-lock-example.html
.container {
    display: flex;
  justify-content: center;
  background-color:red;
  align-items: center;
  height: 100vh;
}

.example-box {
  align
  width: 200px;
  height: 200px;
  border: solid 1px #ccc;
  color: rgba(0, 0, 0, 0.87);
  cursor: move;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  background: #fff;
  border-radius: 4px;
  position: relative;
  z-index: 1;
  transition: box-shadow 200ms cubic-bezier(0, 0, 0.2, 1);
  box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2),
              0 2px 2px 0 rgba(0, 0, 0, 0.14),
              0 1px 5px 0 rgba(0, 0, 0, 0.12);
}

.example-box:active {
  box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
              0 8px 10px 1px rgba(0, 0, 0, 0.14),
              0 3px 14px 2px rgba(0, 0, 0, 0.12);
}

  I can only be dragged up/down


text:
Q: Google Cloud Free Trail confuse me a lot, am I going to pay automatically or not? Thing is that I have just activated a google cloud free trail, and it says everywhere that I am not going to pay anything even if the trail ends, unless I explicitly update my account to a paid one. But when I go to billing configuration it says that I am going to pay the first day of the month or before if I surpass a certain threshold. I still have 90 days of the free trail, but now my question is.
Am I going to pay automatically once these 90 days passes? What can you tell me in your experience. Thank you very much.

A: You will not be charged anything until you explicitly convert your account to paid account. You will not be charged after 90 days, just your services will terminate.