text:
Q: Upload image to the server blackberry 10 qml i need to upload the image to the server i have used file picker to fetch the image, i have attached my  sample code but its not working
my file picker code
                        `   Button {
                    text: "Change Profile Image"
                    onClicked {
                         filePicker.open();
                    }
                       attachedObjects: [
                        FilePicker {
                            id: filePicker
                            property string selectedFile
                            type: FileType.Picture
                            onFileSelected: {
                                selectedFile = selectedFiles[0]
                                image.imageSource = selectedFile
                                   _settings.showToast( selectedFile);
                                  _settings.isUpdate(selectedFile);
                            }
                        }
                   ]`

my image update code in c++
             `void Settings::isUpdate(QString selectedFile){

    QString path("asset:///Icon/mess.jpg");

    //php script that receives the image

    QNetworkRequest requete(QUrl("http://192.168.1.176:2222/api?type=uploadimages&name=IMG_00000001.jpg&pin=123456")); //our server with php-script

    QByteArray boundary = "-------------------------87142694621188";
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly))
    {
        qDebug()<<"erreur read image";
        return;
    }
    QByteArray fileContent(file.readAll());
    QByteArray data = "--" + boundary + "\r\n";
    data += "Content-Disposition: form-data; name=\"data\"; filename=\"IMG_00000001.jpg\";\r\n";
    data += "Content-Type: image/jpg\r\n\r\n" + fileContent + "\r\n";
    data += "--" + boundary + "--\r\n";

    requete.setRawHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    requete.setRawHeader("Content-Length", QString::number(data.size()).toAscii());
    file.close();
    qDebug() <<"data"<< data.size();
    QNetworkAccessManager *am = new QNetworkAccessManager(this);
    QNetworkReply *reply = am->post(requete,"&data="+data);
    QObject::connect(am, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));

}
       void Settings::replyFinished(QNetworkReply *reply)
          {
         reply->open(QIODevice::ReadOnly);
         if(reply->error() == QNetworkReply::NoError)
           {
                QByteArray str=(reply->readAll());
                 QString response = QString::fromUtf8(str.data(), str.size());
                   qDebug()<<" re "<<response;
                      }

                      else
                       qDebug()<<"error response server";
                      }`

i can able to get response,but can't able to upload the image in the server
thanks

A: QString body = "" ;

const QUrl url("http://someurl.to/make/the/post" );
 QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
 QHttpPart textPartData;
 body = "" ;
 QTextStream(&body) << "";
 textPartData.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; charset=utf-8");
 textPartData.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"data\""));
 textPartData.setBody(body.toAscii());

     for(int i=0; i< number_of_files_to_send ; i++){
             QHttpPart imagePart;
             QString header_body = "";
             QTextStream(&header_body) << "form-data; name=\"" << name_of_the_file << "\"; filename=\"" << name_of_the_file << ".jpg\"" ;
             imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(header_body));
             imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));

             //prepare file for upload
             QString filepath;
             QTextStream(&filepath) << FunkyPigeonBlackberry::getInstance()->dataModelProductDetails()->custom_image(i).value("cut_image").toString();

             // pack the new file
             QFile *file = new QFile(filepath);
             file->open(QIODevice::ReadOnly);
             imagePart.setBodyDevice(file);
             file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart
             multiPart->append(imagePart);
     }

 multiPart->append(textPartData);
 multiPart->append(textPartProductDetails);
 multiPart->append(textPartDataDelivery);

 QNetworkRequest request(url);

 QNetworkReply* reply = m_networkAccessManager->post(request, multiPart);
 connect(reply, SIGNAL(finished()), this, SLOT(onNetworkResponse()));


text:
Q: Environment Variables not being set by Webpack Environment variables are not being passed through to the Webpack build.
This repository has our current configuration and demonstrates the problem.
It runs the following script:
const p = (typeof process === 'undefined' ? null : process)
console.log({
  process: p,
  env: p?.env,
  var: p?.env?.VITE_TEST_VAR,
})

This prints:
{ process: null, env: undefined, var: undefined }

I have a .env file with the following contents:
VITE_TEST_VAR=testing_key

I have tried the following methods:
{
  new webpack.DefinePlugin({
    process: JSON.stringify({}),
    'process.env': JSON.stringify(process.env)
    'process.env.VITE_TEST_VAR': JSON.stringify(process.env.VITE_TEST_VAR)
    process: { env: { VITE_TEST_VAR: JSON.stringify(process.env.VITE_TEST_VAR) } }
    'process.env.VITE_TEST_VAR': process.env.TEST_VAR
    'VITE_TEST_VAR': JSON.stringify(process.env.VITE_TEST_VAR)
  }),
  new webpack.EnvironmentPlugin (['VITE_TEST_VAR']),

Nothing works. Any alternatives?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex to replace a string that may or may not be quoted I'm trying to replace all instances of the key INPUT_CSV in a string with a file path that is guaranteed to not have any single or double quotes (or other unsafe characters for paths) within it.  However, this file path will be surrounded by double quotes.
The key may be surrounded by double quotes, single quotes, or no quotes at all in the input string.  I want to be as flexible as possible, and replace all of those instances with the same, double-quoted file path.
This is how I'm currently doing it:
Dim doubleQuotedCsvFilePath As String = """" & generatedCsvFilePath & """"

scriptStr = scriptStr.Replace("""INPUT_CSV""", doubleQuotedCsvFilePath)
scriptStr = scriptStr.Replace("'INPUT_CSV'", doubleQuotedCsvFilePath)
scriptStr = scriptStr.Replace("INPUT_CSV", doubleQuotedCsvFilePath)

Is there some sort of nifty regex (or possibly some other method) that can do essentially this more succinctly?  If this is the best way to do it, I'm fine with that too - just wondering if there is a better way.  Thanks!
P.S. Not a requirement, but if there was some way to make the regex case-insenstive too (so that e.g. "input_csv", 'input_CSV', or INPut_CSV all get replaced), that would be great also.  Thanks!

A: You can use back reference for matching the first quote:
  string scriptStr= "'INPUT_CSV'";
  string pattern = @"(""|'?)INPUT_CSV\1";
  Regex rgx = new Regex(pattern);
  scriptStr = rgx.Replace(scriptStr, doubleQuotedCsvFilePath);

See https://msdn.microsoft.com/en-us/library/thwdfzxy%28v=vs.110%29.aspx

A: Here is my attempt:
(?i)(['""]?)input_csv\1

(?i) turns on case-insensitive search, then we capture an optional single or double quote into a capturing group, match the input_csv string and then check if there is the same closing quote as the opening one.
VB.NET:
Dim doubleQuotedCsvFilePath As String = """" & "InPuT_CsV" & """"
Dim scriptStr As String
Dim m As Regex = New Regex("(?i)(['""]?)input_csv\1")
scriptStr = m.Replace(doubleQuotedCsvFilePath, "$1INPUT_CSV$1")

C#:
var doubleQuotedCsvFilePath = "\"InPuT_CsV\"";
var scriptStr = string.Empty;
var m = new Regex(@"(?i)(['""]?)input_csv\1");
scriptStr = m.Replace(doubleQuotedCsvFilePath, "$1INPUT_CSV$1");

Output:
"INPUT_CSV"

DISCLAIMER: Only use it if you are not re-inventing the wheel with a CSV parser.


text:
Q: DB4o Linq query - How to check for null strings Hey there - simple query:
var q = (from SomeObject o in container
    where
 o.SomeInt > 8
 && o.SomeString != null //Null Ref here
    select o;

I always get a null reference exception.
If I use String.IsNullOrEmpty(o.SomeString) the query takes about 100 times as long, as if I use && o.SomeString != "" (which is way faster, but obviously not correct).
I'm guessing because DB4o needs to activate the objects, in order to pass them in to the IsNullOrEmpty call, and can't use the indexes.
My question is, what's a better way to check for nulls in this situation? Is there something like: mystring != Db4o.DBNull.Value, or something?
Cheers,
Dave

A: Actually your query should work without any issues. You're query should just run fine. It also shouldn't require any activation. db4o tries to translate the queries into SODA-Queries and avoid activating the objects.
Which version of db4o are you using? There was a bug which caused a NullRefrence-Exception in LINQ-Queries. It should be fixed.
Have you added the Db4objects.Db4o.Linq.dll assembly to your project. Are the mono-assemblies present?
I would tried to avoid using String.IsNullOrEmpty at the moment, because I will prevent the query-optimization. As soon a you call complex methods withing your query, the optimizer won't be able to translate the query into SODA. Then you run basically  LINQ to Objects, which will be slow on a large dataset.


text:
Q: Django - Custom save method in model (Using Django 1.11.5)
Traditionally, I've always created a model like so:
class Animal(models.Model):
    is_hungry = models.BooleanField(default=True)

Then make changes like so:
animal = Animal()
animal.save()

animal.is_hungry = True
animal.save()

Recently, I saw a friend define a model with a custom save method:
class Animal(models.Model):
    is_hungry = models.BooleanField(default=True)

    def feed_animal(self):
        self.is_hungry = False
        self.save()

And calling this method appears to work as expected:
>>> from testapp.models import Animal
>>> a = Animal()
>>> a.save()
>>> a.is_hungry
True
>>>
>>> a.feed_animal()
>>> a.is_hungry
False

Are there any benefits/drawbacks in defining such a custom save method in the model definition? Is there any reason to prefer calling .save() on the object directly?

A: There's no drawbacks but it might be not best practice to have implicit saves buried into model's methods. It'd be cleaner to define feed_animal method that just modifies the state of the model object and leave the saving to the view.py code:
# model.py
class Animal(models.Model):
    is_hungry = models.BooleanField(default=True)

    def feed_animal(self):
        # makes sense if ther's more to it than just setting the attribute
        self.is_hungry = False

# view.py
a = Animal()
a.feed_animal()
a.save()

The pattern with defining custom save methods is understood in Django as overriding save method of Model class in child class and make sense if you need to permamently change the object behaviour on save:
# model.py
class Animal(models.Model):
    is_hungry = models.BooleanField(default=True)

    def feed_animal(self):
        # makes sense if ther's more to it than just setting the attribute
        self.is_hungry = False

    # let say we need to save only well fed animals
    def save(self, *args, **kwargs):
        self.feed_animal()
        super(Model, self).save(*args, **kwargs)

A: This depends on your use cases.
In the example given above, if animal is fed, it will eventually end up the animal(object) being not hungry. Hence, in feed_animal function after setting up self.is_hungry(where self is the object itself), self.save is called to save the final state of object.


text:
Q: mysql fetch previous or next record order by anyother field name and not by using order by id I am displaying a list.
The user can edit any item.
I am displaying next previous buttons which when clicked it dynamically fetches the next previous records form db. no page reload.
this is working well with id. like how can i get next and previous field id with php from mysql and MySQL next/previous ids (arbitrary sort order)
Currently i am displaying like

select * from table order by name asc

and for next and previous i used like this...
select * from table where id > $id order by name asc limit 1
select * from table where id < $id order by name desc limit 1

the above is what i got when i searched the internet.
in this order the id will not be in an order so i cannot use id to fetch next and previous record i think so.
i want to get next and previous records with respect to any other field and not by id.
so some thing like this.

select * from table where id > 5 order
  by name asc or desc limit 1.

what would be the query?
Note
There are 15000 records. which is half filled by default. the rest half is supposed to be updated by admin. so instead of reloading the page after the admin had updated one record i fetch the other and show dynamically on the screen so that he can continue updating content. there will not any page reload. he just clicks update and the next record appears. he can select previous or next button to navigate between records.

A: You need to filter on the value of name:
SELECT * FROM `table`
WHERE name < 'Foo'
ORDER by name DESC
LIMIT 1

This only works if the names are unique. If there can be duplicates you need a tie-breaker. You can for example use the id column to tie-break.
SELECT * FROM `table`
WHERE name < 'Foo' OR (name = 'Foo' AND id < 42)
ORDER by name DESC, id DESC
LIMIT 1

A: You're better doing more tradition pagination.
$itemsPerPage = 10;

$page = (int)$_GET['page'];  // do more validation to check this is a valid integer

$start = ($page * $itemsPerPage) - $itemsPerPage;

$sql = "SELECT * FROM `table`WHERE name < ? ORDER by name DESC limit $start, $itemsPerPage";


text:
Q: Google Identity Toolkit returns INVALID_CREDENTIALS I'm currently trying to implement a forgot password feature using the Google Identity Toolkit. The PHP backend is trying to get the oob code because client (iOS) does not have sufficient privileges.
Whenever I run the script I get an error of INVALID_CREDENTIALS, more specifically:
oob Code: string(249) "{ "error": { "errors": [ { "domain": "global", "reason": "authError", "message": "Invalid Credentials", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Invalid Credentials" } } "

I am not sure where to get the authToken or whether this is sending the post request correctly.
$authToken = "xxxxxxxxxxxxxxxxx";
$email = $_POST['email'];
$uIp = $_POST['ip'];
//Post Data in Array
$postData = array(
    'kind' => 'identitytoolkit#relyingparty',
    'requestType' => 'PASSWORD_RESET',
    'email' => '$email',
    'challenge' => 'verified',
    'captchaResp' => 'verified',
    'userIp' => '$uIp',
    'newEmail' => 'null',
    'idToken' => 'null'
    );

//Setup cURL
$ch = curl_init('https://www.googleapis.com/identitytoolkit/v3/relyingparty/getOobConfirmationCode?key=xxxxxxxxxxxxxxxxxxxx');
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Authorization: '.$authToken,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($postData)
));
//Send Request
$response = curl_exec($ch);

A: This documentation on the Google API PHP client shows you how to get an OAuth token for your app.
However, you will probably find it easier to use the Identity Toolkit specific PHP client. To generate the forgot-password link, all you need to do is call the getOobResults() method on an initialized GitkitClient.


text:
Q: Change file permission from -rwxrwxr-x to drwxrwxr-x I have a php file which is trying to read and write xml files on my Ubuntu server, however the problem is that it does not have permission to do this (permission denied error).
I have tried the following chown www-data read_write.php with no luck
What is the proper way to change permission for this file?
more info
-rwxrwxr-x 1 www-data www-data 14092 Sep  6 12:33 read_write.php

A: Maybe you are a little confused...
The "d" character in front of your string means only that this is a directory, not a file. You should look at your XML's permissions instead!

A: Just check where is it writing the files, which directory and either do chmod 777 /path/to/xml/directory or chown it to the username and group which either apache is running as or in case you're using fcgi or similar(like php-fpm) chown it to the username and group which the php fcgi/php-fpm processes are running as.


text:
Q: Time complexity of calculating the final digit sum of a number I want to calculate the time complexity of calculating the "final" digit sum of a number n: sum of the digits until I get A single digit number.
I know that in the first iteration an algorithm will perform O(log n) actions, in the second iteration it will be O(log log n) and so on, up until log(log(...(log(n))...)) < 10. Thus the number of iteration is O(log* n), where log* n is the log-star value of n.
Is there a closed form for this sum?

A: This sum works out to Θ(log n). One way to see this is to notice that log n < n / 2 for all but tiny values of n, so we have that

log n + log log n + log log log n + …
≤ log n + (log n) / 2 + (log n) / 4 + (log n) / 8 + …
≤ log n (1 + 1/2 + 1/4 + 1/8 + …)
= 2 log n
= O(log n).

To see that the sum is Ω(log n), note that the first term itself is log n, so the sum is at least log n.


text:
Q: Data migration with taosdump in TDengine We have a machine with TDengine 2.0.6.0 installed. We didn't install taosdump tool at first. Now we want to export the data.
I tried to copy the taosdump in 2.0.15.0 to the appropriate directory. Then I encountered an error:

taosdump:symbol lookup error: taosdump:undefined symbol:taosWriteImp.

How can I configure it correctly?

A: You copied a higher version taosdump, 2.0.15.0, from the error message it realies on some APIs that are not defined in 2.0.6.0 libraries.
It's recommended to upgrade TDengine to same version and install taosdump, not just copy, because there may be some other dependencies you don't know.


text:
Q: How to create subquery with elasticsearch I need to create a query on elasticsearch for the condition below.
When the last element added with the "rabbitmq.queue.name" attribute is equal to "service_test_error" and the value from "rabbitmq.queue.messages.total.count"  is different of "0"
The sql query below works for my search, but I could not to do the same query with elasticsearch
select * from metric where rabbitmq.queue.messages.total.count != '0' and rabbitmq.queue.name = 'service_test_error' and timestamp = (select max(timestamp) from metric where rabbitmq.queue.name = 'service_test_error')

These records below are examples that exist in my metric-xpto index
[
  {
    "_index": "metric-xpto",
    "_type": "_doc",
    "_id": "jYP1WnEBmYyEo7K68Zme",
    "_version": 1,
    "_score": null,
    "_source": {
      "@timestamp": "2020-04-08T18:03:14.899Z",
      "rabbitmq": {
        "queue": {
          "name": "service_test_error",
          "messages": {
            "total": {
              "count": 0
            }
          }
        }
      }
    }
  },
  {
    "_index": "metric-xpto",
    "_type": "_doc",
    "_id": "jYP1WnEBmYyEo7K68Zme",
    "_version": 1,
    "_score": null,
    "_source": {
      "@timestamp": "2020-04-07T18:03:14.899Z",
      "rabbitmq": {
        "queue": {
          "name": "service_test_error",
          "messages": {
            "total": {
              "count": 3
            }
          }
        }
      }
    }
  },
  {
    "_index": "metric-xpto",
    "_type": "_doc",
    "_id": "jYP1WnEBmYyEo7K68Zme",
    "_version": 1,
    "_score": null,
    "_source": {
      "@timestamp": "2020-04-03T17:03:14.899Z",
      "rabbitmq": {
        "queue": {
          "name": "service_alpha_test_error",
          "messages": {
            "total": {
              "count": 8
            }
          }
        }
      }
    }
  },
  {
    "_index": "metric-xpto",
    "_type": "_doc",
    "_id": "jYP1WnEBmYyEo7K68Zme",
    "_version": 1,
    "_score": null,
    "_source": {
      "@timestamp": "2020-04-03T18:03:14.899Z",
      "rabbitmq": {
        "queue": {
          "name": "service_test_error",
          "messages": {
            "total": {
              "count": 8
            }
          }
        }
      }
    }
  }
]

How can I create a similar query using elasticsearch?

A: In query part you can only fetch top most record and then check has to be in client side on message count.
In aggregation part this can be done.
{
  "size": 0,
  "query": {
    "term": {
      "rabbitmq.queue.name.keyword": {
        "value": "service_test_error"
      }
    }
  },
  "aggs": {
    "date": {
      "terms": {
        "field": "@timestamp",
        "size": 1,
        "order": {
          "_term": "desc"
        }
      },
      "aggs": {
        "message_count": {
          "terms": {
            "field": "rabbitmq.queue.messages.total.count",
            "size": 10
          },
          "aggs": {
            "filter_count": {
              "bucket_selector": {
                "buckets_path": {
                  "key": "_key"
                },
                "script": "if(params.key>0) return true; else return false;"
              }
            }
          }
        },
        "select_timestamp": {
          "bucket_selector": {
            "buckets_path": {
              "key": "message_count._bucket_count"
            },
            "script": "if(params.key>0) return true;else false;"
          }
        }
      }
    }
  }
}

Result: If top most records message count is zero then buckets will be empty else there will be data
 "hits" : {
    "total" : {
      "value" : 7,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "date" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 6,
      "buckets" : [ ]
    }
  }

Elastic search doesn't have joins , So in query it is not possible to compare one document with another


text:
Q: Git - Get Commit back to changes Im using Github and the integrated Git-Control within Visual Studio 2019. I've just made changes to the master branch and pushed them to the repo. My problem is that I made a mistake with that commit. Is there a possibillity to revert those commit AND get those changes I made back to my local changes (non committed).
So not just a simple revert of a commit because I want to modify that commit. To be more specific I want to get this commit not into the master branch, instead the commit should be pushed to another branch and not to the master branch. I can simply revert the commit in the master branch but how can I move it to another branch?

A:
Is there a possibillity to revert those commit AND get those changes I
made back to my local changes (non committed).

git reset HEAD~

git push -f

After that, you should see your's commit as non committed changes and removed from the remote master.
Now you can create a new branch and make a new commit there or you can commit anywhere you want at any branch and make the push to the specified branch (git push origin my_local_branch_name:remote_branch_name)


text:
Q: How to diagnose my computer's issue? I have a serious problem here, my desktop suddenly shutdown. I was testing my HDD and I found that it has some bad sectors, so I bought a new one: WD GREEN 500gb. After that everything went right, however this two days, while working or playing games on my desktop, it turns off on it's own. I even installed other operating systems, and while installing lubuntu 15 it shutdown during the installation. I'm sure there is something wrong with the hardware but I don't know what piece is damaged.
What steps can I use to diagnose the problem?

A: The best way to test the HW is run Windows Live CD (Windows PE) running from CD/DVD/USB.
First of all I advise to create a bootable CD/USB to boot from with test utilities. Run Memtest86+ from DOS mode to test RAM. After that Boot to Windows PE and start working, run test utilities to load CPU/RAM and hence, to consume more power. You can use AIDA64 with burn-in tests inside. If it doesn't crash, it's likely not motherboard/RAM/video related.
If it turns off in Win PE mode - take a note if it first falls to BSOD or immediately turn off. Note that you need enable blue screen debug (BSOD) in Windows (if it is turned off) so that you can read BSOD dump files later with BlueScreenView. If it just turns off immediately, it is very likely caused by PSU.
P>S> Good Windows PE builds by Strelec
Or you can use AOMEI PE Builder to build your own PE.


text:
Q: How to change scope back to original function after calling a "local" function within module.exports in Node.JS I am trying to call another local function 'MessageScoring' within another function 'NextMessageCalculation' which are both in module.exports, however I am having trouble with getting the scope to change back. The function successfully calls the other local function, however the scope is then changed and variables in the previous scope all return undefined now. How would I fix this or is there a better way to call the local function to avoid this?
module.exports = {
   MessageScoring: function(){
    var attrs_list = Object.keys(message_attr_obj);
    var score = 0;
    for (i in attrs_list){
            if(user_data[attrs_list[i]]){
                score = score + user_data[attrs_list[i]]["beta"];
            }
            else{
                //user has no response with that attr yet so score is not added
            }
    }
    score = score / attrs_list.length;
    return score}... //returns an int

   NextMessageCalculation: function(){ //has a call to a mongodb and the logic takes place in the callback
MESSAGE_collection.find({'message_set':user_data.message_set,'id':{$nin:[1111]}}).toArray(function(err,doc){
                 if (doc.length === 0)
                   {
                        USERDATA_collection.update({phone:phone_num},{$set:{send_message:false}},function(err,res) {
                           db.close()
                        });
                   }
                    else{
                        var highest_score = "";
                        var next_message = "";
                        for (i in doc)
                        {
                            console.log(doc[i]['id']);
                           var score = module.exports.MessageScoring(doc[i].attr_list,user_data);
                           console.log(doc[i]['id']); <---- becomes undefined here after calling scoring function which correctly returns int
                            if (highest_score === "")
                            {
                                console.log(doc[i]);
                                next_message = doc[i].id;
                                highest_score = score;
                            }
                            if (highest_score < score)
                            {
                                next_message = doc[i].id
                                highest_score = score;
                            }
                            console.log(doc[i].id);
                        }

A: Use function hoisting, step out from the modules.expors closure, and be sure that MessageScoring doesn't mutate data.
module.exports = {
   MessageScoring,
   NextMessageCalculation:
}

function MessageScoring() {

}

function NextMessageCalculation(){
  const d = [{ id: 'ok' }];
  const i = 0;
  console.log(d[i]['id']); //returns ok
  var score = MessageScoring(doc[i].attr_list,user_data);
  console.log(d[i]['id']); //returns ok
}


text:
Q: Help with real-analysis Let $\mathit{n \in \Bbb{R}}$ consider a polynomial $\mathit{}p(x) = a_0 + a_1 x + ...+a_n x^n$ with real coefficients. ($\mathit{a_n \neq 0}$ and all coefficients $\in \Bbb{R}$).
If $\mathit{x_0} \in \Bbb{R}$ and $\mathit{p(x_0) \neq 0}$ shows that there is $\mathit{\varepsilon \gt 0}$ such, if $\mathit{|x - x_0| \gt \varepsilon}$ then $\mathit{p(x)}$ has the same sign as $\mathit{p(x_0)}$.
I'm tring to solve this without using continuity, integrability and derivability. Any suggestion?

A: Can you use local boundedness of polynomials? This follows from continuity since a continuous function is bounded on any interval $[a,b]$, but maybe there's some other way of looking at it. Then using the factor theorem for polynomials, we have that
$$p(x) - p(x_0) = q(x)(x-x_0) \implies |p(x) - p(x_0)| = |q(x)|\cdot |x-x_0|$$
for any $x \in \mathbb{R}$ for some polynomial $q$. Therefore if $|q(x)|$ is bounded near $x_0$ in any way (by $C$ let's say), choosing $\epsilon = \frac{p(x_0)}{C}$ yields
$$ |p(x) - p(x_0)| = |q(x)|\cdot |x-x_0| < C\cdot\frac{p(x_0)}{C} = p(x_0)$$
and so $p(x)$ has the same sign as $p(x_0)$ in that interval.
Edit: You can prove boundedness of polynomials without continuity; setting the constants $D= |x_0| + 1$ and $B = \max\{b_0,\ldots,a_n\}$, then for any $x \in \mathbb{R}$ with $|x| \leq D$ we have that
$$|q(x)| = |b_nx^n + \ldots + b_1x + b_0| \leq |b_nx^n| + \ldots + |b_1x| + |b_0| \leq BD^n + \ldots + BD + B, $$
the right-hand side a constant, and so certainly $q$ is bounded on the interval $[x_0-1,x_0+1]$. To finish just make $\epsilon = \min\left\{1,\frac{p(x_0)}{C}\right\}$.

A: Show that if $\Delta$ is a real variable, $q(\Delta) = p(x_0+\Delta)-p(x_0)$ is a polynomial in $\Delta.$
Show that the constant term of $q(\Delta)$ is zero.
Figure out how small you have to make $\epsilon$ so that $\lvert \Delta\rvert<\epsilon$ guarantees that $\lvert q(\Delta) \rvert < \lvert p(x_0)\rvert.$


text:
Q: Microsoft Azure Graph API Subscription Errors on Validation request using Custom Api as Listener for notifications I have looked at the post of people saying the resolved this issue by allowing the API to accept "text/plain".
Even though I have done so, I am still getting the below error:

"{  \"error\": {    \"code\": \"InvalidRequest\",    \"message\": \"Subscription validation request failed. Notification endpoint must
  respond with 200 OK to validation request.\",    \"innerError\": {
  \"request-id\": \"ec325726-5b30-4cb1-bec5-3ba3debf88b0\",
  \"date\": \"2020-03-23T13:02:01\"    }  }}"

I have tested my API on Postman using the same request Microsoft sends when they are validating an API.
All seems to be fine in Postman.
The image shows Postman results:

Please help.

A: Subscribing to user's mailbox settings for change notifications is not supported at the moment by Microsoft Graph. If you'd like to request support for such feature, please go to uservoice and create/upvote an idea.
If it were to be added to supported resources for change notifications, it more than likely that the resource would be /users/{userid}/mailboxsettings as /users/mailboxsettings is not a valid resource on Microsoft Graph. (resources for subscriptions follow the same pattern as the URLs of the APIs)


text:
Q: Can't use sub-query or variable in window frame Why can't I use a  sub-query, or variable in window frame statements like the code below:
    CREATE FUNCTION aaa (@i AS INT)
    returns TABLE AS
    RETURN
    SELECT   sum(freight) OVER(partition BY custid ORDER BY orderdate rows
    BETWEEN 1 following AND      @i following ) AS su,
             *
    FROM     sales.orders

A: You need dynamic SQL here like below -. Dynamic SQL is not possible a function. Use a stored procedure and call that inside a function.
DECLARE @i AS INT
DECLARE @SQL AS VARCHAR(MAX) = 'SELECT  * , sum(freight) OVER(partition BY custid ORDER BY orderdate rows
        BETWEEN 1 following AND ' + CAST(@i AS VARCHAR(50)) + ' following ) AS su
        FROM sales.orders'
EXEC ( @SQL )

If you can try to create the same with hardcoded value, you will able to create. See this 10 following hardcoded value ..i am passsing.
CREATE FUNCTION aaa (@i AS INT)
    returns TABLE AS
    RETURN
    SELECT   sum(freight) OVER(partition BY custid ORDER BY orderdate rows
    BETWEEN 1 following AND  10 following ) AS su,             *
    FROM     sales.orders


text:
Q: Change a single value of a tensor inside a while loop How do I change a single value of a Tensor inside of a while loop?
I know that I can manipulate a single value of a tf.Variable using tf.scatter_update(variable, index, value), but inside of a loop I cannot access variables. Is there a way/workaround to manipulate a given value of a Tensor inside of a while loop.
For reference, here is my current code:
my_variable = tf.Variable()

def body(i, my_variable):
    [...]
    return tf.add(i, 1), tf.scatter_update(my_variable, [index], value)

loop = tf.while_loop(lambda i, _: tf.less(i, 5), body, [0, my_variable])

A: Inspired by this post you could use a sparse tensor to store the delta to the value you want to assign and then use addition to "set" that value. E.g. like this (I'm assuming some shapes/values here, but it should be straight-forward to generalize it to tensors of higher rank):
import tensorflow as tf

my_variable = tf.Variable(tf.ones([5]))

def body(i, v):
    index = i
    new_value = 3.0
    delta_value = new_value - v[index:index+1]
    delta = tf.SparseTensor([[index]], delta_value, (5,))
    v_updated = v + tf.sparse_tensor_to_dense(delta)
    return tf.add(i, 1), v_updated

_, updated = tf.while_loop(lambda i, _: tf.less(i, 5), body, [0, my_variable])

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(my_variable))
    print(sess.run(updated))

This prints
[1. 1. 1. 1. 1.]
[3. 3. 3. 3. 3.]


text:
Q: Can't open my mac after installing windows using bootcamp My macbook pro isn't working well after I installed windows 8.1 using bootcamp. It displays the blue screen, and get an error. Now there is only Windows option in startup, and it says that your PC need to repair.
I can't open either Windows, or Mac, and the big thing is there's no mac option on startup.

A: Boot to recovery mode and then choose the Mac startup disk might be the fastest way to determine if the Mac is still bootable.
Apple documents this and the other ways to switch back and forth at:

*

*https://support.apple.com/en-us/HT204417
If you've meticulously done all the steps, you might ask a second follow on question with more details about what the situation is.


text:
Q: How to pass data to Bootstrap modal I have a table that's populated in an Angular 6 SPA app with elements of my type "quote". I'm using *ngFor to build the table.
Each row contains a button to allow the user to delete that element, but I'd like'd like to offer a confirmation dialog that names that quote element. It should say something like "Do you want to delete "quote.symbol" in "quote.region"?"
To do this I'd like to pass these values to my dialog.
I use a button to open the dialog.
Delete
How do I pass quote.symbol and quote.region to the modal dialog?
Thanks,

A: I've come up with a solution. The button that targets the modal tag, can also execute a (click) method. I use the click method to save my row parameters in class variables in the typescript behind.
Then I can display those variables in my dialog and pass them to the procedure that does the work, from the click method when the use clicks OK in the dialog.


text:
Q: Google Cloud Remote Jupyter Notebook- Kernel Not Connecting When using a GCP AI Platform Jupyter Lab I am experiencing a unresponsive Jupyter Notebook.
The jupyter notebook is accessed over https (using the Open Jupyterlab button in GCP AI Platform).
The notebook says "Kernel Connecting" for several minutes before saying "Kernel Disconnected" in the status window.  When inspecting the browser error messages, it is reporting the below error message:
WebSocket connection to 'wss://475211ea312377e9-dot-us-east1.notebooks.googleusercontent.com/api/kernels/e77c9731-fc84-48d0-89ae-dfba685c37c1/channels?session_id=a6e7c6a9-ac86-4723-b435-74ca34036ded' failed:     _createSocket   @   default.js:73

I am using the basic Python 3 image with no special settings.
I am accessing the jupyter notebook from a Windows 10 Pro Corporate computer behind a corporate firewall / proxy.
When trying to access the jupyter notebook on an android phone, the jupyter notebook works fine, but when using company laptop, it is not working.  I have tried modifying several firewall settings, but still not able to connect.
Has anyone else experienced a similar issue?  Any ideas on how I can resolve the issue and connect via Windows corporate laptop?

A: You should take a look at WebSockets connections, as your test implied the connections are blocked by your Firewall. I would recommend to open a case with the Firewall vendor, check Websocket settings. If WS is not supported, I would use SSH to connect to it.
https://cloud.google.com/vertex-ai/docs/workbench/user-managed/ssh-access

A: There is a simple Remote Utility to connect to the Jupyter Notebook. GCP recommend to use SSH to connect Kernel from remote.


text:
Q: NUnit TestRunner working directory is different depending on target framework of project I am developing a library which has a test project in the solution. The library uses several framework from the .NET universe (like net462 or netcoreapp2.0) and works fine. The test project currently uses netcoreapp2.1 and the latest NUnit framework and test runner.
I have tests that rely on files that are included in the test project and are copied to the output folder during the build process. When the test project uses .NET Core as target framework, the files are found and the tests pass. When the test project uses anything else than .NET Core (I didn't test all .NET Framework versions, but some), the files are not found and the tests fail.
When not using .NET Core the working directory of the test runner seems to be located at C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\ which is not the project's output directory.
This is the not working project file
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <OutputPath>bin\Release\</OutputPath>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
   <OutputPath>bin\Debug\</OutputPath>
  </PropertyGroup>

    <PropertyGroup>
    <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.8.0" />
    <PackageReference Include="NUnit" Version="3.10.1" />
    <PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
  </ItemGroup>
</Project>

And this is the working project file
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
    <OutputPath>bin\Release\</OutputPath>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
   <OutputPath>bin\Debug\</OutputPath>
  </PropertyGroup>

    <PropertyGroup>
    <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.8.0" />
    <PackageReference Include="NUnit" Version="3.10.1" />
    <PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
  </ItemGroup>
</Project>

Does anyone know more about this behaviour? How do I fix this?

A: As explained in the cited issue, NUnit does not change the current working directory at all. This is by design, based on the notion that library programs should never change the cd but should leave it as set by the calling program.
There may be reasons why either the runner or Visual Studio itself changes the directory in the case of a .NET Core project. I don't know what they are but I do know that NUnit doesn't do it.
The obvious workaround is to use TestContext.TestDirectory in your tests. It is provided by NUnit for this purpose. Note that it only works in test code. If you need something similar outside of the test code, you can copy the logic from TestContext.TestDirectory, which is quite well tested.


text:
Q: How to ...... hide columns of a CxGrid with drag and drop How to popup a customization dialog to hide columns, like this:

A: "To achieve the desired result, set the GridView's OptionsCustomize.ColumnQuickCustomization property to True. Once it is done, you will notice a small button on the left of the column headers area. When you click it, a list of columns will be shown."
Source: https://supportcenter.devexpress.com/ticket/details/q324077/tcxgrid-list-of-columns-to-hide-unhide

A: .Controller.Customization := True;


text:
Q: Android.Webkit.WebView not load url in Xamarin.Android Android.Webkit.WebView not load url
I Created a method in main activity class this method have a WebView but not load url
public void LaunchBrowserView(string authorizationServerUrl)
        {
            try
            {
                var web_view = new Android.Webkit.WebView(this);

                web_view.Settings.JavaScriptEnabled = true;
                web_view.Settings.DomStorageEnabled = true;
                //web_view.Settings.= true;
                //web_view.Settings.AllowContentAccess = true;
                web_view.SetWebViewClient(new MyBrowser());
                web_view.Settings.LoadsImagesAutomatically = true;
                web_view.LoadUrl(authorizationServerUrl);
            }
            catch (System.Exception ex)
            {
            }
        }

class MyBrowser : WebViewClient
    {
        override public bool ShouldOverrideUrlLoading(Android.Webkit.WebView view, string url)
        {
            view.LoadUrl(url);
            return false;
        }

        public override void OnReceivedSslError(Android.Webkit.WebView view, SslErrorHandler handler, SslError error)
        {
            base.OnReceivedSslError(view, handler, error);
        }

    }

A: I test the code you provided, and invoke on my own, it works well.
activity_main.xml
<android.webkit.WebView
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

MainActivity.cs
protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.activity_main);

        LaunchBrowserView("https://www.google.com");
    }

Result:

I have upload on GitHub, you could download from WebView folder for reference.
https://github.com/WendyZang/Test.git
Updated:
If you want to do this without axml file, you could create the layout in activity.
 protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        // Set our view from the "main" layout resource
        //SetContentView(Resource.Layout.activity_main);
        RelativeLayout layout_main = new RelativeLayout(this);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent, RelativeLayout.LayoutParams.MatchParent);
        layout_main.LayoutParameters = layoutParams;

        WebView webView = new WebView(this);
        webView.LayoutParameters = layoutParams;

        layout_main.AddView(webView);
        SetContentView(layout_main);
        LaunchBrowserView("https://www.google.com", webView);
    }
    public void LaunchBrowserView(string authorizationServerUrl, WebView webView)
    {
        try
        {
            webView.Settings.JavaScriptEnabled = true;
            webView.Settings.DomStorageEnabled = true;
            //web_view.Settings.= true;
            //web_view.Settings.AllowContentAccess = true;
            webView.SetWebViewClient(new MyBrowser());
            webView.Settings.LoadsImagesAutomatically = true;
            webView.LoadUrl(authorizationServerUrl);
        }
        catch (System.Exception ex)
        {
        }

Result:

I have upload on GitHub, download from WebViewDemo2 for reference.
https://github.com/WendyZang/Test.git


text:
Q: EXC_BAD_ACCESS error C beginner program I am learning C and when I copy the tutorial code into Xcode it works. I tried to write my own simple I/O. The goal of the program is to ask input for each variable, a, b, c, etc. When I try to run my code the terminal says (11db) then I get EXC_BAD_ACCESS error and a warning that there are more % conversions than data arguments. Not sure what the problem is as I entered code almost identical to what the tutorial used. I used int variable since the idea is 1+2+3. I tried to place sum = a + b + c both before and after the printf and scanf functions and neither have worked. I am at a loss for what is causing this to occur. I did notice that in my feedback window
a (int) 33234 b = (int) 32766 c = (int) -272632304 sum = (int) 0

I am not sure how b and c were populated as it stops after the first data entry. Help is appreciated.

Tutorial Code:
#include <stdio.h>
int main()
{
    float a;
    int b;
    char ch;

    printf("\nEnter value of float\n");
    scanf("%f", &a);

    printf("\nEnter value of int\n");
    scanf("%d", &b);

    printf("\nEnter value of char\n");
    scanf(" %c", &ch);

    printf("\nValue of float : %f", a);
    printf("\nValue of int : %d", b);
    printf("\nValue of char : %c", ch);
    printf("\nValue of float(rounded) : %.2f\n", a);

    return 0;
}

My Code:
#include <stdio.h>
int main()
{
    int a;
    int b;
    int c;
    int sum;

    printf("\nEnter value of a\n");
    scanf("%d , &a");

    printf("\nEnter value of b\n");
    scanf("%d , &b");

    printf("\nEnter value of c\n");
    scanf("%d , &c");

    sum = "a + b + c";

    return 0;

}

A: The corrections are in comments.  I also added a printf() call to display the sum.
#include <stdio.h>
int main()
{
    int a;
    int b;
    int c;
    int sum;

    printf("\nEnter value of a\n");
    scanf("%d", &a); /* moved &a out of quotes */

    printf("\nEnter value of b\n");
    scanf("%d", &b); /* moved &b out of quotes */

    printf("\nEnter value of c\n");
    scanf("%d", &c); /* moved &c out of quotes */

    sum = a + b + c; /* got rid of quotes altogether */
    printf("%d + %d + %d = %d\n", a, b, c, sum); /* added to display results */

    return 0;

}

Give that a try and see if it works better for you.  C uses (") quotes to enclose a string constant.  Such a constant is just data, not code. "a + b + c" doesn't do anything.  It's just a bunch of characters. (You'll find out later that's actually an array of char values, with and extra binary 0 byte as an end marker. That's important, but it's not today's lesson.)


text:
Q: NullPointerException on calling getter method I have three classes TestGUI , MainFrame and ReportsJPanel.
MainFrame object is passed as parameter in ReportsJPanel constructor. When I try to call getter method of MainFrame object that was passed and get the value of private variable, from ReportsJPanel object I get the NullPointerException error. Error happens on this line in ReportsJPanel instalationLocation=mainFrame.getInstalationLocation();
Code for TestGUI:
package testgui;

public class TestGUI {

    public static void main(String[] args) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(RiskManagerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RiskManagerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RiskManagerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RiskManagerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

                MainFrame mainFrame = new MainFrame();
                mainFrame.initComponents();
                mainFrame.setVisible(true);
            }
        });
    }

}

Code for MainFrame:
package testgui;

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import left_panel_package.ReportsJPanel;

public class MainFrame extends JFrame{

    private String instalationLocation;

    public MainFrame(){
        setInstalationLocation("TEST_Location");
    }

    public void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("TEST");

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setBackground(new Color(0, 0, 0));

        JPanel leftPanel = new JPanel();
        leftPanel.setBackground(new Color(255, 0, 0));
        leftPanel.setPreferredSize(new Dimension(200,100));
        leftPanel.setLayout(new GridLayout(3,0));

        JPanel rightPanel = new JPanel();
        rightPanel.setBackground(new Color(0, 255, 0));
        rightPanel.setPreferredSize(new Dimension(200,100));

        JPanel centerPanel = new JPanel();
        centerPanel.setBackground(new Color(0, 0, 255));

        JPanel toolBar = new JPanel();
        toolBar.setBackground(new Color(0, 255, 255));
        toolBar.setPreferredSize(new Dimension(100,100));

        ReportsJPanel reportsPanel = new ReportsJPanel(this);
        reportsPanel.initComponents();

        leftPanel.add(reportsPanel);

        mainPanel.add(leftPanel, BorderLayout.WEST);
        mainPanel.add(rightPanel, BorderLayout.EAST);
        mainPanel.add(centerPanel, BorderLayout.CENTER);
        mainPanel.add(toolBar, BorderLayout.NORTH);

        setContentPane(mainPanel);

        GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
        int width = gd.getDisplayMode().getWidth();
        int height = gd.getDisplayMode().getHeight();
        setSize(width, height);
        setLocationRelativeTo(null);
    }

    public String getInstalationLocation() {
        return instalationLocation;
    }

    private void setInstalationLocation(String instalationLocation) {
        this.instalationLocation = instalationLocation;
    }

}

Code for ReportsJPanel:
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import testgui.MainFrame;

public class ReportsJPanel extends JPanel{

    private MainFrame mainFrame;
    private String instalationLocation;

    public ReportsJPanel (MainFrame mainframe){

        this.mainFrame=mainFrame;

        setBorder(new TitledBorder("Reports"));

    }
    public void initComponents(){
        instalationLocation=mainFrame.getInstalationLocation();
    }
}

A: Simple typo. In your constructor for your ReportsJPanel you have this.
public ReportsJPanel(MainFrame mainframe) {
    this.mainFrame = mainFrame;
    setBorder(new TitledBorder("Reports"));
}

You need to capitalize the f in the MainFrame object that you pass to the constructor.
public ReportsJPanel(MainFrame mainFrame) {
    this.mainFrame = mainFrame;
    setBorder(new TitledBorder("Reports"));
}

Otherwise, you will be setting this.mainFrame to itself, and the mainframe you pass in will not be used.

A:  public ReportsJPanel (MainFrame mainframe){

        this.mainFrame=mainFrame;

        setBorder(new TitledBorder("Reports"));

    }

names not matching in your code this.mainFrame = mainframe;
method parameter name is mainframe

I suggest you to use eclipse like IDE tool


text:
Q: Como indexar contenido dinamico en busquedas de google Bueno estoy haciendo una pagina tipo diccionario, la pagina tiene un cuadro de busqueda donde el usuario ingresara una palabra y se le enviara a una pagina con el resultado, pero esa pagina al principio estara en blanco y se ira cambiando el contenido segun la busqueda que realize el usuario, supongamos que lanze mi pagina web como haria que el contenido dinamico aparezca en las busquedas de google. Disculpen mi ignorancia en el tema pero soy nuevo en programacion web
Que me aparezca mas omenos asi:
tengo esa duda porque al principio la pagina estara en blanco y el contenido ira cambiando segun la busqueda que realize cada persona.
Este es mi codigo de la pagina principal:

<form action="busqueda.php" method="get">
  <input type="text" name="buscar" value placeholder="Buscar"/>

  <input type="submit" name="enviar" value="buscar"></input>

</form>

y este es el codigo de la pagina de busqueda:

<meta charset="utf-8">
<title>Documento sin título</title>

<?php
 $db_host="localhost";
 $db_nombre="diccionario";
 $db_usuario="root";
 $db_contra="";
 $conexion=mysqli_connect($db_host,$db_usuario,$db_contra,$db_nombre);
mysqli_set_charset($conexion,"utf8");
  $busqueda=$_GET["buscar"];
$palabra;
$definicion;
 $consulta="select * from significados where palabra='$busqueda'";
   $resultado=mysqli_query($conexion,$consulta);
 while($fila=mysqli_fetch_array($resultado,MYSQLI_ASSOC))
 {
 $palabra=$fila["palabra"];
 $definicion=$fila["definicion"];
 }
 ?>

  <?php echo $palabra;
 ?>

  <?php echo $definicion;

 ?>


text:
Q: How to upload image from VueJS to Symfony with Axios? I have the VueJS component installed without problem in my project with Symfony 4 but at the moment I want to upload an image. I follow this reference from Laravel: How to upload image from VueJS to Laravel with Axios?
I get to the controller but that's where the value in base 64 does not reach just the console message.
Code:
//CargaFoto.vue
<template>

{{ msg }}

        <input type="file" name="image" @change="getImage" accept="image/*">
        <button @click="updateAvatar">Subir Imagen</button>

</template>

And this the controller code:
/**
 * @return JsonResponse
 * @Route("/jsonimagen", name="jsonimagen", methods="POST")
 */
public function jsonimagen(Request $request):JsonResponse
{

    $data= $request->get("data");
    return $this->json($data);
}

The answer is null The doubt that I have is how I upload the image to the local server.

A: You're sending file content as avatar variable, why do you try to get request's data then?
Correct form would be:
$avatar = $request->file('avatar');

Also, you can omit adding _method: 'POST' to sent data as you're doing axios.post already.

A: Based on the link of a comment indicated by Fran I could see that the header was missing and then collect the data in Symfony in the same route that was already defined.
The template file was like this:
//CargaFoto.vue
<template>

{{ msg }}

                File
                    <input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>

                <button v-on:click="submitFile()">Submit</button>

</template>

In the file where the data is request, the controller is:
//src/UsuarioController.php
/**
 * @return JsonResponse
 * @Route("/jsonimagen", name="jsonimagen", methods="POST")

 */
public function jsonimagen(Request $request):JsonResponse
{
    $usuario = $this->getUser();
    $data = $request->files->get('file');
    $fileName = $usuario.'.'.$data->guessExtension();
    // moves the file to the directory where usuarios are stored
    $data->move(
        $this->getParameter('usuarios_directorio'),
        $fileName
    );
    echo $data; exit;
    return $this->json($data);
}

Also configure the path where the images will be loaded in the file
//services.yaml
parameters:
    locale: 'en'
    usuarios_directorio: '%kernel.project_dir%/public/uploads/usuarios'

Here you can see the image loaded in this capture.


text:
Q: Arithmetic operations on list with missing values I'm trying to do some arithmetic on a list that may contain missing values.
So far, I'm representing my list with Option[Int]:
val mylist=List( Option(4), Option(8), None )

With this representation, I can easily apply a function over the list (say, multiply by 2):
scala> mylist.map(_.map(_*2))
res2: List[Option[Int]] = List(Some(8), Some(16), None)

However, this looks more complicated than it needs be, so I'm wondering if I'm missing something.
Also, I can't figure out how to write things like the sum. I guess it should be possible with a (big) reduce expression...
So, I'd like to know if:

*

*List[Option[Int]] is a good representation for this use case

*mylist.map(_.map(_*2)) is the best way to map

*is there a simple way to do a sum?

A: Well, it's not a pattern I've used myself, but if values can be "missing" then an Option is appropriate. But a List probably isn't. In a List the position isn't usually something you should be relying on, since it's not random-access. Maybe a Vector would be better, or you need to think of a better way of modelling your problem, i.e. not as a list with missing values.
You can deal with Option nicely using for-expressions:
for (o <- mylist; x <- o) yield x * 2

or flatten the list:
mylist.flatten.map(_ * 2)

To sum it:
mylist.flatten.sum

A:

*

*List[Option[Int]] is a good representation for this use case

Is it possible to flatten it earlier with flatMap? For example, if you are creating this list using map, you could use flatMap instead and not have missing values. My suggestion is to not even represent the missing values if possible. If you need to represent them, Option is ideal.

*

*mylist.map(_.map(_*2)) is the best way to map

*is there a simple way to do a sum?

The nested map is probably preferable. You can foldLeft also.
foldLeft is also helpful if you need to do something besides sum/product.
scala> val mylist=List( Option(4), Option(8), None )
mylist: List[Option[Int]] = List(Some(4), Some(8), None)

scala> mylist.foldLeft(0){
     |   case (acc, Some(i)) => acc + i
     |   case (acc, _) => acc
     | }
res7: Int = 12

scala> (0 /: mylist) {
     |   case (acc, Some(i)) => acc + i
     |   case (acc, _) => acc
     | }
res8: Int = 12

scala> (0 /: mylist) {
     |   case (acc, Some(i)) => acc - (i * 2)
     |   case (acc, _) => acc
     | }
res16: Int = -24

A:
So, I'd like to know if:
List[Option[Int]] is a good representation for this use case

Option is definitely the preferable way to express missing values. You could also think about changing it into a List[(Int, Int)] where the first element indicates the position in your original list and the second element represents the value.

mylist.map(_.map(_*2)) is the best way to map

In my opinion there is no shorter or cleaner way to express that. (You have two "levels" that's why you need two maps!) With my suggested data structure this would turn into mylist.map(t => (t._1, t._2*2)).

is there a simple way to do a sum?

No easier way than om-nom-nom suggested. With my data structure it would be mylist.map(_._2).sum

A: The most general and most concise way to do this is with Scalaz's semigroup type class. That way, you're not restricted to List[Option[Int]] but can apply the same function to List[Int].
import scalaz._
import Scalaz._

object S {
  def double[A:Semigroup](l:List[A]) = l.map(x => x |+| x)
  def sum[A:Semigroup](l:List[A]) = l.reduce(_ |+| _)

  def main(a:Array[String]) {
    val l = List(Some(1), None, Some(2))
    val l2 = List(1,2)
    println(double(l))
    println(sum(l))
    println(double(l2))
    println(sum(l2))
  }

}

This prints
List(Some(2), None, Some(4))
Some(3)
List(2, 4)
3

A: i'm not sure what it is you are trying to achieve, but this does'nt seem like the right approach. if you need to determine if a value exists in your "list", then perhapse a Set would suit your needs better:
scala> val s = Set(4,8)
s: scala.collection.immutable.Set[Int] = Set(4, 8)

scala> s(4)
res0: Boolean = true

scala> s(5)
res1: Boolean = false

scala> s map (_ * 2)
res2: scala.collection.immutable.Set[Int] = Set(8, 16)

scala> s reduceLeft((a,b) => a+b)
res3: Int = 12

or even easier:
scala> s sum
res4: Int = 12

if you need something more sophisticated, and the index of the element in your list is important, you may use a Map where the keys simulate the index, and missing values can be mapped to some default value:
scala> val m = Map(1 -> 4, 2 -> 8) withDefault(n => 0)
m: scala.collection.immutable.Map[Int,Int] = Map(1 -> 4, 2 -> 8)

scala> m(1)
res5: Int = 4

scala> m(3)
res6: Int = 0

scala> m map {case (k,v) => (k,2*v)}
res7: scala.collection.immutable.Map[Int,Int] = Map(1 -> 8, 2 -> 16)

scala> m.foldLeft(0){case (sum,(_,v)) => sum+v}
res8: Int = 12

again, not sure what your needs are, but it feels like you are going the wrong way...
Option is a type i would think twice before using. ask yourself if it's realy necessary. there might be solutions that would achieve what you are trying to do in a more elegant way.


text:
Q: how to change the time unit for survfit results in r I am working to create a nice looking plot of the survfit return in R. The default  time unit on the x-axis is a long integer, which I am assuming is seconds or milliseconds. This persists no matter what the unit of time is that is originally passed to the Surv(time, event) function. I have tried passing the start and stop times as POSIXcs dates as well as in milliseconds. Does anyone know how to indicate to either survfit or plot.survfit that I would like the time result to be in either Days, Hours format or HH:MM format? Thanks for your help.
survival <- survfit(Surv(time=starteventtime,event=endevent,time2=stoptime)~1)
plot(survival)

the current plot rendered


text:
Q: C# General Error in GDI+ when saving Image I'm trying to save a System.Drawing.Image to a File.
This is my code:
    using(WebClient webClient = new WebClient())
        webClient.DownloadFile(new Uri(defaultPic), defaultPicPath);

    var tempImg = System.Drawing.Image.FromFile(defaultPicPath);
    using(System.Drawing.Image RoundedImage = RoundCorners(tempImg, 90, System.Drawing.Color.Transparent)) {
        RoundedImage.Save(defaultPicPath);
        tempImg.Dispose();
    }

In the RoundedImage.Save(...); line, I'm getting the Error

General Error in GDI+.

I am pretty sure the File is not locked by any WPF Control or Image.
Any Help is appreciated!
Thanks!

A: From what I can see from your code, you are not releasing the file.
You should,

*

*First read the image and create a local deep copy of it(tempImage). (Note: Shallow copy using Clone method will not work.)

*Release the image file.

*Modify your local copy.

*Overwrite the original file.

*Dispose local copy(tempImage).
Try following, it should work;
Image tempImage;
using(var img = System.Drawing.Image.FromFile(defaultPicPath))
    tempImage=new Bitmap(img);

using(System.Drawing.Image RoundedImage = RoundCorners(tempImg, 90, System.Drawing.Color.Transparent))
    RoundedImage.Save(defaultPicPath);
tempImg.Dispose();


text:
Q: Firefox addon uploading canvas contents to imgur I am writing an addon in firefox that automatically sends the contents of a canvas to imgur. I have already built a similar extension in chrome, where it works as expected, so I know that the usage of imgurs API is correct. When I use the same approach in the Firefox addon, I always get this response:
{
"data": {
    "error": "Image format not supported, or image is corrupt.",
    "request": "/3/upload",
    "method": "POST"
},
"success": false,
"status": 400
}

This is what I use to extract the image data and send it to the imgur API:
Request({
   url: 'https://api.imgur.com/3/upload',
   contentType : 'json',
   headers: {
       'Authorization': 'Client-ID ' + imgurClientID
   },
   content: {
   type: 'base64',
   key: imgurClientSecret,
   name: 'neon.jpg',
   title: 'test title',
   caption: 'test caption',
   image: getImageSelection('image/jpeg').split(",")[1]
},
onComplete: function (response) {
    if (callback) {
       callback(response);
    } else {
         var win = window.open(response['data']['link'], '_blank');
         win.focus();
         closeWindow();
    }
}

}).post();

and this is used to get a selection from a canvas and get the dataurl of that selection:
function getImageSelection(type) {
    //Create copy of cropped image
    var mainImageContext = mainImage.getContext('2d');
    var imageData = mainImageContext.getImageData(selection.x, selection.y, selection.w, selection.h);

    var newCanvas = tabDocument.createElement("canvas");
    newCanvas.width = selection.w;
    newCanvas.height = selection.h;

    newCanvas.getContext("2d").putImageData(imageData, 0, 0);

    return mainImage.toDataURL(type)
}

I have tried everything: using the dataurl from the original canvas (mainImage), getting the dataUrl without any type, this: .replace(/^data:image\/(png|jpg);base64,/, "");
But imgur keeps complaining about bad format.

A: In the end, it turned out that the usage of the Request module of the Firefox addon SDK was wrong.
Instead of using contentType to provide the type of the content (like in jquery/ajax), you have to use dataType. See below:
Request({
        url: 'https://api.imgur.com/3/upload',
        dataType : 'json',
        headers: {
            'Authorization': 'Client-ID ' + imgurClientID
        },
        content: {
            type: 'base64',
            key: imgurClientSecret,
            name: 'neon.jpg',
            title: 'test title',
            caption: 'test caption',
            image: getImageSelection('image/jpeg', true)
        },
        onComplete: function (response) {
            response = JSON.parse(response.text);
            if (callback) {
                callback(response);
            } else {
                var win = window.open(response['data']['link'], '_blank');
                win.focus();
                closeWindow();
            }
        }
    }).post();


text:
Q: What to put in HTML snapshot for hash-bang URL for SEO? I am using hash-bang URLs in my AJAX application and I am implementing the server-side for:

handle ?_escaped_fragment_=key1=value1%26key2=value2

So when I look at Google's FAQ, it says that this URL has an equivalent snapshot
It is easy to see that the snapshot content is not the same as corresponding hash-bang url.  This Google example does not help and therefore my question:
My HTML page has three components/panels/sections  that are being  updated by AJAX. I use the onclick event  on the hash-bang URLs to fetch the  content from server and then update  relevant section of the HTML page.   My panels are updated independent of  each other and each panel has its own hash-bang URL .
My question  is:
Should the HTML snapshot contain the entire page with all 3 sections  or only the  updated section?
If I am to return the entire page, it is almost impossible to get the state of the other 2 sections correctly, so would the Googlebot reject my site if the other 2 sections are returned in their default state ?

A: this is a good question, sadly no answer for this one :( im looking for the same. My problem is that EVERYTHING are news loaded with ajax, so each news is actually a little peace of text so im asking myself if my snapshots should be only the current new or a full page with all the info that i have in my home plus current new's content

A: Do you have news about that topic ?


text:
Q: How to nest a table, or anything else, inside align* or flalign*? This is my first day with latex and the basics aren't hard to pick up, but if I want to do anything more than default formatted formulas it's taking me forever to figure out how it works.
What I'm trying to do now is type up my homework. I want question numbers vertically aligned to the left and the answers are all tables. So, something like:
23a)  (table here)

  b)  (table here)

etc.

My code snippet is below and I just can't get it to compile. I get multiple "missing $ inserted" or "extra }, or forgotten $" errors. I have no idea what I'm doing and I can't find any remotely usable documentation.
\begin{flalign*}
\textbf{32a)} &
    \begin{tabular}{|c|c|c|}
        p & \neg p & p \rightarrow \neg p \\ \hline
        \text{T} & \text{F} & \text{F} \\
        \text{F} & \text{T} & \text{T} \\
    \end{tabular} &\\
\textbf{c)} &
    \begin{tabular}{|c|c|c|c|}
        p & q & p \lor q & p \oplus (p \lor q) \\ \hline
    \end{tabular} &\\
\end{flalign*}

A: Just replace tabular' byarray'.
\begin{flalign*}
\textbf{32a)} &
\begin{array}{|c|c|c|}
    p & \neg p & p \rightarrow \neg p \\ \hline
    \text{T} & \text{F} & \text{F} \\
    \text{F} & \text{T} & \text{T} \\
\end{array} &\\
\text{\bf c)} &
\begin{array}{|c|c|c|c|}
    p & q & p \lor q & p \oplus (p \lor q) \\ \hline
\end{array} &\\
\end{flalign*}

A: Rather use a list to enumerate your answers:

\documentclass{article}

\usepackage{amsmath}

\newcommand{\TRUE}{\text{T}}
\newcommand{\FALSE}{\text{F}}

\begin{document}

\begin{enumerate}
  \item[\bfseries 32a)]
    $\begin{array}[t]{|c|c|c|}
      p & \neg p & p \rightarrow \neg p \\
      \hline
      \TRUE  & \FALSE & \FALSE \\
      \FALSE & \TRUE  & \TRUE  \\
      \TRUE  & \TRUE  &        \\
      \FALSE & \FALSE &
    \end{array}$

  \item[\bfseries c)]
    $\begin{array}[t]{|c|c|c|c|}
      p & q & p \lor q & p \oplus (p \lor q) \\
      \hline
      \TRUE  & \TRUE  & & \\
      \TRUE  & \FALSE & & \\
      \FALSE & \TRUE  & & \\
      \FALSE & \FALSE & &
    \end{array}$
\end{enumerate}

\end{document}

I also switched to an array since the content is math-specific. Also for consistency and convenience, defined \TRUE and \FALSE to represent the truth values of the variable(s).

A: Try this:
\begin{flalign*}
\textbf{32a)} &
    \begin{tabular}{|c|c|c|}
        p & $\neg$ p & p $\rightarrow \neg$p \\ \hline
        \text{T} & \text{F} & \text{F} \\
        \text{F} & \text{T} & \text{T} \\
    \end{tabular} &\\
\textbf{c)} &
    \begin{tabular}{|c|c|c|c|}
        p & q & p $\lor$ q & p $\oplus$ (p $\lor$ q) \\ \hline
    \end{tabular} &\\
\end{flalign*}

A: Similar to Werner answer, but with tabular:

\documentclass{article}

\begin{document}
\begin{itemize}
\item[\textbf{32a)}]\quad
    \begin{tabular}[t]{|c|c|c|}
        p & $\neg$ p    & p $\rightarrow \neg$p \\ \hline
        T & F           & F \\
        F & T           & T \\
    \end{tabular}
\item[\textbf{c)}]\quad
    \begin{tabular}[t]{|c|c|c|c|}
        p & q & p $\lor$ q & p $\oplus$ (p $\lor$ q) \\ \hline
    \end{tabular}
\end{itemize}
\end{document}

Addendum:
With use of package enumitem, the use of list is even simpler:
\documentclass{article}
\usepackage{enumitem}

\begin{document}
\section*{Task}
\begin{itemize}[font=\bfseries,labelwidth=2em,labelsep=2em,leftmargin=!]
\item[32a)]
    \begin{tabular}[t]{|c|c|c|}
        p & $\neg$ p    & p $\rightarrow \neg$p \\ \hline
        T & F           & F \\
        F & T           & T \\
    \end{tabular}

    some comment about solution in table (if it is necessary)
\item[c)]
    \begin{tabular}[t]{|c|c|c|c|}
        p & q & p $\lor$ q & p $\oplus$ (p $\lor$ q) \\ \hline
    \end{tabular}
\end{itemize}
\end{document}

IN this case, if the task number is longer as it in example, you need to encrease labelwidth. For exaple for task number 123) a suitable labelwidth is 3em.


text:
Q: How to replace a character only when found within a specific words within a csv file Problem description:
Parse a csv file (with a pipe character as a delimiter) with pipe in one of the data fields. This data field will always be in an XML tags i.e.,  (starting tag) and  (closing tag). So, I am looking to parse the csv file with some kind of exclusion logic to ignore delimiters if found within the tags.
My goal is to parse this data corrected pipe delimited file (as shown below in the Expected result)  using Pentaho Data Integration tool to load into our database. After the data correction it is plain and simple to read the csv file.
Sample data:
abc| <evar29> d|e|f</evar29> | ghijk
xxx| yyyy| <evar29>z|z</evar29>

Expected Result ("|" replaced within evar29 tags with a "@@"):
 abc| <evar29> d @@ e @@ f</evar29> | ghijk
xxx| yyyy| <evar29>z @@ z</evar29>

A: For your case: (?<=<evar29>.*)(?=.*</evar29>)\|
For general: (?<=<.+?>.*)(?=.*<.+?>)\|

A: Answering my own question here after reading about sed and awk. However, this doesn't seem to be working well for multiple occurrences of the pipe character within those tags. I am currently working on that. Appreciate any help.
Command:  sed -n 's/<evar29>\(.*\)|\(.*\)<\/evar29>/<evar29>\1@@\2<\/evar29>/pg' test.txt
Description: Substitute the pipe character that occurs in between the evar29 tags.
The string right after the evar29 starting tag is broken down and captured using capture groups and then concatenated later using the desired character (in my case @@).
Command to replace the character and write to a file is below:
sed -i 's/<evar29>\(.*\)|\(.*\)<\/evar29>/<evar29>\1@@\2<\/evar29>/g' test.txt

Hope this helps anyone looking for a solution of this kind.


text:
Q: Separate Previous and Next button CSS I'm making a Slideshow for personal use and I'm having trouble trying to get my previous button on the left and the next on the right. (See image) I've tried a few things in CSS that I thought would work but have had no luck.

My markup:

CSS:
#image-wrap {
  border: 7px groove #fd0;
  height: 580px;
  width: 580px;
  margin: 0 auto;
  position: relative;
}

#title,#description,#controls {
  display: none;
  z-index: 999;
}

#image-wrap:hover #title,
#image-wrap:hover #description,
#image-wrap:hover #controls {
  display: block;
}

#controls {
  position: absolute;
  top: calc(50% - 29px);
}
#controls #prev { left: 0 }
#controls #next { right: 0 }

How can I get the "Next" button to appear on the right of the image?

A: You have to add width: 100% to #controls container and position: absolute to navigation buttons.

#image-wrap {
  border: 7px groove #fd0;
  height: 580px;
  width: 580px;
  margin: 0 auto;
  position: relative;
}

#title,#description,#controls {
  display: none;
  z-index: 999;
}

#image-wrap:hover #title,
#image-wrap:hover #description,
#image-wrap:hover #controls {
  display: block;
}

#controls {
  position: absolute;
  top: calc(50% - 29px);
  width: 100%;
}
#controls #prev { position: absolute; left: 0; }
#controls #next { position: absolute; right: 0; }


text:
Q: Apply DOM queries on C# webresponse I am creating web request and having webresponse object with me in C#.
Is there any way that I can apply DOM queries (document.getElementByClass('') etc ) on web response string?

A: Yes you can with the Html Agility Pack you can query nodes with XPath or Linq.


text:
Q: Image sending to php server from iOS I want to send image file to a php server using this piece of code
-(void)saveImageToServer
{
    NSData *dataImage = UIImageJPEGRepresentation([arrImage objectAtIndex:0], 0.8f);
    NSString *urlString = @"http://myurl:8002/FileService/REST/UploadFile?fileName=file.png";
    NSString *filename = @"test";
    NSMutableURLRequest* request= [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@.png\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[NSData dataWithData:dataImage]];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postbody];
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString* returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"test %@",returnString);
}

But I m receiving on server is what like
"
-----------------------------14737809831466499882746641449
Content-Disposition: form-data; name="image"; filename="test.png"
Content-Type: application/octet-stream
ˇÿˇ‡"
any idea what mistake im making


text:
Q: Go to another site automatically How can I make a Web page that takes me automatically without clicking to another site? (I use in HTML)
I tried to find a answer but I didn't find any answer that it in HTML.
I tried to write like this:

<a href="http://www.boutell.com/newfaq/">

</a>

 but this not take me automatically.

can someone help me?
thanks!

A: Write this in the head section of the HTML document.
<meta http-equiv="refresh" content="0; url=randomname.com" />

As soon as the page loads, on 0 seconds, you can go to your page.


text:
Q: How to make sure your dealloc code is called on application termination? According to NSObject's documentation:

Important: Note that when an
  application terminates, objects may
  not be sent a dealloc message since
  the process's memory is automatically
  cleared on exit --- it is more
  efficient simply to allow the
  operating system to clean up resources
  than to invoke all the memory
  management methods.

That's fine, but if my objects needs to do something on dealloc, such as saving its state to disk or log something?  How can I make sure that code gets called?

A: Persistency management should not be tied to dealloc. If you want to save object state, you should have some kind of session object that will collect the dirty objects and save the changes once in a while or when the application terminates/goes into background.
An example using application settings: Let's say you don't want to use NSUserDefaults for you application's settings, maybe because you have some extra logic to do. You have a Settings class that keeps all the settings and obviously you would like to keep the changes persisted.
You could stuff all the persistency logic into the Settings class, but that violates the single responsibility principle. (= There are good reasons why this would cause you pain.) So you could add a Session class that will take of persisting the changes made in Settings.
When the application starts you will create an instance of the Session and ask for Settings:
Session *session = [[Session alloc] init];
Settings *settings = [session loadSettings];

Now if there is a file on the disk that contains saved settings, the session will load it (which is simple, as the Settings class implements NSCoding). If not, the session will create a fresh Settings instance and return that. In addition, the session will probably start watching for changes in the returned Settings instance, say using NSNotificationCenter. (It's quite natural that a Settings object would fire a notification when the settings change.)
Now when you change something inside a Settings instance that you got from the session, the session will notice that and it will save the changes to disk. Which should be trivial, since Settings implement NSCoding. You could also mark the object as dirty and only save the changes every few seconds, which is a better solution in case you update the object quite frequently. In that case you might also want to force-save the session when the application is going to terminate or is going background.
I'm not saying this scenario is perfect, but it's certainly better than objects that persist themselves in dealloc :-)

A: Make sure the object gets released in your applicationWillTerminate: (NSApplicationDelegate).


text:
Q: Best place to keep secure information in java spring web application I have web application implemented using java spring.Basically each user in application can store some critical information. Once user enters that data , it should be persisted .Is there any standard way to store that secure information. I can think of following places to store that information
1) In database
2) On Webserver as different files for each user. We can encrypt data in those files using some key.

I prefer for webserver as files for each user.But I have following questions:
1) Where can we store those files on webserver
2) How can we restrict access to those files?
3) Is there something available in spring to achieve this?
4) What kind of encryption library I can use to achieve this. And where I can store key for each user.
5) How we can sync those files on multiple instances. Is there some standard library for this also?

A: I'm not familiar with Spring but I recently worked on secure file storage so here is what I can say :
Where can we store files ?

*

*On the server
You can just store the files on the server and read them, but if your server is corrupted, then the attacker gets the files

*In the database
Well known DBMS like MySQL or MongoDB allows you to store files (as blobs or sets of chunks).

The advantage of storing files in the DB is the following : If the attacker reaches your server, then he will not get the files, he will have to find the DB password.

 How can we restrict access to those files ?

*

*Restrict access to the eventual attacker
Create a new user on the server who's the only one that can access your DB or your files and use a strong password.

*Restrict access to other users
Just ask for authentication ! But simple password isn't very secured ...

 Authentication
For a strong enough authentication method, you must ask 2 of this 3 questions to your user :

*

*What do you know ? (e.g a password)

*What do you have ? (e.g SMS Phone Verification)

*What are you ? (e.g fingerprint, eye scan ...)

Not secure enough ? Let's have a quick talk about file encryption ...

What kind of encryption library I can use to achieve this. And where I can store key for each user ?
For the librairies, I don't know (my apologizes) but for the encryption method, keep it simple : use well known and efficient algorithms like RSA, AES or Triple DES.
How to handle encryption ?
Here is the result of a conversation I've had with friends about file encryption and key storage :

*

*Storage :
The client has to encrypt the file. Then he sends the key and the filename (or file ID) to a server (server1) and the encrypted file to another server (server2)

*Download :
The client gets the encrypted file from the server2, read the filename (or the file ID) and get the right key from server1 so he can decrypt the file.
The best thing to do is to secure the 2 servers (1 and 2) with Two Factors authentication (2 of the 3 questions) but it could be a break to the user's experience.
Hope it could help,


text:
Q: What is an alternative to get_page_by_title()? I'm coding a theme where I want to display information in the footer that's only available on a template page. I have been using get_page_by_title() which works well if you know what the page will be called, but in my opinion it's not very dynamic, it's impossible to predict what a user will name a page in your theme.
In my research I found a function called get_all_page_ids() which returns a numerically indexed array of ids from the site. This function would be a lot cooler if it was an associative (or even a post object), but I digress.
I have considered using something like this:
$all_page_ids = get_all_page_ids();

foreach ($all_page_ids as $id) {
    // get_post() {@link https://developer.wordpress.org/reference/functions/get_post/}
    $post_object = get_post($id);

    // preg_match() {@link http://php.net/manual/en/function.preg-match.php}
    if(preg_match("/\b(contact)\b/i", $post_object->post_title)) {
        // do something here
    } else {
        // for readability
        continue;
    }
}

However, this still creates the problem of having to know that the user chose to have the word contact in their title. What if they created a page called "Get in Touch" that is their contact page? This would break.
So, in short, my question revolves around best practice for theme designers. Is get_page_by_title() the best way to get another page's ID, or is there a way to combine a few functions/variables to get another page's ID without knowing the title?
Or are there WordPress functions that do this kind of heavy lifting or is get_page_by_title() the only close one? My suspicion is there's a hackier, but better way to do this, I just don't have any ideas. Thanks for any help you're able to give on this.

A: If you don't force a title, and obviously do not know the id, the only way you can do it is by letting the user select which page to use, usually done in the theme's options page, but can be done in the costumizer, or even as part of page editing

A: If your page is a template page then you can use is_page_template($template_name)
Otherwise as Mark mentioned you have to create a theme option and let the user decide.
More: https://codex.wordpress.org/Function_Reference/is_page_template
UPDATE
I misread your question. You can get all pages using a certain template name but again a user could made more than one such pages with the same template so you are not sure which one to choose.
 $args = array(
    'meta_key'         => '_wp_page_template',
    'meta_value'       => 'page-about.php',
    'post_type'        => 'page'
 );
 $posts_array = get_posts( $args );

Another idea is to create yourself your page with code at the activation of the theme/plugin and then save the id as an option but also provide a theme option to the user to change the page if he/she wants. That's how WooCommerce works with the Shop Page.
Again I believe Mark's approach is better and safer.


text:
Q: Azure Function not stateless I have a .NetCore 2 Azure Function (runtime 2) on a consumption plan that makes use of reflection, it loads an assembly in the current Domain (Assembly.LoadFrom()) and does other stuff with it.
Most times the function runs fine, but sometimes it complains that the assembly is already loaded. I though this should not be possible as functions in the consumption plan should be running statelessly...
Am I missing something?

A: It's stateless yes, but your app domain will remain loaded indefinitely unless you unload it. As you are using Azure Functions v2, this means you are in the land of .NET Core, meaning you don't have an AppDomain you can use. However, you can use AssemblyLoadContext. For example:
public class FooContext : AssemblyLoadContext
{
    public FooContext() : base(isCollectible: true)
    {
    }
}

And now:
var myLoader = new FooContext();

var assembly = myLoader.LoadFromAssemblyPath("your-path");

// Now do stuff with "assembly" as you did before

Finally, remember to clean up:
myLoader.Unload();

A: Azure function is stateless and as David said in comments:

your app domain will remain loaded indefinitely unless you unload it

If you still want to load it, you can try to use the code below:
byte[] fileData = File.ReadAllBytes(dllPath);
Assembly asm = Assembly.Load(fileData);

But this code can't load the associated assembly.


text:
Q: Facebook Login for Android to use default browser I integrated a Facebook sign in with my Android app following the rules:
https://developers.facebook.com/docs/facebook-login/android
The documentation states:

If people don't have the Facebook Android app installed, Facebook Login uses Facebook Lite instead to display the login screen and get credentials.

But a new screen requires to enter email/password on each open.
Is there a way to open a default system browser? I'm assuming many people are signed in on browser thus it would ease a friction to sign in into my app.
I could build a website sign in but I think there's no easy way to report back to the app a user ID (generating some kind of tokens in app?).

A: Facebook Login tries to log in on Android via Facebook app or FBLite app if that is installed and then send to the default browser. The logic there is that a person is more likely to be logged in to their Facebook app if they have that on their device. You can specify if somebody is sent to Chrome Custom Tabs like this versus the default browser: https://developers.facebook.com/docs/facebook-login/android#chrome_custom_tabs

A: Add below code in Your AndroidManifest It will open default chrome browser once you saved credentials in browser no need to enter username and password each time.
<activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>

Here fb_login_protocol_scheme is
<string name="fb_login_protocol_scheme">fbYOUR_FB_ID</string>


text:
Q: tabularx column width not behaving as expected I'm trying to reproduce the following tabular design as close as possible:

This is what I have right now:
\documentclass[12pt,a4paper]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage{tabularx}
\newcolumntype{Y}{>{\centering\arraybackslash}X}

\begin{document}
    \begin{tabularx}{\textwidth}{X X X X X X}
        \hline
        \multicolumn{3}{|Y|}{Width 1/2} & \multicolumn{3}{Y|}{Width 1/2} \\
        \hline
        \multicolumn{3}{|X|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } & \multicolumn{3}{X|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } \\
        \hline
        \multicolumn{6}{|Y|}{Width 1} \\
        \hline
        \multicolumn{6}{|X|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } \\
        \hline
        \multicolumn{2}{|Y|}{Width 1/3} & \multicolumn{2}{Y|}{Width 1/3} & \multicolumn{2}{Y|}{Width 1/3} \\
        \hline
        \multicolumn{2}{|Y|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } & \multicolumn{2}{Y|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } & \multicolumn{2}{Y|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } \\
        \hline
    \end{tabularx}
\end{document}

However I end up with this:

*

*The column width is not working

*Text is not vertically centered

*I'm not sure if the text in the cells will linebreak

How can I improve the result? I'm close to using Word/Excel for this...

A: You really don't want tabularx here as you know in advance how wide you want the columns to be. Your attempt failed as tabularx essentially does some calculations and then replaces every X by p{x} for some width x (the same value in every case) but you want cells that are half, full or third width.

\documentclass[12pt,a4paper]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage{array}
\newcolumntype{Y}{>{\centering\arraybackslash}X}
\setlength\extrarowheight{3pt}
\begin{document}
\noindent
    \begin{tabular}{cccccc}
        \hline
        \multicolumn{6}{|c|}{Title}\\
        \hline
        \multicolumn{3}{|p{\dimexpr(\textwidth-3\arrayrulewidth-4\tabcolsep)/2\relax}|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } & \multicolumn{3}{|p{\dimexpr(\textwidth-3\arrayrulewidth-4\tabcolsep)/2\relax}|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } \\
        \hline
        \multicolumn{6}{|c|}{Width 1} \\
        \hline
        \multicolumn{6}{|p{\dimexpr\textwidth-2\arrayrulewidth-2\tabcolsep\relax}|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } \\
        \hline
        \multicolumn{2}{|c|}{Width 1/3} & \multicolumn{2}{c|}{Width 1/3} & \multicolumn{2}{c|}{Width 1/3} \\
        \hline
        \multicolumn{2}{|p{\dimexpr(\textwidth-4\arrayrulewidth-6\tabcolsep)/3\relax}|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } & \multicolumn{2}{p{\dimexpr(\textwidth-4\arrayrulewidth-6\tabcolsep)/3\relax}|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } & \multicolumn{2}{p{\dimexpr(\textwidth-4\arrayrulewidth-6\tabcolsep)/3\relax}|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } \\
        \hline
    \end{tabular}
\end{document}

A: A slight improvement with vertical centring of the cell contents and a title:
\documentclass[12pt,x11names, a4paper]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage{array}
\newcolumntype{Y}{>{\centering\arraybackslash}X}
\setlength\extrarowheight{3pt}
\usepackage{ragged2e}
\usepackage{xcolor, colortbl}
\usepackage{etoolbox}

\usepackage{enumitem}
\AtBeginEnvironment{tabular}{%
\setlist[itemize, 1,2]{label=\color{LightSteelBlue3}\textbullet, leftmargin = 0.8em,nosep, before =\leavevmode\vspace{-\baselineskip}\RaggedRight, after=\leavevmode\vspace{\dimexpr-\baselineskip + \extrarowheight\relax},}%itemsep=1pt, , topsep=0pt,
}
\begin{document}
\noindent
    \begin{tabular}{cccccc}
        \hline
        \multicolumn{6}{|c|}{\cellcolor{LightSteelBlue3}\sffamily\bfseries\color{white}Title}\\
        \hline
        \multicolumn{3}{|p{\dimexpr(\textwidth-3\arrayrulewidth-4\tabcolsep)/2\relax}|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } & \multicolumn{3}{|p{\dimexpr(\textwidth-3\arrayrulewidth-4\tabcolsep)/2\relax}|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } \\
        \hline
        \multicolumn{6}{|c|}{Width 1} \\
        \hline
        \multicolumn{6}{|p{\dimexpr\textwidth-2\arrayrulewidth-2\tabcolsep\relax}|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } \\
        \hline
        \multicolumn{2}{|c|}{Width 1/3} & \multicolumn{2}{c|}{Width 1/3} & \multicolumn{2}{c|}{Width 1/3} \\
        \hline
        \multicolumn{2}{|p{\dimexpr(\textwidth-4\arrayrulewidth-6\tabcolsep)/3\relax}|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } & \multicolumn{2}{p{\dimexpr(\textwidth-4\arrayrulewidth-6\tabcolsep)/3\relax}|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } & \multicolumn{2}{p{\dimexpr(\textwidth-4\arrayrulewidth-6\tabcolsep)/3\relax}|}{
            \begin{itemize}
                \item Item 1
                \item Item 2
                \item Item 3
            \end{itemize}
        } \\
        \hline
    \end{tabular}
\end{document}


text:
Q: Trigger in mysql used for auto updation got an error My Previous question  's answer is right. The trigger is got an error
Here i use that in my program the following error occurred
2014-02-25T11:51:52.737+0530  ERROR  line 1:2: unexpected token: CREATE
2014-02-25T11:51:52.737+0530  ERROR  line 1:2: unexpected token: CREATE
line 1:2: unexpected token: CREATE

This is the code
@SuppressWarnings("unchecked")
public static void expMember(){

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.setFlushMode(FlushMode.MANUAL);
session.beginTransaction();

java.util.Date utilDate=new java.util.Date();
java.sql.Date sqldate=new java.sql.Date(utilDate.getTime());

List<Member> members = (List<Member>) session.createQuery(
        "from Member where exp_status = 'false' ").list();;

for(Member i : members){

Date exp=i.getRenewDate();

try {

    members = (List<Member>) session.createQuery(
" CREATE  TRIGGER autoupdation_"+ sqldate +" BEFORE UPDATE  ON tbl-member FOR EACH
      ROW BEGIN IF"+ exp .compareTo(sqldate)+" THEN  SET NEW.status = 1;
      ELSE SET NEW.status = 0; END IF;END;").list();

}

catch(Exception exception){

}
}
}

A: You are Trying to run a native sql query so for those please use createSQLQuery instead of createQuery
Also Why do you create triggers on fly . Your logic of creating triggers within a loop is wrong. You just need to create one trigger that can be done at database creation itself.
The MySQL Table Editor in MYSQL workbench  provides a work space that has tabs used to perform these actions:

Columns: Add or modify columns

Indexes: Add or modify indexes

Foreign Keys: Add or modify foreign keys

Triggers: Add or modify triggers

Partitioning: Manage partitioning

Options: Add or modify various general, table, and row options

Please check
https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/querysql.html
http://www.mkyong.com/hibernate/hibernate-native-sql-queries-examples/
https://dev.mysql.com/doc/workbench/en/wb-table-editor.html


text:
Q: How do I use django mptt? I have a model:
class Company(models.Model):
    name = models.CharField( max_length=100)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
mptt.register(Company, order_insertion_by=['name'])

and
class Financials(models.Model):
    year = models.IntegerField()
    revenue = models.DecimalField(max_digits = 10, decimal_places = 2)

So how can I add Financials as a child to Company in the mptt tree structure?

A: I don't quite follow your question. A tree stores one type of object, in your case Company. To link Financials to Company just add a foreign key from Financials to Company.
If this doesn't help please expand your question to give us some more detail about what you are trying to achieve.