text:
Q: Can puppet update package to latest minor release? For example I have php-fpm installed:
Name        : php-fpm
Arch        : x86_64
Version     : 5.4.16
Release     : 23.el7_0.3
Size        : 4.5 M
Repo        : installed
From repo   : updates
Summary     : PHP FastCGI Process Manager
URL         : http://www.php.net/
License     : PHP and Zend and BSD

The goal is to keep PHP on the latest 5.4 release. Currently I have this in the manifest: ensure => '5.4.16-23.el7_0.3',.
That won't update if a new version or release comes out, while I don't want it to update to 5.5 unexpectedly.
I have tried the following:

*

*ensure => '5.4.16',

*ensure => '5.4',

*ensure => '5.4.16-*',

*ensure => '5.4.*',
All of which give me something similar to:
change from 5.4.16-23.el7_0.3 to 5.4 failed: Could not update: Failed to update to version 5.4, got version 5.4.16-23.el7_0.3 instead
This being on RHEL/CentOS it is probably meet the requirement to simply have ensure => latest, for PHP, I am just using PHP as an example. I stil like to know:

*

*The puppet way to manage minor releases. (If there is one, or two... I read that at least you can maintain your own repo, but is there a pure puppet syntax like the one I guessed above?)

*There are obviously packages other than PHP, how would you use puppet to manage packages from that are perhaps from different repo, or perhaps for a distro other than RHEL/CentOS, etc.

*I read from the puppet reference that the ensure "values can match /./", is that regex or what? http://docs.puppetlabs.com/references/3.7.5/type.html#package-attribute-ensure
I am running open source Puppet 3.7.5 on RHEL/CentOS 7.

A: No, puppet can't update to latest minor, but can only ensure specific version, or can ensure package is present, or latest.
What you should do is create your own custom repositories, which will have only packages of your relevance (for example 5.4 series of PHP) and then in puppet just set:
package { 'php-fpm': ensure => latest }

This will check every puppet run if there is an update.
Also, if you don't use additional repositories which offer newer PHP packages to your system, ensure => latest will behave exactly as you want it - because of the way CentOS updates its packages. There will never be php-5.5 in CentOS 7, but php will stay at 5.4 series. 5.5 and any newer updates will be provided through php55, php56, etc. - which means you will have to change the package name in puppet manifest to reflect the version you want, for example:
package { 'php56-fpm': ensure => latest }

So, answer is NO, you have to ensure your repositories only offer the major version you want and then you can use ensure => latest within puppet.
To set that up in repositories, you can use things like:

*

*include

*exclude

*priority


text:
Q: Not able to retrieve variable in template in Django ajax call I am trying retrieve counter value passed from view in the html template .It is coming as None, however in the view print and in ajax success log value it is coming correct.
JS ajax func
           $(".pos").click(function(){
            counter=counter+1;
            $(".add").html('add counter '+counter);
            $.ajax(
                { url :'page',
                  type :'get' ,

                  data:{
                    quantity: counter
                   },

                success:function(response){
                  console.log(response);
                }

                }
            );

My view
def page(request):
    counter=request.GET.get('quantity')
    print(counter) ## this is printing fine
    return render(request,'page.html',{'counter':counter})

html template
<body>
    {{counter}}
    <button class="btn neg" name="neg-btn">-</button>
    <button class="btn add" name="add-btn" >add to box</button>
    <button class="btn pos" id="test" name="pos-btn">+</button>
</body>

getting this counter as None

A: Usually you would have two views, one to render the template and another for your ajax request. This helps to keep your code more organized and have functions do exactly one task as most of the its described in its naming.
One important thing that is happening in your view, is that you are returning the HTML generated by the render API and not the counter value. Of course, there are many ways to do this correctly, but here is one possible solution:
page.html
{% extends 'base.html'%}

{% block content %}
<body>
    <div id="counter">
        {{counter}}
    </div>

    <button class="btn neg" id="neg" name="neg-btn">-</button>
    <button class="btn add" id="add" name="add-btn" >add to box</button>
    <button class="btn pos" id="pos" name="pos-btn">+</button>
</body>
{% endblock content %}

{% block script %}
<script>
    let counter = parseInt("{{counter}}");
    let page_url = "{% url 'core:page' %}";
    console.log(page_url)
    $( "#pos" ).click(function() {
        counter += 1;
        $( "#counter" ).replaceWith(`<div id="counter">${counter}</div>`);
    });
    $( "#neg" ).click(function() {
        counter -= 1;
        $( "#counter" ).replaceWith(`<div id="counter">${counter}</div>`);
    });
    $( "#add" ).click(function() {
        $.ajax({
                    url :page_url,
                    type :'post' ,
                    data:
                    {
                        counter: counter,
                        csrfmiddlewaretoken: '{{ csrf_token }}',
                    },
                    success:function(response){
                    console.log(response);
                    }
                });
    });
</script>
{% endblock script %}

views.py
from django.http import JsonResponse

def page(request):
    counter = 0
    if request.method == 'POST':
        counter = int(request.POST.get('counter'))
        print(counter)
        return JsonResponse({'counter': counter})

    return render(request,'page.html',{'counter':counter})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Open source equivalent to FiveRun' Tuneup Is there an open source equivalent to FiveRun's Tuneup product for Ruby on Rails performance measurments?

A: There's ruby-prof
http://ruby-prof.rubyforge.org/
It's a bit more technical in it's reports, but has been proven to be very valuable when hunting for performance issues.


text:
Q: Using do loops with certain conditions So I am making a Craps game in my C class and am having trouble with a particular point. If a user rolls a 4, 5, 6, 8, 9 or 10 that is considered a point. If the user rolls a 7 after rolling a point they lose. My problem is if a user rolls a point, and then they roll again and the sum is equal to their point they win. My program works if they roll a 7 after their point, but not if they roll sum of their point again.
Sorry I know the question is confusing.
        case 1: printf("Enter your name here: ");
            scanf("%s", name);

            for(j = 0; j < i; j++){
                if(strcmp(name, pl[j].players)==0){
                    set = 1;

                    printf("* * * * * * * * * *\n");
                    printf("Press ENTER to roll the dice");
                    getchar();
                    getchar();

                    dice = (rand()%(6-1+1)+1);
                    dice1 = (rand()%(6-1+1)+1);
                    sum = dice + dice1;

                    printf("\nThe values of the dice are %d and %d whose sum is %d\n", dice, dice1, sum);

                    if(sum == 7 || sum == 11)
                    {
                        win++;
                        pl[j].wincount = win;
                        pl[j].balance = pl[j].balance + 10;
                        printf("\nYou win the game. \nYour balance is now: %d\n", pl[j].balance);
                        break;
                    }

                    else if((sum == 2) || (sum == 3) || (sum == 12))
                    {
                        lose++;
                        pl[j].balance = pl[j].balance-1;
                        printf("You lose :(\nYou balance is now: %d\n", pl[j].balance);

                        dice = (rand()%(6-1+1)+1);
                        dice1 = (rand()%(6-1+1)+1);
                        sum = dice + dice1;
                        break;
                    }

                    else
                    {
                        do
                        {
                            printf("\nYou rolled a 'point' you must now roll again.\n");
                            printf("* * * * * * * * * *\n");
                            printf("Press ENTER to roll the dice again");
                            getchar();
                            getchar();

                            dice = (rand() % (6 - 1 + 1) + 1);
                            dice1 = (rand() % (6 - 1 + 1) + 1);
                            sum = dice + dice1;
                            printf("\nThe values of the dices are %d and %d whose sum is %d\n", dice, dice1, sum);

                        }while((sum != 7) && (sum != point));

                        if(sum == 7)
                        {
                            lose++;
                            pl[j].balance = pl[j].balance - 1;
                            printf("You lose :(\nYou balance is now: %d\n", pl[j].balance);
                        }

                        else if(sum == point)
                        {
                            win++;
                            pl[j].wincount = win;
                            pl[j].balance = pl[j].balance + 10;
                            printf("\nYou won the game, you rolled your point \nYour balance is now: %d\n", pl[j].balance);
                        }
                    }
                }
            }


text:
Q: Spring Integration benchmark I would like to know if anyone has any experiences with Spring Integration framework as it's messaging provider?
I couldn't find any benchmarks or details.
Would like to know details concerned to latency,throughput,performance.
Anyone has any experience?
Thanks.

A: As with any framework, there will be some minimal runtime overhead, but that is vastly outweighed by the resulting loosely coupled, agile, robust architecture and the (often) reduced development time.

A: I can't provide any official benchmark-based numbers, but we've been using Spring Integration (with JMS broker in the middle) as an underlying framework for two of our products serving HTTP traffic where latency and throughput were also the most important factors. Both proved their reliability under really heavy load - standing in the first line (just after load balancer) in the infrastructure of some top European e-commerce sites -  no lags, no unexpected fails, great scalability. Of course everything depends on how you design flow in channels, but basis on my previous experience, if I had to develop similar solution once again, I'd definitely go to Spring Integration.


text:
Q: Is data generated via a multivariate normal distribution consistent with OLS assumptions? Suppose I know 3 variables $A,B,Y$ have the following correlation matrix
$$
\begin{bmatrix}
1 & \rho_{AB} & \rho_{AY}\\
\rho_{AB} & 1 & \rho_{BY}\\
\rho_{AY} & \rho_{BY} & 1
\end{bmatrix}
$$
Suppose I generate some fake data using a multivariate normal distribution such that
$$(A,B,Y) \sim N\left(\begin{bmatrix}
0 \\
0 \\
0 \\
\end{bmatrix}, \begin{bmatrix}
1 & \rho_{AB} & \rho_{AY}\\
\rho_{AB} & 1 & \rho_{BY}\\
\rho_{AY} & \rho_{BY} & 1
\end{bmatrix}\right)$$
Would this data set violate any of the OLS assumptions necessary to construct a linear model?
$$Y_i = \beta_0 + \beta_A A_i + \beta_B B_i + \epsilon_i$$
In particular, would the spherical errors assumption hold, i.e.
$$Var(\epsilon|X) = \sigma^2 I$$
Or conditional mean
$$E[\epsilon |X] = 0$$
where $X$ is the design matrix comprised of the columns of data $A$ and $B$.


text:
Q: Function not executing when called second time I am working on a project where I take inputs from a html form and submit them inside of google sheets. Its working fine with no errors. So I wanted to add a function where the user can resubmit the data incase of server-side error.
The issue is when I am calling the same function which submits the data(working) it doesnt seem to respond. I am sending the same array of data yet it doesnt return any server response. If I refresh the entire page it works again, its just that it wont let me run the same function twice in one session.
Here are the codes I used:
Html:
google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).addRecord(rows);

GAS:
function doGet(request) {
return HtmlService.createHtmlOutputFromFile('index');
 }
//division,block,ward,booth,committee,designation,name,phone,email
function addRecord(rows) {
  var url = 'https://docs.google.com/spreadsheets/d/-myProjectID-/edit#gid=0';
  var ss = SpreadsheetApp.openByUrl(url);
  var webAppSheet = ss.getSheetByName("FORM DATA");
  var row = rows.length;
  var column = rows[0].length;

 //LockService.getScriptLock.waitLock(10000);
 // var lock = LockService.getScriptLock();
 // lock.waitLock(10000);    //prevent creating 2 sessions simultaneously

 try {
  webAppSheet.getRange(webAppSheet.getLastRow() + 1, 1, row, column).setValues(rows);
  // lock.releaseLock();
  return "Ok"
  } catch (ex) {
    lock.releaseLock();
    return "Error"
 }
}

function getScriptURL() {
  return ScriptApp.getService().getUrl();
 }

to retry i run the same function "addRecord()" and pass the same array"rows[]".
Can anyone point out where I am doing wrong or is it some special attribute in GAS that prevents me from doing otherwise.

A: I'd try something like this:
gs:

function addRecord(rows) {
  const ss = SpreadsheetApp.openById(myProjectId);
  const sh = ss.getSheetByName("FORM DATA");
  sh.getRange(sh.getLastRow() + 1, 1, rows.length, rows[0].length).setValues(rows);
  return "Ok"
}

js:

function dontknowname() {
  //disable send button here
  google.script.run
    .withSuccessHandler(() => 'enable send button here')
    .addRecords(rows);
}


text:
Q: Adding objects to vectors vs adding pointers to vectors in c++? Adding objects to vectors vs adding pointers to vectors in c++.
Example:
std::vector<Size> buildings;
Size building(buildingWidth, buildingHeight);
buildings.push_back(building);

VS
std::vector<Size*> buildings;
Size *building = new Size(buildingWidth, buildingHeight);
buildings.push_back(building);

Which one is better in terms of memory/performance?
The first one basically creates an object on the stack and adds it to a vector.
So there is one instantiation followed by one copy into the vector.
The second one creates an object on the heap.
There is one instantiation, but there is no copy into the vector.
Am I correct?

A: The two storage techniques serve different purposes.
The first technique is useful with "homogenous" vectors, where you do not need polymorphic behavior, and object slicing is not an issue. You get automated resource management in return: you do not need to worry about the ownership of your objects, because the vector makes a copy. A copy is also made internally every time your vector is resized. This consideration makes the first option less attractive when copying the object is somewhat expensive; you need to profile your code to see if this consideration applies to it.
The second technique puts the responsibility for managing the memory on you: every time you decide to remove an object from your vector of pointers, you need to take the ownership, and eventually delete the object explicitly. You can use smart pointers to address the resource management issue. This technique lets you avoid copying, but the process of accessing elements inside the container becomes slightly more involved.

A: They both usually have relatively similar performance, depending on the object size and copy semantics of the object.
With regards to memory leaks and usability, the first way is usually much better.

A: It really depends on the nature of Size. If the object is big (insofar that the copy constructor has to do a lot of work), then you could consider your pointer idea. However you will have to control the memory yourself and, whatever you do, don't inherit from std::vector as inheriting from the standard containers is not a good idea (for one thing they don't have virtual destructors)!
You could build some copy on write semantics in your Size class (a bit like implementations of std::string).
Or have a default constructor and a swap method for Size (you'll need the default constructor to be used in std::vector anyway). Use the swap method to swap in a new Size object into the position in the vector.
On the basis that "premature optimisation is the root of all evil" (attrib. Tony Hoare), I'd stick with the simplest approach; namely your first idea and see how that goes.

A: It really comes down to

*

*What operations are going to be performed on that vector

*How frequently objects will be pushed onto the vector

If you're going to be doing any kind of mutable operation on the vector, then you'd better go with a shared_ptr type.
Ultimately, with any kind of performance-related question, it's best to test it out yourself under the conditions of your application.

A: Why not do this:
std::vector<Size> buildings;
buildings.resize(1);
buildings[0].setSize(buildingWidth, buildingHeight);

This way the constructor is only called once, and you don't have to manage the memory yourself. The only disadvantage I can think of is that the width and height are set twice (once in constructor, once in "setSize"), but I don't think you can get away from that unless you use the std::vector<Size *> approach.

A: I think the second approach of using vector of pointers is a better of the two options. Because of two simple reasons

*

*If the objects size are bigger then using vector of objects will add unnecessary copying.

*If you are passing the vector of objects as argument to a method and then try to modify any object in the vector then it will not get reflected at all the places.


text:
Q: concatMap fails to process all items in array I am processing an array of files. For each file, I need to request the correct upload URL, and then upload that file to it's correct endpoint.
concatMap is supposed to emit only after the previous value has completed. In this way, the files should be processed sequentially.
Here is my code:
filesChanged(e) {

const files_raw = e.srcElement.files;

of(files_raw)
.pipe(
  flatMap((file) => file),
  tap((file) => console.log("Firing 1", file)),
  concatMap((file) => {
    return this.ms.fetchUploadURL().pipe(withLatestFrom(of(file)));
  }),
  tap((file) => console.log("Firing 2", file)),
  concatMap((values) => {
    return this.ms.uploadDirectToS3(values[0], values[1])
      .pipe(tap(value => console.log('From request', value)), withLatestFrom(of(values[0])));
  })
)
.subscribe(event => {
  console.log('In Subscribe', event);
});
}

If I attempt to upload 4 files, this code will log to the console the following output:

Firing 1
Firing 1
Firing 1
Firing 1
Firing 2
From request <value>
In Subscribe <value>

In other words, only the first file is processed and uploaded. All other files are seemingly ignored. Why is that?
Shouldn't it start fetching the second URL once the first completes?
Also, if I change concatMap to mergeMap, then it does work but it processes all files at simultaneously, instead of sequentially. I thought passing the concurrency option to mergeMap might help, but acts identically to concatMap.

A: First of all I have tried to simulate your case here: https://stackblitz.com/edit/rxjs-ijfky6?devtoolsheight=60.
Note that I use mergeMap rather than flatMap but they are exactly the same.
According to such simulation, and to the logic I see implemented, what you get makes sense and you are probably seeing only 1 occurrence of 'Firing 2' because some error occurs in the second call to uploadDirectToS3. Maybe you should add an error function to subscribe as in the above simulation.
Said that, I guess there are few corrections you should put in your code to get what you want.
Let's start with a simple one. You can substitute
of(files_raw)
.pipe(
  flatMap((file) => file),

with the from(files_raw).
Now let's enter the core of the point. You want to fetch the url to use via this.ms.fetchUploadURL() function (by the way, it surprises me that such function does not have any parameter, suggesting that it returns always the same value, but that's not relevant here). And then you want to call this.ms.uploadDirectToS3 passing both the url and the file as parameters. If this is the case, than you should first call this.ms.fetchUploadURL() and then, via the operator switchMap switch to the other observable returned by this.ms.uploadDirectToS3. These operations should be performed within the concatMap so that you get them performed sequentially.
The final code could look something like this
from(files_raw)
.pipe(
  tap((file) => console.log("Firing 1", file)),
  concatMap((file) => {
    return fetchUploadURL().pipe(
      tap((file) => console.log("Firing 2", file)),
      switchMap(url => uploadDirectToS3(url, file))
    );
  }),
)
.subscribe(
  d => console.log('subscribe', d),
  err => console.error(err)
)

Here a simulation of the new code https://stackblitz.com/edit/rxjs-whip1l?devtoolsheight=60

A: My answer comes a bit late, but I'll post it for people ever experiencing similar issue:
It looks like
 this.ms.fetchUploadURL().pipe(withLatestFrom(of(file)))

never completes, which prevents concatMap from consuming (mapping) subsequent items.
I'm not JS developer, but in RxJava, one can reproduce your issue like that:
 Observable.just(1,2,3,4)
            .doOnComplete {  Log.d("TAG", "Complete 1") }
            .doOnNext { Log.d("TAG", "before concatMap $it") }
            .concatMap { someObservable(it) }
            .doOnComplete {  Log.d("TAG", "Complete 2") }
            .doOnNext { Log.d("TAG", "after concatMap $it") }
            .subscribe()

where someObservable implementation looks like below:
 fun observable(int: Int): Observable<Int> {
    return Observable.create {
        it.onNext(int)
    }
 }

Output for such implementation:
before concatMap 1
after concatMap 1
before concatMap 2
before concatMap 3
before concatMap 4
Complete 1

Concat map (Which is another observable) never completes, because mapper observables never complete.
Simply adding onComplete() in someObservable would fix the issue.
The output would look like below:
before concatMap 1
after concatMap 1
before concatMap 2
after concatMap 2
before concatMap 3
after concatMap 3
before concatMap 4
after concatMap 4
Complete 1
Complete 2

I think that in RxJS it's about the same.
Please check you mapper implementation.


text:
Q: Can I have a different workflow when using nested_form? I'm using the gem nested_form by Ryan Bates. I'm a bit confused about the workflow for the user.
I'm supposed to have a "f.link_to_add" call, that will dynamically add a nested structure for the association. That works as advertised, but I feel that it is cumbersome for the user to FIRST click "Add Book" (as in the commonly used Author/Books example) and THEN type in the new Book fields.
I would like to have an empty set of Book fields shown initially, and if the user fills them and clicks Save, the are added to the Author.
How would I use the nested_form gem to achieve this scenario?
Thx

A: I would suggest checking out build.  For example, your new action for your author could have something like:
@author = Author.new
@author.books.build

Note that if an author could only have one book rather than multiple you'd do something like this instead:
@author = Author.new
@author.build_book

A: I think the short answer is that nested_form is not suitable for this particular workflow.
It's easier achieved with a separate form for the associated class where you in the controller lookup the parent class (Author) and in the Book form keep a hidden field (:author_id in this example).
This only works if you can accept to add Books one by one.
Nested_form is more suitable when you really want to show a long list of Books and let the user have the option of adding/removing multiple items before Saving.


text:
Q: Can I pass different parameters to my php function depending on CSS3 media queries? I have a php function 'limitWords' to limit words of text that is coming from database.
When I call this function I need to pass the number of characters I want to show: lmWord($readDatabase['content'],300)
It is possible execute this function in different way, depending on width of device? Because, Im using media queries in my project, and I want to execute my limitWords() function in different way for differentes media queries.
For example for mobile, I don't want 300 characters, I want  150. It is possible do this?


text:
Q: Mailchimp API - Return certain fields only in JSON response I need to create a newsletter archive on our website so our users have access to previously sent campaigns we have sent via Mailchimp.
I'm trying to return a list of the archive_url and send_time fields from the Campaigns method. The kicker is I need to use Classic ASP to return the data.
Here is my code so far:
<script language="javascript" runat="server" src="/global/json2.min.asp"></script>

Dim oXMLHTTP
Set oXMLHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
varUrl = "https://us10.api.mailchimp.com/3.0/campaigns?offset=0&count=20"

oXMLHTTP.Open "GET", varUrl, False
oXMLHTTP.setRequestHeader "Content-type","application/json"
oXMLHTTP.setRequestHeader "Authorization", "apikey xxx"
oXMLHTTP.send

responseText = oXMLHTTP.responseText

set myJson = JSON.parse(responseText)
archiveURL = myJson.archive_url
sendTime = myJson.send_time

response.write(archiveURL)
response.write(sendTime )

I can return the full response without issue, but can't select the fields I only need. When I try the code above, IIS returns the following error:
Microsoft VBScript runtime error '800a01b6
Object doesn't support this property or method: 'myJson.archive_url'
/global/requests.asp, line 25
Any help with what I am doing wrong would be much appreciated.
Cheers


text:
Q: Having issues with python functions I am making a couple of functions for taking pizza information in one, then using that information to calculate the price in the other function.  When I run this though, it's having problems locating attributes in one of the functions, even after its run.
def calc_pizza_charge(size_cost, meats_cost, veg_cost, num_cost):
    get_pizza_info.size = range(1, 4)
    num_cost = get_pizza_info.quantity
    total = (size_cost + meats_cost + veg_cost) * get_pizza_info.quantity
    if get_pizza_info.size == 1:
        size_cost = 6.50
    if get_pizza_info.size == 2:
        size_cost = 9.50
    if get_pizza_info.size == 3:
        size_cost = 11.50
    meats_cost = (get_pizza_info.meats - 1) * 3.50
    veg_cost = (get_pizza_info.veg - 1) * 1.50

    print("Your total is $", "{:,.2f}".format(total))

def get_pizza_info(size, meats, veg, quantity):
    size = int(input("Enter size from 1-3: "))
    meats = int(input("Enter number of meat toppings "))
    veg = int(input("Enter number of non-meat toppings "))
    quantity = int(input("Enter number of these pizzas "))
    if size >= 4:
        size = 3
    if size <= 1:
        size = 1
    if meats <= 1:
        meats = 1
    if veg <= 1:
        veg = 1

A: To be honest, I was extremely confused when I saw your code. I think you should review how functions work. Anyway, a few pointers:

*

*In get_pizza_info you essentially ask for the order details: store it in some sort of data structure (I used dictionary)

*In get_pizza_charge, you need to use the order details to compute the price of the pizza.

I have included my rewriting of your code:
def calc_pizza_charge():
    pizza_info = get_pizza_info()
    num_cost = pizza_info["quantity"]
    size_cost = get_size_cost(pizza_info["size"])
    meats_cost = (pizza_info["meats"] - 1) * 3.50
    veg_cost = (pizza_info["veg"] - 1) * 1.50
    total = (size_cost + meats_cost + veg_cost) * pizza_info["quantity"]

    print("Your total is $", "{:,.2f}".format(total))

def get_size_cost(size):
    if size == 1:
        return 6.5
    elif size == 2:
        return 9.5
    elif size == 3:
        return 11.50

def get_pizza_info():
    size = int(input("Enter size from 1-3: "))
    meats = int(input("Enter number of meat toppings "))
    veg = int(input("Enter number of non-meat toppings "))
    quantity = int(input("Enter number of these pizzas "))
    pizza_info = {}
    pizza_info["size"] = max(min(size, 3), 1)
    pizza_info["meats"] = max(1, meats)
    pizza_info["veg"] = max(1, veg)
    pizza_info["quantity"] = max(0, quantity)
    return pizza_info

calc_pizza_charge()

A: You have defined all the attribute variables in get_pizza_info function and are trying to access them in calc_pizza_charge function.
Variables declared in a function are local to that function and cannot be accessed by any entity outside that function.
For your problem I would suggest defining a new class that contains both of these functions.
class Pizza:
    def calc_pizza_charge(self):
        num_cost = self.quantity
        if self.size == 1:
            size_cost = 6.50
        if self.size == 2:
            size_cost = 9.50
        if self.size == 3:
            size_cost = 11.50
        else:
            size_cost = 10
        meats_cost = (self.meats - 1) * 3.50
        veg_cost = (self.veg - 1) * 1.50
        total = (size_cost + meats_cost + veg_cost) * self.quantity
        print("Your total is $", "{:,.2f}".format(total))

    def get_pizza_info(self):
        self.size = int(input("Enter size from 1-3: "))
        self.meats = int(input("Enter number of meat toppings "))
        self.veg = int(input("Enter number of non-meat toppings "))
        self.quantity = int(input("Enter number of these pizzas "))
        if self.size >= 4:
            self.size = 3
        if self.size <= 1:
            self.size = 1
        if self.meats <= 1:
            self.meats = 1
        if self.veg <= 1:
            self.veg = 1

piz = Pizza()
piz.get_pizza_info()
piz.calc_pizza_charge()

This code runs fine just like you wanted it to work. There were many fundamental mistakes in your code. I would suggest you to learn basics of functions and classes in Python.

A: Since you are not comfortable with other answers, Here a working code with minimal modifications to your code
def calc_pizza_charge():
    size, meats, veg, quantity = get_pizza_info()

    if size == 1:
        size_cost = 6.50
    elif size == 2:
        size_cost = 9.50
    else:
        size_cost = 11.50

    meats_cost = (meats - 1) * 3.50
    veg_cost = (veg - 1) * 1.50

    total = (size_cost + meats_cost + veg_cost) * quantity

    print("Your total is $", "{:,.2f}".format(total))

def get_pizza_info():
    size = int(input("Enter size from 1-3: "))
    meats = int(input("Enter number of meat toppings "))
    veg = int(input("Enter number of non-meat toppings "))
    quantity = int(input("Enter number of these pizzas "))
    if size >= 4:
        size = 3
    elif size <= 1:
        size = 1
    if meats <= 1:
        meats = 1
    if veg <= 1:
        veg = 1

    return size, meats, veg, quantity

if __name__ == '__main__':
    calc_pizza_charge()


text:
Q: Querying Active Directory with logged on user credentials in c# I'm working on a C# application that requires a list of users to be spooled from Active Directory, an AD credential that has read-only privileges has been created but the organization has a policy for not giving a 3rd party user credentials.
Judging by Nate's answer here it is possible to query AD with the current logged on user. What I would like to know is do I have to preconfigure this in the AppPool Identity or will setting impersonate to "true" in my web.config as shown below solve this?
<identity impersonate="true" lockItem="false"/>
<anonymousIdentification enabled="true"/>
<authentication mode="Windows">

Below is the code I'm using to connect to AD to fetch my list of users:
using (PrincipalContext ctx = new PrincipalContext(contextType, domainName))
{
   try
   {
       // define a "query-by-example" principal - here, we search for all users
       UserPrincipal qbeUser = new UserPrincipal(ctx);
       qbeUser.Name = "*";

       // create your principal searcher passing in the QBE principal
       PrincipalSearcher srch = new PrincipalSearcher();
       srch.QueryFilter = qbeUser;

       // find all matches
       foreach (UserPrincipal result in srch.FindAll())
       {
           WindowsUser usr = new WindowsUser(result); // WindowsUser is my own user-defined class
           resultSet.Add(usr); // resultSet is a list of WindowsUser
       }
   }
   catch (Exception ex)
   {
      throw ex;
   }
}

return resultSet;

Any answers will be greatly appreciated as I have to be at the clients office in a very short space of time.


text:
Q: dispatcher.forward causes infinite loop I am trying to do the following: I create a servlet to handle all requests, and if the url contains the word "hello", then set the response code to 403, otherwise forward the request to an html page. Here is my servlet:
@WebServlet("/*")
public class AllRequestsHandlerServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = request.getRequestURL().toString();
        if(url.contains("hello")) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/static-html-page.html");
            dispatcher.forward(request, response);
        }
    }
}

But after forwarding, since this servlet handles the forwarded request too, it causes an infinite loop. How can I avoid that?

A: This will never work because /* maps to every request - including your forward to /static-html-page.html and path mappings take priority over all other mappings.
There are a couple of ways around this. The simplest (assuming no other content in the web app) would be:

*

*rename /static-html-page.html to /static-html-page.jsp

*change the mapping from /* to /
That does mean that /static-html-page.jsp would be directly accessible. If you don't want that, move it under /WEB-INF. request.getRequestDispatcher("/WEB-INF/static-html-page.html") will still work.


text:
Q: The anti-forgery token could not be decrypted. AutoGenerate cannot be used in I have a project I'm writing in .Net 4.5.2. I have deployed 5 copies of it to windows server with different names. And I'm logging in from a project. Later, when I try to login from other projects, I get this error.
"The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster."


text:
Q: Solving an error (indices must be of integer) I faced the following problem with my code :
lst_patient_array = np.array(lst_patient)
lst_patient_array[2][0][0].shape
print(lst_patient_array.dtype)

Test_fold_0 =[]
i = 0
for i in files_patient:
y = lst_patient_array[0][0][i] # HERE SHOW ME AN ERROR
Test_fold_0 = np.concatenate((Test_fold_0,y))

The error is:
IndexError: arrays used as indices must be of integer (or boolean) type
solve my problem with IndexError: arrays used as indices must be of integer (or boolean) type


text:
Q: Diophantine equation $x^4-x^2y^2-y^4=a^4+a^2b^2-b^4$ Let $A$ be the set of pairs of coprime positive integers $(a, b)$, for which diophantine equation $x^4-x^2y^2-y^4=a^4+a^2b^2-b^4$ has solutions in the positive integers $(x,y)$.
a) Is $A$ finite or infinite?
b) Does this equation have solutions in case $a=b=1$?
My work
I've posted similar question about equation $x^2-xy-y^2=a^2+ab-b^2$
Also, in section b) I've found 2 solutions - $(1,0)$, $(-1,0)$ (using Wolfram Mathemathica), but neither of them are in the positive integers and I do not know how to show the lack of other solutions

A: COMMENT.-Since $x^4\equiv1\text{ or }0\pmod{16}$ we reduce the values, modulo $16$, of $$n=x^4-x^2y^2-y^4$$  to the following six values $n=0,1,3,5,9,15$ modulo $16$ (ten values are discarded as impossible).
►$a$ and $b$ even:$\quad a^4+a^2b^2-b^4\equiv0\pmod{16}\quad n\equiv0\pmod{16}$.
►$a$ and $b$ odd:$\quad a^4+a^2b^2-b^4\equiv a^2b^2\pmod{16}\quad n\equiv1\text{ or }9\pmod{16}$
►$a$ even and $b$ odd:$\quad n\equiv3\text{ or }15\pmod{16}$.
►$a$ odd and $b$ even $\quad n\equiv1\text{ or }5\pmod{16}$.

A: Similar equations have been solved here, in Theorem $2.4.2$ on page $72$. More precisely, the equations
$$
x^4-x^2y^2+y^4=z^2,\; x^4+x^2y^2+y^4=z^2
$$
have been solved in integers. I think the methods are also useful to solve
$$
x^4-x^2y^2-y^4=1
$$
in integers.


text:
Q: Laravel 5* globalization of a eloquent Guys I am a partial _create-note-modal.blade.php and I am trying to share this partial with all the pages and this works perfectly because I included it in the main.blade.php template.

Problem:

This _create-note.blade.php partial file get all the users from the database using eloquent. This users variable need to be share with all the other views because it will get error.

What I have tried:

I tried to write this in my Controller.php.
$users = User::all();
View::share('users', $users);

Question is:

Is that the best way? and what about If I have an entire function that I want to share?

Notes:

$users = User::all() get all the users but actually my project is a CRM for a company that have 25 users on the CRM and won't have more than 100 in the future which is even hard to happen.
Also I return all the users just to view them in <select> and <option> choose.
Any better solution?
Thanks

A: Actually, I wouldn't recommend you to call all user's data without limit. But you have several options. One of these, you have already provided, using construct you can call your users variable in the view.
Option 1:
public function __construct(){
$users = User::all();
View::share('users', $users);
}

Option 2
In your controller.php you can make a simple function
protected function getUsers(){
 return User::all();
}

Then you can call $this->getUsers in your controller. in this option this query will be worked when you call it.
Option 3
Just make a middleware and return it to controller
class getUsers {

    public function handle($request, Closure $next)
    {
      $users = User::all();
      $request -> attributes('users' => $users);

       return $next($request);
    }
}

In your controller
 return Request::get('users');

UPDATE
If you want to load users in the select dropdown in the all views which belongs to this controller, you can use the first option. But your query should be like this:
$users =  Users::pluck('name', 'id');
View::share('users', compact('users'));

You can easily load all users in select dropdown:
Form::select('users', $users, null);

instead of null you can put user's id, if you want to mark it as selected.
But, if you want to call your users query in some views, I would recommend to you using second option.

A: It's quite a broad question. I don't think it will be accepted by moderators. To answer it you need to tell a bit more about the app. That piece of code could be  okay within an app that only has a couple of views, in which you always show that form, and you assume there'll be always a few users.
The line:
$users = User::all();

can be very harmful if you have lots of users stored. So, we can talk a day about sharing something in views, another day about including the same form in all the views, another for always sending a collection of all the users (is it for a selector? autocomplete? just to list them? each one of those situations may have a different solution)

A: There is a section on this exact scenario described in the official documentation.
See: Sharing Data With All Views. App\Providers\AppServiceProvider.php should already exist in your project structure, it is created by default when the installer runs. However I would be careful, unless you truly need this query on every page, it can easily slow down your site substantially if you are adding a couple of global database queries like this.
<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::share('key', 'value');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


text:
Q: Is there a way to obtain the actual A1 range from sheetfu - get_data_range() I am trying to obtain the actual A1 values using the Sheetfu library's get_data_range().
When I use the code below, it works perfectly, and I get what I would expect.
invoice_sheet = spreadsheet.get_sheet_by_name('Invoice')
invoice_data_range = invoice_sheet.get_data_range()
invoice_values = invoice_data_range.get_values()
print(invoice_data_range)
print(invoice_values)

From the print() statements I get:
<Range object Invoice!A1:Q42>
[['2019-001', '01/01/2019', 'Services']...] #cut for brevity

What is the best way to get that "A1:Q42" value?  I really only want the end of the range (Q42), because I need to build the get_range_from_a1() argument "A4:Q14".  My sheet has known headers (rows 1-3), and the get_values() includes 3 rows that I don't want in the get_values() list.
I guess I could do some string manipulation to pull out the text between the ":" and ">" in
<Range object Invoice!A1:Q42>

...but that seems a bit sloppy.
As a quick aside, it would be fantastic to be able to call get_data_range() like so:
invoice_sheet = spreadsheet.get_sheet_by_name('Invoice')
invoice_data_range = invoice_sheet.get_data_range(start="A4", end="")
invoice_values = invoice_data_range.get_values()

...but that's more like a feature request.  (Which I'm happy to do BTW).

A: Author here. Alan answers it well.
I added some methods at Range level to the library, that are simply shortcuts to the coordinates properties.

from sheetfu import SpreadsheetApp

spreadsheet = SpreadsheetApp("....access_file.json").open_by_id('long_string_id')
sheet = spreadsheet.get_sheet_by_name('test')
data_range = sheet.get_data_range()

starting_row = data_range.get_row()
starting_column = data_range.get_column()
max_row = data_range.get_max_row()
max_column = data_range.get_max_column()

This will effectively tell you the max row and max column that contains data in your sheet.
If you use the get_data_range method, the first row and first column typically is 1.

A: I received a response from the owner of Sheetfu, and the following code provides the information that I'm looking for.
Example code:
from sheetfu import SpreadsheetApp

spreadsheet = SpreadsheetApp("....access_file.json").open_by_id('long_string_id')
sheet = spreadsheet.get_sheet_by_name('test')
data_range = sheet.get_data_range()

range_max_row = data_range.coordinates.row + data_range.coordinates.number_of_rows - 1
range_max_column = data_range.coordinates.column + data_range.coordinates.number_of_columns - 1

As of this writing, the .coordinates properties are not currently documented, but they are usable, and should be officially documented within the next couple of weeks.


text:
Q: How do I launch a SmartSim orchestrator without models? I'm trying to prototype using the SmartRedis Python client to interact with the SmartSim Orchestrator.  Is it possible to launch the orchestrator without any other models in the experiment?  If so, what would be the best way to do so?

A: It is entirely possible to do that. A SmartSim Experiment can contain different types of 'entities' including Models, Ensembles (i.e. groups of Models), and Orchestrator (i.e. the Redis-backed database). None of these entities, however, are 'required' to be in the Experiment.
Here's a short script that creates an experiment which includes only a database.
from SmartSim import Experiment
NUM_DB_NODES = 3
exp = Experiment("Database Only")
db = exp.create_database(db_nodes=NUM_DB_NODES)
exp.generate(db)
exp.start(db)

After this, the Orchestrator (with the number of shards specified by NUM_DB_NODES) will have been spunup. You can then connect the Python client using the following line:
client = smartredis.Client(db.get_address()[0],NUM_DB_NODES>1)


text:
Q: How does AWS EC2 scale if more resourses needed? I launched a t1.micro instance running Apache and MySQL servers on Ubuntu. Basically I'm using it to host my photo sharing app that may have huge random spikes in terms of visitors.
How does AWS go about it?
Will the instance automatically upgrade to appropriate horse power to keep up with demand and growing storage demands?

A: No, you have to manually make your instance more powerful by first making sure it is in the stopped state (this requires EBS volumes or you'll lose your data), then going to the AWS console, right click your instance and select 'Change Instance Type'.
If you are interested in a more automated approach, I suggest an Elastic Load Balancer with an Auto-scaling policy. With Auto-scaling, Amazon will spin up or down new instances based on set points that you provide (i.e. CPU usage reaches 80% for 10 minutes).


text:
Q: CLIPS Rules trigger more than once Hi im trying to make an expert system in Clips, but when a Plant should trigger only one time the rule it trigger as much times as characteristics coincide within the ones specified in the rule, is there a way to make this rule trigger only once per plant in the facts?
I tried with the test() (by putting all the conditions or() included in the test) statement but it didn't work it would give me troubles with the plant template
Example of the rule

(defrule ruleexp
   (or
   (Plant (grownt normal))
   (Plant (leaf purple))
   (Plant (roots burned))
   (Plant (fruit dry)))
   =>
   (printout t "this should print only once" crlf))

A: You can use the exists conditional element to create just one activation:
         CLIPS (6.31 6/12/19)
CLIPS>
(deftemplate Plant
   (slot growth)
   (slot leaf)
   (slot roots)
   (slot fruit))
CLIPS>
(defrule ruleexp
   (exists
      (or (Plant (growth normal))
          (Plant (leaf purple))
          (Plant (roots burned))
          (Plant (fruit dry))))
   =>
   (printout t "this should print only once" crlf))
CLIPS>
(assert (Plant (growth normal)
               (leaf blue)
               (roots burned)
               (fruit wet)))
<Fact-1>
CLIPS> (run)
this should print only once
CLIPS>


text:
Q: Want to get a every word entered in the input string in next line
x = int(input("How many times you want the print :"))

if x>0 :
    a = str(input("Enter the string: ""\n" ))
    d = x * a

    print(d)
else:
    print("dont know")

#for example:
How many times you want the print: 3
Enter the string:Aman Singh
#output i want should be : Aman
Singh
Aman
Singh
Aman
Singh


text:
Q: Is there a $W^{2,2}$ isometric embedding of the flat torus into $\mathbb{R}^3$? It is well known that there exists a  $C^1$ isometric embedding of flat torus into $\mathbb{R}^3$, and that this embedding cannot be $C^2$.
Is there a $W^{2,2}$ isometric embedding? (i.e an isometric map $f \in W^{2,2}(\mathbb{T}^2,\mathbb{R}^3)$?)

A: This is just an expansion on my comment to @j.c. 's answer.
We want to use Pakzad's result cited in that answer in order to prove that there is no $f$ as in the original question.
My idea:
By Sobolev embedding theorems we have that $f\in C^{0,\alpha}$ for all $\alpha\in (0,1)$.  In particular, the image $\Sigma=f(\mathbb{T}^2)$ is a compact set.  As such, there is an $R_0>0$ so that
$$\Sigma\subset B_{R_0}(0)$$
where here $B_{R_0}(0)$ is the open euclidean ball of radius $r_0$ centered at the origin.
Now let
$$
R=\inf\{ \rho>0: \Sigma \subset B_\rho(0)\}
$$
and observe that, as $\Sigma$ is compact $\Sigma\cap \partial B_{R}\neq \emptyset$.  In particular, there is a $p'\in \Sigma\cap \partial B_{R}$ and so, there is a $p\in \mathbb{T}^2$ so $f(p)=p'$.
Now pick a small radius $r$ so that $\exp_p: B_r(0)\to \mathbb{T}^2$ is an isometry onto it's image (here we use that the metric on the torus is flat) and consider the map $\tilde{f}=f\circ \exp_p|_{B_r(0)}$.  Observe, that $\tilde{f}(0)=p'$.  By Pakzad's result, up to shrinking $r$ we know that either $\tilde{f}$ is affine or there is a line through $0$ on which $\tilde{f}$ is affine.  As $f$ is isometric these affine functions are non-constant and so the image of $\tilde{f}$ contains a line segment through $p'$. This segment must leave $\bar{B}_R(0)$ which contradicts the choice of $R$.

A: It is a result of Pakzad's that $W^{2,2}$ isometric immersions $f$ of bounded regular convex domains with Lipschitz boundary $\Omega\subset\mathbb{R}^2$ must be developable; more precisely, for every point $x$ of $f(\Omega)$, $f$ must restrict to an affine function on either (1) a neighborhood of $x$ or (2) a line segment passing through $x$ connecting two points of $\partial\Omega$.
This should "rule" out an isometric embedding of $\mathbb{T}^2$ to $\mathbb{R}^3$ (forgive the pun).
See Theorem II of:
Pakzad, Mohammad Reza, On the Sobolev space of isometric immersions, J. Differ. Geom. 66, No. 1, 47-69 (2004). ZBL1064.58009.
What's still missing is a classification of developable surfaces in the $W^{2,2}$ setting; I suspect it should be the same as the classical one but I should think some more...
edit 2: In fact, such a classification is not necessary to show that there is no $W^{2,2}$ immersion of a flat torus into $\mathbb{R}^3$. See RBega's answer for a much nicer proof of that fact than what follows here!
edit: The following was inspired by RBega's comment below before I fully understood it. Hopefully this works:
Suppose there is a point $p$ of type (2). Let $\Omega$ be $\mathbb{T}^2$ minus an $\epsilon$-neighborhood of the cut locus at $p$, thought of as a domain in $\mathbb{R}^2$. $\mathbb{T}^2$ minus its cut locus looks like the Voronoi cell of $p$ in the universal cover so $\Omega$ satisfies the assumptions in Pakzad's theorem. Then by Pakzad's theorem, the line segment through $f(p)$ connects the images of two points $p_1,p_2$ on $\partial\Omega$. Let $r=d_{\mathbb{T}^2}(p_1,p_2)$ and $R=d_{\mathbb{R}^3}(f(p_1),f(p_2))$, so that $f(p)$ lies on a straight line segment $l\subset\mathbb{R}^3$ of length $R$ between $f(p_1),f(p_2)$. For $\epsilon$ sufficiently small, I claim that $R>r$ which leads to a contradiction. Explicitly, $l$ is a minimizer of distance in $\mathbb{R}^3$, so $R$ is a lower bound for the distance between $f(p_1)$ and $f(p_2)$ in $f$, so the true distance $r$ cannot be achieved by $f$.
I don't have a particularly clean proof of $R>r$ for all flat tori but I think that this will follow from some case analysis on the possible Voronoi cells of lattices in $\mathbb{R}^2$. For example, consider the square flat torus of area $a^2$. We can take $\Omega$ to be a square with side length $a-\epsilon$, with $p$ at its center. Then among the pairs of points $(p_1,p_2)$ on $\partial\Omega$ that lie on some geodesic through $p$, the maximal distance $r$ between $p_1$ and $p_2$ is less than $a/2$, while the minimum length $R$ of a geodesic joining $p_1$ and $p_2$ through $p$ is at least $a-2\epsilon$.
Finally, if there can be no points of type (2), then we are left with only points of type (1), but that implies that $f$ itself is affine, which leads to a contradiction as well.


text:
Q: Approximate solution to large mixed integer programming problem What are the available approaches to find an approximate solution to a large mixed integer programming problem?
I ran my problem in the Gurobi MIP solver.
It can find a feasible solution in reasonnable time.
But I need to solve several different MIP problems, and in the end, it takes too much.
Is there something like a least-square approximation to a MIP problem?
Or, any other approach, which can deliver a sub-optimal solution very quickly?
Can a general non-linear optimization solver quickly find an approximate solution of a MIP problem?
My model has one million variables.
I know there is a litterature on quickly finding a feasible solution to a MIP.
But I couldn't find a litterature body on approximate MIP solution.

A: You might try a local optimization approach.  Guess values for the integer variables and solve the remaining continuous linear programming problem.  Using sensitivity
analysis, see if the solution can be improved by changing one of the integer variables.  Repeat as many times as you can or until no further improvements can be found.
You might also try simulated annealing or tabu search: these may produce better results but are more time-consuming, and a million variables might be too much.

A: You could also try genetic programming; that is, start with say 100 assignments of variables, and then, keep the 50 best, clone/mutate a new set of variable assignments, and repeat.


text:
Q: Case insensitive when Is it somehow possible to make when String comparison case insensitive by default?
when (subtype.toLowerCase()) {
    MessagingClient.RTC_SUBTYPE.sdp.toString().toLowerCase() -> onSDPMessageReceived(topic, sender, data!!)
    MessagingClient.RTC_SUBTYPE.bye.toString().toLowerCase() -> onRTCBYEMessageReceived(topic, sender)
    MessagingClient.RTC_SUBTYPE.negotiationOffer.toString().toLowerCase() -> onNegotiationOfferMessageReceived(sender, data!!)
}

This has too much repetetive code! Also note that MessagingClient.RTC_SUBTYPE is enum class and subtype on the first line is received from some client, so we must treat it accordingly.

A: I would convert subtype to MessagingClient.RTC_SUBTYPE like so:
val subtypeEnum = MessagingClient.RTC_SUBTYPE.values().firstOrNull {
   it.name.equals(subtype, ignoreCase = true)
} ?: throw IllegalArgumentException("${subtype} no value of MessagingClient.RTC_SUBTYPE match")

And then use it in when
when (subtypeEnm) {
    MessagingClient.RTC_SUBTYPE.sdp -> onSDPMessageReceived(topic, sender, data!!)
    MessagingClient.RTC_SUBTYPE.bye -> onRTCBYEMessageReceived(topic, sender)
    MessagingClient.RTC_SUBTYPE.negotiationOffer -> onNegotiationOfferMessageReceived(sender, data!!)
}

A: var s1 =editText.text.toString()
var s2=textView_.text
var s3 =s1.equals(s2 ,true)


text:
Q: Read Big File (over 60GB) and Write new File There is one file that is 60GB in size and 200,000,000 rows . The payload of the file is shown below.
source.txt
0.0 4.6 6.3 3.8 5.0 0.0 -3.8 -5.9 1.5 14.2 0.0 1.0 6.9 5.8 6.1 0.0 5.4 -7.1 0.9 6.8 0.0 -1.8 2.6 0.0 -11.5 -0.0
0.0 13.4 -1.8 5.2 2.4 0.0 -7.1 -12.5 -2.8 11.8 0.0 2.0 5.5 3.5 8.2 0.0 9.2 -18.2 -3.4 1.7 0.0 -16.1 3.2 0.0 9.7 -0.1
0.0 12.2 -2.0 7.2 0.1 0.0 -9.1 -11.8 -2.5 8.8 0.0 1.1 4.6 3.8 8.0 0.0 8.3 -18.5 -5.0 0.6 0.0 -14.3 2.8 0.0 10.6 -0.0
0.0 10.6 -0.6 8.3 -2.2 0.0 -9.4 -8.4 -1.5 5.3 0.0 1.9 3.5 3.6 7.1 0.0 7.6 -16.5 -5.7 0.6 0.0 -9.5 1.9 0.0 7.8 0.0

I want to read the files in order and make a new file including the sequence number. The payload of the file to be created is as follows.
destination.txt
 1: 0.0 4.6 6.3 3.8 5.0 0.0 -3.8 -5.9 1.5 14.2 0.0 1.0 6.9 5.8 6.1 0.0 5.4 -7.1 0.9 6.8 0.0 -1.8 2.6 0.0 -11.5 -0.0
 2: 0.0 13.4 -1.8 5.2 2.4 0.0 -7.1 -12.5 -2.8 11.8 0.0 2.0 5.5 3.5 8.2 0.0 9.2 -18.2 -3.4 1.7 0.0 -16.1 3.2 0.0 9.7 -0.1
 3: 0.0 12.2 -2.0 7.2 0.1 0.0 -9.1 -11.8 -2.5 8.8 0.0 1.1 4.6 3.8 8.0 0.0 8.3 -18.5 -5.0 0.6 0.0 -14.3 2.8 0.0 10.6 -0.0
 4: 0.0 10.6 -0.6 8.3 -2.2 0.0 -9.4 -8.4 -1.5 5.3 0.0 1.9 3.5 3.6 7.1 0.0 7.6 -16.5 -5.7 0.6 0.0 -9.5 1.9 0.0 7.8 0.0

I can use Java to do the following
    String filePath = "/filepath";

    Path path = Paths.get(filePath+"/source.txt");

    BufferedReader bufferedReader = Files.newBufferedReader(path);

    Stream<String> lines = bufferedReader.lines();
    AtomicLong seq = new AtomicLong(0);

    BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get(filePath+"/dest.txt"));

    lines.forEach(txt -> {
        try {
            bufferedWriter.append(seq.addAndGet(1) + ":" + txt);
            bufferedWriter.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

but I'm wondering if it's possible using a distributed universal framework like Spark or Storm or Hadoop. I think big data frameworks make it faster

A: There is something which may be helpful in Spark.

*

*Create an RDD from the CSV file

*Use a combination of zipWithIndex, sortBy, map

Check https://stackoverflow.com/a/26081548/290036 for a zipWithIndex example


text:
Q: Swift scrollToItem and center in middle of the cell I have been having trouble trying to understand how to programmatically use scrollToItem in a CollectionView and center the cell in the middle of the screen. It seems that when I use scrollToItem, it scrolls to the item horizontally but then stops at the beginning of the cell that I wanted to scroll to and not in the center of it. Any help or insight is greatly appreciated.
override func viewDidLoad() {
    super.viewDidLoad()
    self.cv.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    self.view.layoutIfNeeded()
}

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
         return CGSize(width: view.bounds.width, height: view.bounds.height - 150)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
         return UIEdgeInsets(top: 100, left: 0, bottom: 0, right: 0)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
         return 0
     }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }


text:
Q: Make a multiplication of two tables in SQL Server 2008 If you have two SQL tables and you see them like matrices, The product C of two matrices A and  B is defined as
c_ik = a_ij*b_jk

where j is summed over for all possible values of i and k and the notation above uses the Einstein summation convention. The implied summation over repeated indices without the presence of an explicit sum sign is called Einstein summation, and is commonly used in both matrix and tensor analysis. Therefore, in order for matrix multiplication to be defined, the dimensions of the matrices must satisfy

so

where

for example
a1  a2  a3
----------
14   9   4
2   11   5
0   12  17
5    2   3

b1   b2
-------
12   25
 9   10
 8    5

is equals to
c1     c2
---------
273   455
243   235
244   205
102   160

I was thinking in doing a While loop, but I guess there is a better way to do this
maybe using pivot or a CTE with coords of i,j,k?
DECLARE @count int
DECLARE @max int

SET @count int = 1
SET @max = 4

WHILE @count < @max
BEGIN
   INSERT INTO C_Table (c1, c2)
  --Do not know how to make the other products or how to get them...
   Select Sum(   (T1.Value * T2.Value)   )
    From A As T1
    Join B As T2
    ...
   SET @count = @count + 1
END

I am a little lost here...


text:
Q: Find all records based on quarter I have a table named Accidents. I am tying to return all records based on which quarter the reported date is in.
This is how the table looks like:
Accidents Table

| acc_id  | acc_descrip |reported_date|
| 1       | collision   |2019-20-01
| 2       | hit and run |2019-08-01
| 3       | collision   |2019-10-06

So this works in terms of giving me all the records in the table and which quarter and year they fall in. But I want to pass a parameter of year only and get the results of that year of records and the quarter which it falls in?
alter PROCEDURE AccidentByQuarter
AS
BEGIN
SELECT *,
CASE
WHEN MONTH(ReportedDate) IN (1,2,3)  THEN convert(char(4), YEAR(ReportedDate) - 1) + 'Q3'
WHEN MONTH(ReportedDate) IN (4,5,6)  THEN convert(char(4), YEAR(ReportedDate) - 1) + 'Q4'
WHEN MONTH(ReportedDate) IN (7,8,9)  THEN convert(char(4), YEAR(ReportedDate) - 0) + 'Q1'
WHEN MONTH(ReportedDate) IN (10,11,12) THEN convert(char(4), YEAR(ReportedDate) - 0) + 'Q2'
END AS Quarter  FROM Incident
END

A: If performance is not a big issue, I would do:
alter procedure AccidentByMonth (
    @ReportedDate int
)
AS
Begin
    select *
    from Incident
    where month(ReportedDate) / 4 = @ReportedDate / 4
End;

That is a little bit arcane -- because the values start at 1 and not 0.  It is probably more readable to do:
    where (month(ReportedDate) - 1) / 4 = (@ReportedDate - 1) / 4

Or:
   where datepart(quarter, RepertedDate) = (@ReportedDate - 1) / 4

A: Here is another possible solution.
This query dynamically computes the dates of quarter start and end for the given @ReportedDate parameter. Hence it will take advantage of an index on column ReportedDate, since no computation happens on the left side of the comparison operators.
ALTER PROCEDURE AccidentByMonth (@ReportedDate int)
AS
BEGIN
    SELECT *
    FROM Incident
    WHERE
        ReportedDate >= DATEADD(q, DATEDIFF(q, 0, @ReportedDate), 0)
        AND ReportedDate < DATEADD(d, -1, DATEADD(q, DATEDIFF(q, 0, @ReportedDate) + 1, 0))
END

A: You should try this. According your parameter name @ReportDate I assume that is date as integer (20190207 = 2019-02-07). I use CONVERT function because your function param is INT.
ALTER PROCEDURE AccidentByMonth
    (
        @ReportedDate int
    )
AS
    BEGIN
        SELECT *
        FROM   Incident
        WHERE  DATEPART(QUARTER, ReportedDate) = DATEPART(QUARTER, CONVERT(DATE,CONVERT(VARCHAR(10),@ReportedDate,101)));
    END;


text:
Q: Why does Python think this is a tuple? def my_function(fname):
    print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

def my_greeting(*fname):
    print(fname + " Smith")

my_greeting("Don")

The first part runs fine the second part crashes. Here are the results.
Emil Refsnes
Tobias Refsnes
Linus Refsnes

Traceback (most recent call last):
  File "C:/Data/Python/turtleFun/kikiFunction.py", line 19, in <module>
    my_greeting("Don")
  File "C:/Data/Python/turtleFun/kikiFunction.py", line 17, in my_greeting
    print(fname + " Smith")
 TypeError: can only concatenate tuple (not "str") to tuple

I haven't created a tuple, I'm not trying to concatenate. The structures are the same but one runs and the other crashes. Why does Python 3.8.3 think I have a tuple? How do I fix? Tuples would be
myTuple = ("Don", "Fred", "George", "Paul", "John", "Ringo")

A: Problem
The * next to *fname makes fname a tuple, always.
Understanding what's going on
Let's see what a function with *fname as a parameter really does.
>>> def func(*fnames):
...     print(fnames)
...     print(type(fnames))
>>> func('str 1', 'str 2')
('str 1', 'str 2')
<class 'tuple'>

Look at that! Even though it seems like func takes just 1 parameter (*fnames) we don't get an error even though when we call it with 2 parameters ('str 1' and 'str 2'). That's because the * in *fnames lets any number of parameters (including 0!) to be passed to func, and all of those parameters get passed in as 1 tuple.
This is why, even when you pass just 1 argument to the function, fnames still takes on the type of tuple. In your example:
def my_greeting(*fname):
    print(fname)  # let's not concatenate for now

my_greeting('Don')  # prints a tuple: ('Don',)

Why doesn't Python only use tuples when *fnames is given 2+ args?
Python always uses tuples for *-type arguments so that our code can always expect a certain type. Otherwise, my_greeting('Don') would set fnames to a str, while my_greeting('Don', 'Don2') would set fnames to a tuple of str.
I hope this helps you learn!


text:
Q: desktop application system where i wants to backup the data base I have created a desktop application system where I want to backup  the database.
I am using the code shown below:
 process p = null;
 p = runtime.exec("E:/xampp/mysql/bin/mysqldump -uroot --add-drop-database -B clinic_management -r "+path+".sql");

 int processComplite = p.waitFor();

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

 if(processComplite==0) {
      JOptionPane.showMessageDialog(null, " backup complite
 Check this folder
"+path+"");
      jTextField1.setText("");
 } else {
       JOptionPane.showMessageDialog(null, " backup  not complite");
 }

It's working fine in some systems but sometimes it shows
 processComplite=1

A: See the javadoc for waitFor():
Returns: the exit value of the subprocess represented by this Process object. By convention, the value 0 indicates normal termination.
In other words: your database operation is failing. There are two things you can do:

*

*Check if mysqldump generates log files; and see if you can find anything in there

*As of now, you are completely ignoring any output that would be written to stdout/stderr when making that process call.

Meaning: you can get access to messages potentially written by msqldump by doing something like:
 InputStream stdout = p.getInputStream();
 InputStream stderr  = p.getErrorStream();
 int returnCode = p.waitFor();
 if (returnCode == 0) {
   ... give positive message
 } else {
   read data from streams and display those


text:
Q: covering of a connected genus? Let $\Sigma_n$ be a connected sum of $n$ tori for $n \in \mathbb{N}$. So basically, $\Sigma_0$ is the sphere, $\Sigma_1$ is the torus and then it's basically connected tori and the whole thing has $n$ holes. (I hope you get the picture.) I want to know for which values of $n$ does the sphere $S^2$ cover $\Sigma_n$.
I think the $\Sigma_n$ can be written as $S^2\times S^2\times \cdots \times S^2$ with $n$ many $S^2$'s, but does it mean that $S^2$ can cover the $\Sigma_n$ for all values of $n$?

A: If $X$ is an $n$-fold cover of $Y$ then (under mild hypotheses which are satisfied here, say, for finite CW complexes) we have $\chi(X) = n \chi(Y)$ where $\chi$ is the Euler characteristic. The Euler characteristic of $\Sigma_g$ is $2 - 2g$, so it follows that if $\Sigma_g$ covers $\Sigma_h$ (any such covering map is necessarily finite, because $\Sigma_g$ is compact) then $1 - h$ must divide $1 - g$.
Setting $g = 0$ gives that $1 - h$ must divide $1$ (and the quotient must be positive, since it must be the degree of the cover) which gives $h = 0$. In other words, the only closed orientable surface that $S^2$ covers is itself.
An alternate argument is thinking about universal covers. $S^2 = \Sigma_0$ is simply connected, $T^2 \cong \Sigma_1$ has universal cover $\mathbb{R}^2$, and for $g \ge 2$, $\Sigma_g$ has universal cover the upper half plane $\mathbb{H} \cong \mathbb{R}^2$ (e.g. by the uniformization theorem although one can also write down a covering map explicitly). In particular the universal cover of $\Sigma_g$ is noncompact for $g \ge 1$ (this is is equivalent to the fundamental group being infinite) and so cannot be $S^2$.

A: Firstly, $\Sigma_n$ cannot be written as a product $S^2 \times \cdots \times S^2$.
Secondly, using the fact that the Euler characteristic of a covering is the product of the Euler characteristic of the base space and the degree of the cover, we see that $S^2$ can only cover $\Sigma_0$ (i.e., itself) since $\chi(\Sigma_n) = 2 - 2n$.


text:
Q: Find documents 7 days apart in mongodb Suppose, we have this type of documents :
{
"_id" : ObjectId("4c02c58de500fe1be1000305"),
"date" : ""20090530"
}

{
"_id" : ObjectId("4c02c58de500fe1be1000005"),
"date" : ""20090607"
}

Is it possible to find/group all documents with 7 days between them?
With aggregate?

A: You can write something like this, I believe you won't be needing aggregation here, if you are doing this for the same collection:
db.collectionName.find({date: { $gte: "20090530", $lte: "20090607" } } );

Reference: $lte and $gte


text:
Q: appcelerator get-chat group showing all groups not just the one logged in user is in I need help on tiny issue for developing an app using appcelerator cloud.
I want to show ONLY the list of chat groups(using table view) the logged in user is involved with.
But somehow, it is showing all the chat group.
And when i clikc each row, I cant seem to proceed to the chat page where the actual chat messages are,,,
thanx in advance for your help?
Cloud.Chats.getChatGroups({

        // i thinkg this is where i need help, this query with 'where' part
        where : {
        participate_users : { "$in" : user}
        }
},
    function (e) {
    if (e.success) {
        if (e.chat_groups.length == 0) {
                table.setData([
                    { title: 'No Results!' }
                ]);
            }
        var tbl_data = [];
        for (var i = 0; i < e.chat_groups.length; i++) {
            var group = e.chat_groups[i];

             //some code

            tbl_data.push(row);
        }
        var table = Titanium.UI.createTableView({
            data:tbl_data
        });
        table.addEventListener('click', function(e){
                 //some code defining 'groudid'
                var loginwin,loginInc;
                    loginInc = require('conversation');
                    loginwin = new loginInc.convo(groudid);
                    loginwin.open();
                loginwin.open();
            });
        chatview.add(table);
    } else {
        alert('Error:\n' +
            ((e.error && e.message) || JSON.stringify(e)));
    }
});


text:
Q: Microsoft access - Percentage Complete Basically i would like to create a form/Report that shows a user what percentage of a job is complete (i have done that) but from the percentage, work out how much of the "quote" is completed (e.g. Quote = £100..... Percentage = 50% complete.... so the job would now be at £50 complete.
The next stage would then be working out the total of ALL the quotes (e.g. £100,000) and gathering The completion money count (e.g. £40,000, as some job may have different percentages complete) i can then compare the expected amount with the dates they are due by and what the actual completion amount is, at the moment.
I'm not saying its an easy or hard task to do, but if someone were willing to help that would be excellent.

A: As you have the percentage calculated, say 50% which is 0.5, all you need is to multiply:
QuoteCompleted = QuoteTotal * CalculatedPercentage

or, as a ControlSource:
=[Quote]*[TextboxHoldingCalculatedPercentage]


text:
Q: Declaring variables at top of js file I have been declaring variables I use in multiple functions at the top of the file.
var a;

window.onload = function() {
   a = 10;
}

function bar() {
  if(a > 5)
    //do something
}

This may be a bad example, but the question is does declaring variables at the top of the file harm anything?

A: Declaring variables at the top of the function they should be scoped to (which is the top of the file for globals), is a common practice used to:

*

*Avoid confusion new developers experience when encountering hoisting

*Make it clear which variables are scoped where to developers reading the code (but putting them all in one place per scope).

It doesn't introduce any problems (beyond altering the way you have to clean up old code when you stop using a variable).


text:
Q: Adding Administrators Via Group Policy My Windows Vista work computer is a member of a domain.  The domain administrators have set up a group policy that keeps adding them as Administrators of my computer every night.
Is there a way I can prevent this from happening?  I am an Administrator on the computer.

A: These are serious answers:

*

*disconnect your PC from the network

*remove your PC from the domain

You can't change group policy: it can override local settings or not be overridden.
Domain admins trump local admins in AD
But why?

A: There is no (useful) way. This isn't however a technical problem at all but a policy problem (if a problem at all). Take it up with your administrators and your boss. Ask them why and they should explain.
This behaviour is a default policy by the way.

A: Yes, you can.  There are a number of ways at your disposal.  A few ideas:

*

*Delete their local admin. Add your own local admin user with the same username but a different password.  The GPO addition will assume the user is already there and not make any changes.

*Update registry permissions to remove access to any of the several keys required to add a user.  Mark Russinovich describes procedures on his blog.

*Edit the NTFS permissions on the directory where the group policy objects are cached.  (this, of course, will break all GPOs, not just the local admin...)
bottom line: as a local admin, you can do anything.  In order for Group Policy to work and for the GPO to add a local user, it must do something.  Break any part of that something and you've found your solution.
Of course, just because you can, but that doesn't mean you should.  I was an IT guy, users did this to me, and it's irritating.  It's a policy issue and should be handled via non-technical means.

A: Every time you connect to your work network this will happen, it's how companies control their computers, I recommend talking to a network administrator.

A: *

*Open Regedit.exe.

*Browse to the following path - HKEY_CURRENT_USER\Software\Policies\Microsoft\MMC\

*Expand the unique key contained within

*Set Restrict_Run to the value 1 (done by double clicking to edit and typing 1)

http://www.computerstepbystep.com/group_policy_windows_7.html


text:
Q: Python typing - return value is instance of parameter I have a function that receives a class and returns an instance of that class. A simple example:
def instantiate(class_: Type[enum.Enum], param: str) -> enum.Enum:
    return class_(param)

The return value is the same as the type of the parameter class_, so if class_ is MyEnum, the return value will be of type MyEnum.
Is there some way to declare that?

A: There sure is! This should work perfectly for your use case.
from enum import Enum
from typing import TypeVar, Type

E = TypeVar('E', bound=Enum)

def instantiate(class_: Type[E], param: str) -> E:
    return class_(param)

And to just do a quick test of it to confirm that type hinting is working as intended:
class MyEnum(Enum):
    ONE = '1'
    TWO = '2'

# I hover over 'e' and PyCharm is able to infer it's of type MyEnum.
e = instantiate(MyEnum, '1')

print(e)
# MyEnum.ONE

Note: As mentioned in comments, in Python 3.9, some typing constructs like Type, List, and Dict are deprecated, as you can just use the builtin types. So the above annotation could be defined like type[E] if you have a newer Python version.

A: That is pretty standard. You would have found this in the documentation pretty top level:
from typing import Type

class MyClass:
    def __init__(self, param: str) -> None:
        self.param = param

def instantiate(cls: Type[MyClass], param: str) -> MyClass:
   return cls(param)


text:
Q: Is there an advantage to pre-scattering data objects in Dask? If I pre-scatter a data object across worker nodes, does it get copied in its entirety to each of the worker nodes? Is there an advantage in doing so if that data object is big?
Using the futures interface as an example:
client.scatter(data, broadcast=True)
results = dict()
for i in tqdm_notebook(range(replicates)):
    results[i] = client.submit(nn_train_func, data, **params)

Using the delayed interface as an example:
client.scatter(data, broadcast=True)
results = dict()
for i in tqdm_notebook(range(replicates)):
    results[i] = delayed(nn_train_func, data, **params)

The reason I ask is because I noticed the following phenomena:

*

*If I pre-scatter the data, delayed appears to re-send data to the worker nodes, thus approximately doubling memory usage. It appears that pre-scattering is not doing what I expected it to do, which is allow for the worker nodes to reference the pre-scattered data.

*The futures interface takes a long time to iterate through the loop (significantly longer). I am currently not sure how to identify where the bottleneck here is.

*Using the delayed interface, from the time the compute() function is called to the time that activity is reflected on the dashboard, there is an extensive delay, which I suspected was due to data copying.

A: Pre-scattering is designed to avoid placing large object data into the task graph.
x = np.array(lots_of_data)
a = client.submit(add, x, 1)  # have to send all of x to the scheduler
b = client.submit(add, x, 2)  # again
c = client.submit(add, x, 3)  # and again

You'll feel this pain because client.submit will be slow to return, and Dask may even throw a warning.
So instead we scatter our data, receiving a future in return
x = np.array(lots_of_data)
x_future = client.scatter(x)
a = client.submit(add, x_future, 1)  # Only have to send the future/pointer
b = client.submit(add, x_future, 2)  # so this is fast
c = client.submit(add, x_future, 3)  # and this

In your situation you're almost doing this, the only difference is that you scatter your data, then forget about the future it returns, and send your data again.
client.scatter(data, broadcast=True)  # whoops!  forgot to capture the output
data = client.scatter(data, broadcast=True)  # data is now a future pointing to its remote value

You can choose to broadcast or not.  If you know that all of your workers will need this data then it's not a bad thing to do, but things will be fine regardless.


text:
Q: Magento 1.9 Customer Group Display Price Without Tax I have created a Tax Free Customer Group, so when a customer logged in, the price should be displayed without tax. And this is working find on a clean Magento installation.
When I implement this on my live site, all prices are displayed with tax. It simply ignored my Tax Free Customer Group.
I have the following code to display price, which is the same code as in a clean Magento installation.
$this->helper('checkout')->formatPrice($this->getTotal()->getValue())

Any reason why this code doesn't take customer group in consideration?
PS: I've also checked the admin, which is the same setup as in a clean Magento installation, where the tax free customer group worked.

A: OK, I fixed it.
It's the Enable Cross Border Trade calculation setting under System -> Configuration -> Sales -> Tax, that needs to be turned off.


text:
Q: N=4 d=3 susy algebra Does anybody know how to derive the $\mathcal{N}=4$ d=3 susy algebra doing a dimensional reduction from the most famous $\mathcal{N}=4$ d=4?
Equivalently, does it exist a reference in the literature in which such an algebra is explicitly written out?
Thanks


text:
Q: Best Practices for Multiple GUI Objects This is my first post to this forum, so if I screw something up, please let me know.
I have been using the information provided on this site for a good few months at this point to help me with various questions, so I thank you all for it the help!
Anyway, enough fluff and on to the question:
I am currently writing my first company-use program in the Java language and I have run into something for which I haven't given much thought until last week.
Currently, I have created a program that uses two separate swing-type GUIs - one to log in a user and one that I am dubbing "the main GUI." As with any language, there are multiple ways to achieve this and after much thinking about what the best way to do it is, I was wondering if anyone with experience had any insight as to the best practice for implementing multiple GUIs.
Right now, I have the login GUI's action listener creating the main GUI object, but I do not think this is the best way to go about it (I'm sure some of the more seasoned Java programmers are probably cringing at the thought of creating a GUI object from an action listener - it's like I can feel them wanting to smack the back of my head!).
So, to be direct - I have thought of about 3 different ways to acheive the objective, from recycling the JFrame to creating the GUI objects in main and setting visibility, and am wondering what the best practice (industry standard) is. Can anyone point me in the right direction?
I have posted this question to another group and was completely ignored.  I am beginning to think there may not be a real answer to the question, but would like to try you experts at Stack Overflow before I give up.  What are your thoughts?  How have you implemented them in the past?  Is better to instantiate them in main and manipulate visibility? While I have found posts that speak of best practices for creating a GUI, I haven't seen much that speaks of multiple GUIs in the same program.  Thanks for your time!

A: I believe what you did with the actionListener was overall okay to do, considering the first thing that appears is the log in screen. I've been in the same spot as you have and I've done 2 different things:
1) I created them both and just changed the visibility. I linked the frames to my main frame, so I could grab data from all the other frames. So you could use this method if you'd like to use the data from the log in screen on your main JFrame.
2) I used an actionListener to wait for the user to log in successfully, and on succession, the main GUI would be created.
My opinion: I would go with method 1. It will allow you to use any of the JFrames to gather any necessary data. Also, it will provide the user with what GUIs were designed for, quick and easy access to whatever the project (or product) was created for. People don't want to spend time waiting for each new JFrame they want to access load. It would be best to load the program all at once, so that it looks as if they GUI is operating at a fast speed, and provides results almost instantly.


text:
Q: Find and Replace using patterns in Xcode 8 I was trying to update one of my old Xcode 7 answers that described how to do regular expression matching. However, I can't get the Textual Matching Style to work now. In Xcode 7, I could do something like this:

which gave me pattern matching like this:

But in Xcode 8 the green bubbles don't show up. I get a (\w+) but that doesn't match anything in the Textual style anymore. And when I am in The Regular Expression Matching Style, I don't have all the nice Insert Pattern hints anymore.
What am I doing wrong?
Note: I'm not asking for the regex answer. I'm asking how to get the Insert Pattern hints to work.

A: You switched your find options Matching Style from Text to Regular Expression. To revert this, simply click on the magnifying glass next to the search field, select Edit find options... and set the Matching Style back to text.


text:
Q: What is the difference of envfit vegan result using scores function and extract the vectors? What is the difference among the vectors (fit$vectors) obtained from envfit function of vegan (R package) and extract it using (scores function):
library(vegan)
data(varespec, varechem)
ord <- metaMDS(varespec)
fit <- envfit(ord, varechem, perm = 999)

fit$vectors
            NMDS1    NMDS2     r2 Pr(>r)
N        -0.05699 -0.99837 0.2538  0.044 *
P         0.61934  0.78513 0.1938  0.116
K         0.76606  0.64277 0.1809  0.124
Ca        0.68482  0.72871 0.4119  0.006 **
Mg        0.63219  0.77481 0.4271  0.003 **
S         0.19092  0.98161 0.1752  0.115
Al       -0.87184  0.48978 0.5269  0.001 ***
Fe       -0.93628  0.35126 0.4450  0.005 **
Mn        0.79879 -0.60162 0.5230  0.001 ***
Zn        0.61731  0.78672 0.1879  0.121
Mo       -0.90312  0.42938 0.0609  0.515
Baresoil  0.92521 -0.37947 0.2508  0.052 .
Humdepth  0.93300 -0.35987 0.5199  0.002 **
pH       -0.64823  0.76144 0.2307  0.070 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Permutation: free
Number of permutations: 999

or
data.frame(scores(fit, "vectors"))
               NMDS1      NMDS2
N        -0.02871183 -0.5029777
P         0.27264080  0.3456235
K         0.32580371  0.2733667
Ca        0.43952421  0.4676897
Mg        0.41315337  0.5063630
S         0.07992162  0.4109201
Al       -0.63286315  0.3555304
Fe       -0.62458948  0.2343268
Mn        0.57765907 -0.4350718
Zn        0.26758332  0.3410181
Mo       -0.22295444  0.1060014
Baresoil  0.46331553 -0.1900256
Humdepth  0.67275508 -0.2594927
pH       -0.31134547  0.3657210

why each NMDS columns have different values, which of them are the best to plot the significant (<0.05) variables against sites ???
sites <- data.frame(ord$points)

scores function
sc <- data.frame(scores(fit, "vectors"))

or
sc <- data.frame(fit$vectors)

ggplot(data=sites, aes(x=MDS1, y=MDS2)) + geom_point() + coord_fixed() +
    geom_segment(data = sc, aes(x = 0, xend = NMDS1, y = 0, yend = NMDS2),
                 arrow = arrow(length = unit(0.25, "cm")), colour = "grey") +
    geom_text(data = sc, aes(x = NMDS1, y = NMDS2, label = rownames(sc)),
              size = 3)

using scores function or using fit$vectors  ???
Thanks so much

A: According to the documentation (see ?envfit) "The printed output of continuous variables (vectors) gives the direction cosines which are the coordinates of the heads of unit length vectors." Further it explains that "In plot these are scaled by their correlation (square root of the column 'r2') so that "weak" predictors have shorter arrows than "strong" predictors.  You can see the scaled relative lengths using command scores." The last piece of information is confirmed at the end of the documentation which says "The results can be accessed with scores.envfit function which returns ... the fitted vectors scaled by correlation coefficient". So the difference is correlation, and you should use the results extracted by scores. The directly accessed direction cosines will draw unit-length arrows (like you should see) irrespective of the strength of the variable.
The conventional plot function in vegan can select variables by permutation P-values, but geom_text and geom_segment have no idea of doing this. You should only pass those rows that you want to plot, and remove the other scores.


text:
Q: How to write the coordinates of a point on a parabola as a function of the distance traveled on the parabola to reach that point? Assume the parabola $y=kx^2$ in the 2D Cartesian coordinate system.
If I walk a distance $s$ on that curve from origin, what will my coordinates be?
It is easy to find the distance traveled on the parabola if I know my $x$ coordinate at the destination. But, here the reverse is needed.
It is evident that immediately after finding $x(s)$, $y(s)$ can be found using $y=kx^2$. So the goal is to find $x(s)$.
$$ds=\sqrt{(f'(x)dx)^2+dx^2}=\sqrt{1+(f'(x))^2}\ dx=\sqrt{1+4k^2x^2}\ dx$$
So we are facing the boundary value problem $ds=\sqrt{1+4k^2x^2}\ dx$, $x(0)=0$, $x(s)=?\,$.
This is separable. After integrating, we have:
$$s=\int_0^x\sqrt{1+4k^2X^2}\ dX$$
To calculate the integral, we use the known formula:
$$\int\sqrt{1+x^2}\ dx=\frac12x\sqrt{1+x^2}+\frac12\ln|x+\sqrt{1+x^2}|+\mathbb{constant}$$
and the substitution $x=2kX$, so $dX=\frac{dx}{2k}$. Finally, assuming $x\ge0,$
$$kx\sqrt{1+4k^2x^2}+\frac12\ln(2kx+\sqrt{1+4k^2x^2})=2ks$$
Up to here, the formal way was used. From now on, These are my own ideas (which may not be the best methods).
Using the substitution $2kx=\tan\theta$, we can go further simplifying the relation:
$$\tan\theta\sec\theta+\ln(\tan\theta+\sec\theta)=4ks$$
The goal was to find $x(s)$ which is equivalent to finding $\theta(x)$. But, I am stuck here.
Mathematica says it can't solve it with available methods. Can anyone help me?

EDIT:
I could achieve more simplifications. Denoting $\tan\theta$ by $T$ we can have a better look...

$$T\sqrt{1+T^2}+\ln(T+\sqrt{1+T^2})=4ks$$
That $\ln(T+\sqrt{1+T^2})$ is saying "write me in terms of hyperbolic functions!"
$$T\sqrt{1+T^2}+\sinh^{-1}(T)=4ks$$
This means there exists a $z$ such that $T=\sinh(z)$. Rewriting anything so that we have only $z$:
$$\sinh(z)\sqrt{1+\sinh(z)^2}+z=4ks$$
$$\sinh(z)\cosh(z)+z=4ks$$
$$\frac12\sinh(2z)+z=4ks$$
$$\sinh(2z)+2z=8ks$$
Now say $\psi=2z$, we have:
$$\psi+\sinh(\psi)=8ks$$
This implies we are very close to an explicit expression of $\psi(s)$!
But I again have to leave the rest up to you...

A: EDIT 1/2
In 3D it is easier,  arc length $s$ does not change even when cone is developed. For this purpose semi vertical cone angle $\alpha $ is brought in:
$$ r= \tan \,\alpha z $$
$$ z{\prime } = \cot \alpha\, r{\prime}  $$
$$ \dfrac{ds}{d \theta} = \sqrt{ r^2+ r^{\prime^2}+z^{\prime ^2} } $$
which can be integrated in closed form using relations for polar forms:
$$ r= \dfrac{a}{1-\cos \theta}  $$
$$ r{\prime }= \dfrac{a\sin \theta}{(1-\cos \theta)^2}  $$
$$ \theta_{dev} = \theta \sin \alpha $$
$$ r_{dev}  = \rho = r/ \sin \alpha $$
$ \theta$  is projected angle $ \rho$ true radius in development.
EDIT 3
2- dimensional straight-forward calculation:
$$ x = 2 f t, y= f t^2, \,  \frac{dy}{dx} = t = \tan \phi \tag1 $$
$$   y= \frac{x^2}{4f},\,  y^{\prime \prime} = \frac{1}{2 f }, \quad \kappa = \frac{1/2f}{(1+\tan ^2 \phi)^{3/2}} \tag2 $$
$$ 2f \kappa = 2f \frac{ d\phi}{ds}= \cos^3\phi \tag3 $$
$$ ds = 2f \frac{d \phi} {\cos ^3 \phi} \tag4 $$
$$ \frac{s}{ 2f}= \int \sec^3 \phi \, d \phi \tag5  $$
$$\frac{s}{ f} =  log\, \frac{1+\tan \phi/2}{1-\tan \phi/2} + \sec\phi \tan \phi \tag6 $$
as arbitrary constant zero at parabola vertex. This can be expressed in terms of $x,t, x = 2 f \tan \phi, $ hyperbolic functions etc., please cross verify.


text:
Q: php - inserting the values of multiple checkbox selections the site i'll be refering to is
http://www.iaddesignandstudio.com/offline select the quote tab
if a person where to fill out this form and select more than one checkbox in either number 1 or number 3. how would i insert those selected values into a database so that when i retreive the information the user inputed or selected i can see which checkboxes he/she selected?

A: You can set your checkboxes to be in one array after the form is submitted by adding [] at the end of the name attribute like such:
<input type="checkbox" name="services[]" value="Podcasting Services" />
Podcasting Services
<input type="checkbox" name="services[]" value="Local Search" />Local Search

When the form is submitted, your $_POST['services'] variable will be an array containing all checked values. ex:
#var_dump($_POST['services']);
array(2) {
  [0]=>
  string(19) "Podcasting Services"
  [1]=>
  string(12) "Local Search"
}

Then you can do anything you want with that, wether it be sending an email or adding fields to the database using ether foreach() or implode() to loop through the values.
Hope this helps!

A: I would have separate fields in the database for them. Like in question 1, the posted form might submit $_POST['admycomp'] and $_POST['provideresource'] as having been checked. If so, insert a 1 into the database field admycomp or provideresource. That way you have recorded which fields they checked.

A: I would suggest storing the values in your database would be to use the SET datatype (eg: http://dev.mysql.com/doc/refman/5.0/en/set.html). This would store each of the checkbox values from a checkbox group in a single column in a storage-efficient way. You would probably need to use implode as mentioned above to create an SQL query to insert your set.


text:
Q: NodeJS : Share a log module instance inside my app I create for my project a log module and i am actually creating a new instance in all module to allow them to log in cli with the right syntax,color conf etc.
For example (a simplified example)
// index.js

const {Log,Ansi} = require("./class/log.js");
const Tool       = require("./class/tool.js");
const argv       = require("yargs").argv;

let log = new Log({
   levelIcon:true,
   powerlineRoot:{
       name:"root",
       backgroundColor:Ansi.BLACK_BRIGHT,
       text: "myappName"
   }
});

let tool = new Tool(argv.toolName,argv.envName)

tool.run().then(() => {
   log.print("Tool is running","info");
}).catch((err) => {
   log.print(err,"critical");
});

// tool.js

const {Log,Ansi} = require("./log.js");

class Tool {

    let log = new Log({
        levelIcon:true,
        powerlineRoot:{
            name:"root",
            backgroundColor:Ansi.BLACK_BRIGHT,
            text: "myappName"
        }
    });

    run(){

        return new Promise((resolve, reject) => {
            resolve()
        }

    }
}

module.exports = Tool

I am wondering if there is a way to create only one instance in my index.js and share it with the instance of modules like Tools. I don't know if it's possible but i think that it will be less memory consumption to share one instance of Log than creating multiple one
I hope that my question is enough clear. Feel free to ask me more information if needed

A: Yes you can do that absolutely. Since the entry is index.js you can consider it will finally run as if it was a single file, in a single thread. You can create one more module logger.js like:
const {Log,Ansi} = require("./class/log.js");

const logger = new Log({
   levelIcon:true,
   powerlineRoot:{
       name:"root",
       backgroundColor:Ansi.BLACK_BRIGHT,
       text: "myappName"
   }
});
module.exports = logger;

Now you can just import logger and use it like:
const logger = require("./logger")
logger.print("hello world!");

A: Like @jjsingh says i use global variable to store the object.
Not sure it's the better way but for the moment it resolve my issue.
        global.log = new Log({
             levelIcon:true,
             powerlineRoot:{
                 name:"root",
                      color:{
                          background:Ansi.BLUE_SEA,
                          foreground:Ansi.RED,
                 },
                 text:global.conf.get("infos").name
            }
        });


text:
Q: Channel Declaration in UPPAAL Why isn't the UPPAAL-compiler throwing an error when I declare a channel within a template section?
If I got it right, no other Template can access these Channels, thus Channel declaration only appears to make sense in the overall Declaration section.
Or am I overlooking something?
Thanks!
PS I'd like to model "internal" Template communication via synchronous channels and hoped that declaring a channel within a Template might be a solution. The upper question just appears to be easier to pose and answer :)

A: You can have urgent broadcast chan ASAP locally and force urgent transitions without synchronizing with anything.
As for the "internal" communication you can share specific channels by passing a channel reference as a parameter and use only channel declarations from the system declaration section.