text:
Q: Edit Listing Form is Duplication I have a listing system on my website and am currently creating a page which allows the user to edit their listing, I've got most of it working however I am stuck on saving their updated form. Currently if they save the edited form rather than updating the model it creates a whole new listing entry and still leaves the old one there. If anyone could please look at my code that would be great, I've been stuck on this problem for so long!
View -
@login_required(redirect_field_name='login')
def editlisting(request, pk):

    post = JobListing.objects.get(pk=pk)

    if str(request.user) != str(post.user):
        return redirect("index")

    if request.method == "POST":
        print("test")
        form = JobListingForm(request.POST, instance=post, force_update=True)

        if form.is_valid():
            form.save()
            return redirect('index')

    else:
        print("else")
        form = JobListingForm(instance=post)

    context = {
        "form": form
    }

    return render(request, "editlisting.html", context)

Model -
class JobListing(models.Model):

    region_choice = (
        ('Auckland', 'Auckland'),
        ('Wellington', 'Wellington'),
        ('Christchurch', 'Christchurch')
    )
    industry_choice = (
        ('Accounting', 'Accounting'),
        ('Agriculture, fishing & forestry', 'Agriculture, fishing & forestry'),
        ('Automotive', 'Automotive'),
        ('Banking, finance & insurance', 'Banking, finance & insurance'),
        ('Construction & Architecture', 'Construction & Architecture'),
        ('Customer service', 'Customer service'),
    )
    employment_type_choice = (
        ('Full Time', 'Full Time'),
        ('Part Time', 'Part Time'),
        ('One-off', 'One-off'),
        ('Other', 'Other')
    )

    user = models.CharField(max_length=50)
    job_title = models.CharField(max_length=30)
    pay_rate = models.DecimalField(max_digits=10, decimal_places=2)
    employment_type = models.CharField(max_length=10, choices=employment_type_choice)
    job_description = models.CharField(max_length=2000)
    business_address_region = models.CharField(max_length=50, choices=region_choice)
    business_address_suburb = models.CharField(max_length=50)
    business_industry = models.CharField(max_length=50, choices=industry_choice)
    email = models.EmailField(max_length=50, blank=True, null="True")
    telephone = models.IntegerField(blank=True, null='True')
    active_listing = models.BooleanField(default=True)

    class Meta:
        verbose_name = 'Job Listing'

    def clean(self):
        if not (self.email or self.telephone):
            raise ValidationError("You must specify either email or telephone")
        if not self.email:
            self.email = "Not Provided"

    def __unicode__(self):
        return "%s" % self.job_title

Piece of code from my registration app which could be affecting it?
def signup(self, request, user):
    SignUpProfile.objects.create(
        user=user,
        account_type=self.cleaned_data['account_type'],
        contact_number=self.cleaned_data['contact_number']
    )

Form -
class JobListingForm(forms.ModelForm):

    class Meta:
        model = JobListing
        fields = ['job_title', 'pay_rate', 'employment_type', 'job_description', 'business_address_region',
            'business_address_suburb', 'business_industry', 'telephone', 'email']
        widgets = {
            'job_title': forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Job Title'}),
            'pay_rate': forms.NumberInput(attrs={'class': 'form-input', 'placeholder': 'Hourly Rate or One Off Amount'}),
            'employment_type': forms.Select(attrs={'class': 'form-input'}),
            'job_description': forms.Textarea(attrs={'class': 'form-textarea',
                'placeholder': 'Tell us additional information about your job listing e.g. Times, Business Info, Number of positions etc. (2000 Character Limit)'}),
            'business_address_region': forms.Select(attrs={'class': 'form-input'}),
            'business_address_suburb': forms.TextInput(attrs={'class': 'form-input', 'placeholder': 'Business Suburb'}),
            'business_industry': forms.Select(attrs={'class': 'form-input'}),
            'email': forms.EmailInput(attrs={'class': 'form-input', 'placeholder': 'Email'}),
            'telephone': forms.NumberInput(attrs={'class': 'form-input', 'placeholder': 'Contact Numnber'}),
        }

Form HTML -

Edit Your Job Listing

    <form class="createjoblisting" id="createjoblisting_form" method="post" action="{% url 'createjoblisting' %}">
        {% csrf_token %}
        {{ form.non_field_errors }}

 Job Title

        {{ form.job_title }}

{{ form.job_title.errors }}

Pay Rate

        {{ form.pay_rate }}

{{ form.pay_rate.errors }}

Employment Type

        {{ form.employment_type }}

{{ form.employment_type.errors }}

Job Description

        {{ form.job_description }}

{{ form.job_description.errors }}

Business Region

        {{ form.business_address_region }}

{{ form.business_address_region.errors }}

Business Suburb

        {{ form.business_address_suburb }}

{{ form.business_address_suburb.errors }}

Business Industry

        {{ form.business_industry }}

{{ form.business_industry.errors }}

Contact Number (Must provide either Contact Number or Email)

        {{ form.telephone }}

{{ form.telephone.errors }}

Email

        {{ form.email }}

{{ form.email.errors }}
        <button type="submit" class="form-button">Update Job Listing</button>
    </form>

URLS -
urlpatterns = [
    url(r'^createjoblisting/', views.createjoblisting, name='createjoblisting'),
    url(r'^(?P<pk>[0-9]+)/editprofile/', views.editprofile, name='editprofile'),
    url(r'^(?P<pk>[0-9]+)/editlisting/', views.editlisting, name='editlisting'),
    url(r'^editlistingportal/', views.editlistingportal, name='editlistingportal'),
]

A: Your form's action is wrong. Change it to:
<form action="{% url 'editlisting' %}" class="createjoblisting" id="createjoblisting_form" method="post" >

As you have copied the creation template, your form posts your data to the view which creates the listing instead of editing it.


text:
Q: How do I replace colours in a movieclip? I am trying to take a movieclip of a character and change the colour of their clothes. The character is comprised of vectors.
So far I have semi-sucessfully used this method:

*

*stop the movieclip

*take the bitmap data from the current frame

*use threshold to replace the colour

*store the resulting bitmap data in an array

*add an onenterframe function - clear the current frame and add the bitmap data from the processed data in the array

So - this works pretty well. Each frame is only processed once at the beginning and then the write to the movieclip is very quick.
However! As the replacement is being performed on a bitmap there is an amount of aliasing that takes place to remove jaggies/pixelation. This produces colours that are not matched using threshold. So the main colour is replaced correctly but it is surrounded by a halo of mixed colours :(
I am sure there should be a better way to do this. Any ideas or answers would be greatly apreciated - Thanks.

A: Would playing with Grant Skinner's easier to use ColorMatrix class ) get the job done ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apache not able to restart Trying to restart apache from terminal using the following command:
 sudo service apache2 restart

When executing that command, I'm getting below error:
Job for apache2.service failed. See "systemctl status apache2.service" and "journalctl -xe" for details.

On excuting "systemctl status apache2.service" I get this output:
apache2.service - (null)
   Loaded: loaded (/etc/init.d/apache2)
   Active: failed (Result: exit-code) since Sat 2015-05-30 02:22:41 IST; 12s ago
     Docs: man:systemd-sysv-generator(8)
  Process: 4866 ExecStart=/etc/init.d/apache2 start (code=exited, status=1/FAILURE)

Apache error.log:
AH00489: Apache/2.4.12 (Unix) configured -- resuming normal operations
AH00094: Command line: '/usr/local/apache2/bin/httpd'

A: Maybe this will help to find the cause:
journalctl | tail

In my case it was a mistake in the configuration file:
AH00526: Syntax error on line 5 of /etc/apache2/sites-enabled/mydomain-wsf.lan.conf

A: Problem:
Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details.

Solution:

*

*To fully remove the apache2 config files, you should:
1) sudo apt-get purge apache2

*which will then let you reinstall it in the usual way with:
2) sudo apt-get install apache2
==> It Works fine...
thanks....

A: I got the same error after removing a virtual host. The problem was the lingering SSL conf file associated with that host located in /etc/apache2/sites-enabled. The SSL was through Let's Encrypt so the code for me to remove was:
sudo rm yourdomain.com-le-ssl.conf

A: The problem is because some configuration files are deleted, you have to reinstall it.
REINSTALL APACHE2:
To replace configuration files that have been deleted, without purging the package, you can do:
sudo apt-get -o DPkg::Options::="--force-confmiss" --reinstall install apache2

To fully remove the apache2 config files, you should:
sudo apt-get purge apache2

which will then let you reinstall it in the usual way with:
sudo apt-get install apache2

Purge is required to remove all the config files - if you delete the config files but only remove the package, then this is remembered & missing config files are not reinstalled by default.
Then REINSTALL PHP5:
apt-get purge libapache2-mod-php5 php5 && \
apt-get install libapache2-mod-php5 php5

A: you most likely have a syntax error. for me it was in my 'sites-enabled' folder.
i mis-spelled 'ServerAlias' to 'ServerAlisa'.

A: There is some syntax error in the file apache2.conf.
In a terminal, type:
cd /etc/apache2

Then:
apache2ctl configtest

It will show you where is the error in the apache2.conf file to correct.

A: I got the Same errors While working with .htaccess
I just put this command
<Directory /var/www/html>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
</Directory>

in /etc/apache2/sites-enabled/000-default.conf this folder
after adding this i have getting the error
then i delete these peace of command from the file and my error has resolved.

A: This is mostly a configuration error. I just now had an old site enabled on apache, what caused this error. So I had to disable it before reloading apache.
sudo a2dissite <my-site>
sudo service apache2 reload

Problem solved :)

A: Thank you for your help! I was able to install correctly with Solution:
To fully remove the apache2 config files, you should:

*

*sudo apt-get purge apache2
which will then let you reinstall it in the usual way with:

*sudo apt-get install apache 2
It now works fine.

A: I think the problem is that you have some site enabled but you deleted its configuration file. Try disabling the site with
    sudo a2dissite "name"
and then restart apache server. At least this was the problem for me and this action solved it.

A: In my case, the error started to appear after doing apt upgrade. After playing a lot I went to following directories to see what I can disable.

*

*/etc/apache2/mods-enabled - a2dismod  (to turn back on a2enconf)

*/etc/apache2/conf-enabled - a2disconf   (to turn back on a2enconf)

In my case, I had to those MODS enabled.

It seems that apt-upgrade must have removed/broken php7.2 because as soon as I disabled it and restarted everything worked. Of course, in anyone else's case, it may be something different. When Apache crashes it may be bad config or bad mod. You have to pick your battles.

A: For what it may be relevant at this stage, but today I came across the same problem and it turned out to be an issue with the certificate file.
So eventually the config was all ok, but in uploading the new .crt content I did in the wrong file, meaning there were no more matching for a particular site and the whole server was refusing to start.
No indication of incorrect SSL certificate in the log or anywhere else, which took me a while to figure out.


text:
Q: No gradient of color with geom_raster I'm trying to plot a raster image (ocean bathymetry) with geom_raster but I'm having a hard time to crack down the code. I would appreciate any help.
I've downloaded the following xyz file (Dropbox link).
SF.bath <- read.table("SF_bath.txt", header=F,col.names=c("lon","lat","z"))
> head(SF.bath)
       lon     lat   z
1 -67.9917 50.9968 757
2 -67.9750 50.9968 693
3 -67.9583 50.9968 673
4 -67.9417 50.9968 769
5 -67.9250 50.9968 761
6 -67.9084 50.9968 733

When I try the following code, the colours do not show on my map?
v <- ggplot(SF.bath, aes(lon, lat,z=z))
print(v + geom_raster(aes(fill=z)) + stat_contour(size=0.2) + scale_fill_gradient("z"))

I get the following message: Using alpha as value column: use value_var to override. Any ideas of what might be the problem?

A: EDITED to emphasize the key answer
The code in the question with the provided dataset achieves the desired result:

After discussion in the comments, the key lesson turns out to be a suggestion that when the system behaves strangely, it may be wise to update.packages() as part of troubleshooting.


text:
Q: Declaring important oglplus objects throws the exception oglplus::MissingFunction I want to create C++ programs using OpenGL with the C++ OpenGL wrapper library oglplus, but I can't get programs using oglplus to run because when I declare certain oglplus objects the oglplus::MissingFunction exception is always thrown.
My OS is archlinux.
My programs compile but don't run. For example:
#include <cassert>
#include <iostream>

#include <GL/glew.h>
#include <GL/glut.h>

#include <oglplus/all.hpp>

int main()
{
    oglplus::VertexShader vs;
    return 0;
}

This program compiles, but when I run it, the exception oglplus::MissingFunction is thrown.
Since my programs compile, I believe this means I have the necessary packages installed and have the correct libraries linked. I just don't understand why the exception is being thrown. The description of the exception says that the occurrence of it being thrown means that some pointers used to call OpenGL functions are uninitialized.
So far I've observed oglplus::MissingFunction being thrown when I declare objects of types:

*

*oglplus::VertexShader

*oglplus::FragmentShader

*oglplus::Program

*oglplus::Program

*oglplus::VertexArray

*oglplus::Buffer

Any suggestions as to how to solve this problem?

A: Before you can use any OpenGL resources, you need to create an OpenGL context. This example shows how to set up a context using GLUT:
https://github.com/matus-chochlik/oglplus/blob/develop/example/standalone/001_hello_glut_glew.cpp
Essentially, you need this part:
#include <iostream>

#include <GL/glew.h>
#include <GL/glut.h>

#include <oglplus/all.hpp>

int main(int argc, char* argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);

    GLint width = 800;
    GLint height = 150;

    glutInitWindowSize(width, height);
    glutInitWindowPosition(100,100);
    glutCreateWindow("OGLplus+GLUT+GLEW");

    if(glewInit() == GLEW_OK) try
    {
        // Your code goes here.

        return 0;
    }
    catch(oglplus::Error& err)
    {
        std::cerr << "OGLPlus error." << std::endl;
    }

    return 1;
}


text:
Q: How to find a point on 2-d weighted map, which will have equidistant (as close as possible) paths to multiple endpoints? So let's say I got a matrix with two types of cells: 0 and 1. 1 is not passable.
I want to find a point, from which I can run paths (say, A*) to a bunch of destinations (don't expect it to be more than 4). And I want the length of these paths to be such that l1/l2/l3/l4 = 1 or as close to 1 as possible.
For two destinations is simple: run a path between them and take the midpoint. For more destinations, I imagine I can run paths between each pair, then they will create a sort of polygon, and I could grab the centroid (or average of all path point coordinates)? Or would it be better to take all midpoints of paths between each pair and then use them as vertices in a polygon which will contain my desired point?

A: It seems you want to find the point with best access to multiple endpoints. For other readers, this is like trying to found an ideal settlement to trade with nearby cities; you want them to be as accessible as possible. It appears to be a variant of the Weber Problem applied to pathfinding.
The best solution, as you can no longer rely on exploiting geometry (imagine a mountain path or two blocking the way), is going to be an iterative approach. I don't imagine it will be easy to find an optimal solution because you'll need to check every square; you can't guess by pathing between endpoints anymore. In nearly any large problem space, you will need to path from each possible centroid to all endpoints. A suboptimal solution will be fairly fast. I recommend these steps:

*

*try to estimate the centroid using geometry, forming a search area

*Use a modified A* algorithm from each point S in the search area to all your target points T to generate a perfect path from S to each T.

*Add the length of each path S -> T together to get Cost (probably stored in a matrix for all sample points)

*Select the lowest Cost from all your samples in the matrix (or the entire population if you didn't cull the search space).

The algorithm above can also work without estimating a centroid and limiting solutions. If you choose to search the entire space, the search will be much longer, but you can find a perfect solution even in a labyrinth. If you estimate the centroid and start the search near it, you'll find good answers faster.
I mentioned earlier that you should use a modified A* algorithm... Rather than repeating a generic A* search S->Tn for every T, code A* so that it seeks multiple target locations, storing the paths to each one and stopping when it has found them all.
If you really want a perfect solution to the problem, you'll be waiting a long time, so I recommend that you use any exploit you can to reduce wasteful calculations. Even go so far as to store found paths in a lookup table for each T, and see if a point already exists along any of those paths.
To put it simply, finding the point is easy. Finding it fast-enough might take lots of clever heuristics (cost-saving measures) and stored data.


text:
Q: jQuery :visible is true while executing hiding animations I realize that this is how it's supposed to behave, but it creates a problem when I'm trying to determine the visibility of an element while it's in the process of hiding (or showing if I invert when ':animated' is true).
So how can I use jQuery to determine whether an element is visible, with the caveat that elements currently visible but in the process of hiding themselves are considered hidden (not current behavior) and elements in the process of showing themselves continue to be considered visible (current behavior)?
The problem is made worse by the fact that the check for :visible happens in jQuery events, so there's no direct code path from where the element is shown/hidden to where the visibility check needs to happen.  Therefore, I can't just pass an animation status through all the functions in between.
Here's some code to illustrate the problem:

    <input id="btn" name="btn" type="button" onclick="toggle();" value="Click Me!"/>

    I am the text!

A: Is it possible to use the animation callback methods to guarantee the final state of the element instead of querying and possibly getting an incorrect status.  Since your example is contrived to simply demonstrate the problem it's hard to know if this would be applicable to your application, but I almost always find that putting the code that is dependent on the animation being completed in a callback is easier than working around the animation process.


text:
Q: What is a "request scoped variable" in JSF I was reading an article titled: "JSF 2 GETs Bookmarkable URLs".
The article has the following paragraph:

Introducing view parameters
  The API documentation describes a view parameter, represented by the javax.faces.component.UIViewParameter component class, as a declarative binding between a request parameter and a model property. The binding to the model property is expressed using an EL value expression (e.g., #{blog.entryId}). If the expression is omitted, the request parameter is bound instead to a request-scoped variable with the same name.

Could someone kindly provide an example of a request scoped variable.

A: A "request scoped variable" is an variable which is stored as an attribute of the HttpServletRequest.
request.setAttribute("foo", foo);

This attribute is available in EL the usual way by #{foo}. The HttpServletRequest itself has a lifetime of exactly one HTTP request-response cycle. Once the HTTP response associated with the HTTP request has arrived fully at the client (the webbrowser), then the HttpServletRequest instance, including all of its attributes, is garbaged. JSF request scoped managed beans are by the way also stored as an attribute of the HttpServletRequest.
As JSF runs "on top" of the basic HTTP Servlet API, this is all easier to understand if you also understand how HTTP and the Servlet API work. This answer might give some enlightenment: How do servlets work? Instantiation, sessions, shared variables and multithreading.

Your subsequent question shall probably be "How is this related to the quoted paragraph then?" Well, it is basically telling that, when you omit the value attribute of the <f:viewParam>, that it instead is been put as a variable in the request scope.
So, if you use
<f:viewParam name="entryId" />

instead of
<f:viewParam name="entryId" value="#{blog.entryId}" />

then it becomes available as #{entryId} in the request scope.

The entry ID view parameter is: #{entryId}

This is however not the way view parameters are usually been used. You'd alternatively also just have used the #{param} map instead, hereby making the whole <f:viewParam> superfluous.

The entry ID view parameter is: #{param.entryId}

See also:

*

*ViewParam vs @ManagedProperty(value = "#{param.id}")

A: A request scoped variable is instancinated for a each single request. So a request scoped variable instance does not exist in the context of another request.

A: A request scoped variable is, as the name implies, only valid in the current http request. A good use for request variables is when forwarding a request from a servlet to jsp. E.g set the variable in servlet, later read the same variable in jsp with ${myvar}
example(servlet)
request.setAttribute ("greeting", "world");
getServletConfig().getServletContext().getRequestDispatcher("/jsp/page.jsp").forward(request, response);

example(jsp)
    Hello ${greeting}

A: id is mapped with entryId in Managed-bean config or u can use annotations.
<managed-bean>
   <managed-bean-name>blog</managed-bean-name>
   <managed-bean-class>com.acme.Blog</managed-bean-class>
   <managed-property>
     <property-name>entryId</property-name>
      <value>#{param['id']}</value>
   </managed-property>
</managed-bean>

@RequestScope: (this is the default scope of a managed bean). This puts the bean in request scope. It makes a new instance for every HTTP request. Commonly, the bean is instantiated twice, once when form is displayed and once when it is submitted.


text:
Q: Google sheet SendEmail Script send a message to the same email address multiple times/ It hasn't happened untill today. Any way To solve it? Stack overflowers!
I have a problem with my Sendemail Script, which is sending the same message for 8 times (really annoying, isn't it?) to each mail address. (It has been working fine until today though, I send remainders to five people daily; and my google sheet has two columns, one is for email address and the other is the message)
My code looks like this:
function sendEmails() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2; // First row of data to process
  var numRows = 5; // Number of rows to process
  // Fetch the range of cells A2:B6
  var dataRange = sheet.getRange(startRow, 1, numRows, 5);
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i in data) {
    var row = data[I];
    var emailAddress = row[0]; // First column
    var message = row[1]; // Second column
    var subject = 'ATTENTION!!!!!!';
    MailApp.sendEmail(emailAddress, subject, message);
  }
}

How can I solve this annoying problem? (I am not a developer; I am just a learner who can use internet sources very well; So, I don't understand scripts much and still can edit or change it a bit.)

A: There is currently a bug with time-driven triggers
As a consequence, the trigger might fire multiple times - more frequent than you specify.
You can "star" the issue on Google's Issue Tracker to indicate that you are also concerned.
In the meantime, as a workaround:

*

*Use Script Properties to save the last execution time

*Implement an if statement at the beginning of your code that executes the rest of the code only if the last execution time (retrieved from the script properties) is not less than the specified interval

Sample:
function sendEmails() {
  if(!PropertiesService.getScriptProperties().getProperty("lastExecution")){
    PropertiesService.getScriptProperties().setProperty("lastExecution", new Date().getTime());
  }
  var lastExecution = PropertiesService.getScriptProperties().getProperty("lastExecution");
  var now = new Date().getTime();
  var oneDay = 1000*3600*24;
  if(now-lastExecution >= oneDay){
    //here the rest of you code
    var sheet = SpreadsheetApp.getActiveSheet();
    var startRow = 2; // First row of data to process
    var numRows = 5; // Number of rows to process
    // Fetch the range of cells A2:B6
    var dataRange = sheet.getRange(startRow, 1, numRows, 5);
    // Fetch values for each row in the Range.
    var data = dataRange.getValues();
    for (var i in data) {
      var row = data[I];
      var emailAddress = row[0]; // First column
      var message = row[1]; // Second column
      var subject = 'ATTENTION!!!!!!';
      MailApp.sendEmail(emailAddress, subject, message);
      PropertiesService.getScriptProperties().setProperty("lastExecution", now);
    }
  }
}


text:
Q: Skaffold 1.4.0: "Skipping deploy due to sync error: copying files:" Using:

*

*Skaffold 1.4.0

*minikube 1.6.2

*kubectl: client 1.15.5 and server 1.17.0

*Django 3.0.3

*Python 3.8.2
I just recently started receiving this error as I'm working on a Django API. Anytime I save after making a change I get a:
WARN[0234] Skipping deploy due to sync error: copying files: Running [kubectl --context minikube exec api-deployment-6946878554-n7lc2 --namespace default -c api -i -- tar xmf - -C / --no-same-owner]
 - stdout:
 - stderr: error: unable to upgrade connection: container not found ("api")
: exit status 1

Not sure what has changed to cause this. I have to do a CTRL + C to shutdown Skaffold and restart it to get the changes to be reflected.
This is my skaffold.yaml:
apiVersion: skaffold/v1beta15
kind: Config
build:
  local:
    push: false
  artifacts:
    - image: postgres
      context: postgres
      docker:
        dockerfile: Dockerfile.dev
      sync:
        manual:
          - src: "***/*.sql"
            dest: .
    - image: testappacr.azurecr.io/test-app-api
      context: api
      docker:
        dockerfile: Dockerfile.dev
      sync:
        manual:
          - src: "***/*.py"
            dest: .
deploy:
  kubectl:
    manifests:
      - manifests/dev-ingress.yaml
      - manifests/postgres.yaml
      - manifests/api.yaml

Also the api.yaml:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      component: api
  template:
    metadata:
      labels:
        component: api
    spec:
      containers:
        - name: api
          image: testappacr.azurecr.io/test-app-api
          ports:
            - containerPort: 5000
          env:
            - name: PGUSER
              valueFrom:
                secretKeyRef:
                  name: test-app-secrets
                  key: PGUSER
            - name: PGHOST
              value: postgres-cluster-ip-service
            - name: PGPORT
              value: "1423"
            - name: PGDATABASE
              valueFrom:
                secretKeyRef:
                  name: test-app-secrets
                  key: PGDATABASE
            - name: PGPASSWORD
              valueFrom:
                secretKeyRef:
                  name: test-app-secrets
                  key: PGPASSWORD
            - name: SECRET_KEY
              valueFrom:
                secretKeyRef:
                  name: test-app-secrets
                  key: SECRET_KEY
            - name: DEBUG
              valueFrom:
                secretKeyRef:
                  name: test-app-secrets
                  key: DEBUG
          livenessProbe:
            tcpSocket:
              port: 5000
            initialDelaySeconds: 2
            periodSeconds: 2
          readinessProbe:
            tcpSocket:
              port: 5000
            initialDelaySeconds: 2
            periodSeconds: 2
          volumeMounts:
          - mountPath: "/mnt/test-app"
            name: file-storage
      volumes:
        - name: file-storage
          persistentVolumeClaim:
            claimName: file-storage
---
apiVersion: v1
kind: Service
metadata:
  name: api-cluster-ip-service
spec:
  type: ClusterIP
  selector:
    component: api
  ports:
    - port: 5000
      targetPort: 5000

Any suggestions about what might be going on here?

A: Figured out the issue was caused by my readinessProbe and livenessProbe in the api.yaml.
          livenessProbe:
            tcpSocket:
              port: 5000
            initialDelaySeconds: 2
            periodSeconds: 2
          readinessProbe:
            tcpSocket:
              port: 5000
            initialDelaySeconds: 2
            periodSeconds: 2

Now I don't get this error.
However, the reason I had them there in the first place was because skaffold will sometimes boot up the database after the API, causing it to fail. So that is the trade off in my case: without probes DB occasionally boots after API causing failure or have them and it more frequently results in the error related to this question.

A: For others completely new to Kubernetes, note that this error can occur simply because your server script/process completed before the skaffold-sync command was attempted; kubernetes interprets the ending of your process as meaning that it failed, and therefore closes the container (or at least makes it so that skaffold is unable to make a call into it to apply the file sync).
More info here: How can I keep a container running on Kubernetes?
So the solution is to "keep your process alive", by having it run a sleep-and-log loop or something. (even if it has no real work left to do, eg. if you just wrote a test script that logs and exits)
NodeJS example:
console.log("Test server-script started!");

// loop forever, to keep process alive, so kubernetes doesn't kill the container, so skaffold-sync can work
while (true) {
    console.log("Keep-alive loop. Time:", Date.now());
    await new Promise(resolve=>setTimeout(resolve, 1000));
}


text:
Q: Can you call an external API to shorten links based on google sheets input? I have a spreadsheet that contains links created after a form entry. I'd like to call the external API of a link shortening service (not google's link shorten-er) to take the link created in a given cell, shorten it, return the value and have Google Apps Script insert that shortened link into a new cell.
Is this possible? Specifically, can I use jQuery's AJAX methods? Where should I start.

A: By checking the internet, I found this stackExchange question, you can try to follow the solution in this post. What you need here is URL shortener API under the resources in the script editor (Tools > Script editor) select the Advanced Google Services and activate the UrlShortener.
Here is the sample code that you need to use.
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("Shorten")
.addItem("Go !!","rangeShort")
.addToUi()
}

function rangeShort() {
var range = SpreadsheetApp.getActiveRange(), data = range.getValues();
var output = [];
for(var i = 0, iLen = data.length; i < iLen; i++) {
var url = UrlShortener.Url.insert({longUrl: data[i][0]});
output.push([url.id]);
}
range.offset(0,1).setValues(output);
}

For more information, explanation and some sample pictures, just check the link above.


text:
Q: Android : setText on TextView which programmatically generated so I want to have a X number of TextView which is programmatically created and added to its parrent layout, and set each textView with different text depends on its id.
I already manage to created and added X number of TextView into its parrent Layout ,although I'm not sure do I manage to give each of them different id which I created manually with simple string manipulation and store them inside a HashMap.
next step, I try to get each TextView with findViewById() using the id from HashMap and setText each TextView but I have no idea why my TextView is still blank. I already try to hardcode the text directly when the TextView is created but it still give me blank view, but this seems only happen with TextView, I also tried add X number ImageView programmatically with the same way I add the TextView, and setImageResourse depends on each id, and it works
honestly, I dont know where my mistake and I hope you can point me in the right direction .Thanks
I'm using minimal SDK Jelly Bean 4.2.2(API 17)
here's my onCreate()
int allEventNumber,imageId,textNameId,textDateId,textTappedId = -1;
    LinearLayout layoutUtama,eventLayout,detailLayout;
    ImageView thumbnailImageView;
    TextView textViewName,textViewDate,textViewTapped;
    String  imageIdKey,textNameIdKey,textDateIdKey,textTappedIdKey,textDate,textTapped,textName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event);
        HashMap<String,Integer> keyId = new HashMap<String,Integer>();
        keyId = initAll(keyId);
        fillAllById(allEventNumber,keyId);

    }

initAll(HashMap)
public HashMap<String,Integer> initAll(HashMap<String,Integer> hMap){
        allEventNumber = 6;     //hardcode
        layoutUtama = (LinearLayout) findViewById(R.id.layout_utama);
        hMap = insertLayout(hMap,allEventNumber);
        return hMap;
    }

insertLayout(HashMap, int)
public HashMap<String,Integer> insertLayout(HashMap<String ,Integer> hMap, int jumlahEvent){
        //

        for (int i =1;i<= jumlahEvent;i++){

            eventLayout = new LinearLayout(this);
            eventLayout.setOrientation(LinearLayout.HORIZONTAL);
            eventLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT));

            thumbnailImageView = new ImageView(this);
            imageIdKey = "key_image_view_" + i;
            imageId = View.generateViewId();
            hMap.put(imageIdKey,imageId);
            thumbnailImageView.setId(imageId);
            thumbnailImageView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));

            detailLayout = new LinearLayout(this);
            detailLayout.setOrientation(LinearLayout.VERTICAL);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            layoutParams.setMargins(15,0,0,0);
            detailLayout.setLayoutParams(layoutParams);
            detailLayout.setGravity(Gravity.CENTER);

            textViewName = new TextView(this);
            textNameIdKey = "key_text_view_name_" + i;
            textNameId = View.generateViewId();
            hMap.put(textNameIdKey,textNameId);
            textViewName.setId(textNameId);
            textViewName.setGravity(Gravity.LEFT);
            textViewName.setTextSize(R.dimen.event_name_text_size);
            textViewName.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

            detailLayout.addView(textViewName);
            eventLayout.addView(thumbnailImageView);
            eventLayout.addView(detailLayout);
            layoutUtama.addView(eventLayout);

        }
        return hMap;
    }

fillAllById(int,HashMap)
public void fillAllById(int allEventNumber,HashMap<String,Integer> hMap){
        for (int i=1;i<=allEventNumber;i++){
            imageIdKey = "key_image_view_" + i;
            textNameIdKey = "key_text_view_name_" + i;
            imageId = hMap.get(imageIdKey);

            textNameId = hMap.get(textNameIdKey);

            thumbnailImageView = (ImageView) findViewById(imageId);
            textViewName = (TextView) findViewById(textNameId);

            thumbnailImageView.setImageResource(R.drawable.thumbnail_event3);
            textName = "Name Event";

            textViewName.setText(textName);
        }
    }

and my xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="0dp"
    android:paddingRight="0dp"
    android:paddingTop="0dp"
    android:paddingBottom="0dp"
    tools:context="com.example.hansel.tapbandung_v00.Event">
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true">
    <LinearLayout
        android:id="@+id/layout_utama"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginBottom="0dp">

            </LinearLayout>
    </ScrollView>
</RelativeLayout>


text:
Q: How do I query data from the database base on user in a completely separated frontend Django REST So I have this basic model:
class Text(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=255)

    def __str__(self):

        return self.title

so usually when you're using regular Django and you want to query Text from the database based on the user you would do:
def main_page(request):

    userTexts = Text.objects.filter(user=request.user)

    context = {}
    return render(request, '', context)

but now I've been using Django REST React stack and built a completely separated frontend and the only way I access the data from the backend is by making HTTP request to it, so now request.user wont work anymore because it's just going to return anonymousUser
fortunately though I already have an authentication system working and already have a user object inside my react state all I have to do is design a view and an API call to query the data from the backend
but I cant imagine how to do both of those things.

A: Actually, here is no matter how you try to access backend URL, directly inserting it in browser bar or using React's xhr.
You just need to set session cookies for backend URL (domain.com:port) that is not accessible by javascript in perfect world:

A cookie with the HttpOnly attribute is inaccessible to the JavaScript
Document.cookie API; it is sent only to the server. For example,
cookies that persist server-side sessions don't need to be available
to JavaScript, and should have the HttpOnly attribute. This precaution
helps mitigate cross-site scripting (XSS) attacks.

anonymousUser means that session cookie is not set and authentication (login) process didn't complete.
Why it happens? I don't know, it depends on backend architecture, login process details, etc...
And don't forget to set proper CORS policies if frontend's and backend's domain.com:port are different.


text:
Q: Can I insert ACF repeater fields into MaxMegaMenu via JS? I have to add a Slick slider with ACF repeating fields to MaxMegaMenu, unfortunately I don't know how to add such a large piece of code via Javascript (passing js Var?). Has anyone tried to add ACF repeater using Javascript?
My code below
++++++++++++++++
<?php if ( have_rows('postgraduate_studies', 'option') ) :
 while( have_rows('postgraduate_studies', 'option') ) : the_row(); ?>

    <?php the_sub_field('sub_field_name', 'option'); ?>
    <div style="background-image: url( <?php the_sub_field('postgraduate_studies_image', 'option'); ?>);"  class="">
      <a href="<?php the_sub_field('postgraduate_studies_link', 'option'); ?>">

<?php the_sub_field('postgraduate_studies_text', 'option'); ?>

  <?php endwhile; ?>

<?php endif; ?>


text:
Q: PHP: Running if and else if inside a while loop? I'm trying to run if and else if inside a while loop in my PHP code.
The code looks like this:
<?php

$sql = "SELECT * FROM table ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query);
if ($productCount > 0) {
    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
        $deviceType = $row["deviceType"];

        if($deviceType == 'iPhone' || $deviceType == 'iPad'){
            echo 'IOS';
        }else if($deviceType == 'Android'){
            echo 'Android';
        }
    }
} else {
}

?>

The code above works (sort of) but not as I was expecting it.
To give you an example, lets say I have 2 rows in MYSQL database.
like this:
id     deviceType

1      Android
2      iPhone

when i run my PHP code above, I get this echo-ed on my page:
IOS
IOS
Android
Android

BUT I only have 2 rows in the database so the result should be:
IOS
Android

Could someone please advise on this issue?

A: This question is clearly misrepresenting your actual code/data.
When your database table has 2 rows, but you are receiving 4 rows then the onus is not on the fetching function, but on your query or database table data.
If your actual query is as posted in your question, then your table data contains more than two rows.
If your actual query is different from what you posted (say, joining the table with a copy of itself), then your data is fine and your query is failing you.
Regardless of if you are using mysqli_fetch_array($result), mysqli_fetch_array($result,MYSQLI_ASSOC), or mysqli_fetch_assoc($result), your while() loop will only do one iteration for each row of data.
The difference in resultset fetching functions:
mysqli_fetch_array($result):
array(0=>'1', 'id'=>'1', 1=>'Android', 'deviceType'=>'Android')  // 1 row w/ 4 elements
array(0=>'2', 'id'=>'2', 1=>'iPhone', 'deviceType'=>'iPhone')  // 1 row w/ 4 elements

mysqli_fetch_array($result,MYSQLI_ASSOC), or mysqli_fetch_assoc($result):
array('id'=>'1', 'deviceType'=>'Android')  // 1 row w/ 2 elements
array('id'=>'2', 'deviceType'=>'iPhone')  // 1 row w/ 2 elements

I will rewrite your code and implement some good practices:
if($result=mysqli_query($db_conx,"SELECT `deviceType` FROM `table` ORDER BY `id`;")){
    if(mysqli_num_rows($result)){
        while($row=mysqli_fetch_assoc($result)){
            echo ($row["deviceType"]=="Android"?"Android":"IOS");  // inline condition is a personal preference
        }
    }else{
        echo "No rows in `table`.";
    }
}

*

*Only bother declaring a variable if you will use its value more than once (*or if it dramatically improves readability to separate it from its single use.)

*So that your variable names are intuitive, name your query variable $sql or $query; and name your query's result variable $result.

*Only SELECT columns that you intend to use; * is unnecessary for your case.

*Backtick ` wrapping is not required on column and table names, but doing so will avoid any potential clashes with MySQL keywords.

*Perform a conditional check and declare the $result variable as false or [resultset] in a single step.

*Always check that $result is true before calling any functions that access the resultset. (e.g. mysqli_num_rows() and mysqli_fetch_assoc()).

*if(mysqli_num_rows($result)){ will check for a non-falsey value -- I mean 0 equates to false and anything greater than 0 will be true.

A: Your code appears to be perfectly fine. However, instead of the expected output, you get more items than needed. If I am not mistaken, this means that you have duplicate deviceType in your database table. $productCount probably has a value of 4. You can get two values if you use this query instead:
SELECT DISTINCT `deviceType` FROM `table` ORDER BY `id`

but while this should fix the output you get, your data will still hold duplicates, so you might want to look into the data of your table and into the way it was created, find out and fix the problem.

A: the answer is very simple you are fetching the results twice with the while loop change this line
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){

to
while($row = mysqli_fetch_assoc($query)){

then it will work right, you can see buy the order iPhone iPhone android android that is doing it twice instead of once per loop


text:
Q: How to initialize flexslider on http.get callback data in angular 2 I need to fetch 2 json files data one after another. That means I am calling one json file, depending on data received calling another json file. This I have done. Concern is I need to initialize a flexsider on data received from second json file. Can someone help me.

export class popularProductsComponent implements OnInit, AfterViewInit {
  public popProductIds: string[] = [];
  public popProductData: Array < Object > ;
  private sub: any;
  public errorMessage: string;
  constructor(
    private route: ActivatedRoute,
    private popService: PopularDataService) {}

  ngOnInit() {
    console.log("@@@@@@@@@@@@@@@ popular-products.component ngOnInit");
    this.sub = this.route.params.subscribe(params => {
      let id = +params['id'];
      this.popService.getPopularProdData(id).then(
        //console.log("inCallbackroute")
        popData => this.extractPopularProducts(popData)
      );
    });
  }

  ngAfterViewInit() {
    // landing Most Popular for large devices
    $('.js-landing-upper-carousel').flexslider({
      selector: '.slides:first > li',
      animation: 'slide',
      animationLoop: false,
      slideshowSpeed: 3000,
      animationSpeed: 500,
      slideshow: false,
      controlNav: false,
      reverse: false,
      itemWidth: 358,
      itemMargin: 12,
      minItems: 1,
      maxItems: 3,
      move: 1,
      smoothHeight: false,
      useCSS: false,
      customDirectionNav: $('.promotions-carousel-navigation a')
    });
  }

  extractPopularProducts(popData) {
      for (var i = 0; i < popData.MarketingSpotData[0].baseMarketingSpotActivityData.length; i++) {
        this.popProductIds.push(popData.MarketingSpotData[0].baseMarketingSpotActivityData[i].productId);
      }
      this.popService.getPopularProductDetails(this.popProductIds).then(
        popData1 => this.popProductData = popData1,
        error => this.errorMessage = < any > error
      );
    }
}

@
Injectable()
export class PopularDataService {
  constructor(private http: Http) {}
  private popularProdUrl = '/assets/json-mocks/popular-prod.json';
  private popularProdDetailsUrl = '/assets/json-mocks/popular-prod-details.json';
  getPopularProdData(id: number): Promise < Array < Object >> {
    // return;
    console.log("popular-data.service.ts || getPopularProdData. id = " + id + " url = " + this.popularProdUrl);
    return this.http.get(this.popularProdUrl).toPromise().then(response => response.json());
  }
  getPopularProductDetails(popProductIds: string[]): Promise < Array < Object >> {
    console.log("popular-data.service.ts || getPopularProductDetails. popProductIds = " + popProductIds + " url = " + this.popularProdDetailsUrl);
    return this.http.get(this.popularProdDetailsUrl).toPromise().then(response => response.json());
  }
}

I am not sure where to put my code to initialize my flexslider. ngAfterViewInit getting called prior to my data. Hence it is not working. Please can someone advise me?

A: I think you should put it right after you get your data!
  this.popService.getPopularProdData(id).then(

    popData => this.extractPopularProducts(popData)

HERE
  );


text:
Q: SonarQube Java rule for checking debug/trace logging level I'm trying to write a customized java rule to check if the debug/trace log levels are enabled. If the log level check has been forgotten, the rule should report an issue.
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;

public class CheckDebugAndTraceLevel {

    private static final Log LOG = LogFactory.getLog(CheckDebugAndTraceLevel.class);

    void foo()
    {
        if(LOG.isDebugEnabled())
        {
            LOG.debug("some debug text..");
        }
        LOG.debug("some debug text.."); // Noncompliant {{ check LOG.debug with an if statement}}

        if(LOG.isTraceEnabled())
        {
            LOG.trace("some debug text..");
        }
        LOG.trace("some text.."); // Noncompliant {{ check LOG.trace with an if statement}}
    }
}

I tested my rule with loggers and recieved "Log.debug" and "Log.trace" from my example class. Still, I get an assertion error while executing jUnit test.
public class DebugAndTraceRule extends BaseTreeVisitor implements JavaFileScanner {

private JavaFileScannerContext context;
private boolean logFlag = false;

@Override
public void scanFile(JavaFileScannerContext context) {
    this.context = context;
    scan(context.getTree());
}

@Override
public void visitMethod(MethodTree tree) {
    super.visitMethod(tree);

    String logOption;
    for (StatementTree statement : tree.block().body()) {
        if (statement.is(Kind.EXPRESSION_STATEMENT)) {
            logOption = statement.firstToken().text() + ".";
            //System.out.println(statement);

            ExpressionStatementTreeImpl eStatement = (ExpressionStatementTreeImpl) statement;
            MethodInvocationTreeImpl methodInvoc = (MethodInvocationTreeImpl) eStatement.expression();
            MemberSelectExpressionTreeImpl memberSel = (MemberSelectExpressionTreeImpl) methodInvoc.methodSelect();
            logOption += memberSel.identifier();

            // check logOption
            if (logFlag && (logOption.equals("LOG.debug") || logOption.equals("LOG.trace"))) {
                //System.out.println(logOption + " - line:" + statement.firstToken().line());
                context.reportIssue(this, tree, "debug/trace levels of your logger must be enabled!");
            }
        }
    }
}

@Override
public void visitVariable(VariableTree tree) {
    super.visitVariable(tree);

    if (tree.type().symbolType().toString().equals("Log")) {
        logFlag = true;
    }
}

}
If someone could help me out, I would really appreciate it!


text:
Q: database query limitation So, I have this mysql query:
SELECT member_id, text FROM review WHERE text != "" ORDER BY date DESC LIMIT 2
This returns the latest two reviews, my question is can I somehow restrict this query returning two rows with the same member_id? I've tried adding DISTINCT before member_id but has no effect.

A:
can I somehow restrict this query returning two rows with the same member_id?

If your member Id is MEMBERID you can use this query.
SELECT member_id,
       TEXT
FROM   review
WHERE  TEXT != ""
       AND member_id = memberid
ORDER  BY DATE DESC
LIMIT  2

A: You can use group by. But if you have more than two rows for the same id, you cannot know which text will come.
    SELECT r.member_id, r.text
    FROM review r, (Select member_id, max(date) dat from review WHERE text != "" group by member_id) t1
    WHERE r.member_id =t1.member_id and t1.dat=r.date
    LIMIT 2


text:
Q: Filling in a rational orthogonal matrix given one row Quick version: given natural $n$ and a row of $n$ integers such that the sum of the squares is another square, call it $m^2.$ For $n=5,6,7$ is it always possible to fill in the rest of an $n$ by $n$ matrix of integers, call it $M,$ so that $M M^T = m^2 I? $ If so, $M/m$ is rational orthogonal.
Notes: this is true for $n=1,2,3,4,8.$ 1 is trivial 2 uses complex numbers, 4 uses quaternions, 8 uses octonions. 3 uses quaternion stuff applied to ternary quadratic forms, papers of Jones and Pall mostly, the main one 1939. The naive adaptation of the Jones-Pall formalism to our $n=7$ does not work very well, see Realizing proper pure octonions as conjugates
This is false for $n = 9,17,25,33,\ldots.$ Indeed, take any odd $n = k^2,$ let the first row have all entries $1,$ no second row is possible that is orthogonal to the given first row, consists of integers, and has the same length. Problem mod 2, insofar as the dot product of the two rows is odd, therefore nonzero. Actually, for any $n >1, \; \; \; n \equiv 1 \pmod 8,$ one may specify any $n-3$ odd numbers, then find the final three (also odd) by Gauss three square theorem to get an odd square sum, no luck.
Anyway, I did some computer checks, entirely successful for small entries for $n=5,6,7,$ and instinct tells me that it only gets easier with larger entries.
So, that is the short version, does this work for any first row of integral length (sum of squares is another square) in dimension $n=5,6,7?$

A: Yes, it is possible to fill in. Your problem is a particular case of a completion problem and is treated in the following paper:
Hsia, J.S.
Two theorems on integral matrices. Linear Multilinear Algebra 5, 257-264 (1978).


text:
Q: Whats steps can I suggest to achieve the best Geolocation Result We are using Geolocation (getCurrentPosition()) in a website to determine a users position when using our site from a mobile device.
I want to write an article explaining how the user can obtain the best results.
Am I correct in assuming:

*

*Enabling GPS will yield the best result when in rural areas (less buildings to obscure line of sight to the satelites)

*Enabling Wi-Fi will yield the best results when in urban areas (generally more Wi-Fi hotspots available)

*Is it true that Android phones have better results from silently harvesting Wi-Fi hotspot details?

Any links to reference material on this are appreciated

A: Remember that even with the best signal, GPS without supplementation is accurate only to 10m.  AFAIK, most mobile devices do not use supplementation, but many dedicated GPS devices (such as Garmin's) use supplementation and have a better degree of accuracy.
1) GPS generally works better in a rural area than an urban area, yes.  But that's not to say that GPS in an urban area is completely useless.  It simply may not be as accurate.
2) Not necessarily.  Wi-Fi location can be notoriously inaccurate, and GPS may still be better here.  Wi-Fi location is probably better in an urban / suburban area than rural though.
3) There are too many android devices to make a blanket statement like this.  As a user, I'd be pretty torqued to find out that "silent" tracking had been enabled without my permission.  To my knowledge, there is nothing that would distinguish an android phone over an iOS or Windows phone in this category.  Windows 8 phones can use Wi-Fi location, I don't know if Win 7 (or whatever it's called) phones can do so or not but I believe they can.


text:
Q: What is $(26+15(3)^{1/2})^{1/3}+(26-15(3)^{1/2})^{1/3}$? $$(26+15\cdot\sqrt3)^{1/3}+(26-15\cdot\sqrt3)^{1/3}$$
I'm trying to get the result of this number. Through some algebra I found that it is close to $52^{1/3}$. Through some observation I found that it is a root of this cubic equation $x^3-3x-52=0$ and I found that the only real solution of that eq. is $4$ so now I know that the number I'm looking for is $4$ (close to my first try $52^{1/3}$). My question is, is there any algebraic process to get from the original expression and simplify it to $4$?
Thank you all very much in advance.

A: $26 + 15 \sqrt{3} = 8 + 12 \sqrt{3} + 18 + 3 \sqrt{3} = 2^3 + 3 \cdot 2^2 \sqrt{3} + 3 \cdot 2 \sqrt{3}^2 + \sqrt{3}^3 = (2 + \sqrt{3})^3.$
$26 - 15 \sqrt{3} = 8 - 12 \sqrt{3} + 1 8- 3 \sqrt{3} = 2^3 - 3 \cdot 2^2 \sqrt{3} + 3 \cdot 2 \sqrt{3}^2 - \sqrt{3}^3 = (2 - \sqrt{3})^3.$
$(26 + 15 \sqrt{3})^{\frac{1}{3}} + (26 - 15 \sqrt{3})^{\frac{1}{3}} = 2 + \sqrt{3} + 2 - \sqrt{3} = 4.$


text:
Q: Disable button on a userForm I'm trying to figure out how to disable a button within my userForm if a certain cell within my spreadsheet equals a certain number.  I tried the code stated below, but it isn't working.
Private Sub UserForm_Initialize()
Label2 = Sheets("DATA").Range("AM2").Value
Label4 = Sheets("DATA").Range("AO2").Value
Label7 = Format(Sheets("DATA").Range("R8").Value, "Currency")

If Sheets("DATA").Range("AL10").Value = 10 Then
ActiveSheet.Shapes("CommandButton1").Select
UserFormact_Upgrade.CommandButton1.Enabled = False

Else

End If

End Sub

A: Your code should be working, as you're on the right path.
To test it, simply create a new form and add this code, you'll see it should work. Maybe you're having problems within the IF clause?
Besides, you don't need to select the shape prior to disabling it; just disable it right away.
Private Sub UserForm_Initialize()

    CommandButton1.Enabled = False

End Sub

A: I know this is old, but got to this thread trying to solve my problem, and found a solution that wasn't mentioned here. So in case someone gets here like I did, and this didn't quite get them where they needed to go, I thought this might help.
I had a userform with a drop down box called cmdADAMFields, and I didn't want my submit button called FieldsSubmitButton to be enabled until I selected something from the dropdown box.
I had to break up my argument into two different private subs vs one larger If-Then-Else statement.
First, I put:
Private Sub UserForm_Activate()
If cmbADAMFields.ListIndex = -1 Then FieldsSubmitButton.Enabled = False
End Sub

Then when for my pulldown's private sub when it's value changed I wrote:
Private Sub cmbADAMFields_Change()
FieldsSubmitButton.Enabled = True
End Sub

A: The proper place for setting  Enabled property is in Activate event (associated with Show method) and not Initialize event (associated with Load instruction).
The below code disable the button CommandButton1 when AL10 cell >= 10.
        Private Sub UserForm_Activate()
           CommandButton1.Enabled = ( Sheets("DATA").Range("AL10") < 10 )
        End Sub

For buttons you can choose between normal buttons (property Enabled=False and property Visible=true), disabled buttons (property Enabled=False and property Visible=true) and invisible buttons (property Enabled=False and property Visible=False), that it is a cleaner interface, in most cases.
Concerning text boxes, besides normal, disabled and invisible status, there is a locked status, that is enabled and visible, but cannot be user edited. (property Locked = True)
A locked control only can be changed by VBA code. For instance, someone can includes date text boxes, that it's filled using a secondary popup date form with Calendar control.


text:
Q: Does deleting a collection in the firebase/firestore console delete all sub collections? I am aware of how to delete sub collections when a parent collection is deleted programmatically however I can't find any documentation on what happens when you delete a parent collection from the console manually.
Follow up question:
Is there a way to check for undeleted sub collections?
I assume these use up storage.

A: I just tested what happens in the Firebase console when you delete a collection, and it shows this dialog:

So it looks like deleting a collection in the console also deletes any subcollections under it.


text:
Q: How to Swap the options of two select Boxes I have a Two select Boxes as below.
    <form name="test">
        <select id="s1" name="select1">
         <option selected>1</option>
         <option>2</option>
         <option>3</option>
        </select>

        <select id="s2" name="select2">
         <option>1</option>
         <option>2</option>
         <option selectd>3</option>
        </select>

<input type="button" value="swap" id="swap">

    </form>

"1" is selected in the select box 1 and "3" is selected in the select box 2.
Now by clicking a button those two value should swap. Means "3" in select box 1 and "1" in select box 2.
I have tried some jquery for that. That code is as below.
$("#swap").click(function(){
 v1=document.getElementById("s1");
 v2=document.getElementById("s2");
 document.form.select1.value=v2;
 document.form.select2.value=v1;
});

But i didnt get the result. Whats wrong i am doing.??
Thanks in advance,
Shoba.

A: $('#swap').click(function(){
    var v1 = $('#s1').val(),
        v2 = $('#s2').val();
    $('#s1').val(v2);
    $('#s2').val(v1);
});

Works fine for me.

A:   <select name="" id="select_one" multiple>
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
  </select>
  <button onclick="swap('select_one','select_two','left_to_right')">--></button>
  <button onclick="swap('select_one','select_two','right_to_left')"><--</button>
  <select name="" id="select_two" multiple>
     <option value="5">1*5</option>
     <option value="6">2*5</option>
     <option value="7">3*5</option>
     <option value="8">4*5</option>
  </select>
  <script>
     var cloneArr = function(arr){
         var result = [];
         for(var item=0; item<arr.length;item++){
             result[item]=arr[item];
         }
         return result;
     }

     function swap(select_one,select_two,direction='left_to_right') {
         select_one = document.querySelector('#select_one');
         select_two = document.querySelector('#select_two');
         if (direction=='left_to_right') {
             var oneOptions = select_one.selectedOptions;
            var arr = cloneArr(oneOptions);
             for(var item=0; item<oneOptions.length;item++){
                 select_one.remove(oneOptions[item].index);
             }
             for(var item=0; item<arr.length;item++){
                 select_two.add(arr[item]);
             }
         }

         if (direction=='right_to_left') {
             var twoOptions = select_two.selectedOptions;
            var arr = cloneArr(twoOptions);
             for(var item=0; item<twoOptions.length;item++){
                 select_two.remove(twoOptions[item].index);
             }
             for(var item=0; item<arr.length;item++){
                 select_one.add(arr[item]);
             }
         }

     }
  </script>


text:
Q: Specifiy colors for labels in alt.Chart() Let's say I would like to plot ['foo', 'bar', 'test'] with the respective colors ['blue', 'yellow', 'green']. My suggestion to solve this is as following:
alt.Chart(df, height=600, width=1100).mark_circle(size=100).encode(
        x='x',
        y='y',
        color=alt.Color('title:N', legend=None, scale=alt.Scale(range=['blue', 'yellow', 'green'])),
        tooltip=['sample', 'title']
    ).properties(
        selection=click
    ).interactive()

But this seems to pick the colors in an arbitrary order, and not in an ascending order as I expected. I would like foo to be assigned the blue color and bar should become yellow and so on.
Is it possible to link this (labels and colors) somehow?

A: There is some information on this in the docs in the Customizing Colors section. Briefly, if you would like to control which values are assigned to which colors, you can use the domain argument:
scale = alt.Scale(domain=['foo', 'bar', 'test'], range=['blue', 'yellow', 'green'])


text:
Q: Data memory unit I started Verilog a few weeks ago and now I'm implementing MIPS pipelining on an FPGA board and I'm on the MEM part of the pipelining stage. I'm trying to code the Data memory unit (in picture -> Data memory Unit).

I don't understand the use of memread. I understand that if memwrite is 1, the contents of the current address is passed to read data.
So far, this is my code:
module data_memory (
input wire [31:0] addr,             // Memory Address
input wire [31:0] write_data,       // Memory Address Contents
input wire memwrite, memread,
output reg [31:0] read_data     // Output of Memory Address Contents
);

reg [31:0] MEMO[0:255];  // 256 words of 32-bit memory

integer i;

initial begin

   read_data <= 0;

   for (i = 0; i < 256; i = i + 1)
     MEMO[i] = i;

   end

always @ (addr) begin

   //**I don't understand the use of memread**//

   if (memwrite == 1'b1)
       MEMO[addr] <= write_data;
   end
end

assign read_data = MEMO[addr];

endmodule

Do I need another if statement for the memread? Any help is greatly appreciated. Thanks

A: In the design you have coded above, you dont use memread, instead choosing to combinationally read from the memory via the last line of your module. And without more details on how exactly the memory in your diagram is suppose to function, its difficult to say the exact usage of memread. Typical memories only have a memwrite and assume that if an address is supplied and memwrite is deasserted, the access is a read. In this case, I can only assuming memread should be asserted to read from the memory. Also, I would suggest a few edits to your code to make it work better and follow a better synchronous design style (this will incorporate memread so you can see how it can be used):
module data_memory (
input wire [31:0] addr,          // Memory Address
input wire [31:0] write_data,    // Memory Address Contents
input wire memwrite, memread,
input wire clk,                  // All synchronous elements, including memories, should have a clock signal
output reg [31:0] read_data      // Output of Memory Address Contents
);

reg [31:0] MEMO[0:255];  // 256 words of 32-bit memory

integer i;

initial begin
  read_data <= 0;
  for (i = 0; i < 256; i = i + 1) begin
    MEMO[i] = i;
  end
end

// Using @(addr) will lead to unexpected behavior as memories are synchronous elements like registers
always @(posedge clk) begin
  if (memwrite == 1'b1) begin
    MEMO[addr] <= write_data;
  end
  // Use memread to indicate a valid address is on the line and read the memory into a register at that address when memread is asserted
  if (memread == 1'b1) begin
    read_data <= MEMO[addr];
  end
end

endmodule

Important to note also the need for a clock in your design. Most block diagrams at that level will omit the clock as it is assumed but all synchronous elements (memories and registers) will be synchronized to a common clock (or multiple clocks in some cases).

A: @Unn gives excellent answer, moreover I just want add that, if you not use read_enable, Then it may unsynchronised data read operation, It is also preferred to flop the output read_data on read_clk.
Here with see below templent for reference.
parameter RAM_WIDTH = <ram_width>;
parameter RAM_ADDR_BITS = <ram_addr_bits>;

(* RAM_STYLE="{AUTO | BLOCK |  BLOCK_POWER1 | BLOCK_POWER2}" *)
reg [RAM_WIDTH-1:0] <ram_name> [(2**RAM_ADDR_BITS)-1:0];
reg [RAM_WIDTH-1:0] <output_dataB>;

<reg_or_wire> [RAM_ADDR_BITS-1:0] <addressA>, <addressB>;
<reg_or_wire> [RAM_WIDTH-1:0] <input_dataA>;

//  The forllowing code is only necessary if you wish to initialize the RAM
//  contents via an external file (use $readmemb for binary data)
initial
   $readmemh("<data_file_name>", <ram_name>, <begin_address>, <end_address>);

always @(posedge <clockA>)
   if (<enableA>)
      if (<write_enableA>)
         <ram_name>[<addressA>] <= <input_dataA>;

always @(posedge <clockB>)
   if (<enableB>)
      <output_dataB> <= <ram_name>[<addressB>];


text:
Q: Navigating back to home screen from other screen which is opened from push notification I have multiple screens and I'm using named routes in flutter using getx package.
The problem I'm facing is I'm able to navigate to any other screen when tapped on push notification, but when I go back from that screen my app closes.
But expected outcome is when navigating back I should go to home screen and app should not close.
Please help

A: Try using the following when back button is pressed:
Navigator.popAndPushNamed(context, '/homeScreen')


text:
Q: NHibernate doesn't save one property only I'm trying to update a single column in the table. No UPDATE issued whatsoever (checked using SQL Profiler). No errors.

*

*Class mapping has dynamic-update="true".

*No versioning enabled on the class.

*Flush mode Commit.

*Property mapped without any insert/update modifiers (<property name="Deleted" />).

*Property is auto-implemented (public virtual bool Deleted { get;set;}).

*NH 3.3.0, .NET 4, x64.
using (var transaction = this._session.BeginTransaction())
{
    try
    {
        var order = this.session.Load<Order>(id);
        order.Deleted = true;
        this._session.Update(order);
        transaction.Commit();
    }
    catch (Exception)
    {
        transaction.Rollback();
        throw;
    }
}

A: Based on the comments, what you are trying to do is create a proxy without getting the current state from the DB (using session.Load), then issue a dynamic update.
This will not work. NHibernate does not record individual changes to properties; instead, it:

*

*Compares the current state of tracked entities against a snapshot of the property values that were retrieved from the database.

*Based on that, determines which entities are dirty (i.e. have changes)

*It generates the SQL update statement. If using dynamic-update, it will only contain the modified properties.

If you use session.Load, as soon as you access the Deleted property, NH will load the record from the database. Whether you use session.Load or session.Get, session.Update on an already tracked entity is a no-op.
Alternatively, if you already have the state for all the order properties, you can update without loading:
var order = GetTheOrderFromMemory();
order.Deleted = true;
session.Update(order);
transaction.Commit();

This will not respect dynamic-update, as NH doesn't have a snapshot to compare with...
...which is why HQL is the only way to do a one-shot update of an individual property.


text:
Q: QGraphicsView slow with lots of QGraphicsPixmapItem I've made a small code to test QGraphicsView capabilities using QtCreator.
The code is quite simple, just created a class thats inherited from QGraphicsView that has a QGraphicsScene on it. Fill the scene with lots of QGraphicsPixmapItem (in this case 2000) scaled to 100x100 and randomly place them into the scene.
Then inside the custom class and using a QTimer move a bit all the elements of the scene.
(Added a second QTimer to see the how many times per second the first QTimer is called).
It work great with a few hundred elements but if the elements numbers increase, the performance drops.
Could someone give me a hint on how to increase the performance?
Maybe the access to the elements using a QList is slow ...
or the use of a QTimer for this simple animation is a very bad idea ...
or just a few optimization flags must be added somewhere ...
maybe forget QGraphicsView and try QtQuick and QML ...
The final application should draw lots of images in screen and animate some of them using png images as source.
test.pro
QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = test
TEMPLATE = app

SOURCES += main.cpp \
    c_view.cpp

HEADERS  += \
    c_view.h

FORMS    +=

RESOURCES += \
    res.qrc

C_View.h
#ifndef C_VIEW_H
#define C_VIEW_H

#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QTimer>

class C_View : public QGraphicsView
{
    Q_OBJECT

public:
    C_View();

    QGraphicsScene *scene;

    QGraphicsTextItem *label_fps;

    QTimer timer;
    QTimer timer_fps;
    int interval=0;
    int fps=0;
private slots:
    void random_move();
    void show_fps();
};

#endif // C_VIEW_H

C_View.cpp
#include "c_view.h"

C_View::C_View()
{
    this->scene = new QGraphicsScene();
    this->setScene(this->scene);

    // Label to see how many times per seconds the random_move function gets called
    this->label_fps=new QGraphicsTextItem();
    this->label_fps->setDefaultTextColor(Qt::black);
    this->label_fps->setFont(QFont("times",16));
    this->label_fps->setPos(10,10);
    this->scene->addItem(this->label_fps);

    // Qtimer to enter random_move function
    connect(&this->timer,SIGNAL(timeout()),this,SLOT(random_move()));
    //this->interval=10; // 100 FPS?
    this->interval=25; // 40 FPS?
    //this->interval=50; // 20 FPS?
    //this->interval=100; // 10 FPS?
    this->timer.setInterval(this->interval);
    this->timer.start();

    // QTimer to update the FPS label
    connect(&this->timer_fps,SIGNAL(timeout()),this,SLOT(show_fps()));
    this->timer_fps.setInterval(1000); // Once a second
    this->timer_fps.start();

}

// Funcion that moves a bit all the items of the scene
void C_View::random_move()
{
    QList <QGraphicsItem*> l = this->items();
    int ini=0;
    for(int i=ini;i<l.size();i++)
    {
        l[i]->setPos(l[i]->x()+(rand()%3)-1,l[i]->y()+(rand()%3)-1);
    }

    this->fps++;
}

// Just show how many times random_move function gets call, since last time
void C_View::show_fps()
{
    this->label_fps->setPlainText("FPS "+QString::number(this->fps));
    this->label_fps->setZValue(1);
    this->fps=0;
}

main.cpp
#include <QApplication>

#include "c_view.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    C_View *view = new C_View();

    // Fill the QGraphicsView with lots of images
    for(int i=0;i<2000;i++)
    {
        QGraphicsPixmapItem *item=new QGraphicsPixmapItem();
        item->setPixmap(QPixmap(":/images/p.png").scaled(100,100));
        item->setPos(rand()%view->width(),rand()%view->height());
        view->scene->addItem(item);
    }

    view->show();

    return a.exec();
}

A: The suggestion to give up Qt is a bit fatalistic and premature, in my opinion. Our application uses QGraphicsScene with many tens of thousands of items and we have good performance. Most of them aren't images, however, and we don't move thousands of them at a time. Switching to something else may end up being the case, but it's worth some additional experimentation first.
A profiler, if you have one, can certainly help you. We use Visual Studio and the profiler works well there, but I don't know if Qt Creator has any profiling ability. Your sample application is very simple, and I don't see anything obvious to change, but profiling is often very revealing.
Since you're moving things around the scene, experiment with the options for QGraphicsScene::setItemIndexMethod and QGraphicsScene::setBspTreeDepth. The recommended settings for those vary depending on how you tend to use the scene.
Moving 2000 items every second seems like a lot in my opinion. You say that your final application with have lots of images but with only some of them moving. Do you expect that 2000 of them will move?
Also, what version of Qt are you using? Later versions make better decisions about the rendering engine to use and our experience is that it's pretty good about that.

A: Start your timer after your view shows up (in the main function for instance). That should fix that strange behaviour. Edit: No that will change nothing. Try
setViewportUpdateMode(BoundingRectViewportUpdate);
//setCacheMode(QGraphicsView::CacheBackground);

instead. Here are the docs: setViewportUpdateMode | setCacheMode. Don't forget to read about those functions argument types.
On the other hand, you normally do not need to handle a pointer to a QGraphicsScene inside a QGraphicsView since this class provides you with a scene() function. If your code do require this pointer, I think naming your attribute m_scene (or whatever except the scene() function name) would be more convenient.
Edit2
Another way to improve rendering speed is to lower your scene item' bounding rectangle. To do so, you can scale your pixmap items to 50*50 (for instance) instead of 100*100. Indeed the fewer scene items collide, the faster Qt rendering process will be. Furthermore, here is an article issuing some optimization tricks when using customized QGraphicsItem inside QGraphicsView: Qt: Improving QGraphicsView Performance. You aren't currently using customized items but reading that article would be benefic I think.


text:
Q: Magento - PayPal IPN configuration I have set up a web shop using Magento (v. 1.5) and one of my payment options is PayPal standard payments. Everything works fine so far but now I would like to trigger a script on another server by using the IPN URL from PayPal when a payment is received.
The PayPal account is also used for other web platforms and it has the correct IPN URL for the script already set up in the account configuration. However, the Magento module seems to overwrite this URL and always sets it to "http://myshop.com/paypal/ipn/" when someone buys something in the Magento shop.
My problem is that I can not find any possibilities to change this behaviour in Magento itself. The backend module configuration offers nothing in that direction and I also looked into the IPN model and controller files in the core directories (Mage/Paypal/controllers/IpnController.php and Mage/Paypal/Model/Ipn.php).
It has to be possible to change the IPN URL but I'm out of ideas at this point... so I'd be very thankful for any helpful hints!

A: The IPN notification URL is set in Mage_Paypal_Model_Standard::getStandardCheckoutFormFields:
$api->setNotifyUrl(Mage::getUrl('paypal/ipn/'))

The function is called by Mage_Paypal_Block_Standard_Redirect, so you can override either the model or the block to change/remove the URL. But keep in mind that Magento needs the IPN notification to update order status etc.


text:
Q: How to remove brackets from SQLAlchemy filter parameters? I am trying to filter a SQLAlchemy model inside of an Ubuntu Docker Container using OBDC drivers provided by MS, but when doing a filter_by the driver is adding square brackets to the parameters
I tried running this exact code on a Windows box, and the parameter is formatted as sqlalchemy.engine.base.Engine ('4') instead of sqlalchemy.engine.base.Engine (['4'])
def get():
    reqargs = request.args
    data = tblData.query.filter_by(**reqargs).all()
    data = DataSchema.dump(data).data
    return {'status': 'success', 'data': data}, 200

URL: https://{internalhost}/getData?ID=4
SQLALCHEMY_ECHO log:
2019-04-11 17:00:00,148 INFO sqlalchemy.engine.base.Engine SELECT [tblData].[CreatedDtTm] AS [tblData_CreatedDtTm], [tblData].[CreatedBy] AS [tblData_CreatedBy], [tblData].[UpdatedDtTm] AS [tblData_UpdatedDtTm], [tblData].[UpdatedBy] AS [tblData_UpdatedBy], [tblData].[ID] AS [tblData_ID],[tblData].[Description] AS [tblData_Description], [tblData].[AdditionalNotes] AS [tblData_AdditionalNotes], [tblData].[IsEnabled] AS [tblData_IsEnabled] ,
FROM [tblData] ,
WHERE [tblData].[ID] = ?
2019-04-11 17:00:00,148 INFO sqlalchemy.engine.base.Engine (['4'])

Error:
(pyodbc.ProgrammingError) ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column, parameter, or variable #1: Cannot find data type 4. (2715) (SQLExecDirectW)')

A: Resolved the issue. I need to add .to_dict() to the args
    def get(self):
        reqargs = request.args.to_dict()


text:
Q: How to append/write huge data file text in Java I have a database with 150k records.  I want to write this to file as fast as possible.  I've tried many approaches, but all seem slow.  How do I make this faster?
I read these records in blocks of 40k. So first I read 40k then another 40k and so on.
After reading the records, this process returns a StringBuilder which contains 40k lines. Then we write this StringBuilder to a file.
private static void write(StringBuilder sb, Boolean append) throws Exception {
    File file = File.createTempFile("foo", ".txt");

    FileWriter writer = new FileWriter(file.getAbsoluteFile(), append);
    PrintWriter out = new PrintWriter(writer);
    try {
        out.print(sb);
        out.flush();
        writer.flush();
    } finally {
        writer.close();
        out.close();
    }
}

I read this other example but it is equally slow: Fastest way to write huge data in text file Java
I also tried it with NIO api:
private static void write(StringBuilder sb, Boolean append)) throws Exception {
    FileChannel rwChannel = new FileOutputStream("textfile.txt", true).getChannel();
    ByteBuffer bb = ByteBuffer.wrap(sb.toString().getBytes("UTF-8"));
    rwChannel.write(bb);
    rwChannel.close();
}

Which is the best method to write/append huge data into file?

A: If you have a huge amount of data, it's better that you don't store it to StringBuilder and then write it to file at once.
This is the best scenario:
1) Before you start process on the data create FileInputStream
FileOutputStream fos = new FileOutputStream("/path/of/your/file");

2) Create and OutputStreamWriter from this file
OutputStreamWriter w = new OutputStreamWriter(fos, "UTF-8");

3) Create BufferedWriter (Improve file writing performance)
BufferedWriter bw = new BufferedWriter(w);

4) Pass bw to your process function and then flush/close
bw.flush();
bw.close();

The functionality of StringBuilder and BufferedWriter is almost same, So you do not need to change your code so much. The only negative point of this scenario is that, your process will involve all the time that the data are writing to file, but if you don't process the data in different thread, it is not an issue.
In this way, it doesn't matter how large data is it

A: You don't need a PrintWriter here. If you have whatever kind of Writer (e.g. a FileWriter) you can simply invoke append(sb) on it. And you don't need to flush, close implies flushing.
private static void write(StringBuilder sb, Boolean append) throws Exception {
  File file = File.createTempFile("foo", ".txt");

  try(FileWriter writer = new FileWriter(file.getAbsoluteFile(), append)) {
      writer.append(sb);
  }
}

On my system I encountered a small performance improvement using a Channel rather than an OutputStream:
private static void write0a(StringBuilder sb, Boolean append) throws Exception {
  File file = File.createTempFile("foo", ".txt");

  try(Writer writer = Channels.newWriter(new FileOutputStream(
      file.getAbsoluteFile(), append).getChannel(), "UTF-8")) {
    writer.append(sb);
  }
}

However these are only slight improvements. I don't see much possibilities here as all the code ends up calling the same routines. What could really improve your performance is keeping the Writer alive during the invocations and not flushing every record.

A: You are using a FileWriter (or a FileOutputStream in the second example). These are not buffered! So they write single chars resp. bytes to the disk.
That means, you should wrap the FileWriter in a BufferedWriter (or the FileOutputSystem in a BufferedOutputSystem).
private static void write(StringBuilder sb, Boolean append) throws Exception {
    File file = File.createTempFile("foo", ".txt");
    Writer writer = new BufferedWriter(new FileWriter(file.getAbsoluteFile(), append));
    PrintWriter out = new PrintWriter(writer);
    try {
        out.print(sb);
        out.flush();
        writer.flush();
    } finally {
        writer.close();
        out.close();
    }
}

A: You are opening the file, writing one line, then closing it. It's the opening and closing that takes the time here. Find a way to keep the output file open.

A: Did you try Apache IO, is the performance still the same?


text:
Q: Dell E6520 wont boot ubuntu unless plugged in on AC power I've got a problem booting. Ubuntu 16.04 on my Dell E6520 laptop boots normally when plugged in.  However, when booting on battery power it shuts down entirely.  Sometimes it makes it as far as the Ubuntu loading screen, but then stops and the laptop shuts off entirely.
I tried searching and found this results for a Lenovo Y560, though I'm not really knowledgeable about kernels so I'm not sure if a similar fix would be relevant for a Dell.
What can I do to boot while on battery power?  Thanks.
Updates
I've also tried booting from USB and recovery mode while on battery power, both failed.
I've also noticed when I boot from AC power, then unplug the battery, sometimes the system shuts off on its own, but only after I do something.
Reproduction steps:

Shutdown at login screen issue

*

*Boot from AC power

*Wait for login screen

*At login screen, unplug AC power

*Type password and click login

*Immediately after clicking login, the laptop shuts down

I set a timer and waited 10 minutes after step 3 to see if the battery was the issue, but it only shuts down if I take an action, in this case clicking the login button.

Shutdown using Chrome on battery power

*

*Boot using AC power

*Wait for login screen

*Type password and click login (still from AC power)

*Wait for desktop to load, then disconnect AC power

*Open Chrome

*Type http://www.google.com in the address bar

*Click Go or press CTRL+Enter, and the laptop immediately shuts down

I left the laptop powered on at step 5, thinking maybe it was a battery issue. It ran for almost 3 hours until the battery was completely drained.

It seems the laptop only shuts down when on battery power after some type of user action, or during boot from battery power.
I'm stumped, any thoughts on what the cause is?

A: I had the same issue on a Lenovo G50-45, the fix for this was so simple it made it complicated.
Go to 'System Settings' in Ubuntu, go to 'power' and change the option below "On Battery Power" so they are the same as the options below "When plugged in".
Let me know how you get on! :)

A: You can add this line
dis_ucode_ldr

into your grub file
/etc/default/grub as a root user of course.
This allows booting after a bad microcode update and fixes the non-booting issue when you are not on AC Power. I've seen this issue a lot of times on some Dell computers on Ubuntu.

A: I've been facing a similar problem with Ubuntu Mate 20.04 recently and after a couple of days and countless attempts to find the solution (adding dis_ucode_ldr in grub did not help) finally discovered a simple one that has worked for me.
Try editing grub adding the nomodeset option in the line GRUB_CMDLINE_LINUX_DEFAULT (if present), so that it reads as follows:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash nomodeset"

Hope that might help someone as well.
More details on nomodeset here: What does `nomodeset` do


text:
Q: How to get  to work in Polymer 2.x Narrow Question
By troubleshooting, I think I have narrowed my "larger problem" down to the following question. (But I could be wrong.):
How do I properly download the latest version of <iron-icons> to my local machine?
By "latest version," I mean the version that is imported via the following:
<base href="//polygit.org/polymer+:master/components/">
<link rel="import" href="iron-icons/iron-icons.html">

The above version of importing <iron-icons> works on my demo here.
However, when I do either of the following:
bower install --save PolymerElements/iron-icons

bower update --save

And try to import on my local server like this:
<link rel="import" href="/bower_components/iron-icons/iron-icons.html">

it fails silently and I see no icons at all. But I do see extra space where the icons are supposed to render.
Bigger Question (the real problem I'm trying to solve)
I am trying to get my <iron-icons> to render properly in the browser.
What I expect to see
I expect to see a two <iron-icon> elements like this:

(anchored in between other test elements: Hello World and )
What I actually see
No icons at all. But white space where they should render.
Steps to reproduce
Run
bower install --save PolymerElements/iron-icons

or, if <iron-icons> is already installed:
bower update --save

then
polyserve

or
polymer serve

Version
I believe I am using v2.0.1 of <iron-icons>. Here is the entire contents of the bower.json file.

bower.json

"iron-icons": "PolymerElements/iron-icons#^2.0.1",

Configuration
OS: macOS Sierra 10.12.6
Hardware: MacBook Air
Browser: Chrome Version 60.0.3112.113 (Official Build) (64-bit)
Demo
Here is my Plunker demo.
Code
The following code does render <iron-icons> as expected:
http://plnkr.co/edit/pKnrlIbGhfQPFq10aAJS?p=preview
<base href="//polygit.org/polymer+:master/components/">

<link rel="import" href="polymer/polymer-element.html">
<link rel="import" href="iron-icons/iron-icons.html">
<link rel="import" href="iron-icon/iron-icon.html">

<dom-module id="demo-el">
  <template>

    Hello world
    <iron-icon icon="add"></iron-icon>
    <iron-icon icon="favorite"></iron-icon>

  </template>

</dom-module>

The following code does NOT render <iron-icons> as expected (served locally):
<link rel="import" href="/bower_components/polymer/polymer-element.html">
<link rel="import" href="/bower_components/webcomponentsjs/webcomponents-lite.js">
<link rel="import" href="/bower_components/iron-icon/iron-icon.html">
<link rel="import" href="/bower_components/iron-icons/iron-icons.html">
<link rel="import" href="/bower_components/paper-input/paper-input.html">

<dom-module id="app-main">
  <template>

    Hello world
    <iron-icon icon="add"></iron-icon>
    <iron-icon icon="favorite"></iron-icon>

  </template>

</dom-module>

However, the above code does render <iron-icons> as expected when I do a direct substitution of:
<base href="//polygit.org/polymer+:master/components/">
<link rel="import" href="iron-icons/iron-icons.html">

for
<link rel="import" href="/bower_components/iron-icons/iron-icons.html">

Edit
By comparing the text of the imported files using the CDN
<base href="//polygit.org/polymer+:master/components/">
<link rel="import" href="iron-icons/iron-icons.html">

and local imports:
<link rel="import" href="/bower_components/iron-icons/iron-icons.html">

I discovered there is a discrepancy in the imported version of the iron-iconset-svg.html file. My bower.json file says the dependent version is "iron-iconset-svg": "1 - 2" or "iron-iconset-svg": "polymerelements/iron-iconset-svg#^2.0.0" but the bower.json file here says the dependent version is "iron-iconset-svg": "polymerelements/iron-iconset-svg#^1.0.0"
So, now the question appears to reduce to how do I get the local version of iron-icons.html to import the same version of iron-iconset-svg.html as the online CDN import version.
Edit 2
The problem persists when I just copy the iron-iconset-svg.html file from the CDN and paste it into my local file system. So, apparently something else is going on too.
Edit 3
I followed the instructions here for upgrading to Polymer 2.0:
https://www.polymer-project.org/2.0/docs/upgrade#update-bower-dependencies

*

*Remove the existing bower_components folder.

rm -rf bower_components

*Update the Polymer version in bower.json to the latest versions.

Component            | Version
---------------------|--------
Polymer              | ^2.0.0
webcomponentsjs      | ^1.0.0
web-component-tester | ^6.0.0
Polymer elements     | ^2.0.0

*Install the new dependencies.

bower install

This did not solve the problem. However I could not update Polymer elements to ^2.0.0

bower.json

"dependencies" : {
  ...
  "polymer-elements" : "^2.0.0",
  ...
}

caused an error and so did:

bower.json

"dependencies" : {
  ...
  "polymerelements" : "^2.0.0",
  ...
}

and so did:

bower.json

"dependencies" : {
  ...
  "PolymerElements" : "^2.0.0",
  ...
}

A: The solution proposed by @Ofisora in the comments works for me—update iron-selector and iron-meta:
bower install --save PolymerElements/iron-meta
bower install --save PolymerElements/iron-selector

A:
iron-icons is a utility import that includes the definition for the
  iron-icon element, iron-iconset-svg element, as well as an import
  for the default icon set.

This means that iron-icons is directly dependent on both iron-icon and iron-iconset-svg. And both iron-icon and iron-iconset-svg element depends on iron-meta.
When you update iron-icons to the latest version, these elements iron-icon, iron-iconset-svg and iron-meta might not get updated since you will get all these components by default. So, updating iron-meta is one of the solution.

Also, when you install or update element in polymer you will see messages like:

Unable to find a suitable version for iron-icons, please choose one by
  typing one of the numbers below:

Always choose the suitable or latest version depending on other element you have.
When finished updating or installing you will see a note like:
Please note that,
    iron-iconset-svg#a47e824859 depends on iron-meta#2.0-preview which resolved to iron-meta#7404b31da3
    iron-icon#1.0.13, iron-icon#1.0.13, iron-icon#1.0.13, iron-iconset-svg#1.1.2, iron-iconset-svg#1.1.2 depends on iron-meta#^1.0.0 which resolved to iron-meta#1.1.3
    iron-icon#2.0.0, iron-iconset-svg#2.0.0 depends on iron-meta#1 - 2 which resolved to iron-meta#2.0.2

Make sure you read this and install/update dependencies required.

Note: In my case I had to update iron-selector as well since I was using iron-icon inside the iron-selector.


text:
Q: What notions of independence exist for these random variables? I think I've gotten a bit confused about the notions of independence that the following random variables satisfy. Any help would be greatly appreciated.
Let $x_1, ..., x_k \in \mathbb{Z}_q^n$, each distinct (not random, I want this result to hold in general for any choice of these $x$'s). Let $A_j \in \mathbb{Z}_q^{m \times n}, m < n, b_j \in \mathbb{Z}_q^m$ both uniformly distributed, and independently.
Then define:
\begin{equation}
y_{i,j} = A_jx_i + b_j
\end{equation}
What can I say about the independence of the $y_{i,j}$, i.e., pairwise independence, etc,. I think for each $j$ $y_{i,j}$ are independently and uniformly distributed over $\mathbb{Z}_q^m$, (since they must differ in at least one coordinate), but I am generally confused.
Thanks

A: I presume $\mathbb Z_q$ denotes a finite field.
Are the $b_j$ mutually independent, and independent of the $A_j$ and $x_i$?  Then for each $i$ the $y_{i,j}$ are independent and uniform on $\mathbb Z_q^m$, because this is true conditional on the $A_i x_j$.
EDIT: If $Z_q$ is the integers mod $q$ where $q$ is not prime, the $y_{i,j}$ for different $i$ but the same $j$ may not be pairwise independent.  Thus consider
$y_{1,j} - y_{2,j} = A_j (x_1 - x_2)$.  If $x_1 - x_2$ has all entries divisible by some nontrivial divisor $p$ of $q$, then  $y_{1,j} - y_{2,j}$ also has all its entries divisible by $p$.

A: If you don't have a finite field, you can obtain distributions in ideals of $\mathbb{Z}_q$ instead of uniform distributions.
Let $q=27,$ say, and let all $x_i \in 3 \mathbb{Z}_{27}^n,$ then if the distributions of the $b_i$ are also supported on
$3 \mathbb{Z}_{27}^n,$ you won't get a uniform distribution since all components of the $y_{i,j}$ you obtain will be in
$3 \mathbb{Z}_{27}^m.$


text:
Q: Django template with forloop. Exception Type: IndexErrorm, Exception Value: pop from empty list I have a web page with essays. Each essay (on its own sub-page) can have multiple videos from another model (linked with many-to-many relations).
When I try to invoke a list of videos, with this new code:

    {% for vid in essay_videos %}

{{ vid.video_item_url }}

    {% endfor %}

I'm getting a list of URLs - that's ok, but, when I try to use the embed-video tag (like before):

    {% for vid in essay_videos %}

{% video %}{{ vid.video_item_url }}{% endvideo %}

    {% endfor %}

or

    {% for vid in essay_videos %}
        {% video %}

{{ vid.video_item_url }}

        {% endvideo %}
    {% endfor %}

or

    {% video %}
        {% for vid in essay_videos %}

{{ vid.video_item_url }}

        {% endfor %}
    {% endvideo %}

...In all cases, I've got Exception Type: IndexErrorm, Exception Value: pop from empty list
My models.py:
...
from embed_video.fields import EmbedVideoField
...

class VideoObject(models.Model):

    video_item_url = EmbedVideoField()  # same like models.URLField()
    added_date = models.DateTimeField(auto_now_add=True, null=True)
    title_video = models.CharField(max_length=200)

    class Meta:
        ordering = ['-added_date']

class EssayCls(models.Model):
    title = models.CharField(max_length=200)
    organizer_email = models.EmailField(null=True)
    date = models.DateField(null=True)
    slug  = models.SlugField(unique=True, db_index=True)
    description = models.TextField(validators = [MinLengthValidator(10)])
    details = models.TextField()
    image = models.ImageField(upload_to='images')
    # video = models.ForeignKey(VideoObject, blank=True, null=True, on_delete=models.SET_NULL, related_name="video_obj") # One-to-many relationship
    video = models.ManyToManyField(VideoObject, blank=True, related_name="video_obj") # Many-to-many relationship
    language = models.ForeignKey(ProgLang, null=True, on_delete=models.SET_NULL)
    guest = models.ManyToManyField(SendMeMessage, blank=True)
    tags = models.ManyToManyField(Tag)

My views.py:
class MyEssaysView(View):

    def get(self, request, slug):
        user_agent = get_user_agent(request)
        selected_essay = EssayCls.objects.get(slug=slug)
        user_feedback = UserFeedback() # handling form submission 3.18.20

        context = {
                'essay_found': True,
                'essay_all': selected_essay,
                'post_tags': selected_essay.tags.all(),
                'comments': selected_essay.comments.all().order_by("-id"),
                'essay_videos': selected_essay.video.all()
            }

        if request.method == 'GET':

            if user_agent.is_pc:
                return render(
                            request,
                            'dev/article-content_pc_tablet.html',
                            context
                            )

How to solve it? The problem is with DTL syntax, or somewhere else (views/models)?
EDIT:

*

*{% video %} tag is related to embed-video library.

*The traceback of the exception:

A: The problem was with the syntax in for loop.
A proper way of defining a list of videos from the context provided by a class-based view that uses two models that have a relation many-to-many with the embed-video library is:

    {% for vid in essay_videos %}

{% video vid.video_item_url %}

    {% endfor %}

The rest of the code was fine.