text:
Q: fish shell suggestions messing up integrated terminal in vs code I have fish shell installed with Cygwin on windows 10. to use fish shell as an integrated terminal in vs code I added following settings
"terminal.integrated.shell.windows": "C:\\Cygwin64\\bin\\bash.exe",
"terminal.integrated.shellArgs.windows": ["/bin/xhere", "/bin/fish"]

but, whenever I try to type in my terminal in vs code fish shell suggestions shows up next line

A: since this method changing shell is deprecated and the recommended way is to use profiles, here's what to add in vsc settings
"terminal.integrated.profiles.windows": {
    "Fish": {
    "path": "C:\\Cygwin64\\bin\\bash.exe",
    "args": ["-lic","fish"]
    }
},
"terminal.integrated.defaultProfile.windows": "Fish"

A: TL;DR - changing the omf theme fixed the issue for me.
Earlier today I ran into a similar issue today as what you described.  Using the fish shell in VSCode as the integrated terminal while running Cygwin on Windows 10, and every keystroke seems to also trigger a new line.
I see by your screenshot that you are using the oh-my-fish package manager, with what appears to be the default theme.  I am also running omf, and I had the issue while the theme was set to default.  Switching to another theme resolved the issue and the characters stayed on one line as normal.  In my case I switched to the cyan theme - it seems to cooperate with VSCode just fine.
I'm going to guess that there are a few other omf themes that will have similar issues to this.  My experience of the fish shell has been that it's generally great, but I've come across several themes that do not work out-of-the-box on Cygwin (dangerous is another that comes to mind).  I am not sure why the default theme is not working in VSCode, it seems to do just fine in Cygwin in my experience.


text:
Q: Cannot add a row the second time via mouse clicks I am dealing with an unbound DataGridView control.  It is working quite well in most ways but I have one problem:
I cannot add a second row via the UI after adding the first row (this is different from the other question in which the author was adding rows programmatically).   I have placed Console.Writeline() statements (I am developing a control in a test app) and have noticed that at the same time that I cannot get a response trying to add a row the second time, I also no longer get RowValidating and other events.  It is like all the events have been disabled.   I can still edit cells of existing rows, I just cannot add a row the second time.
I have searched for information on this but have come up empty--hence this post.  BTW, I am using .NET 3.5 and cannot use .NET 4.0 for external compatibility reasons.

A: I discovered the problem. It was a misconfiguration of the DataGridView.  In particular, it was setting the Row Template attribute ReadOnly to true.   This attribute affects added rows to the grid thus only the rows added were read-only and thus could not be changed to add more rows.  Once I set that to "false" (as in the screenshot), it all worked.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can only one action not see HTMLHelper? I'm trying to make a simple asp.net-mvc application. I've made my model class and added it to the database. I used the built-in way to generate a controller with views using Entity Framework. But for some reason, when I try to view the Create page (and only the Create page, not the edit page!) I get a Null Reference Exception (Object reference not set to an instance of an object).
so here's my Create Action:
    public ActionResult Create()
    {
        return View();
    }

here's my Edit Action:
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        SupplierCorrection supplierCorrection = db.SupplierCorrectionSet.Find(id);
        if (supplierCorrection == null)
        {
            return HttpNotFound();
        }
        return View(supplierCorrection);
    }

here's my create page:
@model FAIR.Data.Models.SupplierCorrection

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

SupplierCorrection

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.Partial("_createEdit", Model)

                <input type="submit" value="Save" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

@section scripts{

}

here's my edit page (the astute reader will notice it's very similar):
@model FAIR.Data.Models.SupplierCorrection

@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

SupplierCorrection

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.ID)

        @Html.Partial("_createEdit", Model)

                <input type="submit" value="Save" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

@section scripts{

}

and here's _createEdit:
@model FAIR.Data.Models.SupplierCorrection

    @Html.LabelFor(model => model.FAIRNumber, htmlAttributes: new { @class = "control-label col-md-2" })

        @Html.EditorFor(model => model.FAIRNumber, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.FAIRNumber, "", new { @class = "text-danger" })

    @Html.LabelFor(model => model.Supplier, htmlAttributes: new { @class = "control-label col-md-2" })

        @Html.EditorFor(model => model.Supplier, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Supplier, "", new { @class = "text-danger" })

    @Html.LabelFor(model => model.Closed, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Closed)
            @Html.ValidationMessageFor(model => model.Closed, "", new { @class = "text-danger" })

    Corrections Link

        <input type="file" id="CorrectionsLinkFilePicker" onchange="CorrectionsLinkChosen();" />
        <input type="hidden" name="CorrectionsLink" id="CorrectionsLink" value="@Model.CorrectionsLink" />
        @if (!string.IsNullOrWhiteSpace(Model?.CorrectionsLink))
        {
            @:Currently: @Model.CorrectionsLink
        }
        @Html.ValidationMessageFor(model => model.CorrectionsLink, "", new { @class = "text-danger" })

When I navigate to the Create page (again, not the edit page) it errors on line 24, where I do Html.ValidationMesageFor(model => model.Closed,... But if I remove that, it errors on the previous line. And so on until I'm down using(Html.BeginForm()). I guess as a stopgap I can just rewrite the page without using the Html object at all, but in case this happens again (or on a longer page) I'd like to know why in the world it suddenly went null.
Full Stack Trace:
   at ASP._Page_Views_SupplierCorrections__createEdit_cshtml.Execute() in C:\Users\ttm920632\Desktop\Repos\FAIR\FAIR\Views\SupplierCorrections\_createEdit.cshtml:line 24
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
   at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
   at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
   at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
   at System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection)
   at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model, ViewDataDictionary viewData)
   at System.Web.Mvc.Html.PartialExtensions.Partial(HtmlHelper htmlHelper, String partialViewName, Object model)
   at ASP._Page_Views_SupplierCorrections_Create_cshtml.Execute() in C:\Users\ttm920632\Desktop\Repos\FAIR\FAIR\Views\SupplierCorrections\Create.cshtml:line 18
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
   at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
   at System.Web.WebPages.StartPage.RunPage()
   at System.Web.WebPages.StartPage.ExecutePageHierarchy()
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
   at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
   at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
   at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)


text:
Q: Bootstrap's popover in Rails - no console errors, but it's not rendering I'm trying to use Bootstrap's popover effect in my Rails 3.2 app (the bootstrap-sass gem). I've included all of Bootstrap's scripts in application.js, along with the popover code applied to the element I want:
assets/javascripts/application.js:
//= require bootstrap
$('#elem').popover('show')

In my view I have this test code:
hover for popover

When I view this page in the browser, I see no errors in Firebug, and all the tooltip/popover scripts are included. Why isn't the popover taking place on this element?

A: I've stumbled upon the same issue and spent quite some time tackling it. That what has worked for me:
assets/javascripts/application.js
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require_tree .

assets/javascript/your_controller.js.coffee
$ ->
  $('#elem').popover('show')

views/your_controller/your_view.html.haml
=link_to "hover for popover", "#", id: :elem, rel: :popover, data:{title: "Example Popover", content: "Readymade", trigger: "hover"}

I would suspect that in your case the sufficient change will be
assets/javascript/your_controller.js
$(document).ready(function() {
  $('#elem').popover();
});


text:
Q: Can't understand this error "Unknown label type: 'continuous-multioutput' " I am trying to run several machine learning algorithms on a dataset to predict whether the salary/income is greater than 50k or less than equal to 50k. I made a function and am passing the values to it, with different size sample sets of 1% samples, 10% samples and 100% samples.
I am getting an unknown error 'Unknown label type: 'continuous-multioutput''
I don't know what this error is.
I tried changing the classification algorithms I used but no use. It displays the same error for all the alogrithms.
from sklearn.metrics import fbeta_score, accuracy_score

def train_predict (learner, sample_size, X_train, X_test, y_train, y_test):
    results = {}
    start = time()
    learner = learner.fit(X_train[:sample_size], y_train)
    end = time()
    results['train_time'] = end - start

    start = time()
    predictions_test = learner.predict(X_test)
    predictions_train = learner.predict(X_train[:sample_size])
    end = time()

    results['pred_time'] = end - start
    results['acc_train'] = accuracy_score(X_train[:sample_size], y_train[:sample_size])
    results['acc_test'] = accuracy_score[X_test, y_test]
    results['f_train'] = fbeta_score(X_train[:sample_size], y_train[:sample_size], beta = 1)
    resutts['f_test'] = fbeta_score(X_test, y_test, beta = 1)
    print("{} trained on {} samples. ".format(learner.__class__.__name__, sample_size))
    return results

from sklearn.tree import DecisionTreeClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC

clf_A = DecisionTreeClassifier()
clf_B = GaussianNB()
clf_C = SVC()

samples_100 = len(X_train)       #taking 100% i.e. all the data in training set
samples_10 = int(len(X_train)*.1) # taking 10% of the training data
samples_1 = int(len(X_train)*.01) #taking 1% of the training data

results= {}
for clf in [clf_A, clf_B, clf_C]:
    clf_name = clf.__class__.__name__
    results[clf_name] = {}
    for i, samples in enumerate([samples_1, samples_10, samples_100]):
        results[clf_name][i] = \
        train_predict(clf, samples, X_train, y_train, X_test, y_test)
vs.evaluate(results, accuracy, fscore)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-66-e06d42fbd15b> in <module>
      5     for i, samples in enumerate([samples_1, samples_10, samples_100]):
      6         results[clf_name][i] = \
----> 7         train_predict(clf, samples, X_train, y_train, X_test, y_test)
      8 vs.evaluate(results, accuracy, fscore)

<ipython-input-62-4484b803a707> in train_predict(learner, sample_size, X_train, X_test, y_train, y_test)
      2     results = {}
      3     start = time()
----> 4     learner = learner.fit(X_train[:sample_size], y_train)
      5     end = time()
      6     results['train_time'] = end - start

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\tree\tree.py in fit(self, X, y, sample_weight, check_input, X_idx_sorted)
    799             sample_weight=sample_weight,
    800             check_input=check_input,
--> 801             X_idx_sorted=X_idx_sorted)
    802         return self
    803

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\tree\tree.py in fit(self, X, y, sample_weight, check_input, X_idx_sorted)
    138
    139         if is_classification:
--> 140             check_classification_targets(y)
    141             y = np.copy(y)
    142

C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\multiclass.py in check_classification_targets(y)
    169     if y_type not in ['binary', 'multiclass', 'multiclass-multioutput',
    170                       'multilabel-indicator', 'multilabel-sequences']:
--> 171         raise ValueError("Unknown label type: %r" % y_type)
    172
    173

ValueError: Unknown label type: 'continuous-multioutput'

I want this code to run and show the accuracy and other metrics of these algorithms for this datasets.
P.S. I know the code is too long and cumbersome but please take efforts to go through it and let me know the solution. I am newbie in this machine learning domain. Any help will be highly appreciated.
P.S. Please don't mark this question as duplicate I have already been through similar questions and tried all that was suggested there but in vain. It wan't of any use to me.

A: Ok, I got the error the problem was with the way I was sampling the data sets.
I changed the sampling code using frac attribute and the error disappeared.
samples_100 = df.sample(frac = 1)      #taking 100% i.e. all the data in training set
samples_10 = df.sample(frac = .1)      #taking 10% of the training data
samples_1 = df.sample(frac = .01)      #taking 1% of the training data

A: You are getting that unknown error 'Unknown label type: 'continuous-multioutput'' because, if you see in your code
train_predict(clf, samples, X_train, y_train, X_test, y_test)
This needs to be rearranged as
train_predict(clf, samples, X_train, X_test, y_train, y_test)
As we are splitting data between train and test for variables x and y, order is important to split and assign data properly.
I was facing the same problem and it worked for me.


text:
Q: Morley sequences of arbitrary order type A sequence $(a_j \,|\, j \in J)$ is called independent over $A$ if $a_j \underset{A}{\overset{\vert}{\smile}} \left\{a_k \,|\, k < j \right\}$ for every $j$, i.$\,$e. $\text{tp}(a_j/A \cup \left\{a_k \,|\, k < j \right\})$ does not fork over $A$. A sequence is called a Morley sequence over $A$ if it is both independent and indiscernible over $A$.
I would like to prove the following: For every Morley sequence $(a_j \,|\, j \in J)$ and every infinite linear order $I$ there is a Morley sequence $(b_i \,|\, i \in I)$ which satisfies the Ehrenfeucht-Mostowski type $\mathcal{E\!M}((a_j)_{j \in J} /A)$ of $(a_j)_{j \in J}$ over $A$.
By the standard lemma it follows that there is an indiscernible sequence $(b_i \,|\, i \in I)$ satisying $\mathcal{E\!M}((a_j)_{j \in J} /A)$. However I do not see why it should be independent.
It seems that the statement is used in Tent and Ziegler's book (proof of proposition 7.2.14).

A: It's because forking is always witnessed by a formula ("finite character"), and whether a formula $\varphi(x,c)$ forks over $A$ just depends on $\text{tp}(c/A)$ ("invariance").
Suppose that $(b_i)_{i\in I}$ is not independent. Then there is some $k\in I$ such that $\text{tp}(b_k/Ab_{<k})$ forks over $A$ (notation: $b_{<k} = \{b_i\mid i<k\}$). This is witnessed by some formula $\varphi(x,b_{i_1},\dots,b_{i_n},c)\in \text{tp}(b_k/Ab_{<k})$ which forks over $A$, where $c$ is a tuple from $A$ and $i_1<\dots<i_n<k\in I$.
Now since $(b_i)_{i\in I}$ satisfies $\mathcal{EM}((a_j)_{j\in J}/A)$, pick any $j_1<\dots<j_n<k'\in J$, and we have:

*

*$\varphi(x,a_{j_1},\dots,a_{j_n},c)$ forks over $A$ (since $\text{tp}(a_{j_1} \dots a_{j_n}c/A) = \text{tp}(b_{i_1}\dots b_{i_n}c/A)$), and

*$\varphi(x,a_{j_1},\dots,a_{j_n},c)\in \text{tp}(a_{k'}/Aa_{<k'})$ (since $\text{tp}(a_{j_1}\dots a_{j_n}a_{k'}c/A) = \text{tp}(b_{i_1}\dots b_{i_n}b_kc/A)$).

So $\text{tp}(a_{k'}/Aa_{<k'})$ forks over $A$, contradicting our assumption that $(a_j)_{j\in J}$ is a Morley sequence.


text:
Q: Removing unwanted html from an href tag in Python I want to be able to scrape out a list of links. I cannot due this directly with BeautifulSoup because of the way the html is structured.
start_list = soup.find_all(href=re.compile('id='))

print(start_list)

[Act of Valor,
 Action Jackson]

I am looking to pull just the href information. I am thinking some sort of filter where I can put all of the bold  tags into a list then filter them out of another list which contains the information above.
start_list = soup.find_all('a', href=re.compile('id='))

start_list_soup = BeautifulSoup(str(start_list), 'html.parser')

things_to_remove = start_list_soup.find_all('b')

The idea is to be able to loop through things_to_remove and remove all occurrences of its contents from start_list

A: start_list = soup.find_all(href=re.compile('id='))

href_list = [i['href'] for i in start_list]

href is the attrbute of tag, if you use find_all get bunch of tags, just iterate over it and use tag['href'] to access the attribute.
To understand why use [], you should know that tag's attribute are store in the dictionary.
Document:

A tag may have any number of attributes. The tag
  has an attribute "class" whose value is "boldest". You can access a
  tag's attributes by treating the tag like a dictionary:
tag['class']
# u'boldest'

You can access that dictionary directly as .attrs:
tag.attrs
# {u'class': u'boldest'}

list comprehension is simple, you can reference this PEP, in this case, it can be done in the for loop:
href_list = []
for i in start_list:
    href_list.append(i['href'])


text:
Q: How to check free slots available in RabbitMQ 's queue for a range of time interval? I am working on GMail API. I can send bulk email at once using the Gmail APIs. However now, I need to schedule the mails in different time intervals instead of sending the all the mail at once.
This service of control deliverability of mail is not provided by the Gmail API. So for that I am using the services of rabbitMQ and creating a queue and then enqueuing the mails into it.  While enqueuing , I must provide the delay such that it fits the free slot availability and also the mails are distributed equally among free slots and time intervals.
Currently I am struck at how to find available free slots in the queue.
I have gone through the RabbitMQ - Monitoring Documentations and only relevant thing which I could found is :-Response of queue details
but still I am clueless how to deduct the free available slots for a particular time interval. Help me to find it.
Thanks in advance!

A: Currently there is no feature in GMail API to "schedule" an email to be sent. However there is a long standing Feature Request for that.
Regarding RabbitMQ, I don't think a message queue is meant to work that way, I'd recommend implementing your own take to that approach of a pool of tasks.
For example, having a centralized list of tasks (like a relational DB table) that would have minimal information about:

*

*Type of task to be executed (send email for example)

*Time frame to be executed (Daily | 14:00-16:00 or 2022-02-03 | 14:00-16:00 for example)

*Callback context data ({recipient: "a@a.com", body:"Hello World!"} for example)

A scheduler service that is responsible for adding tasks to this queue/pool table can have a method like findATime() or listAvailableSpotsForTheDay().


text:
Q: Tkinter: update TopLevel window when closing another TopLevel window above first? (Reference?) I'm a python beginner making a program that is supposed to save and present reservations for a campingsite (just for fun...). I've structured it in an OOP-way meaning that I define a class for each seperate window. What I need to do is to update a TopLevel window (SubWindow2) presenting database entries, when another TopLevel window (created from Subwindow2) is closed.
import Tkinter as tk

class MenuWindow(tk.Tk):
    def __init__(self, master):
        self.master = master

        #Widgets

    def open_subwindow1(self):
       self.window = Toplevel(self.master)
       self.SubSubWindow1 = SubSubWindow1(self.window)

    def open_subwindow2(self):
       self.window = Toplevel(self.master)
       self.SubSubWindow2 = SubSubWindow2(self.window)

class SubWindow1(tk.Tk):
    def __init__(self, master):
         self.master = master

         #Widgets

class Subwindow2(tk.TopLevel):
    def __init__(self, master):
         self.master = master

         #Widgets

         self.button = tk.Button(master, text='Quit', command=open_subsub1)

    def load_values(self):
        #loading sqlite db-values into listboxes

    def open_subsub1(self):
        self.window = Toplevel(self.master)
        self.SubSubWindow1 = SubSubWindow1(self.window)

class SubSubWindow1(tk.TopLevel):
    def __init__(self, master):
        self.master = master

        #Widgets

        self.button = tk.Button(master, text='Quit', command=on_quit)

    def on_quit(self):
        #Here I want to call a function that updates SubWindow2 (loads sqlite database values into several listboxes)

        self.master.destroy()

root = tk.Tk()
myprog = MyProg(root)

root.mainloop()

How can i access a function in Subwindow2 from SubSubWindow1? self.master only refers to the TopLevel() instance right?
def on_quit(self):
    self.SubWindow2.load_values()
    self.master.destroy()

doesn't work, I get a TypeError: unbound method load_values() must be called with SubWindow2 instance as first argument (got nothing instead)
Is this an unvalid approch to "nesting" TopLevel-windows? What's the alternative?
Any remarks are greatly appriciated! Thanks for any help

A: I should preface this by claiming that I am also a novice, and I would greatly appreciate the advice of others in order not to spread misinformation.
From what I can see, you have some misunderstandings with how inheritance vs. encapsulation works in Python. Firstly, within a Tkinter application, there should only be a single instance of Tk(). Within your class definitions, you declare...
class SubWindow1(tk.Tk):

This means that whenever you create a new SubWindow1, a new instance of Tk will become instantiated with it, and SubWindow1 will inherit all of its properties.
If you would like to create a class that refers to, and has all the properties, of a Toplevel instance, your Subwindow2 was correct.
class Subwindow2(tk.TopLevel):

However, within the init, you must also initialize this instance of Toplevel as so:
class SubWindow2(tk.Toplevel):
    def __init__(self, master):
        tk.Toplevel.__init__(self)
        self.master = master

Each 'master' refers to the element above it. Tk applications work as a tree hierarchy. This is why you should only have one instance of Tk(), which works as your 'root.' This instance of Tk contains windows within it, which contains windows or elements within them. So each window or element will have a parent, referred to as master, so you will be able to navigate around.
So when you create an instance of SubWindow2, this refers to everything within your SubWindow2, along with everything included in an instance of Toplevel. Because 'self' now refers to a Toplevel, you can pass it into the children to be a master, as such:
self.sub_sub_window1 = SubSubWindow1(self)

self.master only refers to the TopLevel() instance right?

Yes, but since you will be inheriting all of the Toplevel attributes through your SubWindow2 inheritance, you can add on more methods and still refer to them through your self.master tag.
Lastly, you should also call pack() on elements that you would like to show up correctly on your windows.
Altogether, I've made some edits to your program to try and demonstrate some of the concepts of inheritance and how it works within a Tkinter application. I hope you can look at this and take something from it. Please let me know if there are any elements you disagree with, as it is nowhere near perfect.
import Tkinter as tk

class MenuWindow():
    def __init__(self, master):
        self.master = master
        self.sub_window_1 = SubWindow1(self.master)
        self.sub_window_2 = SubWindow2(self.master)

class SubWindow1(tk.Toplevel):
    def __init__(self, master):
        tk.Toplevel.__init__(self)
        self.master = master

class SubWindow2(tk.Toplevel):
    def __init__(self, master):
        tk.Toplevel.__init__(self)
        self.master = master
        self.sub_sub_window1 = SubSubWindow1(self)

    def print_hello(self):
        print "Hello!"

class SubSubWindow1(tk.Toplevel):
    def __init__(self, master):
        tk.Toplevel.__init__(self)
        self.master = master
        self.button = tk.Button(self.master, text='Say Hello & Destroy', command=self.on_quit)
        self.button.pack()

    def on_quit(self):
        self.master.print_hello()
        self.master.destroy()

root = tk.Tk()
myprog = MenuWindow(root)
root.mainloop()


text:
Q: Query country border polygon from OpenStreetMap Is it possible to download the polygons of countries from OpenStreetMap using Nominatim web API? If so, how should I query its points?
In the example responses from Nominatim on OpenStreetMap wiki there is a polygonpoints property (attribute) on place object (tag), but it's not always present in search results when querying for countries. Also, what happens when the country "consists" of more than one polygon - several islands, for instance, can I query all of them?
If it's impossible to do with Nominatim, is there any other freely available API with such functionality?

A: It think it is possible with Nominatim, take a look at the query parameters listed in the documentation: The interesting parameters for you are the ones starting with polygon_, depending on what format you desire you can add polygon_geojson=1 or polygon_kml=1 (or the other ones) to your query.
If a country consists of several islands/polygons they are included as well, take for example Spain. The resulting geometry is a MultiPolygon for GeoJSON, MultiGeometry for KML and so on:

The query URLs may look like this:
http://nominatim.openstreetmap.org/search?country=Spain&polygon_geojson=1&format=json
http://nominatim.openstreetmap.org/search?country=Spain&polygon_kml=1&format=json

Using country= instead of using the general q= as the search parameter seemed to yield better results for your use case.


text:
Q: How can I get the clients IP address from HTTP headers? I understand it's a standard practice to look at both these variables. Of course they can easily be spoofed. I'm curious how often can you expect these values (especially the HTTP_X_FORWARDED_FOR) to contain genuine information and not just be scrambled or have their values stripped away?
Anyone with the experience or statistics on this stuff?
Is there anything else that can be useful for the task of getting the client's IP address?

A: No real answer to your question but:
Generally relying on the clients IP address is in my opinion not a good practice as it is not usable to identify clients in a unique fashion.
Problems on the road are that there are quite a lot scenarios where the IP does not really align to a client:

*

*Proxy/Webfilter (mangle almost everything)

*Anonymizer network (no chance here either)

*NAT (an internal IP is not very useful for you)

*...

I cannot offer any statistics on how many IP addresses are on average reliable but what I can tell you that it is almost impossible to tell if a given IP address is the real clients address.

A: In addition to REMOTE_ADDR and HTTP_X_FORWARDED_FOR there are some other headers that can be set such as:

*

*HTTP_CLIENT_IP

*HTTP_X_FORWARDED_FOR can be comma delimited list of IPs

*HTTP_X_FORWARDED

*HTTP_X_CLUSTER_CLIENT_IP

*HTTP_FORWARDED_FOR

*HTTP_FORWARDED
I found the code on the following site useful:
http://www.grantburton.com/?p=97

A: It depends on the nature of your site.
I happen to work on a bit of software where IP tracking is important, and within a field consumed by parter sites I'd guess some 20% - 40% of requests are either detectably spoofed IPs or headers blanked out, depending on the time of day and where they came from. For a site which gets organic traffic (i.e. not through partners) I'd expect a much higher ratio of good IPs.
As Kosi said, be careful what you're doing with this - IPs are in no way a reliable way to identify unique visitors.

A: IP + "User Agent" could be a better for unique visitor.

A: I've ported Grant Burton's PHP code to an ASP.Net static method callable against the HttpRequestBase. It will optionally skip through any private IP ranges.
public static class ClientIP
{
    // based on http://www.grantburton.com/2008/11/30/fix-for-incorrect-ip-addresses-in-wordpress-comments/
    public static string ClientIPFromRequest(this HttpRequestBase request, bool skipPrivate)
    {
        foreach (var item in s_HeaderItems)
        {
            var ipString = request.Headers[item.Key];

        if (String.IsNullOrEmpty(ipString))
            continue;

        if (item.Split)
        {
            foreach (var ip in ipString.Split(','))
                if (ValidIP(ip, skipPrivate))
                    return ip;
        }
        else
        {
            if (ValidIP(ipString, skipPrivate))
                return ipString;
        }
    }

    return request.UserHostAddress;
}

private static bool ValidIP(string ip, bool skipPrivate)
{
    IPAddress ipAddr;

    ip = ip == null ? String.Empty : ip.Trim();

    if (0 == ip.Length
        || false == IPAddress.TryParse(ip, out ipAddr)
        || (ipAddr.AddressFamily != AddressFamily.InterNetwork
            && ipAddr.AddressFamily != AddressFamily.InterNetworkV6))
        return false;

    if (skipPrivate && ipAddr.AddressFamily == AddressFamily.InterNetwork)
    {
        var addr = IpRange.AddrToUInt64(ipAddr);
        foreach (var range in s_PrivateRanges)
        {
            if (range.Encompasses(addr))
                return false;
        }
    }

    return true;
}

/// <summary>
/// Provides a simple class that understands how to parse and
/// compare IP addresses (IPV4) ranges.
/// </summary>
private sealed class IpRange
{
    private readonly UInt64 _start;
    private readonly UInt64 _end;

    public IpRange(string startStr, string endStr)
    {
        _start = ParseToUInt64(startStr);
        _end = ParseToUInt64(endStr);
    }

    public static UInt64 AddrToUInt64(IPAddress ip)
    {
        var ipBytes = ip.GetAddressBytes();
        UInt64 value = 0;

        foreach (var abyte in ipBytes)
        {
            value <<= 8;    // shift
            value += abyte;
        }

        return value;
    }

    public static UInt64 ParseToUInt64(string ipStr)
    {
        var ip = IPAddress.Parse(ipStr);
        return AddrToUInt64(ip);
    }

    public bool Encompasses(UInt64 addrValue)
    {
        return _start <= addrValue && addrValue <= _end;
    }

    public bool Encompasses(IPAddress addr)
    {
        var value = AddrToUInt64(addr);
        return Encompasses(value);
    }
};

private static readonly IpRange[] s_PrivateRanges =
    new IpRange[] {
            new IpRange("0.0.0.0","2.255.255.255"),
            new IpRange("10.0.0.0","10.255.255.255"),
            new IpRange("127.0.0.0","127.255.255.255"),
            new IpRange("169.254.0.0","169.254.255.255"),
            new IpRange("172.16.0.0","172.31.255.255"),
            new IpRange("192.0.2.0","192.0.2.255"),
            new IpRange("192.168.0.0","192.168.255.255"),
            new IpRange("255.255.255.0","255.255.255.255")
    };

/// <summary>
/// Describes a header item (key) and if it is expected to be
/// a comma-delimited string
/// </summary>
private sealed class HeaderItem
{
    public readonly string Key;
    public readonly bool Split;

    public HeaderItem(string key, bool split)
    {
        Key = key;
        Split = split;
    }
}

// order is in trust/use order top to bottom
private static readonly HeaderItem[] s_HeaderItems =
    new HeaderItem[] {
            new HeaderItem("HTTP_CLIENT_IP",false),
            new HeaderItem("HTTP_X_FORWARDED_FOR",true),
            new HeaderItem("HTTP_X_FORWARDED",false),
            new HeaderItem("HTTP_X_CLUSTER_CLIENT_IP",false),
            new HeaderItem("HTTP_FORWARDED_FOR",false),
            new HeaderItem("HTTP_FORWARDED",false),
            new HeaderItem("HTTP_VIA",false),
            new HeaderItem("REMOTE_ADDR",false)
    };
}

A: If you're behind a proxy, you should use X-Forwarded-For: http://en.wikipedia.org/wiki/X-Forwarded-For
It is an IETF draft standard with wide support:

The X-Forwarded-For field is supported by most proxy servers,
including Squid, Apache mod_proxy, Pound, HAProxy, Varnish cache,
IronPort Web Security Appliance, AVANU WebMux, ArrayNetworks,
Radware's AppDirector and Alteon ADC, ADC-VX, and ADC-VA, F5 Big-IP,
Blue Coat ProxySG, Cisco Cache Engine, McAfee Web Gateway, Phion
Airlock, Finjan's Vital Security, NetApp NetCache, jetNEXUS, Crescendo
Networks' Maestro, Web Adjuster and Websense Web Security Gateway.

If not, here are a couple other common headers I've seen:

*

*X-Client-IP (Apache)

*X-Real-IP (Nginx)

A: Call the Below Action Method from your JS file (To get the ipv4 ip address).
    [HttpGet]
    public string GetIP()
    {
        IPAddress[] ipv4Addresses = Array.FindAll(
            Dns.GetHostEntry(string.Empty).AddressList,
            a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
        return ipv4Addresses.ToString();
    }

Check after keeping Breakpoint, and use as per your requirement.
Its working fine for me.


text:
Q: Insert new points at specific places in the Locator Pane? I am trying to make some  BSplineCurve examples for my students. For fun I created the following Manipulate that draw an elephant using BSplineCurve
img = Import[
  "http://www.clipartqueen.com/image-files/elephant-silhouette.png"]
ptsin = {{984., 950.}, {1113., 898.}, {1188.2, 843.6}, {1226.7,
    784.7}, {1247.1, 748.5}, {1260.6, 712.3}, {1269.7,
    655.7}, {1274.2`, 592.3}, {1278.7, 501.8}, {1292.3,
    452.}, {1328.5, 370.5}, {1249.3, 465.6}, {1224.4, 375.1}, {1224.4,
     341.1}, {1197.3, 289.1}, {1188.2, 232.5}, {1181.4, 164.6}};
Manipulate[
 Show[Image[img, ImageSize -> 400],
  Graphics[{Yellow, Blue, Thick,
    BSplineCurve[pts, SplineDegree -> 3,
     SplineClosed -> True], Polygon[pts]}, Frame -> True,
   PlotRange -> All]], {{pts, ptsin}, Locator,
  LocatorAutoCreate -> True}, "Alt+click to add points"]

I take the following locator Pane:

I need some help on making a nicer LocatorPane! I can draw new points into pts list (using Alt+ click) but these are only inserted  at the end of pts.  Is it possible  each  point is exactly inserted  after  (the position of) the  last clicked  point(and not at the end of pts)? Is it posible to have redo or undo buttons( in other words: How to make a "history" of pts)?
Excuse for the multiple questions here. I found that LocatorPane is very attractive method for making fun with maths,  vector drawings etc.
I hope that is not a duplicate question!

A: I guess you could do everything you wanted but you will have to abandon the general Manipulate and program your own LocatorPane. Here's a try.
First I modified your input data slightly to debugging taste.
With[{width = 400},
  original = Import[
    "http://www.clipartqueen.com/image-files/elephant-silhouette.png"];
  img = ImageResize[original, width] // ColorReplace[#,
      Black -> LightRed, 1] &;
  ptsin = {{984., 950.}, {1113., 898.}, {1188.2, 843.6}, {1226.7,
     784.7}, {1247.1, 748.5}, {1260.6, 712.3}, {1269.7,
     655.7}, {1274.2`, 592.3}, {1278.7, 501.8}, {1292.3,
     452.}, {1328.5, 370.5}, {1249.3, 465.6}, {1224.4,
     375.1}, {1224.4, 341.1}, {1197.3, 289.1}, {1188.2,
     232.5}, {1181.4, 164.6}};
  ptsin *= width/ImageDimensions[original][[1]]];

LocatorPane below has two arguments, both dynamically updated: the locator coordinates and displayed expression. Dynamic of the coordinates has the optional second argument: function that is evaluated whenever the coordinates change. This way the index of the coordinate last moved (i) is stored. EventHandler shows its first argument (Show) and also listens to defined events: in this case the depressing of the mouse right button. (I don't think you can interfere with Alt + clicking, so you must append your functionality to a new event.)
Coded like this, the user interface below is: Alt + clicking appends a new point to the end of ptsin (or removes an existing point), right-clicking inserts a new point after the point last dragged.
DynamicModule[{i = Length[ptsin], last},
 last[prev_, curr_] :=
  If[Length[prev] != Length[curr],
   Length[curr],
   FirstPosition[SameQ @@@ Thread[{prev, curr}], False][[1]]];
 LocatorPane[
  Dynamic[ptsin, (i = last[ptsin, #]; ptsin = #) &],
  EventHandler[
   Show[img,
     Graphics[{Thick, Black, Line[ptsin],
       Text[i, Scaled[{.95, .95}], {1, 1}]}],
     Frame -> True] // Dynamic,
   {{"MouseDown", 2} :> (ptsin = Insert[ptsin,
        MousePosition["GraphicsAbsolute"], i + 1])}
   ],
  LocatorAutoCreate -> True]]

A: A version with buttons. First thing to note: I don't know how to subscribe to the Alt + click event and do appropriate things when it triggers. This is why mixing point adding by Alt + click and right-click is error-prone. If one sticks to adding points merely by right-click (via {"MouseDown", 2} event in LocatorPane), code could be bug-free ...
You start it up by supplying an image and a list of starting points (ptsin in your case for example), or specify the image alone and the locator list will be initially empty.

edit[image_] := edit[image, {}]

edit[image_, starters_] :=
 DynamicModule[{
   p = starters, i = Length[starters], track = {}, last},

  (* index of a locator point last moved/clicked on *)
  last[prev_, curr_] :=
   Position[SameQ @@@ Thread[{prev, curr}], False, 1, 1][[1, 1]];

  Column[{

    (* top row of button controls: Undo, Clear, Random 5 *)
    Row[{
      Button["Undo",
       If[track =!= {}, CompoundExpression[
         p = Delete[p, Last[track]],
         track = Most[track],
         If[i > Length[track], i = Length[track]]]],
       ImageSize -> Automatic], Spacer[5],
      Button["Clear", (p = {}; track = {}; i = 0),
       ImageSize -> Automatic], Spacer[5],
      Button["Random 5",
       (p =
         Table[RandomInteger[{1, #}] & /@ ImageDimensions[image], {5}];
        track = {}; i = Length[p]),
       ImageSize -> Automatic]
      }
     ],

    LocatorPane[
     Dynamic[p, (i = last[p, #]; p = #) &],
     EventHandler[
      Dynamic@Show[image,
        Graphics[{Thick, Black, Line[p],
          Text["Last moved: " <> ToString[i],
           Scaled[{.95, .95}], {1, 1}],
          Text["Insertion track: " <> StringJoin[Riffle[track, " "]],
           Scaled[{.05, .95}], {-1, 1}]}]],
      {{"MouseDown", 2} :> CompoundExpression[
         p = Insert[p, MousePosition["Graphics"], i + 1],
         AppendTo[track, i + 1], i += 1]}],
     LocatorAutoCreate -> True]
    },
   Frame -> True,
   FrameStyle -> Directive[Gray, Thick, Dashed],
   Spacings -> {2, 2}
   ]
  ]


text:
Q: How to include WooCommerce conditional tags in custom plugin I need to use the conditional tag is_product() from the WooCommerce plugin so my custom plugin only loads in the script if the user is at a product page on the front-end.
Additionally, I don't want the plugin to break if WooCommerce is not installed on the website.
My current code:
if ( !is_admin() && is_product() ) {
    function add_script() {
        wp_enqueue_script( 'main', plugin_dir_url( __FILE__ ) . '/js/main.js' );
    }
}
add_action( 'wp_enqueue_scripts', 'add_script' );

This doesn't work at the moment since it can't find the conditional tag is_product().
Any advice?

A: "I don't want the plugin to break if Woocommerce is not installed on the website." Your main plugin file should start with:
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

// Check if WooCommerce is active
if ( ! in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) exit; // Exit if WC not active

Loads the script if the user is at a product page, use:
function add_script() {
    // is_admin() - Determines whether the current request is for an administrative interface page.
    // is_product() - Returns true on a single product page.
    if ( !is_admin() && is_product() ) {
        wp_enqueue_script( 'main', plugin_dir_url( __FILE__ ) . '/js/main.js' );
    }
}
add_action( 'wp_enqueue_scripts', 'add_script' );


text:
Q: Access router management from VPN I'm using a tp-link TL-ER6120 router in order to use a VPN. The LAN is using the IP range 192.168.100.1 - 255, and I have a TP-Link Archer C7 Wireless router (as AP, with DHCP disabled and connected using LAN port) with IP 192.168.100.10.
I'm assigning the VPN clients the IP 192.168.101.1-10, because I can't overlap LAN IPs with VPN IPs.
But when I try to connect to 192.168.100.10 from VPN client the connection doesn't work. I have a web server running with 192.168.100.5 IP, and it works, but with router it just doesn't work.
Why can I connect to a web server but not to the router?


text:
Q: int array[10] = {1 , 2, 0, 3} . How can I find out that there are 4 elements here? I know how to find the size of array I tried this code..As you can see the problem is the empty elements are zero. So, I tried to check with it but the thing is I can have 0 as an element.

int main()
{
    int array[10] = {1, 2, 0, 3, 4};

    printf("%d\n", sizeof(array)/ sizeof(*array)); // This is the size of array

    int i = 0;

    while(array[i] != 0  && i < 10) {
        i++;
    };

    printf("%d\n", i);

    return 0;
}```

A: You can't. int array[10] will always create an array of 10 elements and you can't ask the compiler which of them have been assigned.
What you could do is int array[] = {1, 2, 0, 3, 4} then the compiler will infer the number of elements for you and you'll have sizeof(array)/ sizeof(*array) == 5

A: First set the array to a number outside the range of your inputs. Like a negative number.
for(i = 0;i < 10;i++)
    array[i] = -1;

or set it to INT_MAX or INT_MIN

A:
int array[10] = {1 , 2, 0, 3} . How can I find out that there are 4 elements here?

How can you say there are 4 elements there as you declared that int array[10] with the size of 10 elements. This implies, you already know the no. of elements. Also, in this scenario, you can't use an if statement to determine the no. of elements as you probably know that in C, if you initialize an array of 10 elements with less than 10 values, rest of them will automatically be assigned to 0.

A: You have several options:

*

*You know how many elements are in the initializer, so you create another variable that stores that number:int array[10] = {1, 2, 0, 3, 4};
int num_items = 5;

You'll need to update num_items as you "add" or "remove" items to the array.  If you treat the array as a stack (only add or remove at the highest index), then this is easy-ish:array[num_items++] = 7; // adds 7 after 4
...
x = array[--num_items]; // x gets 7, 7 is "removed" from the array, need special
                        // case logic for element 0

*You pick a value that isn't valid (say -1) and initialize the remaining elements explicitly:int array[10] = {1, 2, 0, 3, 4, -1, -1, -1, -1, -1 };

*You size the array for the initializer, meaning it can only ever store that many elements:int array[] = {1, 2, 0, 3, 4};
Otherwise, you'll need to use a different data structure (such as a linked list) if you need a container that can grow or shrink as items are added or removed.


text:
Q: Mask-RCNN with Keras : Tried to convert 'shape' to a tensor and failed. Error: None values not supported I am trying to run the Keras implemention of Mask_RCNN in inference mode. It is basically running this code demo.ipynb
But when I run it, I get the following error on model creation :
ValueError: Tried to convert 'shape' to a tensor and failed. Error: None values not supported.

And here is the stacktrace :
Traceback (most recent call last):
  File "/snap/pycharm-community/128/helpers/pydev/pydevd.py", line 1758, in <module>
    main()
  File "/snap/pycharm-community/128/helpers/pydev/pydevd.py", line 1752, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/snap/pycharm-community/128/helpers/pydev/pydevd.py", line 1147, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/snap/pycharm-community/128/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "[PATH/TO/Mask_RCNN/]/Own_code/Test.py", line 44, in <module>
    model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
  File "[PATH/TO/Mask_RCNN/]/Mask_RCNN/mrcnn/model.py", line 1833, in __init__
    self.keras_model = self.build(mode=mode, config=config)
  File "[PATH/TO/Mask_RCNN/]/Mask_RCNN/mrcnn/model.py", line 2035, in build
    fc_layers_size=config.FPN_CLASSIF_FC_LAYERS_SIZE)
  File "[PATH/TO/Mask_RCNN/]/Mask_RCNN/mrcnn/model.py", line 947, in fpn_classifier_graph
    mrcnn_bbox = KL.Reshape((s[1], num_classes, 4), name="mrcnn_bbox")(x)
  File "[PATH/TO/venv/]lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py", line 554, in __call__
    outputs = self.call(inputs, *args, **kwargs)
  File "[PATH/TO/venv/]lib/python3.6/site-packages/tensorflow/python/keras/layers/core.py", line 439, in call
    (array_ops.shape(inputs)[0],) + self.target_shape)
  File "[PATH/TO/venv/]lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py", line 7179, in reshape
    "Reshape", tensor=tensor, shape=shape, name=name)
  File "[PATH/TO/venv/]lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 529, in _apply_op_helper
    (input_name, err))

It look like my problem is the same as described here, but there is no real answer to it.
Notes :

*

*I am running it with Python 3.6 and Tensorflow 1.13.1

*I have edited the Keras imports to use the Keras version embedded in Tensorflow

*The code that I run to have this error correspond to the 3 first blocks of the demo notebook.

EDIT
Here is the code I am running :
# Root directory of the project
ROOT_DIR = os.path.abspath("../")

# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library

# Import COCO config
sys.path.append(os.path.join(ROOT_DIR, "samples/coco/"))  # To find local version

# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")

# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
    utils.download_trained_weights(COCO_MODEL_PATH)

# Directory of images to run detection on
IMAGE_DIR = os.path.join(ROOT_DIR, "images")

class InferenceConfig(coco.CocoConfig):
    # Set batch size to 1 since we'll be running inference on
    # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1

config = InferenceConfig()

# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)

This is really a copy/paste of the demo.ipynb from the maskRCNN repo. The last line is where the error occur.

A: I made all the changes recommended in this official issue thread.
Those are basically changes inside the model.py script to use tf.keras functions instead of pure keras functions.
Here is my working fork (updated for TF 2.4.1 - May 2021).
You can find my colab sample inside it or through this link

A: I got the same error, until :

*

*Using keras.__version__ == 2.2.4

*Tensorflow-gpu version == 1.12.0

*Skimage.__version__ == 0.14.2
Not sure what is the error with rest versions, probably something does not fit with pycocotools or
optimizer = keras.optimizers.SGD(
            lr=learning_rate, momentum=momentum,
            clipnorm=self.config.GRADIENT_CLIP_NORM) #this portion.

A: Replace this code in model.py
if s[1] is None:
    mrcnn_bbox = KL.Reshape((-1, num_classes, 4), name="mrcnn_bbox")(x)
else:
    mrcnn_bbox = KL.Reshape((s[1], num_classes, 4), name="mrcnn_bbox")(x)


text:
Q: How to get around with this conversion issue? I created a GUI which inputs a value number into another program and stores them in tags. I have a weird conversion problem. When I input 8.5 I get back a string 8.500000000000000... so I use the TryParse and the Double.ToString() method to get around this issue. But the bizarre part is that when I try with 6.9  the string becomes 6.9000000005367431600000.I use 2 dll which might be the cause of this problem. I've read this Decimals explanation but I don't understand how this can be fix my problem. How to get around with this conversion issue?
My Conversion method
    private bool TryWrite()
            {
// Read() returns a string(which represents int,double, float or string) read from another application
                string Oldcopy = _inTouchWrapper.Read(tagNameBox.Text);
// Write() Write my input number into the application stored in a specific tag
                _inTouchWrapper.Write(tagNameBox.Text, ValueBox.Text);
//OldCopy is to input back the old copy is the Write (new copy) cannot be performed
                string newCopy = _inTouchWrapper.Read(tagNameBox.Text);

                if (ValueBox.Text == Double.Parse(newCopy).ToString())
                {
                    return true;
                }
                else
                {
                    _inTouchWrapper.Write(tagNameBox.Text, Oldcopy);
                    return false;
                }
            }

More explanation about the software/and my code. The software has tags ex: Alarm1, TimeString...
Each tag has a type (int, real(a float), string) and a value. This value depends on the type. I cannot input 5.6 if the tag type is int. So I created this method which verifies is the input value can indeed be added in the software. How it works: I input a value in the software, read it back and if the added value matches with the read value, I indeed input it. Else, I input back the oldCopy.

A: It seems that string "6.9" is not directly converted to double. If is first converted to float and then casted to double. Here is an example:
var f = float.Parse("6.9");
var d = (double)f;
System.Diagnostics.Debug.WriteLine(d.ToString()); //6.90000009536743

PS: Why you not have the same issue with '8.5' is that it can exactly be represented in binary form.


text:
Q: How to transfer data from one system to another system's HDFS (connected through LAN) using Flume? I have a computer in LAN Connection . I need to transfer data from the system to another system's HDFS location using flume.
I have tried using ip address of the sink system, but it didn't work. Please help..
Regards,
Athiram

A: This can be achieved by using avro mechanism.
The flume has to be installed in both the machines. A config file with the following codes has to be made to be run in the source system , where the logs are generated.
a1.sources = tail-file
a1.channels = c1
a1.sinks=avro-sink

a1.sources.tail-file.channels = c1
a1.sinks.avro-sink.channel = c1
a1.channels.c1.type = memory
a1.channels.c1.capacity = 1000

a1.sources.tail-file.type = spooldir
a1.sources.tail-file.spoolDir =<location of spool directory>
a1.sources.tail-file.channels = c1
a1.sinks.avro-sink.type = avro
a1.sinks.avro-sink.hostname = <IP Address of destination system where the data has to    be written>
a1.sinks.avro-sink.port = 11111

A config file with the following codes has to be made to be run in the destination system , where the logs are generated.
a2.sources = avro-collection-source
a2.sinks = hdfs-sink
a2.channels = mem-channel

a2.sources.avro-collection-source.channels = mem-channel
a2.sinks.hdfs-sink.channel = mem-channel
a2.channels.mem-channel.type = memory
a2.channels.mem-channel.capacity = 1000

a2.sources.avro-collection-source.type = avro
a2.sources.avro-collection-source.bind = localhost
a2.sources.avro-collection-source.port = 44444

a2.sinks.hdfs-sink.type = hdfs
a2.sinks.hdfs-sink.hdfs.writeFormat = Text
a2.sinks.hdfs-sink.hdfs.filePrefix =  testing
a2.sinks.hdfs-sink.hdfs.path = hdfs://localhost:54310/user/hduser/

Now, the data from the log file in the source system will be written to hdfs system in the destination system.
Regards,
Athiram


text:
Q: Access Office 365 Library I'm using Office 365 API Tools for Visual Studio. When I run the following code everything works fine and my documents are returned.
    string SPResourceID = "https://tenant.sharepoint.com";
    string SPServiceRoot = "https://tenant.sharepoint.com/_api";
    var authenticator = new Authenticator();
    var result = await authenticator.AuthenticateAsync(SPResourceID, ServiceIdentifierKind.Resource);

    // Create a client proxy:

    this.client = new SharePointClient(new Uri(SPServiceRoot), result.GetAccessToken);
    this.client.Context.IgnoreMissingProperties = true;

However, when I try to access a sub web such as:-
string SPResourceID = "https://tenant.sharepoint.com/test";
string SPServiceRoot = "https://tenant.sharepoint.com/test/_api";

I am asked to reauthenticate and then get the error "AADSTS50001: Resource 'https://tenant.sharepoint.com/test/' is not registered for the account". Has anyone got any ideas as to how I can access libraries in a sub web and is it possible to pass in the name of the library rather than relying on it being the default library.
Thanks,
Geoff

A: Your SPResourceID is still https://tenant.sharepoint.com/.
The resourceId is the ID your Office 365 subscription is registered with in azure ad.


text:
Q: How can I get File.Delete() to actually delete my file? I generate a PDF file, save it on the server:
var bytes = ms.ToArray();
. . .
String fileFullpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), pdfFileName);
. . .
File.WriteAllBytes(fileFullpath, bytes);

...and then save it into a Sharepoint Document Library, and send it as an email attachment to the person who generated the file:
SavePDFToDocumentLibrary(fileFullpath);
String from = GetFromEmailID();
String to = GetUserEmail();
String subjLine = String.Format("The PDF file you generated ({0})", pdfFileName);
String body = String.Format("The Direct Pay PDF file you generated ({0}) is attached.", pdfFileName);
SendEmailWithAttachment(fileFullpath, from, to, subjLine, body);
// Now that it has been put in a Document Library and emailed, delete the file that was saved locally
File.Delete(fileFullpath);

...at which point, I no longer need the file I saved to disk on the server, and so, as shown in the last line above, attempt to delete it.
However, it doesn't work. The now-redundant file is still in the place where it was saved.
Why, and how can I get it to understand that "Delete" really means "delete"?
UPDATE
Here are the methods Scott wanted to see:
// This works; got it from Henry Zucchini's answer at http://stackoverflow.com/questions/468469/how-do-you-upload-a-file-to-a-document-library-in-sharepoint
private void SavePDFToDocumentLibrary(String fullpath)
{
    String fileToUpload = fullpath;
    String sharePointSite = siteUrl;
    String documentLibraryName = "DirectPayPDFForms";

    using (SPSite oSite = new SPSite(sharePointSite))
    {
        using (SPWeb oWeb = oSite.OpenWeb())
        {
            if (!System.IO.File.Exists(fileToUpload))
                throw new FileNotFoundException("File not found.", fileToUpload);

            SPFolder doclib = oWeb.Folders[documentLibraryName];

            // Prepare to upload
            Boolean replaceExistingFiles = true;
            String fileName = System.IO.Path.GetFileName(fileToUpload);
            FileStream fileStream = File.OpenRead(fileToUpload);

            // Upload document
            SPFile spfile = doclib.Files.Add(fileName, fileStream, replaceExistingFiles);

            // Commit
            doclib.Update();
        }
    }
}

// This is adapted from https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage(v=vs.90).aspx
public static void SendEmailWithAttachment(string fileToMail, String from, String to, String subj, String body)
{
    String server = GetSMTPHostName(); //"468802-DEV-SPWF"; // change this to prod when go live, or programatically assign?
    // Specify the file to be attached and sent.
    string file = fileToMail;
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage(
       from,
       to,
       subj,
       body);

    // Create  the file attachment for this e-mail message.
    Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
    // Add time stamp information for the file.
    ContentDisposition disposition = data.ContentDisposition;
    disposition.CreationDate = System.IO.File.GetCreationTime(file);
    disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
    disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
    // Add the file attachment to this e-mail message.
    message.Attachments.Add(data);

    //Send the message.
    SmtpClient client = new SmtpClient(server);
    // Add credentials if the SMTP server requires them.
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", ex.ToString());
    }
    // Display the values in the ContentDisposition for the attachment.
    // May not need/want this section
    ContentDisposition cd = data.ContentDisposition;
    Console.WriteLine("Content disposition");
    Console.WriteLine(cd.ToString());
    Console.WriteLine("File {0}", cd.FileName);
    Console.WriteLine("Size {0}", cd.Size);
    Console.WriteLine("Creation {0}", cd.CreationDate);
    Console.WriteLine("Modification {0}", cd.ModificationDate);
    Console.WriteLine("Read {0}", cd.ReadDate);
    Console.WriteLine("Inline {0}", cd.Inline);
    Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
    foreach (DictionaryEntry d in cd.Parameters)
    {
        Console.WriteLine("{0} = {1}", d.Key, d.Value);
    }
    // </ May not need/want this section
    data.Dispose();
}

UPDATE 2
I see when stepping through it, after adding this test:
if (File.Exists(fileFullpath))
{
    File.Delete(fileFullpath);
}

...that there is an exception after all, in the IOException catch block:
The process cannot access the file 'C:\Users\TEMP.SP.018\Desktop\DirectPayDynamic_2015Jul28_19_02_clayshan_0.pdf' because it is being used by another process.
So how is one of the other methods holding onto it? ISTM that SavePDFToDocumentLibrary() is safe, because it uses using blocks.
Is data.Dispose(); in SendEmailWithAttachment() not enough? Do I need to explicitly call close there, or what?
UPDATE 3
I added "message.Dispose();" just prior to "data.Dispose();" in SendEmailWithAttachment(), but it made no difference.

A: Try disposing the file stream used in SavePDFToDocumentLibrary like so:
using (FileStream fileStream = File.OpenRead(fileToUpload))
{
    ...
}


text:
Q: MVC2 - Consume RSS feed with RDF and namespace http://www.w3.org/1999/02/22-rdf-syntax-ns#' I' trying to read the feed for the Washington Departmene of Fish and Wildlife, and keep etting this error:

The element with name 'RDF' and
  namespace
  'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
  is not an allowed feed format.

Here's the code from RssController:
public virtual ActionResult Index()
{
    string feedUrl = @"http://wdfw.wa.gov/news/newsrss.php";

    using (XmlReader reader = XmlReader.Create(feedUrl))
    {

        **SyndicationFeed rss = SyndicationFeed.Load(reader);**

        return View(rss);
    }
}

I've done seveal RSS applications but nave never ran into this issue. Anyone got any concrete ways of being able to parse this in ASP.NET MVC 2? (the lines with asterics are where the exception happens.

A: There's no support for RSS 1.0. Example of how to roll your own support here : https://web.archive.org/web/20211020140320/https://www.4guysfromrolla.com/articles/031809-1.aspx

A: This may not be applicable to you as it sounds like you are only interested in RSS, but if you want RDF support for your application (RSS 1.0 uses RDF/XML to encode it's data) then you could try my library dotNetRDF.
I suspect that a full blown RDF API is probably overkill though judging from your question.


text:
Q: While loops where only conditions are executed? So I want to execute only while loop statements, without putting anything inside them. For example, I have an array arr from which I have to remove multiple occurrences of some element. The instant the condition statement returns an error, while loop should end.
arr=[1,2,4,2,4,2,2]

This removes only one 2:
arr.remove(2)

I need to run this as long as it does not return error. (C++ has a semicolon put after while to do this).
I want something like this
while(arr.remove(2));

A: The way you are looking to solve this does not yield the results you are looking for. Since you are looking to create a new list, you are not going to want to use the remove function as per @Matthias comment. The idiomatic way to do it would be something along the lines of this:

arr=[1,2,4,2,4,2,2]
arr = [x if x != 2 for x in arr]

A: Three things.
First, it's not considered good practice in Python – it's not "pythonic" – to use an expression for its side effects. This is why, for example, the Python assignment operator is not itself an expression. (Although you can do something like a = b = 1 to set multiple variables to the same value, that statement doesn't break down as a = (b = 1); any such attempt to use an assignment statement as a value is a syntax error.)
Second, modifying data in place is also discouraged; it's usually better to make a copy and make the changes as the copy is constructed.
Third, even if this were a good way to do things, it wouldn't work in this case. When the remove method succeeds, it returns None, which is not truthy, so your loop exits immediately. On the other hand, when it fails, instead of returning a false value, it throws an exception, which will abort your whole program instead of just the loop, unless you wrap it in a try block.
So the list comprehension probably is the best solution here.

A:
So I want to execute only while loop statements, without putting anything inside them.

That's really not necessary. Don't try to copy other language's syntax in Python.  Different languages are designed with different objectives and hence, they have different syntax (or grammar of the language). Python has a different way of doing things than C++.
If you want to focus on the effectiveness of the program, then that's the different story. See this for more information on this.
Unfortunately, remove doesn't return anything (it returns None). So, you can't have anything that would look neat and clean without putting anything inside while.
Pythonic way to remove all occurrence of a element from list:
list(filter((2).__ne__, arr))

Or
arr = [x for x in arr if x != 2]

Or
while 2 in arr:
    arr.remove(2)

A: you can use:
arr = [1,2,4,2,4,2,2]

try:
    while arr.pop(arr.index(2)):
          pass
except ValueError:
    pass

print(arr)
#[1, 4, 4]

A: I am assuming you want to remove all occurrences of an element. This link might help you.
click here


text:
Q: Redirect all pages with missing Itemid to home page Most of the pages on my website have missing Itemid values, that's no number attached to the Itemid key.
I want any pages with a missing Itemid to redirect to the home page. Here are a few examples of URLs:
 http://www.xyz.com/?page=16&&option=com_news&view=list&Itemid=
 http://www.xyz.com/index.php?option=com_news&view=detail&n_id=366&Itemid=
 http://www.xyz.com/index.php?option=com_car&view=search&Itemid=
 http://www.xyz.com/index.php?option=com_car&view=product&Itemid=&id=34&vid=133

How do I redirect these pages where the Itemid value is missing to the home page?
I have tried some permutations and combinations but all in vain; please help if possible.
Thanks.

A: Yo may try this:
RewriteEngine on
RewriteBase /
RewriteCond %{QUERY_STRING} Itemid=(&|$)
RewriteRule .*  http://homepage.com/?      [L]

Remove the last question mark ? if you want to keep the query in the substitution URL.


text:
Q: Monodroid How to get the PPI of a display Does anyone know any formula or any way to find the PPI of an android phone display?
Thank you in advance!

A: I think this was answerd a coupple fn times here. Check the DisplayMetrics class.
DisplayMetrics metrics = getResources().getDisplayMetrics();


text:
Q: Photons can be regarded as particles? So I've been reading an article and stopped at this sentence :
"Likewise, we can take energy (such as particles of light, called photons) and turn it into matter."
He gave an example of energy which is particle of light... But I know that particles are regarded as matter, and photons are a pack of energy, is it right to call them particles? I'm confused

A: To answer the question in the title: yes, light is composed of photons which are classified as particles.
Your confusion arises from the word 'matter'. Matter is an ill-defined concept with no fundamental significance in physics. Nevertheless, it is common to use the term 'matter' to mean something with a rest mass. This seems to be the definition employed in the article you link: photons do not have a rest mass, but they can generate particles that do have rest mass.

A: The wording of the article is simply very misleading and somewhat incorrect. Mass and energy can be viewed as interchangeable which is expressed appropriately on the website but the case of the photon is a bit more complex because it is considered to be massless. The one property that it does have is energy and I think that is what the article refers to. This energy can lead to pair production but only in the vicinity of a massive particle such as an atomic nucleus for mass to be conserved.
Nonetheless the photon is considered to be a particle that has an associated spin.


text:
Q: integral equation Given the integral equation
$$\exp(x)-1=\int_0^{\infty} \frac{\mathrm dt}{t}\operatorname{frac}\left(\frac{ \sqrt x}{\sqrt t}\right) f(t)\;,$$
where $\operatorname{frac}$ denotes the fractional part of a number, $ \operatorname{frac}(x)= x-\lfloor x\rfloor$.
My questions are:

*

*Can we deduce from this integral equation that $ f(x)= O(x^{1/4+\epsilon}) $ for some positive $\epsilon$?

*Can we solve this integral by the Hilbert-Schmidt method?

A: You cannot conclude anything for the asymptotics of the integrand, because the function can have very high, very narrow peaks that contribute almost nothing to the integral.

A: The integral equation has the form $$\int_{0}^{\infty}\frac {dt} {t} f\left(x/t\right)g\left(t\right)=h\left(x\right)$$
The left hand side is known as the Mellin convolution. Defining the Mellin transforms:
$$F\left(s\right)=\int_{0}^{\infty}dt t^{s-1}f\left(t\right)$$
$$G\left(s\right)=\int_{0}^{\infty}dt t^{s-1}g\left(t\right)$$
$$H\left(s\right)=\int_{0}^{\infty}dt t^{s-1}h\left(t\right)$$
Your integral equation implies that
$$F\left(s\right)G\left(s\right)=H\left(s\right)$$
See this Mellin convolution and Mellin transform. Does this help?


text:
Q: Why is the hardest part of programming is naming things? I have heard that the hardest part for a programmer is naming variables, classes, objects and methods etc. really? then why do we focus more on algorithms and Data Structure?

A: Well on my opinion any project should have the documentation where you will define a naming convention for the project.
Beacause if you leave all programmers to name classes, variables, properties, methods etc... by itself. It might lead to difficulty in understand instantly what is purpose of the class, method etc...
Think about this, the name should be as much self describing for person which never saw your code to understood what it intendeed for.

A: Because naming stuff is something that requires you to understand human language and the problem domain of a program, which so far only humans can do. There is research going on into solving the naming problem, it is called "artificial intelligence" or "natural language generation", "expert systems" and the like.
It's just that these areas are still so much in their infancy. Computers these days can barely understand what people tell them in natural language, forget actually coming up with sentences and general-purpose answers and solutions of their own. So this research might as well not yet exist as far as programming language researchers are concerned.
What is possible these days is usually too much effort for what it's worth. We could probably look up some algorithms and implement an "algorithmic spell check" for programs based on variable names and bleeding-edge tech like Wolfram Alpha, but who would pay for that if you can just get a pre-made implementation of that algorithm off of Github or from your language's standard library?
Mind you, that is today. Once AI and the more modern equivalents have advanced, I'm sure it'll all be integrated into programming languages.


text:
Q: Progress bar com JQuery contando negativo Olá, eu uso esse código para aumentar a barra de progresso:
$(function()
{
    var bar = $('.bar');
    var percent = $('.percent');
    var status = $('#status');

    var upload = $('form').ajaxForm(
    {
        beforeSend: function()
        {
            status.empty();
        },
        uploadProgress: function(event, position, total, percentComplete)
        {
            document.getElementById("progressBarCurrentFile").style.display = 'block';
            var total_perc = total | 0;
            var current_perc = position | 0;
            document.getElementById("progbarFile").innerHTML = Math.floor((current_perc / (total_perc / 100)) * 100) / 100 + '%';
            document.getElementById("progbarFile").style.width = current_perc / (total_perc / 100) + '%';
        },
        complete: function(xhr)
        {
            location.href = 'home';
        }
    });
});

O problema é que quando o arquivo é maior que 2GB ele começa a contar negativo.
Mesmo eu colocando no pho.ini post_max_size = 9999999M e upload_max_filesize = 9999999M

A: Minha ideia: você guarda o primeiro valor que chegar o servidor como valor corrente e usa ele como se fosse o seu 0.
$(function()
{
    var bar = $('.bar');
    var percent = $('.percent');
    var status = $('#status');
    var first_val, minimal_perc;
var upload = $('form').ajaxForm(
{
    beforeSend: function()
    {
        first_val = true;
        status.empty();
    },
    uploadProgress: function(event, position, total, percentComplete)
    {
        document.getElementById("progressBarCurrentFile").style.display = 'block';
        if (first_val) {
          minimal_perc = position;
          first_val = false;
        };
        var total_perc = total | 0;
        var current_perc = position | 0;

        if (current_perc < 0) total_perc -= minimal_perc;

        document.getElementById("progbarFile").innerHTML = Math.floor((current_perc / (total_perc / 100)) * 100) / 100 + '%';
        document.getElementById("progbarFile").style.width = current_perc / (total_perc / 100) + '%';
    },
    complete: function(xhr)
    {
        location.href = 'home';
    }
});


text:
Q: Embedding A Matrix Okay, I have a matrix $A \in M_k(\mathbb{C})$ that I want to view it as embedded in some larger matrix in $M_n(\mathbb{C})$, which means $k < n$, with zeros filling in the rest of the entries so as to make the dimension of $A$ "large enough" (i.e., equal $n$). For example, if $k = 2$ and $n =4$, then I have
$$
\begin{bmatrix}
 A& \cdot &0 & 0 \\
\cdot & \cdot & 0 & 0 \\
0 & 0 & 0 & 0 \\
0&0&0&0
\end{bmatrix}
$$
but I could also have $k=3$, in which case the embedding becomes
$$
\begin{bmatrix}
 \cdot& \cdot & \cdot&0   \\
\cdot& A & \cdot & 0  \\
\cdot & \cdot & \cdot & 0\\
0 & 0 & 0 & 0
\end{bmatrix}
$$
Pardon the lack of agreeable formatting. Is a more standard, more concise way of viewing this "embedding," perhaps even as a product of some sort (initially I had thought of a Kronecker product, but quickly realized that that would not work)?

A: The easiest way I see is to define
$$A\mapsto I_{n,k}AI_{k,n},$$
where $I_{n,k}$ is the $n\times k$ matrix, where the top $k\times k$ block is the identity, and the rest is $0$, and similarly for $I_{k,n}$. But I don't know if you like this better.


text:
Q: C# Increment operator (++) question:Why am i getting wrong output? I have a simple c# console application but i am getting wrong output why?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication11
{
class Program
{
    static void Main(string[] args)
    {
        int i = 100;
        for (int n = 0; n < 100; n++)
        {
            i = i++;
        }
        Console.WriteLine(i);
    }

}
}

A: i++ is an expression which returns i, then increments it.
Therefore, i = i++ will evaluate i, increment i, then assign i to the original value, before it was incremented.
You need to use ++i, which will return the incremented value.

A: I'm guessing that you really want an explanation as to why it doesn't work as expected, rather than to actually get the result since you can get that by setting i equal to 200 in the first place.
The postincrement operator is applied after a temporary copy of the variable is created.  The temporary is used for operations in the statement then the assignment is performed, thus your loop is equivalent to:
    for (int n = 0; n < 100; n++)
    {
        j = i;
        i++;
        i = j;
    }

Since that's the case, the increment is basically discarded and i is never actually incremented.

A: i = i++;

This sets i to the old value of i, then increments it.  I think you want:
i++;

Or better yet if your compiler is lame and doesn't optimize the return:
++i;

Cheers.

A: The line i = i++; writes twice to the variable i. The post increment is executed first, but then the assignment statement overwrites it.
Try just i++;

A: Just use i++, not i = i++.


text:
Q: How do I change where the alert message is displayed on the screen? The alert message is the following:
if (allInputValid) {
           var bC = parseInt(document.getElementById("BCutId").value);
           if(bC>0){
                $.ajax({
                    url: BrowserSide.Url.getFullUrl('C/Edit'),
                    type: 'Post',
                    data: $(CForm).serialize(),
                    success: function (result) {
                        $('#CId').val(result.cId);
                        if (result.type == "created") {
                            BrowserSide.C.PopupMsg("created successfully!!");
                        }
                        else {
                            BrowserSide.C.PopupMsg("modified successfully!!");
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        BrowserSide.AjaxLog.HandleAjaxCallFail(XMLHttpRequest, textStatus, errorThrown, "ajax error in in C.js clickSubmitBt");
                    }
                });
            } else {
               BrowerSide.C.PopupMsg("Please select bC!");
            }
        }
        return false;

However, the alerts is standardized to pop up center in the screen. I want the pop up/alert to pop up on the center left of the screen. How do I do that?
I'm using ASP.NET MVC 4
EDIT:
I have this functions that's supposed to change the window to appear on the left but it still appears centered. Why?
PopupMsg: function (msg) {
        var browser = BrowserSide.BrowserCompatibility.GetBrowser();
        if (browser.toLowerCase().indexOf("explorer") != -1) {
            //alert(msg);
            $("#CasePopupDialog").html(msg);
            $("#CasePopupDialog").dialog(
           {
               dialogClass: "no-close",
               modal: true,
               title: 'Message Window',
               //show: 'slide',
               //hide: 'slide',
               width: '315px',
               height: 'auto',
               //resizable: true,
               closeOnEscape: true,
               focus: true,
               position: ['left',100],
               buttons: {
                   Ok: function () {
                       $("#CasePopupDialog").html("");
                       $(this).dialog("close");
                   }
               },
           });

        } else {
            alert(msg);
        }
    },


text:
Q: Prevent slide down sub-menu from sliding up when clicking on next menu item I have a slide down menu that has links in the sub-menu, when I click on another link in the menu I want the sub-menu links to fade in while the others fade out (without closing and opening again). Currently, when I click on another menu item, the sub-menu slides up then back down to reveal the items in that sub-menu.
Here is the fiddle http://jsfiddle.net/EGp35/1/. Feel free to structure the code better if needed. Also, the only active links are "shows" and "films". Thanks!
$(document).ready(function() {
    $('#shows').click(function(e) {
        $('.sub-menu-1').slideToggle(200);
        $('.sub-menu-2').hide();
            return false; // prevent default click action from happening!
            e.preventDefault(); // same thing as above
    });
});

$(document).ready(function() {
    $('#films').click(function(e) {
        $('.sub-menu-2').slideToggle(200);
        $('.sub-menu-1').hide();
            return false; // prevent default click action from happening!
            e.preventDefault(); // same thing as above
    });
});

A: Replace
   $('.sub-menu-1').slideToggle(200);
   $('.sub-menu-2').hide();

with
  $('.sub-menu-1').slideDown();
  $('.sub-menu-2').slideUp();

Here the fiddle


text:
Q: Explanation of some physical terms related to hydodynamic limit to a non-physicist & Integrable system I'm a mathematician, and I'm reading an article and am struggling with some of the terminology
related to physics.

[...] This equation is formally obtained from the hydrodynamic limit of the
Hamiltonian system of Calogero-Sutherland, describing the motion of particles on
a circle of radius L, interacting according to a potential at $1/sin^2 x$.

what does hydrodynamic limit mean?

[...] A change of variable of Madelung type leads to equation (0.1),

What does  a change of variable of  Madelung type mean?
And,

the constraint u correspond to a condition of chirality.

What does mean: a condition of chirality?
Finaly, I have another question that isn't related to termenology.
Does the limit of an integrable system is an integrable system?
I'm asking this question here because at the begining of the article, I have an equation that is obtain as a hydrodynamic limit of the system of Calogero-Sutherland. And we know that the system of Calogero-Sutherland is completly integrable. So my question does the new equation is an integrable equation just because it's the limit of an integrable equation?


text:
Q: Flash coding for typewriter effect I am a complete amateur in Flash so I hope you can explain to me what is wrong with this coding. Thank you!
Here is the coding that is written on just one keyframe:
    var myString: String = "This is a\nTeSt.";
var myArray: Array = myString.split("");
addEventListener(Event.ENTER_FRAME, frameLooper);
function frameLooper(event:Event):void {
if(myArray.length > 0) {
    welcomeTxt.appendText (myArray.shift());
}
else {
    removeEventListener(Event.ENTER_FRAME, frameLooper)
}

}
Below is what is shown in the output panel repeatedly, probably for each letter that I want to display:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at WEBSITE_fla::MainTimeline/frameLooper()

A: Your code is fine. I took it and use it in Flash and it worked as expected. Double check that the instance name of the textfield is set to welcomeTxt. If your able to post a link to the fla I can take a look if your still having issues.


text: Q: Session are breaking when going to some page How can I check weather the session is working or not properly? When I login correctly it's working fine, and also allows me to visit some pages but when going to some other page in same controller it redirects me to the login page. Can anyone suggest the solution.


text:
Q: Finding order of $Aut(\mathbb{Z}_{3})$ with just the very basics In my Abstract Algebra class, our professor just introduced the concepts of groups to us, and one of the problems on our homework assignment is to compute the order of the automorphism group $Aut(\mathbb{Z}_{3})$ of the additive group $\mathbb{Z}_{3}$. I've been searching online and in books how to do this, because our professor did not tell us. What I have found is that most of the time this is done by applying one of many theorems, including using the fact that $\mathbb{Z}_{3}$ is cyclic (We haven't learned what a cyclic group is yet.), that it's isomorphic to $U_{3}$ (We haven't learned yet how that even helps).
Basically, it looks like I have to do this by using the proverbial "stone knives and bear skins". I know that $\mathbb{Z}_{3}$ is an additive group, consisting of the elements $\{0, 1, 2\}$, and that an automorphism is a bijective map from a group to itself that preserves the group structure. So, I suppose the identity map that would map $\mathbb{Z}_{3}$ to itself would work. But, how do I list out what all the possible bijective homomorphisms from $\mathbf{\mathbb{Z}_{3}}$  to itself without using any slick tools? There must be a lot of them!

A: What do you know about the image of $0$ under a group homomorphism?
Do you know how many bijective maps exist on a $3$-element set?
Can you combine this knowledge to narrow down the possibilities? Do you know how to check those possibilities?

A:
Lemma. Let $G$ and $G'$ be two groups. Let $\varphi:G\rightarrow G'$ be a group morphism. One has: $$\varphi(1_G)=1_{G'}.$$

Proof. One has: $$\varphi(1_G)=\varphi(1_G\times 1_G)=\varphi(1_G)^2.$$
Right-composing the equality by $\varphi(1_G)^{-1}$ leads to the result. $\Box$
Therefore, an element of $\textrm{Aut}(\mathbb{Z}_3)$ must send $\overline{0}$ to $\overline{0}$. Then, you are free to send $\overline{1}$ on $\overline{1}$ or $\overline{2}$, otherwise the map won't be bijective. Afterward, check that the two constructed maps are morphisms.


text:
Q: Menu choice error, couldnt find any solution. menu identifier not found I have a question,
Im new to c++ and general with coding.
I have this problem Im coding right now an Loader for a game and want to make a choice menu.
I have this error and I dont know how to fix it.
If you could help I would be happy.
This is my code https://ghostbin.co/paste/x8hz3
int DLL();
int Beta();

int select()
{
    int selection;
    do
    {
        selection = menu();
        switch (selection)
        {
        case 1:    DLL();
            break;
        case 2:    Beta();
            break;  cout << "Exiting program.\n\n\n";
        }
    } while (selection != 2);
    return 0;
}

int menu()
{
    int choice;
    cout << "Loader menu\n";
    cout << "--------------------------------\n";
    cout << "Normal\n";
    cout << "--------------------------------\n";
    cout << "1) Beta\n";
    cout << "--------------------------------\n";
    cout << "2) Dll methods\n";

    cin >> choice;
    while (choice < 1 || choice > 2)  // Check to see if user's input is correct
    {
        cout << "Invalid Selection. Enter 1, or 2: ";
        cin >> choice;
    }
    return choice;
}

int DLL()
{

    cout << "Test" << endl;

}

int Beta()
{

    cout << "Test" << endl;

}

A: You don't need to return anything for select() seemingly. You should declare the main() and write there:
.
select();
.

Important: You haven't defined any proper definition for menu(). On the beginning of the code, just add a single line int menu(); and you're good to go.


text:
Q: Why does my list value not change when it is plugged into a function? This code is part of a Tic-Tac-Toe script, in which a player inputs a number based on what space they wish to place their marker. To test the script out, I only wrote code for board[1].
board = ['','','','','','','','','','']
count = 0
turn_counter = 1

def print_board():
    print(board[1] +  "  |"  + board[2]  +  "  |"  +  board[3])
    print("--+--+--")
    print(board[4] +  "  |"  + board[5]  +  "  |"  +  board[6])
    print("--+--+--")
    print(board[7] +  "  |"  + board[8]  +  "  |"  +  board[9])

def main_operator(board_val):
    global turn_counter
    global count

    if turn_counter == 1:
        board_val = 'X'
        count = count + 1
        turn_counter = turn_counter + 1

    elif turn_counter == 2:
        board_val = 'O'
        count = count + 1
        turn_counter = turn_counter - 1

def game_start():
    user_input = int(input("Player " + str(turn_counter) + ", choose a space"))
    if user_input == 1:
    main_operator(board[1])

for i in range(9):
    print_board()
    game_start()

However, the main_operator() function does not change the value for board[1], instead leaving it unchanged. What am I doing wrong?


text:
Q: Compass on Win using relative paths outside of Compass project dir I was using Sass on an existing site and decided to get Compass up and running on Win7x64. Ruby, HAML, Compass all installed fine (afaik).
I have a project at c:\project with a static files served out of c:\project\static with a directory structure that has to stay the same. I went into c:\project\static and ran this:
compass create css-compass

This resulted in the following dir structure
c:\project\static\css (previously existed; output css)
c:\project\static\css-sass (previously existed; source css)
c:\project\static\css-compass (the new compass dir created by compass)

And here is my config.rb:
# Require any additional compass plugins here.
# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "..\\css"
sass_dir = "..\\css-sass"
images_dir = "images"
javascripts_dir = "javascripts"

When I go to c:\project\static and run compass watch compass-css, I get the following error:

Nothing to compile. If you're trying
  to start a new project, you have left
  off the directory argument. Run
  "compass -h" to get help.

However, if I create symlinks inside c:\project\static\css-compass from css->..\css and css-sass => ..\css-sass then everything works just fine.
What the what?

A: facepalm
Apparently you need to set relative_assets = true in your config.rb file. Why this isn't the default is beyond me. Oh well!

A: im late :-)
You can also use relative Path's in project_path
Example
project_path    = "../src/main/webapp/"

More Details in this Answer: Can't make grunt-contrib-compass work


text: Q: Passing a python variable a value from an embedded SQL query I'm working on an Amazon Redshift cluster and I have automated some of my regular workflows using a Python script.  The script runs a series of SQL queries and outputs the results to an HTML file.  I want to be able to pass a value from an SQL query result to a Python variable.  The catch is that I have read-only permissions for the DB cluster, so I don't think I can use any user defined functions inside the SQL query.  If I declare a global variable in the script, how do I set the value of that variable to a query result, for example a date?