text:
Q: can not take values in mysql database from the android app ,when it goes in background class , the app stop working after entering the values when i click on register button and it goes in the background class my app stop working , here is the code of that method
     public void userReg(View view)
     {
      name = ET_NAME.getText().toString();
    user_name = ET_USER_NAME.getText().toString();
    user_pass =ET_USER_PASS.getText().toString();
    String method = "register";
    BackgroundTask backgroundTask = new BackgroundTask(this);
    backgroundTask.execute(method,name,user_name,user_pass);
    finish(); }

here is the code of where actual working will perform in backgroundtask class
      protected String doInBackground(String... params) {
      String reg_url = "http://10.0.2.2/webapp/register.php";
    String login_url = "http://10.0.2.2/webapp/login.php";
    String method = params[0];
    if (method.equals("register")) {
        String name = params[1];
        String user_name = params[2];
        String user_pass = params[3];
        try {
            URL url = new URL(reg_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            //httpURLConnection.setDoInput(true);
            OutputStream OS = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
            String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                    URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
                    URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            OS.close();
            InputStream IS = httpURLConnection.getInputStream();
            IS.close();
            //httpURLConnection.connect();
            httpURLConnection.disconnect();
            return "Registration Success...";
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

here is the onpostExecute method , the problem is result receives null value form the background thats why its gonna crash and i dnt know how to fix it
       protected void onPostExecute(String result) {
   if (result.equals("Registration Success...")) {
        Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
    } else {

       // Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
        alertDialog.setMessage(result);
        alertDialog.show();
    }

i dont know whats wrong in this code, as i am new related to server side i took help from youtube video in making this code here is the logcat output
   Process: com.awan.app.webappdb, PID: 26144
   java.lang.NullPointerException
        at       com.awan.app.webappdb.BackgroundTask.onPostExecute(BackgroundTask.java:84)
        at com.awan.app.webappdb.BackgroundTask.onPostExecute(BackgroundTask.java:25)
        at android.os.AsyncTask.finish(AsyncTask.java:632)
        at android.os.AsyncTask.access$600(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:146)
        at android.app.ActivityThread.main(ActivityThread.java:5635)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
        at dalvik.system.NativeStart.main(Native Method)

A: Since you allow doInBackground to return null you should be checking for null values in onPostExecute.
A quick way to change the code so that it can handle null value is to flip the order of the operators inside the if-condition:
if("Registration success...".equals(result)) { ...


text:
Q: How to return id from NHibernate ISession.SaveOrUpdate I am using ISession.SaveOrUpdate to insert new objects and updaet existing.
If I use ISession.Save(..) this returns the identity of the inserted record.
For SaveOrUpdate I am doing the following:
   public int Save(Vehicle entity) {
        using (var txn = _session.BeginTransaction()) {
            _session.SaveOrUpdate(entity);
            txn.Commit();
        }
        return entity.Id;
    }

Is this the best way to return my identity?
Thanks,
Ben

A: There's nothing wrong with that. But since the identity is set on the object, why not make the method return void:
   public void Save(Vehicle entity) {
    using (var txn = _session.BeginTransaction()) {
        _session.SaveOrUpdate(entity);
        txn.Commit();
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why datepicker.parseDate is not working? According to datepicker.parseDate reference, this method accepts two parameters, a format and a date and try an exception if the *date not match the format. Perfect, but then, why this piece of code is not working?
function isDate(value) {
    var isDate = false;
    try {
        var dateFormat = "yy";
        $.datepicker.parseDate(dateFormat, value);
        isDate = true;
    } catch (e) {}
    return isDate;
}

EDIT: I've found a simpler example. This returns an "Invalid date" exception.
$.datepicker.parseDate('yy', '2010');

A: According to the docs:

'Invalid date' if the date is invalid, such as '31/02/2007'

In other words, your string value actually has to be a full date. That gets turned into a Date object and then it formats it for you.
Try:
$.datepicker.parseDate('yy', '18/10/2011');

A: Try this:
var dateObject = $.datepicker.parseDate('d/m/yy', '18/10/2011');

One thing that surprised me is jQueryUI's symbols used in the date format string were a little different than I was used to seeing in C#.  Here is the link that describes what they mean:
http://docs.jquery.com/UI/Datepicker/parseDate

A: try either
$.datepicker.parseDate('yyyy', '2010');

or
$.datepicker.parseDate('yy', '10');


text:
Q: Saving a CSV into a blob I would like to save CSV files that users upload to a blob. I would than like to retrieve the CSV file out of the blob in a format that I can use with the ruby CSV library. Any ideas on how I can accomplish that?

A: You'll have to add a field to your model with datatype :text (because that's what a CSV is, not binary). Let's say your model is called Record and the field is called csv:
record = Record.new
record.csv = File.read 'path/to/csv'
record.save
#... later...
CSV.parse record.csv # => here's your csv

Questions?


text:
Q: ec2 aws only index page is routing, further is error as - URL NOT FOUND Only index page of aws ec2 instance is routing fine. further pages are not routing at all. I get an error as - URL NOT FOUND
It happened after i upgraded from php56 to php70.
I did restart httpd service

A: I got this fixed.
I needed to edit and modify below in httpd.conf inside etc/conf
 AllowOverride All
for Directory /var/www and Directory /var/www/html


text:
Q: Multiple JDBC Statements in Single Try Catch Block. is it Good Practice? I am new to Java, and my Work is all related to JDBC - about inserting and processing data. Over all its working fine.
To reduce code am using single try{} catch()block to write multiple JDBC Statements and Prepared Statements.
Example Code:
public void dashboardReports()
{
    try {

        String total_stock_value="select sum(price*closingstock)as tsv from purchase_table";
        Statement ps_tsv=connection.createStatement();
        ResultSet set_tsv=ps_tsv.executeQuery(total_stock_value);
        if(set_tsv.next())
        {
            total_stock.setText(set_tsv.getString("tsv"));
        }

        String tota_sales="select sum(INVOICE_VALUE) as iv from  PARTYWISE_ACCOUNTS_LEDGER";
        Statement st_total_sales=connection.createStatement();
        ResultSet set_total_sales=st_total_sales.executeQuery(tota_sales);
        if(set_total_sales.next())
        {
            total_sales.setText(set_total_sales.getString("iv"));
        }

        String total_purchases="select sum(CP_INVOICEVALUE)as cpi from COMPANY_PAYMENTS";
        Statement st_tps=connection.createStatement();
        ResultSet set_tps=st_tps.executeQuery(total_purchases);
        if(set_tps.next())
        {
            total_purchases_label.setText(set_tps.getString("cpi"));
        }

        String total_collectionss="select sum(PAYMENT_REC) as payrec from PARTYWISE_ACCOUNTS_LEDGER";
        Statement ps_toco=connection.createStatement();
        ResultSet set_toco=ps_toco.executeQuery(total_collectionss);
        if(set_toco.next())
        {
            total_collections.setText(set_toco.getString("payrec"));
        }

        String total_payments="select sum(CP_PAYMENTREC) as paid from COMPANY_PAYMENTS";
        Statement ps_topa=connection.createStatement();
        ResultSet set_topa=ps_topa.executeQuery(total_payments);
        if(set_topa.next())
        {
            total_payments_label.setText(set_topa.getString("paid"));
        }

    } catch (Exception e) {
        // TODO: handle except
    }
}

So is this Good Way to Handle or another other way?
As of now my code is working very fine, do we have any future problems with this kind of approach.

A: This violates the Single Responsbility and the Single Layer of Abstraction principles.
So although this code is technically valid; you should not only focus on its correctness, but also on its readability. And testability. And I think neither of does are "great" in the input you are showing.
Thus; coming from a clean code (quality) perspective; I would rather advise to go for something along the lines of:
outer method ...
  try {
    helperMethod1();
    helperMethod2();
  } catch( ...

with a small helper for each of the different cases you got there. And of course, you wouldn't stop there; but try to isolate common aspects of those helpers; and to maybe find ways to go with a single, more generic helper.
And of course: you try to avoid catching Exception if possible. Instead, you catch the most specific exception possible!

A: Since you are only doing SELECT operations here, there is no real need for an explicit transaction, because you are not changing the state of the database, and there is nothing to rollback.  There is nothing wrong with grouping all SELECT statements inside a single try block.  However, there is a potential drawback, namely that if one SELECT fails, your code will exit that try block and all subsequent queries will not run.  If you can tolerate this, then you can leave your as is.  An analogy to this would be a series of lightbulbs connected in serial; if one breaks, then they all go out.
An alternative to what you have would be to use separate try blocks for each query.  Then, even if an exception were to happen in one of them, it is possible that the others could complete successfully.  The analogy here would be a series of lightbulbs in a parallel circuit.

A: I think your code is ok.
You need close resultset, statement and connection in block finally.

A: If you are happy with all subsequent SELECTs failing if one fails, then I would change the method to throw an exception
public void dashboardReports() throws SQLException
{
 ....
}

and then catch the SQLException from the calling method.
Note I think it is better to throw/catch a SQLException rather than a Exception

A: Just make sure you close your statements and resultsets:
try {

    String total_stock_value="select sum(price*closingstock)as tsv from purchase_table";
    try (Statement ps_tsv=connection.createStatement();
        ResultSet set_tsv=ps_tsv.executeQuery(total_stock_value)) {
        if(set_tsv.next())
        {
            total_stock.setText(set_tsv.getString("tsv"));
        }
    }

    String tota_sales="select sum(INVOICE_VALUE) as iv from  PARTYWISE_ACCOUNTS_LEDGER";
    try (Statement st_total_sales=connection.createStatement();
            ResultSet set_total_sales=st_total_sales.executeQuery(tota_sales)) {
        if(set_total_sales.next())
        {
            total_sales.setText(set_total_sales.getString("iv"));
        }
    }

    String total_purchases="select sum(CP_INVOICEVALUE)as cpi from COMPANY_PAYMENTS";
    try (Statement st_tps=connection.createStatement();
            ResultSet set_tps=st_tps.executeQuery(total_purchases)) {
        if(set_tps.next())
        {
            total_purchases_label.setText(set_tps.getString("cpi"));
        }
    }

    String total_collectionss="select sum(PAYMENT_REC) as payrec from PARTYWISE_ACCOUNTS_LEDGER";
    try (Statement ps_toco=connection.createStatement();
            ResultSet set_toco=ps_toco.executeQuery(total_collectionss)) {
        if(set_toco.next())
        {
            total_collections.setText(set_toco.getString("payrec"));
        }
    }

    String total_payments="select sum(CP_PAYMENTREC) as paid from COMPANY_PAYMENTS";
    try (Statement ps_topa=connection.createStatement();
            ResultSet set_topa=ps_topa.executeQuery(total_payments)) {
        if(set_topa.next())
        {
            total_payments_label.setText(set_topa.getString("paid"));
        }
    }

} catch (Exception e) {
    // TODO: handle except
}

}

A: 1.You can have a method like , executeQuery(Connection conn, Statement st, String sql) to encapsulate and reduce your lines of code.
2.Don't rely on generic Exception , catch sql specific exception classes too
3.I don't see a finally block there to properly close resources unless you are doing that somewhere else. Alternatively, you can try using try with resource syntax to eliminate need of finally block
4.See what you need to do in catch block - do you need to propagate exception up above the chain or fail the program right there?
5.In my opinion, a ResultSet and Statement needs to live as short as they can so try closing them as soon as you can - don't wait to close them all in single chunk. Point#1 will help in achieving this.
From technical correctness and validity perspective, there is no harm in writing code the way you did- using a single try-catch for all SQLs and eating out any exceptions ( since I see only SELECT sqls there) but there are clean,readable and maintainable code and on that front, your code looks poor.

A: Though your code works, I strongly suggest to refactor it for better maintenance and readability as shown below. Also, ensure that the resources are closed properly:
public void dashboardReports() {
     handleTotalStocks();
     handleTotalSales();
     handleTotalPurchages();
     //Add others
}

handleTotalStocks() method:
private void handleTotalStocks() {
       String total_stock_value="select sum(price*closingstock)as tsv
                     from purchase_table";

     try(Statement ps_tsv=connection.createStatement();
        ResultSet set_tsv=ps_tsv.executeQuery(total_stock_value);) {
         if(set_tsv.next()) {
            total_stock.setText(set_tsv.getString("tsv"));
         }
       }
  }
 //add other methods

A: Better way is to create method that does common operations:
public String execute(String query) throws SQLException {
Statement ps_toco=connection.createStatement();
        ResultSet set_toco=ps_toco.executeQuery(query);
        return set_toco.next();
}

When you call this method surround it with try catch block.


text:
Q: Tesseract getutf8text performance I have been working with an app that uses the Tesseract API in order to support OCR. This is done by using a Surfaceview which shows the camera output (Camera2 API) and a ImageReader instance which is used to get the images from the camera. The camera is setup to be of the type setRepeatingRequest so new images are available very frequent. When I make a call to the getutf8text() method to get the readable text in images it makes the preview of the camera which is showed on the Surfaceview lag.
Are there any settings in the Tesseract API which can be set so it speeds up the getutf8text() method call or anything else I can do in order to get the preview Surfaceview to not lag?
Any help or guidance is appreciated!

A: Most of the things that you can do to speed up performance occur separately from the Tesseract API itself:

*

*Run the OCR on a separate, non-UI thread

*Grab a new image to start OCR on after OCR has finished on the last image. Try capture instead of setRepeatingRequest.

*Downsample the image before OCR, so that it's smaller

*Experiment with different Tesseract page segmentation modes to see what's the fastest on your data

*Re-train the Tesseract trained data file to use fewer characters and a smaller dictionary, depending on what your app is used for

*Modify Tesseract to perform only recognition pass #1

*Don't forget to consider OpenCV or other approaches altogether

You didn't say what Tesseract API settings you're using now, and you didn't describe what your app does in a general sense, so it's hard to tell you where to start, but these points should get you started.

A: There are a few other things which you can try.

*

*Init tesseract with OEM_TESSERACT_ONLY

*Instead of using full-blown training data, use a faster alternative from https://github.com/tesseract-ocr/tessdata_fast.

*Move the recognition to the computation thread.


text:
Q: How to disable migrations for specific Django 1.7 apps? How do you disable migrations for specific apps in Django>=1.7?
I'm trying to upgrade from Django 1.6 to 1.7, and I made some trivial changes to Django's auth app to change labels, but a design flaw in Django>=1.7 now treats all attributes as part of the database schema, triggering a new migration. Moreover, running manage.py makemigration myapp generates a migration for all other apps touching myapp, so even though I'm not explicitly trying to create a migration for auth, it's forcing me to do so, and I see no way to turn this off.
This is creating havoc, since I have a dozen apps that touch auth, so this is causing Django to create over a dozen pointless migrations.
I tried creating a custom auth migration directory using MIGRATION_MODULES, but doesn't seem to work. Any app that relies on auth now throws an error like:
ValueError: Lookup failed for model referenced by field helpdesk.Queue.group: auth.Group

If I try to migrate auth. How do I fix this? Ideally, the simplest solution would be to just "turn off" migrations for auth, since I'm not actually making any changes to it.
Edit: This is the custom migration Django forces me to generate:
class Migration(migrations.Migration):

    dependencies = [
        ('admin', '0001_initial'),
        ('auth', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='LogEntry',
            fields=[
            ],
            options={
                'ordering': ('-action_time',),
                'verbose_name': 'log entry',
                'proxy': True,
                'verbose_name_plural': 'log entries',
            },
            bases=('admin.logentry',),
        ),
        migrations.AlterField(
            model_name='permission',
            name='name',
            field=models.CharField(max_length=500, verbose_name='name'),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='user',
            name='username',
            field=models.CharField(help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True, max_length=75, verbose_name='username', validators=[django.core.validators.RegexValidator('^[\\w.@+-]+$', 'Enter a valid username.', 'invalid')]),
            preserve_default=True,
        ),
    ]

My custom changes are to make the username and email fields the same length (because the two are the same in my system), as well as change the default validator to validate them both as an email address. I've been using these changes since Django 1.3. Presumably, they're only a problem now that I'm no longer using South and have to re-generate all my migrations.
And it looks like I can't use MIGRATION_MODULES to even generate this into a custom migration folder, because I have some other apps that depend on auth's 0001_initial migration, like:
class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

So if I override it with MIGRATION_MODULES like:
MIGRATION_MODULES = {
    'auth': 'myoverrides.auth_migrations',
}

that migration effectively disappears, throwing the error.

A: It's a bit of a hack, but I modified my settings.py to check sys.argv for "makemigrations" and remove the conflicting apps, that are effectively unmanaged, from my INSTALLED_APPS list. This allowed me to properly generate a custom auth migration. e.g.
if 'makemigrations' in sys.argv
    INSTALLED_APPS.remove('conflicting_third_party_app')


text:
Q: Expected a list of items but got type \"int\"." abby_res_data.py
from django.db import models
import uuid # Required for unique book instances
# Create your models here.
from datetime import datetime
import pytz
import shutil
from .abbyuser import userData
from django.utils import timezone

class image_parsing(models.Model):

    id = models.AutoField(primary_key=True,null=False,editable=True)
    user_pk_id = models.ForeignKey(userData, related_name='fk_id', on_delete = models.CASCADE, db_column='user_pk_id' , null=True)
    request = models.CharField(max_length=200, null=True, editable=True)
    filename = models.CharField(max_length=200, null=True, editable=True)
    response = models.CharField(max_length=200, null=True, editable=True)
    created_date = models.DateTimeField(default=timezone.now, blank=True, editable=True, max_length=30)
    updated_date = models.DateTimeField(default=timezone.now, blank=True, editable=True, max_length=30)

user_credits.py
from django.db import models
import uuid # Required for unique book instances
# Create your models here.
from datetime import datetime

class userCredit(models.Model):

    id = models.AutoField(primary_key=True,help_text='unique user_id',default=uuid.uuid4,null=False)
    user_pk_id = models.IntegerField(null=True,editable=True)
    certification = models.CharField(max_length=200, null=True,editable=True)
    awardStatus = (
        ('V','VIP'),
        ('VV', 'VVIP'),
        ('VV', 'VVVIP'),
    )
    user_level_status = models.CharField(max_length=200,choices=awardStatus,blank=True,default='V',help_text='Award Level')
    created_date = models.DateTimeField(auto_now_add=True, blank=True, editable=True)
    updated_date = models.DateTimeField(default=datetime.now, blank=True, editable=True, max_length=30)

    def __str__(self):
        return self.name

model_image_serializers.py
from rest_framework import serializers
from ..models import image_parsing
from ..Serializers import abbyserializers

class imageSerializer(serializers.ModelSerializer):
    user_pk_id = abbyserializers()
    class Meta:
        model = image_parsing
        fields = ('id', 'request', 'filename',  'response',  'created_date',  'updated_date', 'user_pk_id')

model_serializers.py
from rest_framework import serializers
from ..models import userData

class abbyserializers(serializers.ModelSerializer):
    class Meta:
        model = userData
        fields = ("user_id","userName", "user_address", "user_pincode", "user_status", "created_date", "updated_date", "user_level_status")

When I am trying to save data it throws an error:
"user_pk_id": {
    "non_field_errors": [
        "Expected a list of items but got type \"int\"."
    ]
}


text:
Q: Calculator Confusion: fractional roots of negative numbers (Calculator type: Sharp EL-W531)
When I put in the power (-0.2)^(-4/5) it says "calculation error."
Is this not just raising $(-0.2)^{-4}$ then taking the 5th root of that?


text:
Q: How to invoke pardiso function in mex file when using gfortran compiler I'm trying to invoke Parsido function in mex file using gfortran compiler on Linux system. I use following instruction to compile:
mex '-I ${EBROOTIMKL}/mkl/include'...,
    '-L ${EBROOTIMKL}/mkl/lib'...,
    -lmkl_rt...,
    pardiso_sym_f90.f90 ero_dep_fortran.F -output ero_dep_fortran

I can successfully compile the mex file, but when I excute, Matlab crashes without any error information. I know it might be due to the use of -lmkl_rt, which might conflict with the Intel iomp5 implementation of OpenMP which MATLAB uses.
Any suggestions will be appreciated.


text:
Q: How to change http.sys web server response when maxconnection limit reached We are using http sys web server to host web api service. Business requires to limit maximum number of concurrent connections. MaxConnections configuration property used for that purpose:
services.Configure<HttpSysOptions>(options =>
{
    options.MaxConnections = Configuration.GetValue<long?>("MaxConnections");
});

But in case when concurrent connection limit reached all new connections got dropped on a socket level. Is it possible to change this behaviour so server accepts the request and returns 4xx or 5xx response to the client?

A: I have finally managed to find a solution: there is Http503Verbosity property in options. By default it is set to Http503VerbosityLevel.Basic but if to change it to Http503VerbosityLevel .Limited or Http503VerbosityLevel.Full 503 response will be returned for requests above limit. So my code looks like this now:
        services.Configure<HttpSysOptions>(options =>
        {
            options.MaxConnections = Configuration.GetValue<long?>("MaxConnections");
            options.Http503Verbosity = Http503VerbosityLevel.Full;
        });


text:
Q: as3: Box2d how to find nearest bodies How do I find bodies which are located near given body.
About the task. I am trying to detect bodies which are near current. To do it, I've created quite a big collision shape, around the current body, and made it sensor. Collision event was triggered, but it's not what I need. Main thing is that collision event is called only first time when another body entered the detection field... And I want to be able to detect changes in bodies location, after it. (I am considering the fact that other bodies are moving inside detection field)

A: Why not just keep track of collision by storing the bodies in a collection? On a EndContact you can remove said body from the collection.
As for tracking the bodies inside this detection field, you could loop through this collection and check the positions.
Alternavily, if accuracy was not a huge concern, create a few sensor bodies, each with a smaller radius that the last and then you can detect which zone it is in.


text:
Q: How can a k8s namespace admin use top? We have a shared tenant cluster, and we want our developers to be able to run kubectl top pods --namespace dev-namespace
But it seems to me that for top to be usable, you need to be able to run kubectl get nodes. But nodes are not namespaced.
Is there a solution?
We the namespace admin setup like this:
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: admin
subjects:
- apiGroup: rbac.authorization.k8s.io
  kind: User
  name: username@domain

And as a cluster admin I can run the top command, so metrics-server seems to be working fine.

A: Kubernetes has API group metrics.k8s.io, that you can use to give read permission for kubectl top pods -n <namespace>. If you grant get and list permissions for pods, you can run the command.
I tested the configuration below in a GKE cluster running Kubernetes 1.21 with kubectl top pod --as=system:serviceaccount:monitoring:test-account -n monitoring. With these permissions, I can only run kubectl top pod in the monitoring namespace, other commands will fail.
apiVersion: v1
kind: ServiceAccount
metadata:
  name: test-account
  namespace: monitoring
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-reader
  namespace: monitoring
rules:
- apiGroups: ["metrics.k8s.io"]
  resources: ["pods"]
  verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
  namespace: monitoring
subjects:
- kind: ServiceAccount
  name: test-account
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io


text:
Q: Sql Server em C# utilizando BindingSource Estou em um projeto onde tenho uma tela de venda. Ao realizar uma venda, um método verifica se o cliente tem uma conta. Se ele não tiver, ele cria uma pra ele, até aí tudo certo. Mas se o cliente já possuir essa conta, ele precisa alterar os dados apenas. Mas quando vou alterar os dados usando BindingSource, ele altera pelo DataGridView e está alterando o primeiro registro apenas.
Preciso de um filtro que pegue o nome do cliente a ser alterado, e automaticamente ele me coloque na linha do datagridview desse cliente que já vai estar cadastrado. Tentei isso mas não deu certo.
String searchValue = txtNome.Text;

int rowIndex = -1;
foreach (DataGridViewRow row in dgvFicha.Rows)
{
  if (row.Cells[2].Value.ToString().Equals(searchValue))
  {
     rowIndex = row.Index;
     break;
  }
}


text:
Q: RTL HTMl Grid Framework/Css i mostly use bootstrap for designing web application , but bootstrap lack RTL grid system and even Thu there are some third party enhancement to add RTL support to bootstrap most of them have bugs and are  incomplete ,
i was wondering if there is any css grid framework out there that has native support for  RTL .
i know foundation does , but i am afraid using it beside bootstrap will cause some conflict , also i Dont need all feature Foundation is providing , so i am looking for only lightweight grid system .
any suggestion ?


text:
Q: Use a variable from ancestor module when it's declared elsewhere Here's my situation. I have some legacy vanilla JavaScript loaded that contains this code:
window.A = { x: { /* several things live here */ } };

This is the minimal code to repro my problem. In reality A is our global "namespace" object, and x is an object with some legacy functions I want to access in my newer Typescript classes.
So, after the above has run, I'm trying to access x inside a class in a nested Typescript module, like this:
module A {
    module B {
        export class Item {
            constructor(){
                alert(A.x);
            }
        }
    }
}

The Web Essesntials as well as the typescriptlang.org site can generate JavaScript which will in fact work as required, but VS2012' respectively typescriptlang.org's syntax highlighting both complain that:

Property 'x' does not exist on type 'typeof A'.

This makes sense. In this question it's shown how you need to inform the compiler of global variables, so I've tried adding...
declare var x: any;

...to module A, but this doesn't help. I've also tried...
declare var A.x: any;

...both inside and outside module A, but this doesn't help either.
So, how do I inform the Typescript compiler of A.x in a way so that I can access it safely inside Item?

A: If you add this to your TypeScript file it know that x does exist, you can also add typeinfo to this.
Because of the declare it won't produce any code it is just some info for the TypeScript compiler.
declare module A {
    var x;
}

You can find more info here: Writing Definition Files


text:
Q: Print list items - python I have a list with two item, each item is a dictionary. now I want to print the item but as these are dicts, python writes the dicts and not the name. any suggestion?
sep_st = {0.0: [1.0, 'LBRG'], 0.26: [31.0, 'STIG']}
sep_dy = {0.61: [29.0, 'STIG'], 0.09: [25.0, 'STIG']}
sep = [sep_st, sep_dy]
for item in sep:
  for values in sorted(item.keys()):
    p.write (str(item)) # here is where I want to write just the name of list element into a file
    p.write (str(values))
    p.write (str(item[values]) +'\n' )

A: My suggestion is that you use a dict for sep, instead of a list. That way you could make the dict names as string-keys for them:
sep_st = {0.0: [1.0, 'LBRG'], 0.26: [31.0, 'STIG']}
sep_dy = {0.61: [29.0, 'STIG'], 0.09: [25.0, 'STIG']}
sep = {"sep_st": sep_st, "sep_dy": sep_dy} # dict instead of list
for item in sep:
  for values in sorted(sep[item].keys()):
    p.write (str(item))
    p.write (str(values))
    p.write (str(sep[item][values]) +'\n')

As you can see in this other question, it's impossible to access instance names, unless you subclass dict and pass a name to the constructor of your custom class, so that your custom dict instance can have a name that you can have access to.
So in that case, I suggest that you use dicts with name-keys to store your dicts, instead of a list.

A: As sep is a list of variables storing the dictionaries,  when you try to print sep you will print the dictionaries.
If you really need to print each variable name as a string, one way to do that is this to also create an other list with the variable names as strings:
sep_st = {0.0: [1.0, 'LBRG'], 0.26: [31.0, 'STIG']}
sep_dy = {0.61: [29.0, 'STIG'], 0.09: [25.0, 'STIG']}
sep = [sep_st, sep_dy]
sep_name = ['sep_st', 'sep_dy']
for i in sep_name:
    print i

Then you can do the rest of your code.


text:
Q: Erlang: Mixing lists:seq with pattern matching I need your help again. I was wondering if it is possible to use lists:seq(from,to) within pattern matching? Below is the code that I am trying to achieve
product_selling_price_evaluate(lists:seq(1100,1190),standard_produce,Costprice) -> Costprice*10;
product_selling_price_evaluate(lists:seq(1200,1300),standard_produce,Costprice) -> Costprice*20;
product_selling_price_evaluate(lists:seq(1400,1500),standard_produce,Costprice) -> Costprice*30;
product_selling_price_evaluate(lists:seq(1600,1700),standard_produce,Costprice) -> 40*Costprice.

When I compile the code it gives me a illegal pattern error!
Example input would be
selling_price:product_selling_price_evaluate(1100,standard_produce,10).

and I want it to find the first one as a match and give the output as
100

Will lists:seq work with case?
Let me explain in a more simple way. I have the below cases
1100 to 1190   = Apples
1200 to 1300   = Oranges
1400 to 1500   = Bananas
1600 to 1700   = Berries

if I give the input as 1125 I want the output to be Apples. Again if I give the input as 1450, I want the output to be Bananas. I hope u guys understood, what am I trying to achieve!

A: If I interpret right what you are trying to achieve,  what you probably are looking for are guards.
Something like this (untested):
product_selling_price_evaluate(N,standard_produce,Costprice) when N >= 10 andalso N <= 20 -> Costprice*10;
product_selling_price_evaluate(N,standard_produce,Costprice) when N >= 21 andalso N <= 30 -> Costprice*20;
[...]

A: You're not giving the desired input, your function is expecting a list([11001,1101, 1102,...,1189,1190]) as its first argument, where as you're giving a number i.e. 1100.

A: Guards can be comma-separated (,), it has the same meaning same as andalso.
product_selling_price_evaluate(N,standard_produce,Costprice)
    when 10 =< N, N =< 20 -> Costprice*10;
product_selling_price_evaluate(N,standard_produce,Costprice)
    when 21 =< N, N =< 30 -> Costprice*20;
...

<= is illegal here, use =< instead.


text:
Q: Dirac Distribution in Polar Coordinates as a Measure I have a question.
I was browsing different scripts on statistical mechanics and saw a definition of the "area of accessible phase space at energy $E$ " for a single harmonic oscillator. The author quickly corrected himself, stating, that this is more of a contour in phase space. So I calculated both, got different results and need someone explaining, where my mistake is or what is causing this discrepancy.
For simplicity let's define the Hamiltonian as:
$$
H(q,p) = p^2 + q^2
$$
And the curve $\mathcal{C}$ in phase space $\Gamma=\{(q,p)\in\mathbb{R}^2\}$ is the circle, where $H=E$ with the radius $R=\sqrt{E}$.
Now the odd defintion for the mentioned area / contour given by the mentioned textbook author, where $\delta$ is the Dirac Distribution:
$$
N(E)
=\int\mathrm{d}\Gamma~\delta(H(q,p)-E)
$$
If I remember correctly there is also a tool given by the Dirac $\delta$ to evaluate compositions with a function $f$ which will come in handy:
$$
\delta(f(x))
=\sum\limits_{i=1}^N\frac{\delta(x-x_i)}{|{f'(x_i)}|}
$$
Here $x_i$ denote the roots of $f(x)$.
My calculation would now read as follows:
\begin{align*}
N(E)
&=
\int\limits_{-\infty}^\infty
\mathrm{d}q
\int\limits_{-\infty}^\infty
\mathrm{d}p
~
\delta(p^2+q^2-R^2)
=
\int\limits_{0}^\infty
\mathrm{d}\rho
~
\rho
~
\delta(\rho^2-R^2)
\int\limits_{0}^{2\pi}
\mathrm{d}\varphi \\
&=
2\pi
\frac{1}{2R}
\int\limits_{0}^\infty
\mathrm{d}\rho
~
\rho
~
\delta(\rho-R)
=\pi
\end{align*}
Here I used the know parameterization $(q,p)^T=(\rho\cos\varphi,\rho\sin\varphi)^T$.
It's significant, that I get (if I'm not wrong) the area of a unit circle independent of the energy $E$.
That's completely against my intuition so I try it again with an line integral over $\mathcal{C}=\{(q,p)\in\mathbb{R}^2|q^2+p^2=R^2\}$.
$$
N(E)
=
\int\limits_\mathcal{C}
\mathrm{d}s
=
\int\limits_0^{2\pi}
\mathrm{d}\varphi
\left|
\frac{\partial \vec{s}}{\partial \varphi}
\right|
=
\int\limits_0^{2\pi}
\mathrm{d}\varphi
\left|
\begin{pmatrix}
-R\sin\varphi
\\
R\cos\varphi
\end{pmatrix}
\right|
=
2\pi R
=2\pi \sqrt{E}
$$
This is of course a very simple calculation in this case of a circle.
So now my questions: These two results are different right? If yes, why thinks the author of this textbook, he could define a contour in phase space with the help of this Dirac Distribution and if he didn't intend to do that, what is the use of an "area" defined like this (with a DD)?

A: As I know little about the physical context that leads to the quantity $N(E)$, let me focus on the mathematical aspect. Note that
$$ \int_{\mathbb{R}^2} \mathrm{d}q\mathrm{d}p \, \delta(q^2+p^2-R^2)
= \left[ \frac{\partial}{\partial \epsilon} \int_{\mathbb{R}^2} \mathrm{d}q\mathrm{d}p \, \mathbf{1}_{\{ q^2 + p^2 - R^2 \leq \epsilon \}}  \right]_{\epsilon = 0}, $$
where $\mathbf{1}_{\{\cdots\}}$ is the indicator function notation, which takes value $1$ if $\cdots$ is true and value $0$ otherwise. On the other hand, the line integral in your second formulation corresponds to
$$ \int_{\mathcal{C}} \mathrm{d}s
= \int_{\mathbb{R}^2} \mathrm{d}q\mathrm{d}p \, \delta(\sqrt{\smash[b]{q^2+p^2}}-R)
= \left[ \frac{\partial}{\partial \epsilon} \int_{\mathbb{R}^2} \mathrm{d}q\mathrm{d}p \, \mathbf{1}_{\{ \sqrt{\smash[b]{q^2 + p^2}} - R \leq \epsilon \}}  \right]_{\epsilon = 0}. $$
In both cases, the integral is supported on the contour $H(q, p) = E$, but the surface measure is weighted in a different way, i.e., $ \mathrm{d}q\mathrm{d}p \, \delta(q^2+p^2-R^2) = \mathrm{d}q\mathrm{d}p \, \frac{1}{2R} \delta(\sqrt{\smash[b]{q^2 + p^2}}-R) $. Since this "energy shell" as a hypersurface in the phase space does not alone encode the information about the surface measure, it should be specified by other means. I guess that the definition
$$ N(E)
= \int \mathrm{d}\Gamma \, \delta(H(\Gamma) - E)
= \left[ \frac{\partial}{\partial \epsilon} \int \mathrm{d}\Gamma \, \mathbf{1}_{\{ H(\Gamma) \leq E + \epsilon \}}  \right]_{\epsilon = 0} $$
exactly serves this purpose, and perhaps the author's notion of "area" conforms to this choice.


text:
Q: Is there a series approximation in terms of $n$ for the sum of the harmonic progression : $\sum_{k=0}^{n}\frac{1}{1+ak}$? When $a=1$ the sum is given by $ H_{n} $ and we have : $$H_{n}=log(n)+γ+\frac{1}{2n}-\frac{1}{12n^2}+\frac{1}{120n^4} \hspace{0.5cm}.\hspace{.1cm}.\hspace{.1cm}. $$ Does any representation of a similar type exist for arbitrary positive $a$ ?

A: $\newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\sum_{k = 1}^{n}{1 \over 1 + ak} & =
{1 \over a}\sum_{k = 0}^{n - 1}{1 \over k + 1 + 1/a} =
{1 \over a}\sum_{k = 0}^{\infty}
\pars{{1 \over k + 1 + 1/a} - {1 \over k + n + 1 + 1/a}}
\\[5mm] & =
{1 \over a}\pars{H_{n + 1/a} - H_{1/a}}
\end{align}

Now you can use yor asymptotic formula as pleased.

A: $$\sum_{k=1}^{n}\frac{1}{1+ak} = \frac{1}{a}\sum_{k=1}^{n}\frac{1}{k+\frac{1}{a}}=\frac{H_n}{a}-\frac{1}{a^2}\sum_{k=1}^{n}\frac{1}{k\left(k+\frac{1}{a}\right)}=\frac{1}{a}H_n+O\left(\frac{1}{a^2}\right). $$

A: As Felix Marin answered,$$\sum_{k = 1}^{n}{1 \over 1 + ak}=\frac{H_{n+\frac{1}{a}}-H_{\frac{1}{a}}}{a}$$ Now, using the asymptotics $$H_m=\gamma +\log \left({m}\right)+\frac{1}{2 m}-\frac{1}{12
   m^2}+\frac{1}{120 m^4}+O\left(\frac{1}{m^5}\right)$$ $$H_{n+\frac{1}{a}}=\gamma +\log \left({n+\frac{1}{a}}\right)+\frac{1}{2 (n+\frac{1}{a})}-\frac{1}{12
   (n+\frac{1}{a})^2}+\frac{1}{120(n+\frac{1}{a} )^4}+O\left(\frac{1}{n^5}\right)$$ Now, developing each term as Taylor series $$\log \left({n+\frac{1}{a}}\right)=\log \left({n}\right)+\frac{1}{a n}-\frac{1}{2 a^2 n^2}+\frac{1}{3 a^3
   n^3}-\frac{1}{4 a^4 n^4}+O\left(\frac{1}{n^5}\right)$$ $$\frac{1}{ (n+\frac{1}{a})}=\frac{1}{n}-\frac{1}{a n^2}+\frac{1}{a^2 n^3}-\frac{1}{a^3
   n^4}+O\left(\frac{1}{n^5}\right)$$ $$\frac{1}{ (n+\frac{1}{a})^2}=\frac{1}{n^2}-\frac{2}{a n^3}+\frac{3}{a^2
   n^4}+O\left(\frac{1}{n^5}\right)$$  $$\frac{1}{ (n+\frac{1}{a})^4}=\frac{1}{n^4}+O\left(\frac{1}{n^5}\right) $$and replacing, you should get
$$\sum_{k = 1}^{n}{1 \over 1 + ak}=\frac{\gamma-H_{\frac{1}{a}} }{a}+\frac{\log \left({n}\right) }{a}+\frac{a+2}{2 a^2
  }\frac 1{n}-\frac{a^2+6 a+6}{12 a^3 }\frac 1{n^2}+\frac{a^2+3 a+2}{6 a^4 }\frac 1{n^3}+\frac{a^4-30 a^2-60
   a-30}{120 a^5 }\frac 1{n^4}+O\left(\frac{1}{n^5}\right)$$
Take care that, for $a=1$ $$\sum_{k = 1}^{n}{1 \over 1 + k}=H_{n+1}-1=\gamma -1+\log \left({n}\right)+\frac{3}{2 n}-\frac{13}{12
   n^2}+\frac{1}{n^3}-\frac{119}{120
   n^4}+O\left(\frac{1}{n^5}\right)$$ and not $H_n$ (for which you gave the correct expansion) because of the shift of the index.


text:
Q: E-Commerce Product Custom Field Kentico 10 I am using E-commerce module of Kentico portal and it has two fields for Products pricing :  SKUPrice and SKURetailPrice.
I needed one more field to show sell price and I added a new field in Modules application of the portal.(Modules->E-Commerce->Classes->SKU->Fields->New Field)
Now, I need to access this field in my code,but SKUInfo class doesn't show me the newly added field.What I need to do so that the newly added field reflects in my project code ?
I have already build the entire solution multiple times.Any other solutions please.

A: You can use GetValue and SetValue methods for such fields like this:
SKUInfo sku = ...;
string a = sku.GetValue("field").ToString();
sku.SetValue("field", "value");

A: JanH has the answer for custom fields you set, also keep in mind though that there is a "SKUCustomData" for other information that you want to store.  It takes a Name-Value pair dictionary if memory serves me correctly, and useful if you need to store configuration information or other things that won't be located on the normal SKU table.


text:
Q: Glassfish Server4 maximum pool size and max wait time The Glassfish4 server installed on my machine has Maximum Pool Size = 32 connections. Two cron jobs are scheduled from my application after every 10 and 15 mins on this server. The server crashed after 2 hours with the exception "java.sql.SQLException: Error in allocating a connection. Cause: In-use connections equal max-pool-size and expired max-wait-time. Cannot allocate more connections."
So, I altered the JDBC Connection pool settings and put in really large numbers just to see what would happen.
Maximum Pool Size: 1000000000 (1 billion)
Max Wait Time: 300000 (5 minutes)
Now my cron jobs are running fine.
Do you think having set the JDBC Connection pool attributes this high could cause issues? Please advise what values will be optimum.

A: I have resolved this issue with below settings in Glassfish4

Initial and Minimum Pool Size:16
Maximum Pool Size:64
Pool Resize Quantity:4
Idle Timeout:60
Max Wait Time:3000

I enabled connection leak monitoring in Glassfish4.
After enabling connection leak monitoring, when I checked the monitored data after some time, I could see ConnectionLeak exception in logs in some of my java classes. I closed the connections in these classes as they were being made directly from Connection object and JPA Entity Manager was not used in them.
Now all my cron jobs are running without Server crash.


text:
Q: Why is 'goto' seen as bad form? I would find it very useful in Python, and am curious as to why Python doesn't have it. Thanks!

A: Normally goto is explicitly used to make error handling more simple and code more readable by languages like C. Python has try and except for this, so that makes the goto statement unnecessary.


text:
Q: How to Add png Images to JS using Webpack? I'm working on creating an HTML5 game. I'm using a boilerplate that uses Webpack.
I've been trying to add png images from my local folder into a js file but I keep getting the following errors:
GET http://localhost:3000/alien.png 404 (Not Found) and Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.
The code I used in my canvas.js file is as follows:
let alienImg = new Image();
alienImg.src = 'alien.png';
c.drawImage(alienImg, 300, 300)

Am I doing something wrong in the way I'm trying to get the image on to the canvas, or is it something in my webpack.config.js file?
The webpack file is below, for reference:
 module: {
        rules: [
            {
                test: /\.(js)$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['env']
                    }
                }
            },
            {
                test: /\.html$/,
                loader: 'html-loader?attrs[]=video:src'
            },
            {
                test: /\.mp4$/,
                loader: 'url-loader?limit=10000&mimetype=video/mp4'
            },
            {
                test: /\.png$/,
                loader: "url-loader?mimetype=image/png"
            }
        ]
    },

Can anyone please help me? Thank you in advance!

A: I just did this using: html2Canvas
import html2canvas from 'html2canvas';

...
html2canvas(document.querySelector(selector)).then(canvas => {
  console.log(canvas);
  document.body.appendChild(canvas)
  canvas.setAttribute('downloads', 'nameOfImage.png')
  var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
  window.location.href = image
});

I hope this can help in some way. If so, happy days. :)

A: When you use:
alienImg.src = 'alien.png';

You are giving the image a url to the image - which presumably doesn't exist at that path, (given that it's giving you a 404).
I think what you want to do instead is
import alienImage from './alien.png';

And then you can use
alienImg.src = alienImage;

What this is doing is that is giving you the correct URL of the image location - after webpack has done its bundling and exposing public resources.


text:
Q: Java Load Balancing Options Rather than reinvent the wheel, I'd like to utilize an open source load balancer for my Java backend. I'll be using GlassFish as the app server (running an EAR), and each app server will most likely be running on an Ubuntu Server VM.

So the load balancer will probably (although I'm open for other ideas!) be its own Ubuntu Server VM running some sort of open source load balancing software. As to what this is (please note the big "?" in the diagram!) I don't really care so long as it:

*

*Is super fast

*Is secure

*Plays nice with GlassFish

*Is free and open source and comes with a license that doesn't restrict me from selling this system as a product or service

*Is relatively easy to configure (but I'm not scared do get my hands dirty)

Just wondering what my (best) options were. So far I've scouted out:

*

*Apache HTTPd

*haproxy

*nginx

But nothing is blowing my doors down as being the end-all-be-all-obvious-solution to my requirements. Thanks in advance for any suggestions or nudges in the right direction!

A: GlassFish Server Open Source Edition supports AJP (mod_jk, mod_proxy, see the administration guide in the all-in-one docs bundle). Oracle GlassFish Server ships with a plugin that works with Apache httpd, IIS, and the Oracle iPlanet Web Server.
Hope this helps.

A: Here is a complete overview about what comes out-of-the-box and is commonly used.
http://blog.eisele.net/2012/01/throwing-light-on-glassfish-webserver.html
In commercial scenarios I have seen a lot of BigIP products in use.

A: I have used Python Director in the past with great success. This isn't really a Java problem, any SLB ( Software Load Balancer ) will do the job to load balance and proxy HTTP.
We actually hacked ZeroConf / Bonjour into our version of Python Director so that the load balancer would auto discover when things were added or removed from the network automatically.
It worked in production for a couple of years with no issues, we never had to touch it.


text:
Q: How to change the format of abbreviated month with a ending dot in my software R? I am Peruvian and I'm learning to program in R
when I convert a character to date using the function as.Date I get NA.
This is because the abbreviated month does not have a point (Jul. Sep.)

fecha<-c("06-jul-2015","06-sep-2012")
as.Date(fecha, format="%d-%b-%Y")

[1] NA NA
Please. How I can do to R consider the abbreviated month without the point?
Thank You So Much

A: I had exactly the same problem yesterday. I just added the following line
Sys.setlocale("LC_TIME", "C")
fecha<-c("06-jul-2015","06-sep-2012")
as.Date(fecha, format="%d-%b-%Y")

and it works:
"2015-07-06" "2012-09-06"

Edit: for the Spanish and the dot in your comment:
Sys.setlocale("LC_TIME","Spanish")
fecha<-c("06-ene.-2015","06-dic.-2012")
as.Date(fecha, format="%d-%b.-%Y")


text:
Q: Collapsible accordion spreads and collapse instantly I have a collapsible accordion placed inside a form. Pressing the button to spread, the accordion spreads and collapse back instantly. If I don't put it in the form, it works fine for me. This is the simplified code:
index.html:

    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="estilos.css">

    <form  method="post" id="platos">

    <button class="accordion">Section 1</button>

Lorem ipsum...

    <button class="accordion">Section 2</button>

Lorem ipsum...

    <button class="accordion">Section 3</button>

Lorem ipsum...

    </form>

collapsible.js
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
}

A: Your form getting an action submit from the buttons.
you need to add to your function e.preventDefault() like this
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].addEventListener("click", function (e) {
        e.preventDefault()
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    });
}

A: For each button inside the form tag, specify type="button", and these buttons will stop working as a submit:
<button type="button" class="accordion">Section</button>


text:
Q: Deserializing encrypted objects from file I want to deserialize encrypted objects (multiple instances of the same object type) from a file, that were added during execution of a program. The objects were encrypted using CryptoStream.
However, when deserializing i cannot loop through cryptoStream as I intended.
I can serialize and encrypt the objects and the file grows with every object added.
I can also deserialize the first encrypted object. However, following objects cannot be restored.
I have tried different approaches to loop though the stream. Also I tried other cryptostreams and working around that problem.
Serializing:
private void EncryptObjectToFile(TraceMessage pMessage, FileInfo pFileInfo)
    {
        if (pFileInfo == null) { pFileInfo = m_LogFile; }

        m_Formatter.Serialize(m_SerializedStream, pMessage);
        m_SerializedStream.Position = 0;

        using (FileStream logfile = new FileStream(m_LogFile.FullName, FileMode.Append))
        {
            using (CryptoStream cryptoStream = new CryptoStream(logfile, m_Algorythm.CreateEncryptor(key, iv), CryptoStreamMode.Write))
            {
                cryptoStream.Write(m_SerializedStream.ToArray(), 0, (int)m_SerializedStream.Length);
                cryptoStream.FlushFinalBlock();
            }
        }
    }

Deserializing:
private List<TraceMessage> DecryptObjectsFromFile(FileInfo pFileInfo)
    {
        List<TraceMessage> tmp = new List<TraceMessage>();

        try
        {
            READWRITELOCK.AcquireReaderLock(READERTIMEOUTS);
            Interlocked.Increment(ref READS);

            try
            {
                if (pFileInfo == null) { pFileInfo = m_LogFile; }

                m_SerializedStream.Position = 0;

                using (FileStream logfile = new FileStream(m_LogFile.FullName, FileMode.Open))
                {
                    using (var cryptoStream = new CryptoStream(logfile, m_Algorythm.CreateDecryptor(key, iv), CryptoStreamMode.Read))
                    {
                        if (cryptoStream.CanRead)
                        {
                            while (cryptoStream.Position < cryptoStream.Length)
                            {
                                tmp.Add((TraceMessage)m_Formatter.Deserialize(cryptoStream));
                            }
                        }
                    }
                }
            }
            catch(Exception exp) { }
            finally
            {
                READWRITELOCK.ReleaseReaderLock();
                Interlocked.Decrement(ref READS);
            }
        }
        catch (Exception) { }

        return tmp;
    }

In the end what i am trying to achieve is, to encrypt objects (multiple instances of the same object type) and add them to a file. As files can be added any time and cannot be collected in a list and then written to file, I want to add those objects to an already existing file.
Later I want to recreate each object that was encrypted and serialized to the file.


text:
Q: Storing and accessing matrix operated inside a function parallelized by pararrayfun of Octave/Matlab Pararrayfun is used this way
pkg load parallel;
# fun is the function to apply
fun = @(x) x^2;
vector_x = 1:10000;
vector_y = pararrayfun(16, fun, vector_x);

I intend to apply it to a function with this form
fun = @(i) zz(1:100,i+1) = z.^2;

where z is a column vector, and zz is a 100xi matrix. I want to get the matrix zz out after the pararrayfun() but I get nothing back. I dont know if I am using the right code or the right argument as I have just started using octave a month ago. Any help would really be appreciated.
Here is my attempted "full" code:
pkg load parallel;
z = linspace(-1,10,100).';
fun = @(i) zz(1:100,i+1) = z.^2;
i = 0:9999;
pararrayfun(16, fun, i);

I tried to use global zz but I still get nothing.

A: The first answer is that the zz variable inside you fun is a local variable. It would have to be declared as global, but this is not possible inside an anonymous function (defined with @() ...).
One might be tempted to try to define fun with
pkg load parallel;
z = linspace(-1,10,100).';
global zz
zz = zeros(100, 10000);
function fun1(idx, z)
  global zz
  zz(:, idx) = z.^2;
endfunction

fun = @(idx) fun1(idx, z)

idx = 1:10000;
pararrayfun(nproc, fun, idx);

But the zz is not modified. Probably because each thread has its own context.
This is a good thing, because otherwise modifying a global variable inside a pararrayfun call would lead to potential race conditions.
Here is a safer way:
pkg load parallel;
z = linspace(-1,10,100).';
fun = @(i) z.^2;
idx = 1:10000;
zz = pararrayfun(nproc, fun, idx);

As a side note, for this example,
zz = repmat(z, 1, 10000);

would be much faster.


text:
Q: How can I register songs to my stereo? I have a stereo in Animal Crossing, but in order for it to play music I have to register songs
Where can I find these songs?

A: You can buy one of them each day at the ATM inside the resident services tent.
Choose the second option and you'll be able to buy some items with Bells. The available song changes each day.
If the new game follows the old games trend, there should be a couple of "hidden" songs, but I've not unlocked K.K. yet.


text:
Q: Unity find child with component in Start() function fails I can't find child objects of current gameobject(which is Prefab
I've got parent gameobject(it's creating from prefab in another script), and has 2 children. The hierarchy is like:
RewardItemPrefab
----RewardName(Has Text component).
----Image(Has SpriteRenderer component).
void Start ()
    {
        if (RewardText == null)
        {
            RewardText = this.GetComponentInChildren<Text>();
            if (RewardText == null)
            {
                Debug.Log("RewardText == null");
                return;
            }
        }

        RewardText.text = _text;

        if (RewardImage == null)
        {
            RewardImage = this.GetComponentInChildren<Image>();
            if (RewardImage == null)
            {
                Debug.Log("RewardImage == null");
                return;
            }
        }

        RewardImage.sprite = Reward.LoadRewardSprite(RewardImageProp);
    }

But before this, as I said, this gameobject is created from another script:
var go = new GameObject(reward.Name, typeof(RewardProfileView));

go.GetComponent<RewardProfileView>().RewardItem = reward;

The 'RewardItem' property is Reward class property:
    public Reward RewardItem
    {
        get { return _reward; }
        set
        {
            if (value != null)
            {
                _reward = value;

                RewardTextProp = _reward.Name;

                RewardImageProp = _reward.Name;
            }
            else
            {
                _reward = null;
            }
        }
    }

RewardTextProp and RewardImageProp are just string fields.
NOTE: Need to make ability to set children properties of dynamicaly created prefab item.

A: If you create the GameObject in one Start() method, and then try to to access it in another Start() method, you will run into trouble. This is a classic example of a race condition, in which you do not know which Start() method will be executed first.
The easiest and the most straight forward solution is to put the GameObject creation part in an Awake() method.
The Awake() methods are guaranteed to run for all GameObjects before the Start() methods begin to run.


text:
Q: Since morning i am stuck in follwing problem.
at one place the same thing is working and second place its not working
 is not displaying the errors.
I checked there are many times this question has been asked, i refer all the question and solutions, but still the problem is same.follwiing the code I am using in my controller.

@RequestMapping(method = RequestMethod.POST)
    public String findRide(@ModelAttribute("postAd") PostAdRR user,ModelMap model,@Valid PostAdRR postAd,
    BindingResult result,HttpSession session,HttpServletRequest request) {
    if (result.hasErrors()) {
        System.out.println(result.toString());

            return "postAd";
     }

even it enter in error block and print the SOP line.
but its not showing on form.
 <form:form method="POST" commandName="postAd" enctype="multipart/form-data" >
     <form:errors path="contactName"  cssClass="Err"/>

and my domain class(PostAdRR) code is
@NotEmpty(message = "You must provide Title.")
    private String title =null;

and the same code is working on other place
Please suggest something almost i tried all the combinations.

A: I think the problem is in your controller function signature.
You are validating on other object and your model attribute is another object. That is not the correct way to validate the object and show the errors on the form.
Your method signature should be as following.
public String findRide(@Valid @ModelAttribute("postAd") PostAdRR user,ModelMap model, BindingResult result,HttpSession session,HttpServletRequest request)

That is now you will bind the same object to the view which is you are validating.
Hope that helps you.
Cheers.

A: I am a bit wondering why the names in your excample does not match.
On one hand it is: contactName  in <form:errors path="contactName"  cssClass="Err"/> on the other it is: title
May this is the cause.

If this does not work try <form:errors path="*"  cssClass="Err"/> (within the from) to show all error messages. The result of that test hopefully helps you to decide if the problem is in thw view or in the controll.er

A: You can try annotating @NotNull along with @NotEmpty. Also is it possible to try @Valid in your controller before your model attribute. These are just guesses since you told the other page is working.


text:
Q: SQL Azure Data Bricks We have a table 1 Day table aggregated with group by
call_date
,tdlinx_id
,work_request_id
,category_name

another table we have 1 week level data aggregated with group by
week_end_date
,category_name
,sdo_reporting_name

How can I populate the data from day level to week level ???
week_end_date =  date_add(call_date, 7-dayofweek(call_date))

A: what you need is the following functions:
    SELECT current_date() + 7 - dayofweek(current_date());

So, In your case, it would be:
    SELECT call_date + 7 - dayofweek(call_date)
    FROM your_table;


text:
Q: Display Leaflet WMS Layers from same source on different panes I am using the Leaflet WMS plugin to add in layers to my map via a WMS.
I have the following code below that adds all of the layers using the same source but as separate layers.
However, I want to set each of the layers to its own pane so that when I add/remove them to/from the map they appear in the correct order as defined by the list of panes, rather than the order they were added to the map as currently happens without the panes.
var source = L.WMS.source("http://IP ADDRESS:PORT/geoserver/wms", {
format: 'image/png',
transparent: true,
tiled: true,
opacity: 0.6,
minZoom: 12,
tileSize: 512,
attribution: "Attribution Here"
});
var layer1 = source.getLayer("WORKSPACE:layer_1");
var layer2 = source.getLayer("WORKSPACE:layer_2");
var layer3 = source.getLayer("WORKSPACE:layer_3");
var layer4 = source.getLayer("WORKSPACE:layer_4");


text:
Q: Finding indexes of convex points on a contour I have a vector of ordered Points that make up the contour of a worm (found with opencv). I am trying to get points along the skeleton of the worm. I want to do this very fast and so have a simple segmentation function:
void Worm::segmentWorm(void)
{
    int jump = 5;
    int numPoints = wormContour.size();

    int currentIndex = headIndex; //large circle in image w/overlay
    int endIndex = tailIndex;     //small circle in image w/overlay
    int matchingIndex;

    int direction = (endIndex - currentIndex)/abs(endIndex - currentIndex);

    int thisSideLength = abs(endIndex - currentIndex);
    int otherSideLength = numPoints - thisSideLength;

    double lengthPercentage;

    if (direction > 0) {
        while (currentIndex < endIndex - jump) {
            currentIndex += jump;

            lengthPercentage = (double)(endIndex - currentIndex)/(double)thisSideLength;
            matchingIndex = boundCheck((int)((lengthPercentage * otherSideLength) + endIndex), numPoints - 1);

            segments.push_back(pair<int, int>(currentIndex, matchingIndex));
        }
    } else if (direction < 0) {
        while (currentIndex > endIndex + jump) {
            currentIndex -= jump;

            lengthPercentage = (double)(currentIndex - endIndex)/(double)thisSideLength;
            matchingIndex = boundCheck((int)(-(lengthPercentage * otherSideLength) + endIndex), numPoints - 1);

            segments.push_back(pair<int, int>(currentIndex, matchingIndex));
        }
    }
}

The problem with this function is that when the worm bends a lot, i.e. the contour becomes concave on one side the skeleton cuts the corner and no longer represents the center of the worm. My solution is to shift the segment ends if they are concave, correcting the segments and skeleton.
Any suggestions on a very time efficient function that will find all the concave (or convex) points on the contour?
image of problem:

A: There is no way to get the right point pairs out of that array without some geometric calculations.
One solution would be to iterate along one side and then use the normal to find a points' counterpart. I suppose if the worms' width doesn't change too much you could use a fix offset length to search for the other point and also for the other point use a subset of the points on the other side, which would mean that a BF match should be very fast. Then you could update the offset and subset as you iterate.
edit: If the initial guess of the index of the counterpart is not really awful, then a brute force match isn't even necessary since you can traverse the side until no point is closer anymore.


text:
Q: How can I add a JButton to my full screen java program I have followed thenewbostons java game tutorials on youtube and managed to create a base class which will be in full screen mode using a screenmanager class. Well all works just fine, I can draw images and strings and so on, but how the heck can I add JButtons etc etc.
I have uploaded my code on pastie.org so you can see it :)
Main.java
Screen
BaseFrame [the abstract frame]
Menu Frame [Inheritted from BaseFrame]

A: consider following code :
import javax.swing.JButton;
import javax.swing.JFrame;
public class NewClass5 extends JFrame
{
JButton b=new JButton("button");
NewClass5(){
this.add(b);
this.setSize(200, 200);
this.setVisible(true);
}
public static void main(String a[]){
new NewClass5();
}
}

A: Consider adding the button in ahead of time. Don't make it visible. Then when you want to give that option, setVisible(true). Unless you have many buttons that are dynamic and need to change on the fly or something, I think this should work.


text:
Q: Is there a way to hide a view when there is not enough room for it Let's imagine I put 10 ImageViews into a LinearLayout. On some phones, the screen is too small, only 9 could fit. The 10th will be smaller.
Is there a way to hide the 10th if there is not not enough room on the screen?

A: Yes, it is possible. You can get the Height of your screen, and then add an image and calculate the height sum of all the images you added, and compare, if (sumHeightImages >= screenHeight) : then  set the visibility of the rest images to GONE :)

A: Use a ScrollLayout with the nested LinearLayout that contains the ImageViews.


text:
Q: FullCalendar ServerCode for JSON I'm using VisualBasic for my ASPX Programming and want to do a JSON-feed for the fullcalendar.
I have this:
$('#calendar').fullCalendar('addEventSource','ajax.vb/Test');

Imports System.Web
Imports System.Web.UI
Imports System.Web.Services
Imports System.Web.UI.WebControls
Imports System.Web.Script.Services
Imports System.Web.Services.Protocols
Imports System.Data.OleDb

<ScriptService()> _
Partial Public Class ajax

    <WebMethod()> _
   Public Shared Function Test(ByVal start As String, ByVal ende As String) As String
        Dim EventSource As String = ""
        Return EventSource
    End Function
End Class

I get back this:

"NetworkError: 403 Forbidden -
  =1343731700843">http://localhost:58749/ajax.vb/Test?start=1341093600&ende=1344722400&=1343731700843"
   The Pagetype will not be processed.  Description: The requested page
  type is not processed because it is expressly forbidden.

Do I have to use PHP (I don't really want to) or did I do sth. wrong on the serverside?
I tried the code with an vb-Class as above, an .aspx Page and with an WebService (.asmx).

What do I have to do, to sucessfully call the serverside code?

A: I think you will need to use a web service and call it using http:// yourwebsite/ yourService.asmx
I am trying to utilise this as we speak and cannot find any specific documentation about connecting the calendar to a .net service that collects data from SQL.
If anyone has any information on this I would much appreciate it.
Cheers
Gwasshoppa


text:
Q: How do I find the language from a regular expression? How would I find the language for the following regular expressions over the alphabet {a, b}?
aUb*
(ab*Uc)
ab*Ubc*
a*bc*Uac

EDIT: Before i get downvoted like crazy, i'd appreciate it if someone could show me the steps towards solving these problems, not just the solution. Maybe even walking me through one so I can do the rest on my own.
Thanks!

A: Edit: short answer, * means "zero or more repetitions" in almost all regex/grammar syntaxes include perl5 and RFC 5234.  * typically binds more tightly than concatenation and alternation.
You say you want a language over the alphabet (a, b), but include c and U in your expressions.  I'm going to assume that you want a language grammar over the alphabet (a, b, c) in a form like BNF given a regular expression where U is a low-precedence union operator, similar to | in perl re.
In that case,

a|b*

is equivalent to the BNF:
L := a
   | <M>
M := epsilon
   | b <M>

The * operator means zero or more, so the first clause in M is the base case, and the second clause is a recursive use of M that includes a terminal b.
L is just either a single terminal a or the nonterminal M.

(ab*|c)

L ::= a <M>
    | c
M ::= epsilon
    | b <M>

M is derived the same way as above, and the rest is self explanatory.

ab*|bc*

L ::= a <M>
    | b <N>
M ::= epsilon
    | b <M>
N ::= epsilon
    | c <N>

N is derived in the same way as M above.

a*bc*|ac

The * in most regular expression languages binds more tightly than concatenation, so this is the same as
(a*b(c*))|(ac)

which boils down to
L ::= <M> b <N>
    | a c
M ::= epsilon
    | a <M>
N ::= epsilon
    | c <N>

In general to convert a regex to BNF, you simply use adjacency in a regex to mean adjaceny in BNF, and U or | in a regex means | in BNF.
If you define a nonterminal <X> ::= x then you can handle x* thus:
L ::= epsilon
    | <X> <L>

With the same nonterminal <X> ::= x then you can handle x+ thus:
L ::= <X>
    | <L> <X>

That gets you the repetition operators * and + which leaves ?.  x? is simply
L ::= epsilon
    | <X>

A: Although Mike gave grammars generating the languages denoted by the regular expressions, your assignment requests the languages themselves. Because you're dealing with regular expressions, your answers must be regular sets.
Recall the definition of regular sets over an alphabet:
Let Σ be an alphabet. The class of regular sets over Σ is the smallest class
containing ∅, {λ}, and {a}, for all a ∈ Σ, and closed under union, concatenation,
and Kleene star.

Now recall the definition of regular expressions over an alphabet:
Let Σ be an alphabet. The class of regular expressions over Σ is the smallest
class containing ∅, λ, and a, for all a ∈ Σ, and closed under union, concat-
enation, and Kleene star.

The translation, therefore, should be straightforward. In fact, it consists of inserting curly brackets around each letter! For example:
a ∪ b*  denotes {a} ∪ {b}*
ab* ∪ c denotes {a}{b}* ∪ {c}
...

If you want to express the language of each regular expression in set-builder notation, you can revert to the definitions of the operations over regular sets. Recall:
Let A and B be regular sets. Then
   1  A ∪ B = {x : x ∈ A ∨ x ∈ B}
   2. AB    = {xy : x ∈ A ∧ y ∈ B}
   3. A*    = ∪[i = 0 -> ∞]A^i

The regular sets can be translated into set builder notation by substitution of the definitions of the regular set operations. To avoid introducing nested set-builder notation, I've used equality in conjunction with the definition of concatenation to express the concatenation of regular sets.
{a} ∪ {b}*    = {w : w ∈ {a} ∨ w ∈ ∪[i = 0 -> ∞]{b}^i}
{a}{b}* ∪ {c} = {w : (w = xy ∧ (x ∈ {a} ∧ y ∈ ∪[i = 0 -> ∞]{b}^i)) ∨ w ∈ {c}}
...

You should now be able to find the languages denoted by the remaining expressions without difficulty.

A: If you know what star, union and concatenation mean, these should be easy. The first is a union b star. According to order of operations, this means a union (b star). Union means anything in the language on the left or anything in the language on the right. a means the language consisting of the length-one string a; b star means the language consisting of any string which consists of zero or more b symbols and nothing else. So this language is {empty, a, b, bb, bbb, bbbb, ...}. In the second one, ab* means all strings consisting of an a followed by zero or more b symbols. Do star first, then concatenation, then union, obeying the given explicit parentheses.


text:
Q: Giving an IAM User full access Should an IAM User say called User1 be given full access like so:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "*",
      "Resource": "*"
    }
  ]
}

Could it also be used to create Amazon API calls? Is this a security risk or should I create another user just to access the Amazpn API Gateway?

A: You should never give an IAM user full privileges. So many things could go wrong, and yes it may very well be a security risk.
If you need to manage (create, configure, or deploy) your API in API Gateway with this IAM user, you can give the user this policy:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "apigateway:*"
      ],
      "Resource": "arn:aws:apigateway:*::/*"
    }
  ]
}

Or, if you only need to invoke the API, you can use this policy:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "execute-api:Invoke"
      ],
      "Resource": "arn:aws:execute-api:*:*:*"
    }
  ]
}


text:
Q: Print in Laravel I need print a view, like this example:

El Aullido Vespertino

{{$articulo->titulo}}

foto->ruta())}}"/>

{{$articulo->texto}}

Noticia publicada por {{$articulo->user->nombre()}} en el Aullido Vespertino

Esta noticia ha sido publicada el {{$articulo->creado()}}
    @if($articulo->created_at<$articulo->updated_at)
        y se actualizó por última vez el {{$articulo->cambiado()}}
    @endif

If a user have a printer, the can use to download this view. How I can allow them? I have DomPDF to download the view in PDF format.
Y try this function:
public function impresora(Articulo $articulo){
    $pdf = PDF::loadView('pura_noticia', compact('articulo'));
    return $pdf->stream('PDF/'.$articulo->titulo.'.pdf');
}

This is the result:
enter image description here
I need directly print the document.

A: You can print your view on screen with domPdf using stream() method
Simply stream() output the generated PDF to Browser
To direct print try this
https://github.com/dompdf/dompdf/issues/713
You can embedded js into pdf view with domPdf


text:
Q: How to work with Lombok? I am trying to use Lombok jar on my project.
My main class:
package lombok_example;
import lombok.Cleanup;
public class Emp_Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
      Employee emp=new Employee();
      emp.setEmpNo("EMP1");
    }
}

My bean class:
package lombok_example;
import lombok.Data;
@Data
public class Employee {
    private String empNo;
    private String empName;
    private String empAddress;
}

I am trying to set a value at empNo, but can't find any setter method for this. How can i set value in the particular bean?

A: Issue might be Lombok is not installed properly.
Try to re-install the lombok.
If you are using eclipse then restart the eclipse. Link
If you are using Intelij, then follow this link

A: Install plugin for your IDEA.
Lombok add the byte code .


text:
Q: Google vision API not printing a return I'm playing around with some scripts in python and trying to find if these image returns results. However when running python doesn't print anything. I don't get an error but can't seem to figure it out.
import io
import os

# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types

def run(annotations):
# Instantiates a client
    client = vision.ImageAnnotatorClient()

# The name of the image file to annotate
    file_name = os.path.join(
        os.path.dirname(__file__),
        'static/123456.jpg')

# Loads the image into memory
    with io.open(file_name, 'rb') as image_file:
        content = image_file.read()

        image = types.Image(content=content)

    if annotations.pages_with_matching_images:
        print('\n{} Pages with matching images retrieved'.format(
            len(annotations.pages_with_matching_images)))

    matching = annotations.pages_with_matching_images

        print matching

I'm basing the work on these examples
https://cloud.google.com/vision/docs/quickstart-client-libraries#client-libraries-install-python
https://cloud.google.com/vision/docs/internet-detection

A: You are missing some key parts:
import io
import os

# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types

def run():   # remove the argument since you aren't using it
# Instantiates a client
    client = vision.ImageAnnotatorClient()

# The name of the image file to annotate
    file_name = os.path.join(
        os.path.dirname(__file__),
        'static/123456.jpg')

# Loads the image into memory
    with io.open(file_name, 'rb') as image_file:
        content = image_file.read()

    image = types.Image(content=content)   # dedent this

    web_detection = client.web_detection(image=image).web_detection

    """ annotations doesn't exist in your script as is...
    if annotations.pages_with_matching_images:
        print('\n{} Pages with matching images retrieved'.format(
            len(annotations.pages_with_matching_images)))
    """
    # replace above with this
    if web_detection.pages_with_matching_images:
        print('\n{} Pages with matching images retrieved'.format(
               len(web_detection.pages_with_matching_images)))

if __name__ == '__main__':
    run()

Some of the key issues you need to watch out for when editing tutorial scripts is following your objects along.  You can't use an object that is called in the tutorial in your own script if you don't first create that object.


text:
Q: Change UIViewController My problem is: I have a list(UITableView) of news in my application
When I clicking on 1 'new' I opening it and I have a back button inside it that can get me back to the list.
Now the issue is I have to implement on swipe 'new' change so I made my gesture recogniser etc ..
the problem is: I have tried to use
  [self presentViewController:previousNew animated:YES completion:Nil];

to present the previous new
but I think it is obviously for you that when I clicking on back button inside the new instance of new it brings me back to the old new instead of bringing me back to the gallery.
here is my code inside gesture recognition
  if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft)
{
    NSLog(@"get gesture Left");
    NSUserDefaults* defauts = [NSUserDefaults standardUserDefaults];
    NSMutableArray* newsArray = [defauts objectForKey:@"NewsArray"];
    if(_index +1 < [newsArray count])
    {
        NewsDetailsViewController* previousNew = [[NewsDetailsViewController alloc]initWithParameter:_index+1];
       // [self.navigationController pushViewController:previousNew animated:YES];
        //[self.navigationController presentModalViewController:previousNew animated:YES];
     [self presentViewController:previousNew animated:YES completion:Nil];
    }
    else
        return;
}

and here is my back button code
-(void)Back
{
    NSLog(@"atBack");
    [self dismissModalViewControllerAnimated:YES];

}
Please every help will be highly appreciated
(This is my first iOS application so please don't get mad on me I am lack of experience).
Note I am using ARC and NOT using interfaceBuilder

A: Everytime you swipe, you just presented another ViewController on the top of the old new. Thats why when you click Back button, it brings you back to the old new rather than the list.
What I can suggest is, you can use a scrollview which has three pages showing the previous new, current new (the new that you clicked on the list), and the next new. And when you swipe, just adjust the three views to the correct ones. For example, you clicked the 3rd new on the lsit, then the scrollview will be showing the 3rd new (of course) with the 2nd new on the left and the 4th new on the right. Then you swipe to the 2nd new (which is the previous one), now the scrollview is showing the 2nd new (of course) with the 1st new on the left and the 3rd new on the right.


text:
Q: How to use CLI application from node.js child process? I am wordering how to use application with command line interface from node.js. Here is node.js code:
var spawn = require('child_process').spawn;
var child = spawn('java', ['HelloWorld']);

child.stdout.pipe(process.stdout);
child.stdin.write("tratata\r\n;");

child.stdin.end();

it runs java HelloWorld cli app.
here is java code:
import java.io.Console;

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("started");

        Console console = System.console();

        while (true) {
            String s = console.readLine();
            System.out.println("Your sentence:" + s);
        }
    }
}

but it doesn't work. when child.stdin.write executs - nothing happening.

A: Disclaimer: I know next to nothing about Java.
My guess is that java.io.Console does a lot more than just reading from stdin, like opening the console device (/dev/tty on most Unix-like OS'es) itself, thereby circumventing the stdin/stdout/stderr devices being passed in by Node.
If you use java.io.BufferedReader, it works better:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("started");

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            try {
                String s = reader.readLine();
                if (s == null) return; // end of stream reached
                System.out.println("Your sentence:" + s);
            } catch(IOException e) {
            }
        }
    }
}


text:
Q: authentication with has_secure_password and sessions     class User < ActiveRecord::Base
        has_secure_password
        attr_accessor :account

        has_one :company
        has_one :employee
        has_many :messages

        def self.authenticate(user, password)
            user = User.find_by_user(user)

            unless user && user.authenticate(password)
                redirect_to new_session_path
            end

            user
        end

    end

for some reason that I dont get the code inside of the unless condition dont recognize any rails code, like that redirect_to new_session_path or any other path, and throws this:
NameError in SessionsController#create
undefined local variable or method "new_session_path" for #<Class:0x2f0e998>
I did try a raise but was the same, someone knows why that would be?
thanks for your help.
stack trace:
activerecord (3.2.1) lib/active_record/dynamic_matchers.rb:50:in "method_missing"
app/models/user.rb:14:in "authenticate"
app/controllers/sessions_controller.rb:6:in "create"
actionpack (3.2.1) lib/action_controller/metal/implicit_render.rb:4:in "send_action"
actionpack (3.2.1) lib/abstract_controller/base.rb:167:in "process_action"
actionpack (3.2.1) lib/action_controller/metal/rendering.rb:10:in "process_action"
actionpack (3.2.1) lib/abstract_controller/callbacks.rb:18:in "block in process_action"
activesupport (3.2.1) lib/active_support/callbacks.rb:414:in "_run__439917834__process_action__1037818096__callbacks"
activesupport (3.2.1) lib/active_support/callbacks.rb:405:in "__run_callback"
activesupport (3.2.1) lib/active_support/callbacks.rb:385:in "_run_process_action_callbacks"
activesupport (3.2.1) lib/active_support/callbacks.rb:81:in "run_callbacks"
actionpack (3.2.1) lib/abstract_controller/callbacks.rb:17:in "process_action"
actionpack (3.2.1) lib/action_controller/metal/rescue.rb:29:in "process_action"
actionpack (3.2.1) lib/action_controller/metal/instrumentation.rb:30:in "block in process_action"
activesupport (3.2.1) lib/active_support/notifications.rb:123:in "block in instrument"
activesupport (3.2.1) lib/active_support/notifications/instrumenter.rb:20:in "instrument"
activesupport (3.2.1) lib/active_support/notifications.rb:123:in "instrument"
actionpack (3.2.1) lib/action_controller/metal/instrumentation.rb:29:in "process_action"
actionpack (3.2.1) lib/action_controller/metal/params_wrapper.rb:205:in "process_action"
activerecord (3.2.1) lib/active_record/railties/controller_runtime.rb:18:in "process_action"
actionpack (3.2.1) lib/abstract_controller/base.rb:121:in "process"
actionpack (3.2.1) lib/abstract_controller/rendering.rb:45:in "process"
actionpack (3.2.1) lib/action_controller/metal.rb:203:in "dispatch"
actionpack (3.2.1) lib/action_controller/metal/rack_delegation.rb:14:in "dispatch"
actionpack (3.2.1) lib/action_controller/metal.rb:246:in "block in action"
actionpack (3.2.1) lib/action_dispatch/routing/route_set.rb:66:in "call"
actionpack (3.2.1) lib/action_dispatch/routing/route_set.rb:66:in "dispatch"
actionpack (3.2.1) lib/action_dispatch/routing/route_set.rb:30:in "call"
journey (1.0.4) lib/journey/router.rb:68:in "block in call"
journey (1.0.4) lib/journey/router.rb:56:in "each"
journey (1.0.4) lib/journey/router.rb:56:in "call"
actionpack (3.2.1) lib/action_dispatch/routing/route_set.rb:589:in "call"
actionpack (3.2.1) lib/action_dispatch/middleware/best_standards_support.rb:17:in "call"
rack (1.4.5) lib/rack/etag.rb:23:in "call"
rack (1.4.5) lib/rack/conditionalget.rb:35:in "call"
actionpack (3.2.1) lib/action_dispatch/middleware/head.rb:14:in "call"
actionpack (3.2.1) lib/action_dispatch/middleware/params_parser.rb:21:in "call"
actionpack (3.2.1) lib/action_dispatch/middleware/flash.rb:242:in "call"
rack (1.4.5) lib/rack/session/abstract/id.rb:210:in "context"
rack (1.4.5) lib/rack/session/abstract/id.rb:205:in "call"
actionpack (3.2.1) lib/action_dispatch/middleware/cookies.rb:338:in "call"
activerecord (3.2.1) lib/active_record/query_cache.rb:64:in "call"
activerecord (3.2.1) lib/active_record/connection_adapters/abstract/connection_pool.rb:443:in "call"
actionpack (3.2.1) lib/action_dispatch/middleware/callbacks.rb:28:in "block in call"
activesupport (3.2.1) lib/active_support/callbacks.rb:405:in "_run__813925422__call__171472149__callbacks"
activesupport (3.2.1) lib/active_support/callbacks.rb:405:in "__run_callback"
activesupport (3.2.1) lib/active_support/callbacks.rb:385:in "_run_call_callbacks"
activesupport (3.2.1) lib/active_support/callbacks.rb:81:in "run_callbacks"
actionpack (3.2.1) lib/action_dispatch/middleware/callbacks.rb:27:in "call"
actionpack (3.2.1) lib/action_dispatch/middleware/reloader.rb:65:in "call"
actionpack (3.2.1) lib/action_dispatch/middleware/remote_ip.rb:31:in "call"
actionpack (3.2.1) lib/action_dispatch/middleware/debug_exceptions.rb:16:in "call"
actionpack (3.2.1) lib/action_dispatch/middleware/show_exceptions.rb:56:in "call"
railties (3.2.1) lib/rails/rack/logger.rb:26:in "call_app"
railties (3.2.1) lib/rails/rack/logger.rb:16:in "call"
actionpack (3.2.1) lib/action_dispatch/middleware/request_id.rb:22:in "call"
rack (1.4.5) lib/rack/methodoverride.rb:21:in "call"
rack (1.4.5) lib/rack/runtime.rb:17:in "call"
activesupport (3.2.1) lib/active_support/cache/strategy/local_cache.rb:72:in "call"
rack (1.4.5) lib/rack/lock.rb:15:in "call"
actionpack (3.2.1) lib/action_dispatch/middleware/static.rb:53:in "call"
railties (3.2.1) lib/rails/engine.rb:479:in "call"
railties (3.2.1) lib/rails/application.rb:220:in "call"
rack (1.4.5) lib/rack/content_length.rb:14:in "call"
railties (3.2.1) lib/rails/rack/log_tailer.rb:14:in "call"
rack (1.4.5) lib/rack/handler/webrick.rb:59:in "service"
C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/webrick/httpserver.rb:138:in "service"
C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/webrick/httpserver.rb:94:in "run"
C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/webrick/server.rb:191:in "block in start_thread"

A: write this in your user model.
 include Rails.application.routes.url_helpers

or,
use instead of new_session_path
Rails.application.routes.url_helpers.new_session_path

A: Models should not be responsible for redirecting as this is the responsibility of controllers. Try pulling the redirect out of your model and into your controller. The authenticate method should just verify if the user is valid and let the controller take appropriate action based upon that result.


text:
Q: facebook and google plus user verification in server side with the access token send from javascript Am using google plus and facebook javascript sign in feature for my website. I am able to get the user details and the access token in javascript. I want to validate the user in server side(java) also. Is it possible to do the same with the help of access token which i can send as an ajax request?

A: With Google+, the preferred method is to use the client to get a one-time code and to provide this code to the server. The server then exchanges it for an access_token as part of verifying there is no malicious activity going on.
See https://developers.google.com/+/web/signin/server-side-flow for details.


text:
Q: How to Merge unpartitioned space with partitioned system disk in Ubuntu Server I recently installed ubuntu-server and allocated 49GB for system
But there was unpartitioned 1tb storage. I forgot to setup that.
Here is the result of lsblk.
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
loop0    7:0    0 55.4M  1 loop /snap/core18/2128
loop1    7:1    0 61.8M  1 loop /snap/core20/1081
loop3    7:3    0 68.2M  1 loop /snap/lxd/21039
loop4    7:4    0 32.3M  1 loop /snap/snapd/12398
loop5    7:5    0 55.5M  1 loop /snap/core18/2074
loop7    7:7    0 61.7M  1 loop /snap/core20/1026
loop8    7:8    0 32.3M  1 loop /snap/snapd/12704
loop9    7:9    0 68.3M  1 loop /snap/lxd/21260
sda      8:0    0   50G  0 disk
├─sda1   8:1    0  512M  0 part /boot/efi
└─sda2   8:2    0 49.5G  0 part /
sdb      8:16   0    1T  0 disk
sdc      8:32   0  250G  0 disk
sr0     11:0    1 1024M  0 rom

Now I need to merge sda2 partition with sdb. sda2 partition already has services and data. Like mysql , php etc..
I need to do that process without losing data.
Note that ubuntu-server does not have a GUI, I can only connect to it through ssh to a root user, hence it has to be done using commands.


text:
Q: Why there's some "noise" around the edge of my loading gif on my website? Why there's some "noise" around the edge of my loading gif on my website?
It should be all grey, but as you can see in the below screenshot, the edge is all screwed up, it looks bad!

==========================================================================
Edit: attach gif and png snapshot.


text:
Q: Disable polling of DVD Drive - Ubuntu 22.04 LTS My DVD Drive constantly clicks every couple of seconds.
Through other forums I found that this has to do with polling for which there existed a solution with udisks:
udisks --inhibit-polling /dev/sr0
udisks is no longer available for Ubuntu 22.04 and udisks2 does not have this functionality.
Does anyone have an up-to-date fix for that?


text:
Q: How can I avoid autorepeated keydown events in JavaScript? If the user holds down the key, multiple keydown events are fired. For usability reasons I need to use keydown, not keyup, but I want to avoid this situation. My relevant code is the following:
$(document).keydown(function(e) {
        var key = 0;

        if (e == null) { key = event.keyCode;}
        else {  key = e.which;}

        switch(key) {
            case config.keys.left:
              goLeft();
              break;
            case config.keys.up:
              goUp();
              break;
            case config.keys.right:
              goRight();
              break;
            case config.keys.down:
              goDown();
              break;
            case config.keys.action:
              select();
              break;
        }
      });

So when the user holds down the down key, for example, goDown() is fired multiple times. I would like it to fire just once even if the user holds the key down.

A: Another simple adjustment to the accepted answer to allow for the multiple keys scenario:
var keyAllowed = {};

$(document).keydown(function(e) {
  if (keyAllowed [e.which] === false) return;
  keyAllowed [e.which] = false;
  // code to be executed goes here
});

$(document).keyup(function(e) {
  keyAllowed [e.which] = true;
});

$(document).focus(function(e) {
  keyAllowed = {};
});

A: Use event.repeat to detect whether or not the event is repeating. You could then wait for "keyup" before allowing the handler to execute a second time.
var allowed = true;

$(document).keydown(function(event) {
  if (event.repeat != undefined) {
    allowed = !event.repeat;
  }
  if (!allowed) return;
  allowed = false;
  //...
});

$(document).keyup(function(e) {
  allowed = true;
});
$(document).focus(function(e) {
  allowed = true;
});

A: its simple
$(document).keydown(function(e) {
    if (e.repeat) return;
    // ...
});

A: So, if the existing solution seems dubious (it doesn't consider the case when 2 or more buttons is pressed simultaneously), I suggest another solution that takes it into account.
The _prevKeyDown object is to store keys that are currently pressed.
    _prevKeyDown = {}

    function _downKey( event )
    {
        var wh = event.which;
        var kC = event.keyCode;

        if( _prevKeyDown[ wh ] == null )
        {
            _prevKeyDown[ wh ] = {};
        }

        _prevKeyDown[ wh ][ kC ] = true;
    };

    function _upKey( event )
    {
        var wh = event.which;
        var kC = event.keyCode;

        if( _prevKeyDown[ wh ] != null )
        {
            _prevKeyDown[ wh ][ kC ] = null;
        }
    };

    function _isKeyDown( event )
    {
        var wh = event.which;
        var kC = event.keyCode;

        var result = false;

        if( this._prevKeyDown[ wh ] != null )
        {
            if( this._prevKeyDown[ wh ][ kC ] == true )
            {
                result = true;
            }
        }

        return result;
    }

    // now your keydown/keyup handlers
    function keydown( event )
    {
        if( !_isKeyDown( event ) )
        {
            // your once-keydown handler here
            _downKey( event );
        }
    }

    function keyup( event )
    {
        _upKey( event );
    }

A: (Copied from another question which turned out to be a duplicate of this one.)
dmaurolizer's KeyPress library gives fine control over all keyboard events.  You provide callback functions for events.  The keydown event sends an optional isRepeat param so you can ignore auto-repeats.  Here's a sample using that functionality for the thrust control in a video game:
var my_combos = listener.register_many([
    {
        "keys"          : "up",
        "on_keydown"    : function(e, num, isRepeat) {
            if (isRepeat) return ;
            thrust = 0.1;
        },
        "on_keyup"      : function() {
            thrust = 0;
        }
    }
]);