text:
Q: Como trago um select de valores definidos em um Controller no angular.js? Desculpem mas sou leigo e estou começando!
No HTML, eu quero apresentar os dados definidos numa classe controller do angular. Conforme abaixo:
$scope.tiposCategorias = [
                            { id: 1, descricao:'Processados'},
                            { id: 2, descricao:'Naturais'},
                            { id: 3, descricao:'Perecíveis'},
                            { id: 4, descricao:'Antiperecíveis'}
                    ];

Na view faço um crud básico, mas selecionando apenas os dados que já estão definidos na classe controller. Conforme abaixo:
<select class="form-control" ng-model="categoria.tipoCategoria" ng-options="tp.id as tp.descricao for tp in tiposCategorias" required></select>

Após isso, quero apresentá-los em uma tabela do HTML. Conforme o código abaixo:

        {{cate.tipoCategoria==1?'Processados':'Naturais':'Perecíveis':'Antiperecíveis'}}

Porém, quando escolho a opção e salvo, nenhuma informação aparece. A tabela fica nula. Sei que o erro é quando chamo o parâmetro do angular para mostrar a informação dentro da tabela, mas não sei como corrigir isso.
Obrigado desde já se alguém conseguir entender onde está o erro.

A: Olá acredito que entendi oque precisa. Acho que é bem tranquilo pra fazer.
Pra ficar legal você só precisa usar a função filter para buscar o item que quer cadastrar do array inicial.
Vou colocar o código abaixo.

app = angular.module('meuapp', []);

    app.controller('moduloArray', function($scope) {
        $scope.tiposCategorias = [{
            id: 1,
            descricao: 'Processados'
        }, {
            id: 2,
            descricao: 'Naturais'
        }, {
            id: 3,
            descricao: 'Perecíveis'
        }, {
            id: 4,
            descricao: 'Antiperecíveis'
        }];

        $scope.listaCategorias = Array();
        $scope.adicionarItem = function(categoria) {
          $scope.categoria.tipoCategoria = null;
          //filtrando apenas o item que quer cadastrar para pegar a descrição
          var a = $scope.tiposCategorias.filter((item) => (item.id == categoria))[0].descricao;
          $scope.listaCategorias.push({
              id: categoria,
              descricao: a
          });
        }
    })

        <select class="form-control" ng-model="categoria.tipoCategoria" ng-options="tp.id as tp.descricao for tp in tiposCategorias" required></select>
        <button ng-disabled="!categoria.tipoCategoria" ng-click="adicionarItem(categoria.tipoCategoria)">+</button>

                    {{$index+') '+'ID: '+cate.id+' Tipo: '+cate.descricao}}

Espero ter ajudado um pouco.


text:
Q: Stack Overflow - No. of votes are not represented in "kvotes", just like "kviews" I queried for a keyword (core java) and clicked 'votes' tab to see the Q/A with the highest no. of votes. There, I can see a Answer with 10581 no.of Votes with last digit(1) aligned outside of colored box.
It will be good to see, if the no. of votes (exceeding 1000) were represented in "kvotes", just like "kviews". :) [since initially the number(10581) shown me like 1058 votes and below post with 4076 votes & confused why the posts were not sorted in descending.]
See the below screenshot taken:

A: It is very rare to have a question or answer that makes it to 1,000 votes, hence it is something to show as is! like a little show off ;)
Little stats: out of 6.6 million questions on SO (??? million answers), there are only 243 posts (questions + answers) that have 1,000 votes or more, while there are 1.2 million questions that have more than 1,000 views.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stuck with a javascript function? I must call a function to translate French phrases to English and I'm stuck on the showEnglish(). It will not pull the english arrays. And I'm not even sure if I'm referencing the setup function right which I had in a separate JavaScript file.
Here's what I have so far:
window.onload = setup;
function setup() {
    var questions = document.querySelectorAll("article ol li");
    for (var i = 0; i < questions.length; i++){
        questions[i].id = i + "phrase";
        questions[i].onmousedown = showEnglish;
        //questions[i].onmouseup = showFrench;
        questions[i].style.cursor = "pointer";
    }
}
function showEnglish() {
    var phrases = document.getElementById("phrase");
    var phraseNumber = parseInt(phrases.id);
    phraseNumber.innerHTML = english[phraseNumber];
    phraseNumber.style.fontStyle = "italic";
    phraseNumber.style.fontColor = "rgb(191, 22, 31)";
 }

A: Here is a sample snippet which does not use ids and should match your needs.

Questions list can easily be built from translations object using a script. (Check snippet in second solution below)

// On document load (warning: does not work with IE8)
document.addEventListener('DOMContentLoaded', function() {
  setup()
})

// Store French -> English translations
var translations = {
  "Comment vous appelez vous ?": "What's your name ?",
  "Où habitez vous ?": "Where do you live ?"
};

// Attach `translate` function to questions `mousedown` event
function setup() {

     document
     .querySelectorAll("article ol li")
     .forEach(function(el) {
       el.onmousedown = showEnglish
     });
}

// Display translation when mousedown on element
function showEnglish(event) {
    var element = event.srcElement || event.target
    var translation = document.getElementById("translation");
    translation.innerHTML = translations[element.innerText];
 }

Questions

Comment vous appelez vous ?

Où habitez vous ?

Traduction

Other solution
Build DOM from translations

// On document load (warning: does not work with IE8)
document.addEventListener('DOMContentLoaded', function() {
    buildDOM();
})

// Store French -> English translations
var translations = {
    "Comment vous appelez vous ?": "What's your name ?",
    "Où habitez vous ?": "Where do you live ?"
};

// Display translation when mousedown on element
function showEnglish(event) {
    var element = event.srcElement || event.target
    var translation = document.getElementById("translation");
    translation.innerHTML = translations[element.innerText];
}

function buildDOM() {
    var ol = document.createElement("ol");

    for (var t in translations) {
        var el = document.createElement("li");
        el.className = "question";
        el.innerText = t;
        el.onmousedown = showEnglish
        ol.appendChild(el);
    }

    document.getElementById("questions").appendChild(ol);
}

Questions

Traduction


text:
Q: Gradle/Android Studio doesn't pull dependencies from specified repositories NOTE: This is a followup of my last question that still remained unsolved.
I'm using a fully updated AndroidStudio with the default gradle support.
Android Studio can self update (thus sees Internet for sure).
I have no reason to beleive that Gradle can't reach the internet nor any error that could imply that, and I verified that it's not on offline mode.
Here's my Here's my top-level build.gradle:
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

and here's my app/build.gradle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"

    defaultConfig {
        applicationId "com.domain.app"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'com.github.jitpack:android-example:1.0.4'
}

Here I'm trying to pull the jitpack.io sample, and still  getting:
Error:(31, 13) Failed to resolve: com.github.jitpack:android-example:1.0.4

without any additional information.

A: try this :
buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Then in your app/build.gradle :
apply plugin: 'com.android.application'

repositories {
    maven { url "https://jitpack.io" }
    flatDir {
        dirs 'libs'
    }
}

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"

    defaultConfig {
        applicationId "com.domain.app"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'com.github.jitpack:android-example:1.0.4'
}

A: Its not the problem of android studio, To inform you
Neither
compile 'com.github.jitpack:android-example:1.0.4'

Nor
compile 'com.github.User:Repo:Tag'

Both doesn't compile now, Because it's no longer available in the The Central Repository. You don't have any ways rather than seeing the codes inside.


text:
Q: Pass data to modal from other url What I try to do is pass data from main page to popup page(modal) that I call from other html.
What I want to pass is name and description that exist in main to modal.
My main
EDIT

My frmGroupGeneral html(modal/popup)

        <button type="button" class="close" data-dismiss="modal">X</button>

Group Page

Name

              <textarea class="form-control" rows="1" id="textareaName" placeholder="Enter name" maxlength="50"></textarea>

Description

              <textarea class="form-control" rows="5" id="textareaDescription" placeholder="Enter description" maxlength="500"></textarea>

Thanks in advance.

A: You are already using the *data attributes in your html page. All you have to do is to add few more data-* id's according to your need to pass the data from your parent html page to the popup page.
For eg,
Considering your case you can pass the name and description to your modal like this,
EDIT

And in your modal you can retrieve the passed in parameters as,
 var nameValue = $(this).data('name');
 var descriptionValue = $(this).data('description');

To set the retrieved value to any field in model you can simply do,
 $(".modal-body #textareaName").val(nameValue);
 $(".modal-body #textareaDescription").val(descriptionValue);

Hope this helps!


text:
Q: save new mongoose schema for each element of array using ecmascript 6 I am looping through an array and creating a new mongoose schema, adding two fields, and then saving it.
for (var i = 0; i < myArray.length; i++) {
    var newUsers = new UserList({
        email: myArray[i],
        uuid: uuidv4()
    });
    UserList.save(function (err) {
        if (err) console.log(err)
    });
}

Question:
how can I achieve this using ecmaScript 6 best practices?

A: You can achieve your solution by using map method and mongoose insertMany method.
const bulkData = myArray.map(email => new UserList({ email, uuid: uuidv4()}));
UserList.insertMany(bulkData, (error, docs) => {});


text:
Q: Visual C# GUI stops responding when process.WaitForExit(); is used I am creating a GUI application using Visual C# 2005 (net framework 2). I use the following code to start a process:
Process process = new Process();
process.StartInfo = new ProcessStartInfo("app.exe");
process.StartInfo.WorkingDirectory = "";
process.StartInfo.Arguments = "some arguments";
process.Start();
process.WaitForExit();

I want my application to wait until this process is finished, so I used WaitForExit. But the GUI Windows freezes while app.exe is running. I want it to respond (e.g. press a cancel button), but I don't want the code to continue, because there is another process to start after than. Thanks in advance!

A: You can capture the Exited event of the Process class:
void someMethod()
{
    //...possibly more code here
    Process process = new Process();
    process.StartInfo = new ProcessStartInfo("app.exe");
    process.StartInfo.WorkingDirectory = "";
    process.StartInfo.Arguments = "some arguments";
    process.Exited += new EventHandler(ProcessExited);
    process.Start();
}

void ProcessExited(object sender, System.EventArgs e)
{
  //Handle process exit here
}

A: Your waiting for the process on the only thread of your application that is also responsible for handling all GUI events. If you want to wait for some event (like some other process to finish) and still have your code notified of the event then you have to wait on another thread or use an event handler.

A: This should help.  Basically for windows forms and simple tasks like this, a BackgroundWorker is handy.  Below is some simple code to launch notepad and wait for it to either close or the user can kill it by clicking cancel.
    public Form1()
    {
        InitializeComponent();
        backgroundWorker1.WorkerSupportsCancellation = true;
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        Process process = new Process();
        process.StartInfo = new ProcessStartInfo("notepad.exe");
        process.Start();
        while (!process.HasExited)
        {
            if (backgroundWorker1.CancellationPending)
            {
                process.Kill();
                continue;
            }
            else
                Thread.Sleep(1000);
        }
    }

    private void Start_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }

    private void Cancel_Click(object sender, EventArgs e)
    {
        backgroundWorker1.CancelAsync();
    }

A: In order to receive a callback on Exited event, the EnableRaisingEvents must be set to true.
Process correctionProcess = Process.Start(startInfo);
correctionProcess.EnableRaisingEvents = true;
correctionProcess.Exited += new EventHandler(ProcessExited);

Using exited worked well for me and gave me great flexibility to either run sequentially, partially concurrently, or all at once - without locking the UI.

A: Perhaps you should implement a solution with the BackgroundWorker. It is easy to implement and does what you want.
What you have to do is add an instance of a BackgroundWorker in your form, and make the call to the Process running the App.exe from the BackgrondWorker RunWorkerAsync method. Then on you can monitor for a CancelationPending property to stop the process or RunWorkerCompleted event to perform whatever is necessary after the Process has exited.
There is another SO question, concerning the BackgroundWorker cancelation

A: the solution for this is using a multi-threading
start by adding:
using System.Threading;
then look at the code bellow :
    Process process = new Process();
    process.StartInfo = new ProcessStartInfo("app.exe");
    process.StartInfo.WorkingDirectory = "";
    process.StartInfo.Arguments = "some arguments";

//starts a new thread that starts the process so when you call WaitForExit it does not freez the main thread
    Thread th= new Thread(() =>
    {
        process.Start();
        process.WaitForExit();
    });
    th.Start();

if you want to run multiple process back to back it is another case
you will need to use something like a List of process look at the code bellow
    List<Process> processes = new List<Process>();;

    Process process = new Process();
    process.StartInfo = new ProcessStartInfo("app.exe");
    process.StartInfo.WorkingDirectory = "";
    process.StartInfo.Arguments = "some arguments";

    processes.Add(process);

// i add another one manually but you can use a loop for exemple
    Process process2 = new Process();
    process.StartInfo = new ProcessStartInfo("app.exe");
    process.StartInfo.WorkingDirectory = "";
    process.StartInfo.Arguments = "some arguments";

    processes.Add(process2);

// then you will start them though your thread and the 2nd process will wait till the first finishes without blocking the UI
    Thread th= new Thread(() =>
    {
            for (int i = 0; i < processes.Count; i++)
            {
                    processes[i].Start();
                    processes[i].WaitForExit();
             }
    });
    th.Start();


text:
Q: How to download PDF file from php URL in Android? I have a php URL, which when I run in a browser, it returns to me a PDF file. In my application I want to download this PDF file. I'm trying to do this:
HttpURLConnection urlConnection = urlConnection = (HttpURLConnection) url_download_relatorio_funcionario.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();

int totalSizePDF = urlConnection.getContentLength();

But the integer value "totalSizePDF" only returns to me -1 value, instead of the real size of PDF file which is opened if I run this URL in a browser. How can I download this PDF file from the php URL, producing the same effect as a browser?

A: getContentLength() uses the Content-Length header which, according to Google Chrome's Dev Tools, your server isn't returning.
Try setting the length header from your PHP script first.
Downloading the file should be simply reading the returned bytes and saving them to file.


text:
Q: Strange results from Observable.concat(observable,observable) A while a go, I read about RxJava concat and decided to test my understanding. But I've encountered some behavior that I don't quite understand.
The problem is that when I concat two observables I get different behaviours depending on the order in which i pass them to Observable.concat()
val ob1 = createObservableSomehow()

val ob2 = createObservableSomehow()

Observable.concat(ob1,ob2).subscribe(::println) //only prints emissions of ob1

Observable.concat(ob2,ob1).subscribe(...) //concats all emissions correctly

See the attached screenshot to see how am creating the two observables.

A: concat() will wait for the first stream to complete only then it will start emitting items from second stream.
In your case you have not declared, that the first observable has completed its emission, so concat() assumes there are still emissions to come, because no terminal event has ever been dispatched.
As soon as you execute it.onComplete() inside your first stream you will see the output you expect.

A: You need to call onComplete() after last onNext() for first Observable


text:
Q: how to add string to PHPUnit failure message universally I am testing with phpunit and I would like to add the string "**** " to all of the failure message that the developers type in so the message will be easier to identify in the failures.  Now there is the information about which test failed and which assertion failed surrounding the message so you have to work a little harder to find the message - I want to make our messages easier to spot.
I could have the developers just add the string to each message - but that's not very DRY.  Is there a way to universally reformat the failure messages?

A: I think you will want to modify the PHPUnit_TextUI_ResultPrinter class.
https://github.com/sebastianbergmann/phpunit/blob/master/src/TextUI/ResultPrinter.php
Have a look at the printDefect... methods. You should be able to prefix something to the output.


text:
Q: Are there shortcuts for predicting whether an exponential function will evaluate to a positive or negative value? I'm a software architect, working on some algorithms involving unique storage formats for large numbers.
The function I'm working with is:$$y = \frac{mx^p+b}{d}$$ ... where $p$ and $d$ would traditionally $=1$ for standard linear graphs.
However, for the algorithms I'm working on, $p$ may be any integer (including $0$ and negatives), and $d$ may be any integer $\ge0$ (with $0$ resulting in $y$ being undefined, obviously).
$x$ may be any rational number $\ge0$
$m$ and $b$ may be any integer
In this context, are there any consistent, universal shortcuts for predicting whether $y$ will be negative or positive (or undefined for other reasons)?
I've been researching x-intercepts, but I'm not sure where I need to go with this.
I think it boils down to whether $mx^p\gt-b$, but I need to make sure there aren't any nuances with the way $m$, $x$, $p$, and $b$ interact on the whole.
If I can predict certain details of $y$ based on properties (or ranges) of $x$ (and/or $p$ etc.), without having to actually compute the entire function, that would be a huge benefit for optimization purposes, given the algorithms we are using.
I really need to avoid computing the exponent in particular.

A: $d$ has no effect on the sign of $y$, as long as it is not equal to $0$ (and if it is, you have bigger problems anyway).
The value of $y$ will be positive if and only if $mx^p + b>0$ which is true if and only if $$mx^p>-b,$$ as you correctly observed.

Now, if $m>0$, this means that $y$ is positive if and only if $$x^p>-\frac bm.$$
If $b$ is also positive, then this is always true (since $x\geq 0$), and if $b$ is negative, then $-b=|b|$, and then $y$ is positive if $x>\sqrt[p]{\frac{|b|}{m}}$

If $m<0$, then the $>$ sign flips when you divide by $m$ and you get that $y$ is positive iff $$x^p<-\frac bm$$
This has no solution if $b<0$ and has a solution similar to the one above if $b>0$.


text:
Q: Not a JSON Object i have data from server like this :
{
    "error": false,
    "alerts": {
        "code": "200",
        "message": "retrieve success"
    },
    "data": [{
        "incident__task_i_d": "8d37a3f1-d257-4833-9701-4eab0e48076f",
        "address": "Pulo Jahe Motor",
        "task_status": "Completed",
        "incident_i_d": "83eeed0f-4ea4-416b-8721-637e40ac9f72",
        "vehicle_i_d": "36420155-6214-4745-bbf3-7dae7d50ce9c",
        "agent_i_d": "1c3436fd-9338-4910-9686-8c1cd0a33433",
        "dispatched_time": "2016-08-12T08:29:47.89",
        "origin_latitude": "-6.8979664",
        "origin_longitude": "107.6135752",
        "destination_latitude": "-6.198816382772501",
        "destination_longitude": "106.921986633551",
        "created_dt": "2016-08-12T08:29:47.89",
        "departed_time": "2016-08-12T10:13:20.947",
        "arrival_time": "2016-08-12T10:11:14.93",
        "kick_off_time": "2016-08-12T10:13:54.54",
        "finished_time": "2016-08-12T10:14:30.893",
        "incident_reported_dt": "2016-08-11T08:21:34.23"
    }]
}

But i want to get value from array of object .. like i want to get value from incident__task_i_d so how can i get ?
i have a some code like this :
try
            {
                rawContent = new String(content);
                Log.i("TAG", "ALL DATA "+rawContent);

                JsonObject json = new JsonParser().parse(rawContent).getAsJsonObject();
                Gson gson = new GsonBuilder().setDateFormat(ModelRekap.DATE_FORMAT).create();

                Log.i("haha","masuk list ini");
                JsonArray jaray = json.getAsJsonArray("data");

                listInfoAnda  = new ArrayList<>();
                for (int i = 0; i < jaray.size(); i++) {
                    Log.i("TAG", "ARRAY " + i);
                    try {
                        JsonElement address = ((JsonObject)jaray.get(i)).get("address");
                        Log.i("ISI rekap address", "" + address.toString());
                        ModelRekap mCoba = gson.fromJson(jaray.get(i), ModelRekap.class);

                        listInfoAnda.add(mCoba);
                        Log.i("TAG","MODEL" + mCoba.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                onFinishRequest(true, rawContent);
            }
            catch(Exception e)
            {
                e.printStackTrace();
                onFinishRequest(false, rawContent);
            }
        }

But doesn't work correctly , i have some error like this :
08-12 22:31:03.926 6111-6111/com.example.fania.cobalagi W/System.err: java.lang.IllegalStateException: Not a JSON Object: [{"incident__task_i_d":"8d37a3f1-d257-4833-9701-4eab0e48076f","address":"Pulo Jahe Motor","task_status":"Completed","incident_i_d":"83eeed0f-4ea4-416b-8721-637e40ac9f72","vehicle_i_d":"36420155-6214-4745-bbf3-7dae7d50ce9c","agent_i_d":"1c3436fd-9338-4910-9686-8c1cd0a33433","dispatched_time":"2016-08-12T08:29:47.89","origin_latitude":"-6.8979664","origin_longitude":"107.6135752","destination_latitude":"-6.198816382772501","destination_longitude":"106.921986633551","created_dt":"2016-08-12T08:29:47.89","departed_time":"2016-08-12T10:13:20.947","arrival_time":"2016-08-12T10:11:14.93","kick_off_time":"2016-08-12T10:13:54.54","finished_time":"2016-08-12T10:14:30.893","incident_reported_dt":"2016-08-11T08:21:34.23"}]
08-12 22:31:03.931 6111-6111/com.example.fania.cobalagi W/System.err:     at com.google.gson.JsonElement.getAsJsonObject(JsonElement.java:90)
08-12 22:31:03.931 6111-6111/com.example.fania.cobalagi W/System.err:     at com.example.fania.cobalagi.api.ApiRekapData$1.onSuccess(ApiRekapData.java:100)
08-12 22:31:03.931 6111-6111/com.example.fania.cobalagi W/System.err:     at com.radyalabs.async.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:264)
08-12 22:31:03.931 6111-6111/com.example.fania.cobalagi W/System.err:     at com.radyalabs.async.AsyncHttpResponseHandler$ResponderHandler.handleMessage(AsyncHttpResponseHandler.java:134)
08-12 22:31:03.931 6111-6111/com.example.fania.cobalagi W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
08-12 22:31:03.931 6111-6111/com.example.fania.cobalagi W/System.err:     at android.os.Looper.loop(Looper.java:146)
08-12 22:31:03.931 6111-6111/com.example.fania.cobalagi W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5593)
08-12 22:31:03.931 6111-6111/com.example.fania.cobalagi W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
08-12 22:31:03.931 6111-6111/com.example.fania.cobalagi W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
08-12 22:31:03.931 6111-6111/com.example.fania.cobalagi W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
08-12 22:31:03.931 6111-6111/com.example.fania.cobalagi W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
08-12 22:31:03.931 6111-6111/com.example.fania.cobalagi W/System.err:     at dalvik.system.NativeStart.main(Native Method)

I'm new in Android Programming.

A: i suggest to use this approach !! i hope this help you :)
    JsonParser jsonParser = new JsonParser();
    JsonObject data=jsonParser.parse(rawContent).getAsJsonObject().getAsJsonArray("data").get(0)
        .getAsJsonObject();

    String incident= data.get("incident__task_i_d").getAsString();

A: It is simple, you need to know path and index in advance to query json-data.
JSONObject response=new JSONObject(rawContent);
JSONArray data=response.getJSONArray("data");
String incident=data.getJSONObject(0).getString("incident__task_i_d");


text:
Q: Nginx Static File Cache giving 404s I've tried a ton of different stuff to make it work and looked at a bunch of previous Nginx configuration guides, but my site keeps giving me 404 not founds for all of my static content. Below is my configuration.
server {
    listen 80 default_server;
    listen [::]:80 default_server;
   server_name mywebsite.com www.mywebsite.com;
    return 301 https://$server_name$request_uri;
}
proxy_cache_path /tmp/nginx levels=1:2 keys_zone=my_zone:10m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";

server {
        access_log off;
        listen 443 ssl http2 default_server;
        listen [::]:443 ssl http2 default_server;
        include snippets/ssl-mywebsite.com.conf;
        include snippets/ssl-params.conf;

        location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
                expires 30d;
                add_header Vary Accept-Encoding;
                access_log off;
        }

        # Pass requests for / to localhost:3000:
        location / {
                proxy_cache my_zone;
                proxy_cache_bypass  $http_cache_control;
                add_header X-Proxy-Cache $upstream_cache_status;
                include proxy_params;

                proxy_ignore_headers X-Accel-Expires Expires Cache-Control;
                proxy_ignore_headers Set-Cookie;
                proxy_hide_header Set-Cookie;
                proxy_hide_header X-powered-by;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-NginX-Proxy true;
                proxy_pass http://localhost:3000;
                proxy_ssl_session_reuse off;
                proxy_set_header Host $http_host;
                proxy_redirect off;
        }
}

For more background, my static files are all stored in a public folder, so like: /www/Project/public/css/styles.css or /www/Project/public/images/myimage.jpg
The site works if I take away the location ~* .(?:ico|css|js|gif ... ) but then it's not caching.
Does anyone have an idea as to what's going on?

A: Figured it out.
Turns out, my root path was wrong - I did it relative to my project directory (where my app.js file was) when it should've been relative to my absolute root directory on my file system.
E.g. it should've been /home/mycomputerlogin/www/project/public/
so in my ~* .
the first line was
root /home/mycomputerlogin/www/project/public;
It worked fine after that.


text:
Q: How to simplify the derivative of this expression I have the following function
$$f=\text{Tr(A}^T\text{SA}),$$
where $A$ is a matrix, $S$ is given by
$$S_{ij} = \exp(-\frac{(x_i-x_j)^2}{2\sigma^2})$$

Here is my attempt to calculate the derivative of $f$ w.r.t $X$
We have
$$\begin{align*}
f &= \text{Tr}(AA^TS) \\
  &= AA^T:S \\
\implies df &=AA^T:dS \\
  &= AA^T:(\frac{-1}{2\sigma^2})S\odot dS \\
  &= (\frac{-1}{2\sigma^2}) AA^T:S\odot d(diag(X^TX)1^T + 1(diag(X^TX))^T - 2X^TX) \\
  &= (\frac{-1}{2\sigma^2}) AA^T:S\odot (diag(2X^TdX)1^T + 1(diag(2X^TdX))^T - 2X^TdX) \\
  &= (\frac{-1}{2\sigma^2})(S\odot AA^T): (diag(2X^TdX)1^T + 1(diag(2X^TdX))^T - 2X^TdX) \\
  &= (\frac{-1}{2\sigma^2})[-2X(S\odot AA^T):dX + (S\odot AA^T):(diag(2X^TdX)1^T + 1(diag(2X^TdX))^T)] \\
\end{align*}$$
I am stuck with the two terms involving the diag operator,
Could anyone help me to simplify these terms and obtain the final expression of $\frac{df}{dX}$?
Best regards,


text:
Q: Segmentation fault in input handler function Every time I move the joystick I get a segfault. I think it is something to do with std::vector> m_joystickValues; is that true, ahould there be garbage collection with this, if it's wrong in the book what do I replace it with, is it because some of the functions in Vector2d.h are const and some of the values are changing? Is this a memory leak? what do I need to change?
Gdb Output:
Thread 1 "a.out" received signal SIGSEGV, Segmentation fault.
0x0000555555557bb3 in InputHandler::update (this=0x555556fae710)
    at InputHandler.cpp:81
81              m_joystickValues[whichOne].first->setX(0);
(gdb) frame 81
#0  0x0000000000000000 in ?? ()
(gdb) bt
#0  0x0000555555557bb3 in InputHandler::update (this=0x555556fae710)
    at InputHandler.cpp:81
#1  0x0000555555556851 in Game::handleEvents (this=0x5555557732b0)
    at Game.cpp:107
#2  0x000055555555980f in main (argc=1, argv=0x7fffffffded8) at main.cpp:35

(gdb) frame 0
#0  0x0000555555557bb3 in InputHandler::update (this=0x555556fae710)
    at InputHandler.cpp:81
81              m_joystickValues[whichOne].first->setX(0);

(gdb) frame 1
#1  0x0000555555556851 in Game::handleEvents (this=0x5555557732b0)
    at Game.cpp:107
107     TheInputHandler::Instance()->update();

(gdb) frame 2
#2  0x000055555555980f in main (argc=1, argv=0x7fffffffded8) at main.cpp:35
35          TheGame::Instance()->handleEvents();

(gdb) where
#0  0x0000555555557bb3 in InputHandler::update (this=0x555556fae710)
    at InputHandler.cpp:81
#1  0x0000555555556851 in Game::handleEvents (this=0x5555557732b0)
    at Game.cpp:107
#2  0x000055555555980f in main (argc=1, argv=0x7fffffffded8) at main.cpp:35

main.cpp
// the basic functions of a game engine

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "Enemy.h"
#include "Game.h"
#include "GameObject.h"
#include "InputHandler.h"
#include "Player.h"
#include "LoaderParams.h"
#include "TextureManager.h"
#include "SDLGameObject.h"
#include "Vector2d.h"

//our game object

Game* g_game = 0;

const int FPS = 60;
const int DELAY_TIME = 1000.0f / FPS;

int main(int argc, char* argv[])
{
    Uint32 frameStart, frameTime;

    std::cout <<"game init attempt";
    if(TheGame::Instance()->init("Chapter 1", 100, 100, 640, 480,
    false))
    {
        frameStart = SDL_GetTicks();

         std::cout <<"game init success!\n";
        while(TheGame::Instance()->running())
        {
        TheGame::Instance()->handleEvents();
        TheGame::Instance()->update();
        TheGame::Instance()->render();

        frameTime = SDL_GetTicks() - frameStart;

        if(frameTime< DELAY_TIME)
        {
            SDL_Delay((int) (DELAY_TIME - frameTime));
        }
    }
}
    else
    {
        std::cout<<"game init failure - " << SDL_GetError() << "\n";
        return -1;
    }
    std::cout<<"game closing";
    TheGame::Instance()->clean();

    return 0;
}

InputHandler.h
#ifndef __InputHandler__
#define __InputHandler__

#include <iostream>
#include <vector>
#include <utility>
#include <SDL2/SDL.h>
#include "Game.h"
#include "Vector2d.h"

class InputHandler
{
    public:

     static InputHandler* Instance()
     {
         if(s_pInstance == 0)
        {
            s_pInstance = new InputHandler();
        }
        return s_pInstance;
    }

    void update();
    void clean();

    void initialiseJoysticks();
    bool joysticksInitialised() {
         return m_bjoysticksInitialised; }

        int xvalue(int joy, int stick);
        int yvalue(int joy, int stick);

    private:

    InputHandler() {}

    static InputHandler* s_pInstance;

    const int m_joystickDeadZone = 1000;

     std::vector<SDL_Joystick*> m_joysticks;

     std::vector<std::pair<Vector2d*, Vector2d*>> m_joystickValues;

     bool m_bjoysticksInitialised;

};

 typedef InputHandler TheInputHandler;

 #endif /*defined (InputHandler) */

InputHandler.cpp
#include "InputHandler.h"

InputHandler* InputHandler::s_pInstance= 0;

void InputHandler::initialiseJoysticks()
{

     if(SDL_WasInit(SDL_INIT_JOYSTICK) == 0)
     {
        SDL_InitSubSystem(SDL_INIT_JOYSTICK);
     }

         if(SDL_NumJoysticks() > 0)
         {
            for(int i = 0; i < SDL_NumJoysticks(); i++)
            {
             SDL_Joystick* joy = SDL_JoystickOpen(i);
                 if(SDL_JoystickOpen(i) == 1)
                 {
                     m_joysticks.push_back(joy);
                     m_joystickValues.push_back(std::make_pair(new
                     Vector2d(0,0),new Vector2d(0,0))); //add our pair
                 }
                else
                {
                     std::cout << SDL_GetError();
                 }
             }

         SDL_JoystickEventState(SDL_ENABLE);
         m_bjoysticksInitialised = true;

        std::cout<< "Initialised " << m_joysticks.size() <<
        "joystick(s)";
         }
              else
            {
                 m_bjoysticksInitialised = false;
            }
}

void InputHandler::clean()
{
     if(m_bjoysticksInitialised)
     {
        for(unsigned int i = 0; i < SDL_NumJoysticks(); i++)
        {
             SDL_JoystickClose(m_joysticks[i]);
        }
    }
}

 void InputHandler::update()
 {
     SDL_Event event;
     while(SDL_PollEvent(&event))
     {
          if(event.type == SDL_QUIT)
         {
             TheGame::Instance()->quit();
         }
     if(event.type == SDL_JOYAXISMOTION)
     {
         int whichOne = event.jaxis.which;

         //left stick move left or right
         if(event.jaxis.axis == 0)
         {
             if(event.jaxis.value > m_joystickDeadZone)
             {
                 m_joystickValues[whichOne].first->setX(1);
             }
         else if(event.jaxis.value < -m_joystickDeadZone)
         {
               m_joystickValues[whichOne].first->setX(-1);
         }
         else
         {
             m_joystickValues[whichOne].first->setX(0);
         }

 }

// left stick move up or down
if(event.jaxis.axis == 1)
{
     if(event.jaxis.value > m_joystickDeadZone)
     {
         m_joystickValues[whichOne].first->setY(1);
     }
     else if(event.jaxis.value < -m_joystickDeadZone)
     {
         m_joystickValues[whichOne].first->setY(-1);
     }
     else
    {
         m_joystickValues[whichOne].first->setY(0);
    }
}

//right stick move left or right
if(event.jaxis.axis == 3)
 {
     if(event.jaxis.value > m_joystickDeadZone)
     {
         m_joystickValues[whichOne].second->setX(1);
     }
     else if(event.jaxis.value < -m_joystickDeadZone)
    {
         m_joystickValues[whichOne].second->setX(-1);
    }
    else
     {
         m_joystickValues[whichOne].second->setX(0);
     }
 }

  //right stick move up or down
 if(event.jaxis.axis == 4)
 {
     if(event.jaxis.value > m_joystickDeadZone)
      {
        m_joystickValues[whichOne].second->setY(1);
    }
      else if(event.jaxis.value < -m_joystickDeadZone)
     {
        m_joystickValues[whichOne].second->setY(-1);
    }
     else
     {
    ``m_joystickValues[whichOne].second->setY(0);
    }
}
}
 }
}

int InputHandler::xvalue(int joy, int stick)
 {
     if(m_joystickValues.size() > 0)
     {
         if(stick == 1)
         {
            return m_joystickValues[joy].first->getX();
         }
         else if(stick == 2)
            {
                 return m_joystickValues[joy].second->getX();
            }
    }
     return 0;
}

 int InputHandler::yvalue(int joy, int stick)
 {
     if(m_joystickValues.size() > 0)
     {
        if(stick == 1)
         {
             return m_joystickValues[joy].first->getY();
        }
         else if(stick == 2)
         {
              return m_joystickValues[joy].second->getY();
         }
     }
     return 0;
 }

Vector2d.h
#ifndef __Vector2d__
#define __Vector2d__

#include <math.h>
#include <iostream>
#include <vector>
#include <utility>

class Vector2d
{
    public:
    Vector2d(float x, float y) : m_x(x), m_y(y) {}

     float getX() { return m_x; }
     float getY() { return m_y; }

    void setX(float x) { m_x = x; }
    void setY(float y) { m_y = y; }

     float length() { return sqrt(m_x * m_x + m_y * m_y) ; }

    Vector2d operator+ (const Vector2d& v2) const
    {
    return Vector2d (m_x + v2.m_x, m_y + v2.m_y);
    }

    friend Vector2d& operator +=(Vector2d& v1, const Vector2d& v2)
    {
        v1.m_x += v2.m_x;
        v1.m_y += v2.m_y;

        return v1;
    }

     Vector2d operator* (float scalar)
     {
         return Vector2d(m_x * scalar, m_y * scalar);
     }

     Vector2d& operator*= (float scalar)
     {
         m_x *= scalar;
         m_y *= scalar;

        return *this;
    }

     Vector2d operator- (const Vector2d& v2) const
    {
         return Vector2d(m_x - v2.m_x, m_y - v2.m_y);
    }

    friend Vector2d& operator-=(Vector2d& v1, const Vector2d& v2)
    {
        v1.m_x -= v2.m_x;
        v1.m_y -= v2.m_y;

        return v1;

    }

     Vector2d operator/(float scalar)
    {
         return Vector2d(m_x / scalar, m_y / scalar);
    }

    Vector2d& operator/=(float scalar)
     {
         m_x /= scalar;
         m_y /= scalar;

        return *this;
     }

    void normalize()
     {
         float l = length();
         if ( l > 0 )
         {
            (*this) *= l/1;
         }
     }

     private:

    float m_x;
    float m_y;
 };

 #endif /*defined (Vector2D) */

A: the function SDL_Joystick* SDL_JoystickOpen(int device_index) returns a pointer to SDL_Joystick* so you probably need to replace the line if(SDL_JoystickOpen(i) == 1) in the input_handler.cpp by if(SDL_JoystickOpen(i)) or just if(joy)


text:
Q: solr group functions for processing the secondly present group value I'm using solr 4.3.0 and I'm using group functions for getting the desired item details. My requirement is to get the second minimum value from each group. I tried using group.truncate function where I'm able to apply it only for the first value from each group. Can anyone help me out to solve this?

A: You'll have to use group.sort or sort to order the documents inside each group (fieldname asc), and then return at least two documents in each group (group.limit=2). The second lowest value will be the second document in each group.


text:
Q: Как работает OAuth2? Как я понимаю механиз работы OAuth2:
Есть:
а) браузер клиента
б) Сервер ресурсов
в) Авторизационный сервер (например facebook)

1.1 Браузер обращается на resource-server, тот отдаёт ответ 401.
2.1 Пользователь руками вводит логин/пароль от auth-сервера, браузер идет на auth-server, отправляя ему post-ом введённые логин/пароль.
2.2 Auth-server отдаёт браузеру некий token, который будет подтверждением что браузер залогинился на auth-сервере.
3.1 Браузер идет на auth-server, отправляя ему полученный ранее token, а так же cliend_id - id приложения-сервера-ресурсов, к которому хочет получить доступ.
3.2 Auth-сервер отдаёт браузеру code.
4.1 Браузер идет на resource-server, передавая ему code.
4.2 Resource-server получает code и идет с ним на auth-server, тот генерирует access_token и refresh_token, отдаёт их resource-серверу.
4.3 Resource-server передаёт полученные access_token и refresh_token браузеру.
5.1 Браузер идет на resource-server, передавая ему access_token,
5.2 Resource-server удостоверяется в валидности access-токена, отправляя его на auth-server
5.3 Получив ответ от auth-сервера о том что access_token валидный, отдаёт в браузер запрашиваемый ресурс.
Получается, access_token браузер получает не от auth-сервера, а от resource-сервера

*

*Правильно ли я понимаю схему взаимодействия между клиентом-браузером, сервером ресурсов и auth-сервером?

В таком случае, если имеется еще один resource-сервер, который авторизуется через тот же самый auth-server, то браузер клиента обращаясь на него без auth-токена, получит ответ 401. Потом браузер предложит пользователю ввести логин/пароль от auth-сервера, и далее те же самые действия.

*Если это так, то данная схема не избавляет пользователя от повторного ввода логина/пароля для каждого нового приложения, несмотря на то что все они используют один и тот же auth-сервер?

3. Каким образом проверяется не просто аутентификация, но и авторизация пользователя? Т.е. где мы проверяем роли пользователя?


text:
Q: Material UI theme.palette.type typescript error I'm a beginner at Material UI and TypeScript.
ps: I apologize if I have incorrectly formatted the question, the first question on stackoverflow.

A: type only accepts the literal strings 'light' and 'dark'. That is different to the general string type.
The initial value you provide to useState is a literal type, but Typescript widens the return type of function expressions. In other words, mode is of type string.
useState is a generic function and you can pass in the types to prevent the type widening
const [mode, setMode] = useState<'light' | 'dark'>('dark')


text:
Q: Why can't I call a template base class constructor with a const_iterator? For some reason, the following code gives the error Symbol 'TemplateBase' could not be resolved.:
template <typename T>
class TemplateBase
{
    TemplateBase(std::map<std::string, T>::const_iterator anIterator)
    { }
};

class SubClass : public TemplateBase<int>
{
    SubClass(std::map<std::string, int>::const_iterator anIterator) :
        TemplateBase<int>(anIterator) //Error: Symbol 'TemplateBase' could not be resolved.
    { }
};

Strangely, no error appears when I remove the ::const_iterator and only std::map<std::string, int> remains:
template <typename T>
class TemplateBase
{
    TemplateBase(std::map<std::string, T> aMap)
    { }
};

class SubClass : public TemplateBase<int>
{
    SubClass(std::map<std::string, int> aMap) :
        TemplateBase<int>(aMap) //No error.
    { }
};

Additionally, the following function gives no error either, so it really seems related to the combination of a template base class call with a const_iterator:
void function()
{
    std::map<std::string, int>::const_iterator anIterator;
    TemplateBase<int> aTemplateBase(anIterator); //No error
}

Is there some rule against using const_iterator as an argument for base class template constructors that I'm unaware of? Or is this a compiler bug?
I'm compiling with MinGW 64bit 4.9.0 on Windows 7, using C++11.

A: When you use a nested type that depends on a template type you need to use the typename keyword:
TemplateBase(typename std::map<std::string, T>::const_iterator anIterator)
{ }


text:
Q: Spaces are disappearing after I key in word in my edittext My problem is, I want to search "curry house", let say I insert "curry house". The space will disappear the result. but if I search the result which is without space it work perfectly.
MainActivity.java
ADAhere = new SimpleAdapter(getActivity(), data, R.layout.mainproductitem, new String[]{"CategoryName"}, new int[]{R.id.mainproductitem});
mainlistproduct.setAdapter(new PrimaryFragment().ADAhere);

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text
            mainlistproduct.setTextFilterEnabled(true);
            mainlistproduct.setFilterText(cs.toString().trim());

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            if(arg0.length()==0){
                mainlistproduct.clearTextFilter();
            }

        }
    });

A: mainlistproduct.setFilterText(cs.toString().trim());
Every time you type something you automatically trim spaces at the beginning and end.
So..
curr -> curr
curry -> curry
curry[space] -> curry[no_space]
curry h -> curryh

A: Trim the search string,then replace the space from the string,then search the string.
 @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3)     {
            // When user changed the Text
          String  input = cs.toString().trim();
          input = input.replace(" ", "");
          mainlistproduct.setFilterText(input);

        }

A: remove trim() from onTextChanged(). Just use  mainlistproduct.setFilterText(cs.toString());

A: I have modified your code, try this
        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text
            mainlistproduct.setTextFilterEnabled(true);
            mainlistproduct.setFilterText(cs.toString());

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
            if(arg0.length()==0){
                mainlistproduct.clearTextFilter();
            }

        }
    });


text:
Q: Error upload file using Mediawiki::API I'm trying to upload an image to the mediawiki using the Mediawiki::API->upload. To do so, i'm using this code:
use strict;
use MediaWiki::API;
use DateTime::Format::ISO8601;
use encoding 'utf8';
binmode STDERR, ":utf8";
use URI::Escape;
use warnings;
use MediaWiki::API;

 my $url="http://localhost/mediawiki";
 my $wiki_login="nguyenki";
 my $wiki_passwd="linh";
 my $wiki_domain="";
 chomp($wiki_login);
 chomp($wiki_passwd);
 chomp($wiki_domain);
 my $mediawiki;
 mw_connect_maybe();
 # configure the special upload location.
 $mediawiki->{config}->{upload_url} = "$url/index.php/Special:Upload";

 my $name="fl.png"; # Name of fichier to upload

  # upload a file to MediaWiki
  open (my $toi, $name) or die "can't open UTF-8 encoded filename: $!";
  binmode $toi;
  my ($buffer, $data);
  while (my $n=read($toi, $buffer, 65536) )  {
    $data .= $buffer;
    print STDERR "$n bytes read\n";
  }
  close($toi);

  $mediawiki->upload( { title => $name,
                 summary => 'This is the summary to go on the Image:file.jpg page',
                 data => $data } ) || die $mediawiki->{error}->{code} . ': ' . $mediawiki->{error}->{details};

#To login to the wiki page
sub mw_connect_maybe {

    if ($mediawiki) {
        return;
    }
    $mediawiki = MediaWiki::API->new;
    $mediawiki->{config}->{api_url} = "$url/api.php";

    if ($wiki_login) {
        if (!$mediawiki->login({
            lgname => $wiki_login,
            lgpassword => $wiki_passwd,
            lgdomain => $wiki_domain,
        })) {
            print STDERR "Failed to log in mediawiki user \"$wiki_login\" on $url\n";
            print STDERR "(error " .
                $mediawiki->{error}->{code} . ': ' .
                $mediawiki->{error}->{details} . ")\n";
            exit 1;
        } else {
            print STDERR "Logged in with user \"$wiki_login\".\n";
        }
    }
}

And it generated an error:
    HTTP::Message content must be bytes at /usr/share/perl5/HTTP/Request/Common.pm line 91
I don't know how to correct it.
Any suggestion?
Thank.

A: The pragma encoding breaks your code, remove it.

*

*Perl's use encoding pragma breaking UTF strings

*Why do my Perl tests fail with `use encoding 'utf8'`?

*Enabling non-ASCII characters in Perl

A: Mediawiki::API has a bug. well, probably a few bugs, but at least this one (or that one?): it hasn't been ported to the 1.22+ CSRF protection login system. To login to a MediaWiki site now, you need to do it in two steps: first get a token, then use that token to login. This is to protect poor web browser users, but unfortunately that means more pain for us bot writers.
The MediaWiki::Bot project suffered from the same issue, and solved it with this commit, which is a great example of how to fix your code. I was able to build a simple working login script bypassing the builtin MediaWiki::API login mechanism with this:
#!/usr/bin/perl -w

use MediaWiki::API;

my $wiki = MediaWiki::API->new;
my $remote_url = 'http://localhost:1234/wiki';
my $username = 'WikiAdmin';
my $password = 'AdminPass';
my $wiki_domain = 'localhost';

$wiki->{config}->{api_url} = "${remote_url}/api.php";

print "getting a CSRF token\n";
my $query = {action => 'query',
             meta => 'tokens',
             type => 'login'};
my $ref = $wiki->api( $query );
my $token;
if ($ref) {
    $token = $ref->{query}->{tokens}->{logintoken};
} else {
    print 'failed: (error ' . $wiki->{error}->{code} . ': ' .
                    $wiki->{error}->{details} . ")\n";
}

$query = {action => 'login',
          lgtoken => $token,
          lgname => $username,
          lgpassword => $password,
          lgdomain => $wiki_domain,
};
$ref = $wiki->api( $query );
if ($ref && $ref->{login}->{result} eq "Success") {
    print "login worked\n";
} else {
    print 'failed: (error ' . $wiki->{error}->{code} . ': ' .
                    $wiki->{error}->{details} . ")\n";
}

Obviously, this should be patched upstream, but hopefully it should get you going.


text:
Q: Android Development Image Upload Corrupted I'm developing an Android application and I'm trying to upload an image to our server from the client side. When I get onto the server to view the image it is corrupted (gray bar on bottom) sometimes. I'm not sure why this is happening. Can  anyone help me resolve this issue or point me to a guide on how to do this? Below is the code that uploads the image:
try {
    url = new URL(SERVER_URL);
    connection = (HttpURLConnection)url.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "image/jpeg");
    connection.setChunkedStreamingMode(STREAM_CHUNK_SIZE_KB * 1024);
    connection.connect();
    outputStream = new DataOutputStream(connection.getOutputStream());

    // Write file header (userId; Id; contentId; MediaType; size)
    outputStream.writeLong(mUserId);
    outputStream.writeLong(mId);
    outputStream.writeLong(file.getId());
    outputStream.writeUTF(MediaType.getMediaType(file.getMediaType()));
    outputStream.writeInt(file.getSize());

    // Write file data to stream
    int maxBufferSize = (8 * 1024);
    FileInputStream fileInputStream = new FileInputStream(file.getImageFile());
    int bytesAvailable = fileInputStream.available();
    int bufferSize = Math.min(bytesAvailable, maxBufferSize);
    byte[] buffer = new byte[bufferSize];
    int bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0) {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    outputStream.writeBytes("\r\n");
    outputStream.flush();

    // Check response
    int responseCode = connection.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        uploadStatus = true;
        InputStream responseStream = connection.getInputStream();
        BufferedReader responseReader = new BufferedReader(new
            InputStreamReader(responseStream));
        char[] response = new char[4];
        responseReader.read(response, 0, 4);
        responseReader.close();
        int responseValue = 0;
        for (int b = 0; b < 4; b++) {
            responseValue |= response[b] & 0xFF;
            if (b < 3) {
                responseValue <<= 8;
            }
        }

        switch (responseValue) {
            case SAVED_SUCCESSFULLY:
                Log.d("FileUploader::upload -> Server response: Upload successful");
            break;
            case ERROR_SAVING_FILE:
                Log.d("FileUploader::upload -> Server response: Upload failed");
            break;
            case FILE_MORE_THAN_ALLOWED_SIZE:
                Log.d("FileUploader::upload -> Server response: Upload failed, exceeded
                    allowed file size");
            break;
        }
    }

    else {
        Log.d("FileUploader::upload -> responseCode = " + responseCode);
        checkErrorStream(connection.getErrorStream());
    }
}

catch(Exception e) {
    Log.e(Log.getStackTraceString(e));
}

finally {
    try {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    catch(Exception e) {
        Log.e(Log.getStackTraceString(e));
    }

    if (connection != null) {
        connection.disconnect();
    }
}

A: Please try to take image from divece via USB not via network. Would that image be OK or it would be broken too?

A: I can't easily tell you why the image is corrupted without building a test app and running your code, but I can give you a hint:
Save the original image to a file. Grab the image that was transfered over the network. Open up both of them in a hex editor, and then look at what the difference is. (Which is presumably near the end of the file.)
This should tell you what the actual corruption consists of, which in turn will tell you what to look for in your code.
(For example, you could be truncating your file, or appending a newline that shouldn't be there, or any number of subtle errors.)

A: You may have an error in your code:
outputStream.write(buffer, 0, bufferSize);

should be
outputStream.write(buffer, 0, bytesRead);


text:
Q: How do I check if form has error in Python? (selenium) https://imgur.com/rYusFAw
Here is my action,
create an account but empty the first name field, The red box prompt for the empty field.
<label for="first_name" ng-class="{'form-error':regForm.first_name.$error.required && showRegError}"> First Name </label>
<input name="first_name" id="first_name" type="text" maxlength="50" ng-model="reg.first_name" required="" ng-class="{'form-error':regForm.first_name.$error.required && showRegError}" class="ng-pristine ng-invalid ng-invalid-required">

After red box prompt shows.
<label for="first_name" ng-class="{'form-error':regForm.first_name.$error.required && showRegError}" class="form-error"> First Name </label>
<input name="first_name" id="first_name" type="text" maxlength="50" ng-model="reg.first_name" required="" ng-class="{'form-error':regForm.first_name.$error.required && showRegError}" class="ng-pristine ng-invalid ng-invalid-required form-error">

How do I check if the red box prompt is present?
and sorry English is not my native language, the sentence may be incorrect.

A: I am using something along these lines:
prop = self.driver.find_element_by_xpath(element).value_of_css_property('border-top-color')
return prop == u'rgb(202, 202, 198)'

Basically, I am checking for the actual colour value of the border property. The property name and the colour value might vary in your case.


text:
Q: Github - File XYZ is 126.80 MB; this exceeds GitHub's file size limit of 100.00 MB I have a local repository that a large file was accidentally added to. Now im almost 100 commits behind. When I try to push to GitHub it gives me an error.
I need help doing whatever I need to do to be able to push the rest of this repository.
I do not need this file and can delete it permanently
(Side Note: This is a directory with IPython nodes & code. I have a script auto pushing it which is why I'm almost 100 commits behind. I just noticed that it wasn't sync'd)
Here's what I've tried without success:
git status

On branch master
  Your branch is ahead of 'origin/master' by 100 commits.
        (use "git push" to publish your local commits)
  nothing to commit, working directory clean

git filter-branch --index-filter 'git rm --cached --ignore-unmatch "Education/Coursera/Exploratory Data Analysis/Week1/household_power_consumption.txt"' --tag-name-filter cat -- --all

Rewrite d381c7d5037a6a26abb2b5cef06e57d8b86a398b (95/189)rm 'Education/Coursera/Exploratory Data Analysis/Week1/household_power_consumption.txt'
  ..
  Rewrite f639b57714a5d57ff37b9d4a55c1c69fc0b514a8 (176/189)rm 'Education/Coursera/Exploratory Data Analysis/Week1/household_power_consumption.txt'
  Rewrite 587c8b65f19315ebeb6627a75bd703a5dbdec208 (189/189)
Ref 'refs/heads/master' was rewritten
  WARNING: Ref 'refs/remotes/origin/master' is unchanged

git rm "Education/Coursera/Exploratory Data Analysis/Week1/household_power_consumption.txt"

fatal: pathspec 'Education/Coursera/Exploratory Data Analysis/Week1/household_power_consumption.txt' did not match any files

git push

warning: push.default is unset; its implicit value is changing in Git 2.0 from 'matching' to 'simple'. To squelch this message and maintain the current behavior after the default changes, use:
git config --global push.default matching
To squelch this message and adopt the new behavior now, use:
git config --global push.default simple
When push.default is set to 'matching', git will push local branches to the remote branches that already exist with the same name.
In Git 2.0, Git will default to the more conservative 'simple' behavior, which only pushes the current branch to the corresponding remote branch that 'git pull' uses to update the current branch.
See 'git help config' and search for 'push.default' for further information.
  (the 'simple' mode was introduced in Git 1.7.11. Use the similar mode   'current' instead of 'simple' if you sometimes use older versions of Git)
Counting objects: 841, done.
  Delta compression using up to 2 threads.
  Compressing objects: 100% (578/578), done.
  Writing objects: 100% (835/835), 31.79 MiB | 3.14 MiB/s, done.
  Total 835 (delta 196), reused 0 (delta 0)
remote: warning: File .git-rewrite/t/Education/Coursera/Exploratory Data Analysis/Week1/household_power_consumption.txt is 74.92 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
  remote: warning: File .git-rewrite/t/Education/Coursera/Exploratory Data Analysis/Week1/household_power_consumption.txt is 69.38 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: error: GH001: Large files detected.
  remote: error: Trace: f013f5e75b4f35d07de5d2d9ef1116bd
  remote: error: See http://git.io/iEPt8g for more information.
  remote: error: File .git-rewrite/t/Education/Coursera/Exploratory Data Analysis/Week1/household_power_consumption.txt is 126.80 MB; this exceeds GitHub's file size limit of 100.00 MB
To git@github.com:rbohac/IPython-Notebooks.git
  ! [remote rejected] master -> master (pre-receive hook declined)
  error: failed to push some refs to 'git@github.com:rbohac/IPython-Notebooks.git'

A: I had trouble using bfg after installing with brew install bfg even though I usually have great success with homebrew.
This is what worked for me:

*

*Download the latest bfg from https://rtyley.github.io/bfg-repo-cleaner/#download

*Execute bfg like this, then enter the rest of the commands @davidcondrey recommends
cd /my/repo
java -jar ~/Downloads/bfg-1.12.5.jar --strip-blobs-bigger-than 99M
git rm --cached XYZ
git commit --amend -CHEAD
git push

A: Ensure that your latest commit is correct because BFG will assume this and use your latest commit to maintain the status of your repo while it rewrites and cleans the Git history. BFG is similar to 'git-filter-branch' but is a utility written for a more specific purpose whereas the git utility is broader with more functionality at the sacrifice of operating less efficiently.  Read the documentation on BFG for more specifics as I got all of this information from that source.
brew install bfg
bfg --strip-blobs-bigger-than 50M
git rm --cached XYZ
git commit --amend -CHEAD
git push

BFG will update your commits and all branches and tags so they are clean, but it doesn't physically delete anything. Examine the repo to make sure everything is correct and then clear cache and run 'git gc' to strip out the unwanted data which Git will now recognize because it has been removed from history.
Further:

*

*https://help.github.com/articles/removing-files-from-a-repository-s-history/

*https://rtyley.github.io/bfg-repo-cleaner/#usage

A: Another solution without using bfg, I have used this script remove-big-file.sh
developed by Bruno Grande.
Please read the script before executing, and understand each step
Brief explanation: it contemplates a local rebase, edit the commit where you included the large file (remove it from git not physically) and amend the commit and finally push (this would include any other commit done after you tried to fix it).
I had the same issue, my approach was the following: I deleted the file from git, and also updated my .gitignore and committed those changes and still faced the same error. After doing each step of the script (manually), it was solved, be aware that the push will include all the commits you've done locally.


text:
Q: Java "Unexpected return value" for int when returning an int I have this class being executed in another file and java is telling me
"Unexpected return value",

I've searched and searched and can't see what I'm doing wrong. I'm a massive Java Noob so any help will be appreciated.
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

public class PopUpBox {

    public static void display(String title, String message) {
        Stage window = new Stage();
        TextField textField = new TextField();

        //Block events to other windows
        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle(title);
        window.setMinWidth(250);

        //Make a label that closes the window
        Label label = new Label();
        label.setText(message);
        Button closeButton = new Button("Done");
        closeButton.setOnAction(e -> {
                    Integer test = Integer.parseInt(textField.getText());
                    //return test;
                    System.out.println(test.getClass());
                    window.close();
                }
            );

        VBox layout = new VBox(10);
        layout.getChildren().addAll(textField, closeButton);
        layout.setAlignment(Pos.CENTER);

        //Display window and wait for it to be closed before returning
        Scene scene = new Scene(layout);
        window.setScene(scene);
        window.showAndWait();
    }

}

A: Check the documentation of methods you're using:
ButtonBase.setOnAction has a single parameter of type EventHandler. (Button inherits setOnAction from ButtonBase).
EventHandler is an interface with a single method void handle(T event)
This is what your lambda expression is implementing. This is a void method so you cannot return a value of int from it.


text:
Q: Strange error returned from mciSendString - Can anyone help? A few months ago I added audio recording to a MFC app that I'm working on. This turned out to be easy enough and after an hour or two the code was working on my PC and on a couple of the customers test machines (one running XP the other Vista). Recently however one of their test machines was upgraded and now the recording feature refuses to work.
The basic code to start the recording is ..
mcierr=mciSendString("open new type waveaudio alias mysound",tmpstr,80,NULL);
mcierr=mciSendString("set mysound time format ms bitspersample 8 samplespersec 11025",tmpstr,80,NULL);
mcierr=mciSendString("record mysound",tmpstr,80,NULL);

which appears to work fine. To stop recording the following code is executed ..
mcierr=mciSendString("stop mysound",tmpstr,80,NULL);
mcierr=mciSendString("save mysound C:\\filename.wav",tmpstr,80,NULL);
mcierr=mciSendString("close mysound",tmpstr,80,NULL);

The following error occurs when the "save mysound C:\filename.wav" instruction is sent. The error returned is ..
MCI Error A parameter or value was specified twice.  Only specify it once.

But I can't see any error in what I am sending and that error doesn't make sense. Is it possible that the error is because the program is trying to record using a format the PC doesn't support ?
Thanks for your time
Ian

A: OK I managed to find a solution to this. This line in the code ..
mcierr=mciSendString("save mysound C:\\filename.wav",tmpstr,80,NULL);

works fine on my development PC running XP but causes errors on some test PC's running XP and on all of them running Vista. The error goes away however if the filename itself is put within quotes like this ..
mcierr=mciSendString("save mysound "C:\\filename.wav"",tmpstr,80,NULL);

Now the code runs fine on all the XP and Vista PC's it has been tested on.
Ian

A: A detail more is necessary to have it working.
Please watch the double "" before and after the file name:
mcierr=mciSendString("save mysound ""C:\\filename.wav""",tmpstr,80,NULL);

This is fine, too:
mcierr=mciSendString(@"save mysound ""C:\filename.wav""",tmpstr,80,NULL);

With these double quotation marks the code works on my Windows 7 now.


text:
Q: Converting date formats python - Unusual date formats - Extract %Y%M%D I have a large data set with a variety of Date information in the following formats:

*

*DAYS since Jan 1, 1900 - ex: 41213 -  I believe these are from Excel  http://www.kirix.com/stratablog/jd-edwards-date-conversions-cyyddd

*YYDayofyear - ex 2012265

I am familiar with python's time module, strptime() method, and strftime () method.  However, I am not sure what these date formats above are called on if there is a python module I can use to convert these unusual date formats.
Any idea how to get the %Y%M%D format from these unusual date formats without writing my own calculator?
Thanks.

A: You can try something like the following:
In [1]: import datetime

In [2]: s = '2012265'

In [3]: datetime.datetime.strptime(s, '%Y%j')
Out[3]: datetime.datetime(2012, 9, 21, 0, 0)

In [4]: d = '41213'

In [5]: datetime.date(1900, 1, 1) + datetime.timedelta(int(d))
Out[5]: datetime.date(2012, 11, 2)

The first one is the trickier one, but it uses the %j parameter to interpret the day of the year you provide (after a four-digit year, represented by %Y). The second one is simply the number of days since January 1, 1900.
This is the general conversion - not sure of your input format but hopefully this can be tweaked to suit it.

A: On the Excel integer to Python datetime bit:
Note that there are two Excel date systems (one 1-Jan-1900 based and another 1-Jan 1904 based); see https://support.microsoft.com/en-us/help/214330/differences-between-the-1900-and-the-1904-date-system-in-excel for more information.
Also note that the system is NOT zero-based.  So, in the 1900 system, 1-Jan-1900 is day 1 (not day 0).
import datetime

EXCEL_DATE_SYSTEM_PC=1900
EXCEL_DATE_SYSTEM_MAC=1904

i = 42129  # Excel number for 5-May-2015
d = datetime.date(EXCEL_DATE_SYSTEM_PC, 1, 1) + datetime.timedelta(i-2)

A: Both of these formats seems pretty straightforward to work with. The first one, in fact, is just an integer, so why don't you just do something like this?
import datetime

def days_since_jan_1_1900_to_datetime(d):
    return datetime.datetime(1900,1,1) + \
        datetime.timedelta(days=d)

For the second one, the details depend on exactly how the format is defined (e.g. can you always expect 3 digits after the year even when the number of days is less than 100, or is it possible that there are 2 or 1 – and if so, is the year always 4 digits?) but once you've got that part down it can be done very similarly.

A: According to http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
, day of the year is "%j", whereas the first case can be solved by toordinal() and fromordinal(): date.fromordinal(date(1900, 1, 1).toordinal() + x)

A: I'd think timedelta.
import datetime
d = datetime.timedelta(days=41213)
start = datetime.datetime(year=1900, month=1, day=1)
the_date = start + d

For the second one, you can 2012265[:4] to get the year and use the same method.
edit: See the answer with %j for the second.

A: from datetime import datetime

df(['timeelapsed'])=(pd.to_datetime(df['timeelapsed'], format='%H:%M:%S') - datetime(1900, 1, 1)).dt.total_seconds()


text:
Q: Mockito Matchers any Map How can I use any map in mockito? I tried with following codes
when(mockedService.patch("1", Matchers.<Map<String, Object>>any())).thenReturn(object);

and with:
when(mockedService.patch("1", anyMap())).thenReturn(object);

But it returns:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 1 recorded.

It works only when I put any(String.class):
when(mockedService.patch(any(String.class), Matchers.<Map<String, Object>>any())).thenReturn(object);

But I want to have option of puting actual values instead of any String

A: You can't mix matchers and non-matchers. Instead of "1", use Matchers.eq("1"). This creates a matcher that matches any string equal to "1", which satisfies both your needs (equal to "1") and Mockito's (both arguments are matchers).


text:
Q: Could we have an indicator if a flag is escalated to SE employees, along with the current status? It's well-known mods aren't almighty, and some problems require staff intervention. One of those cases is serial voting. Following a discussion here, could we have an indicator if a flag has been escalated, and the current status of it?
There's always going to be a backlog, but it'd still be nice to know the current status when it's been escalated, instead of hoping the flag resulted in escalation. As an example of when this is useful, I recently flagged some serial voting. The first reply said:

helpful - Same goes for upvotes. What can I do about getting a sudden flood of revenge downvotes?

But that doesn't tell me much. Was it escalated to Stack Exchange employees, or shrugged off as "the system will handle it"? Spoiler: It won't. Batches of three serial votes currently don't get reversed. That might be a separate problem on its own. I went ahead and flagged again for good measure, but I still don't know if it was escalated, and therefore if I need to flag again. I understand there's backlogs that need to be handled, but I personally want to know if it will be reviewed or not.
And just to be clear: I'm not asking about this specific flag. This is used as an example. With backlogs though, it would be nice to at least know if the flag has been escalated and will eventually be looked at, or if it'll take a few months and more votes before it gets reversed.
I'm not entirely sure what requires escalation, but I imagine there's other usage areas beyond serial voting. Not knowing the system, if there are such cases where the escalation status shouldn't be revealed, mods could be given an alternative to hide the escalation status, or alternatively, the status when the flag has been reviewed by an employee can be generic, with a simple Reviewed by employee.
Anyway, the general idea is that if a flag is escalated, it throws an additional status on the flag. Something along the lines of:

User comment – Username Aug 8 at 22:37  helpful - Optional moderator reply - Pending employee review

And

User comment – Username Aug 8 at 22:37  helpful - Optional moderator reply - Escalation marked as helpful/declined by employee

Would at least make it possible to tell that there's something going on with the flag, and removes the confusion of a helpful flag with no action taken.
The escalation status should naturally not affect the user's flagging stats in any way, so that won't be a change compared to today as far as I know.

Edit: I failed to think about implementation difficulty. That's on me. If the system I initially proposed is not worth "tripling the complexity of the flag system is worth the tiny number of cases it would affect.", could we at least have an indicator that it has been escalated? Leaving it to moderators to manually type out that it has been escalated first of all takes space (I'm assuming the flag replies have some length restriction as well), and it assumes moderators are able to remember it. Being a moderator on 0 sites, I have no idea how flags are escalated, but if there's a button, throwing in a notice it's been escalated (again, in a style similar to the helpful/declined part of the flag) wouldn't change anything for mods, but let end users get this type of information.
Additionally, if employees would end up never typing anything, how can you expect mods to consistently remember to leave a message when a flag has been escalated? I don't doubt that mods could actually do that, but this could be automated. Linking any of the features I've proposed to (presumably) standard buttons just adds an output with little effect on the process for mods or employees
For the sake of completeness though, I'd also like to suggest adding escalation to the FAQ (something along the lines of "Why was my flag escalated, and what does it imply?"), either here on main meta or in the help center, and link to it from the flag status. This is, again, mainly to avoid confusion when it takes a while for anything to happen for stuff like serial voting, or anything similar.

A: A flag currently has two states: pending or handled.1  At least on my sites, when mods get a flag that requires an employee to take a look, we usually leave the flag pending and contact the team.  If we were to reply, which we can only do by handling the flag, then we would have to send the team a link separately or reflag it internally.  That's more work for all involved.
As a moderator I don't want the ability to send status updates on pending flags.  If we had it for this case, then some users would ask for updates on every flag and that would get tedious and annoying.
Flags are not a good way to have a conversation.  Think of flags as fire-and-forget alerts.  If you think something requires employee attention, use the "contact us" link and submit a ticket that way.  If they need more information or want to give you an update, they can do that through their ticketing system.
1 Consider "aged away" to be one of the cases of "handled".  That's just the system handling a flag instead of mods.


text:
Q: FileHandler Java with Windows I am trying to write an Application which lists down the files from the server . Now I want to give users to open any file from the list (Windows) with any editor for example a text file and User opens with NotePad++.
Now is there anyway I can know that if user saves the file,if yes, then I would upload the file back to the server.

A: Use File#lastModified() to get the time at which the file was lastly modified.

A: There is a tutorial about Watching a Directory for Changes describing the WatchService which was introduced in Java 7. You can use this service to monitor files and directories:
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = ...;
try {
    WatchKey key = dir.register(watcher,
                           StandardWatchEventKinds.ENTRY_CREATE,
                           StandardWatchEventKinds.ENTRY_DELETE,
                           StandardWatchEventKinds.ENTRY_MODIFY);
} catch (IOException x) {
    System.err.println(x);
}


text:
Q: ¿Cómo pongo un label en tkinter que se actualize segun su texto cambie? Usando Python y tkinter.
Estoy haciendo un programa en el que necesito que cuando pulse un botón, este cambie el valor de una variable y que esa variable se actualice en un label.
Estoy haciendo un programa en el que necesito que cuando pulse un botón, este cambie el valor de una variable y que esa variable se actualice en un label.
Estoy haciendo un programa en el que necesito que cuando pulse un botón, este cambie el valor de una variable y que esa variable se actualice en un label.
He mirado a ver si con after() funcionaba, pero no.
Este es el código:
import tkinter as tk

wn = tk.Tk()
wn.geometry("500x500+735+200")
wn.resizable(0, 0)
wn.title("Program")
wn.iconbitmap("images/icon.ico")

state = False

def encendido():
    state = True

def apagado():
    state = False

def printing():
    if state == True:
        value = "Activado"
    else:
        value = "Desactivado"
    etiqueta1.config(text=value)

etiqueta1 = tk.Label(wn, text="estado")
etiqueta1.pack()

btn = tk.Button(wn, text="Pusla para desactivar", command=apagado()).pack()
btn2 = tk.Button(wn, text="Pusla para activar", command=encendido()).pack()

see_state = tk.Label(wn, text=printing())

wn.after(1000, printing())
wn.mainloop()

EDIT
Despues de mucho buscar e intentar lo conseguí sin after() ni na! :D
Lo conseguí este es el codigo:
import tkinter as tk
import customtkinter as ctk

#-->VENTANA
wn = tk.Tk()
wn.geometry("600x400+735+300")
wn.resizable(0, 0)
wn.title("Programa")

#-->DEFINICIONES
def apagado():
    estado = "Apagado"
    etiqueta["text"] = estado

def encender():
    estado = "Encendido"
    etiqueta["text"] = estado

#-->BOTONES Y ETIQUETAS
boton1 = tk.Button(wn, text="Apagar", command= apagado, borderwidth=0, background="#ABB2B9",fg="black", height=10, width=10, font="Calibri", activebackground="#2C3E50")
boton1.pack(side=tk.RIGHT)
boton2 = tk.Button(wn, text="Encender", command=encender, borderwidth=0, background="#ABB2B9",fg="black", height=10, width=10, font="Calibri", activebackground="#2C3E50")
boton2.pack(side=tk.LEFT)
etiqueta = tk.Label(wn)
etiqueta.pack()

#-->LOOP
wn.mainloop()


text:
Q: abort reply crashes with access violation I have a huge problem and I actaully thought that I solved it. I have an application that uses the QNetworkAccessManager. This QNAM is located in a class. When I perform requests on this QNAM all of them are done in a wrapper which holds the reply and does retry logic on it
For example if I have a putBlob (which inherits from baseRequest) in the constructor I pass a reference to the QNAM. I den perform the request on it and save a pointer to the reply. The reply will then be the wrappers child so the QNAM no longer has ownership over it. The wrappers are children of the original class which holds the QNAM.
class has a QNAM, and children "putBlobRequest", which has child "QNetworkReply*"
The issue now is when the user wants to cancel which should delete the main object and everything in it. The wrappers should also abort its QNetworkReply and disconnect (so that it doesnt call finish())
my destructor on the baseRequest (which holds the QNetworkReply and is its parent) looks like this:
if(_reply) {
    if(_reply->isRunning()) {
        _reply->disconnect(SIGNAL(finished()));
        _reply->disconnect(SIGNAL(uploadProgress(qint64, qint64)));
        _reply->abort();
    }
}

The delete is done when the wrapper gets killed in the class that holds it.( right?)
This works sometimes, but sometimes I get a huge access violation and everything crashes with the following callstack:
QtCored4.dll!QObject::disconnect(const QObject * sender, const char * signal, const QObject * receiver, const char * method)  Line 2891 + 0x8 bytes C++
QtNetworkd4.dll!QNetworkReplyImpl::abort()  Line 874 + 0x18 bytes   C++
FrameworkAzure.dll!BaseRequest::~BaseRequest()  Line 129 + 0xa bytes    C++
FrameworkAzure.dll!PutBlobRequest::~PutBlobRequest()  Line 24 + 0x5e bytes  C++
FrameworkAzure.dll!PutBlobRequest::`scalar deleting destructor'()  + 0xb bytes  C++
FrameworkAzure.dll!AzureBlobStorageProvider::~AzureBlobStorageProvider()  Line 41 + 0xa8 bytes  C++

So first the abort() gets called which calls the following:
if (d->outgoingData)
    disconnect(d->outgoingData, 0, this, 0); <--- we go in here

Which takes me to line 2891 in QOBject.cpp here:
const QMetaObject *smeta = sender->metaObject();

where it crashes with the error:

Unhandled exception at 0x66c2c490 (QtCored4.dll) in CloudSync.exe: 0xC0000005: Access violation reading location 0xdddddddd.

The adress "0xdddddddd" is the "sender".
Why is the sender object not readable? What am I doing wrong? Please help!
EDIT:
Also tried:
if(_reply) {
    if(_reply->isRunning()) {
        disconnect(_reply, SIGNAL(finished()), this, SLOT(handleFinishedRequest()));
        _reply->abort();

    }
}

where I also disconnect the uploadProgress in the dervied putBlob. Also tried without the disconnect but with the same issue that the "sender" is violated

A: In my case, I have a function of replyFinished as below:
void MyClass::replyFinished(QNetworkReply *reply)
{
   ...
   delete reply;
}

In my program, this function is connected via QNetworkAccessManager, thus the reply won't disconnect with it even I have called disconnect(reply, ...). Command abort will trigger this function (replyFinished) and delete the reply, I delete it one more time (via reply->deleteLater()) and lead crashing.
Solution: add a property to reply and check them.
disconnect(reply, nullptr, this, nullptr);
reply->setProperty("deleting", 1);
reply->abort();
...
void MyClass::replyFinished(QNetworkReply *reply)
{
   if (reply->property("deleting").isValid())
      return;

   ...
   delete reply;
}

A: latch on to _reply's (QNetworkReply) destruction and don't execute workflows that touch it after that happens (_reply's destruction i.e). your _reply is already deleted and garbled when the issue happens.
    bool bReplyDestroyed = false;

    connect(_reply, &QObject::destroyed, [=](){
       // set something indicative of _reply no longer usable
       bReplyDestroyed = true;
    });

    if(!bReplyDestroyed) {
      if(_reply->isRunning()) {
        disconnect(_reply, SIGNAL(finished()), this, SLOT(handleFinishedRequest()));
        _reply->abort();
      }
    }


text:
Q: Equicontinuous homeomorphism and compact metric Let $(X, d) $ be a metric space and $f: X \rightarrow X$ be a homeomorphism on $X$.
1) We say that $f$ is semi-equicontinuous if for every $\epsilon > 0$ there exists $\delta > 0$ such that $d(x, y) < \delta $ implies $d(f^{n} (x), f^{n} (y)) < \epsilon $ for all $x, y\in X$ and all $n \geq 0$. (This is also a definition of equicontinuity of continuous maps).
2) We say that $f$ is equicontinuous if for every $\epsilon > 0$ there exists $\delta > 0$ such that $d(x, y) < \delta $ implies $d(f^{n} (x), f^{n} (y)) < \epsilon $ for all $x, y\in X$ and all $n \in \mathbb{Z}$.
3)  We say that $f$ is an isometry if $d(f(x), f(y)) = d(x, y)$ for all $x, y\in X$.
4) If $X= \mathbb{R} $ and $0 < \alpha < 1$, then $f(x) = \alpha x$ is non-isometry semi equicontinuous homeomorphism but not equicontinuous.
Questions :
1) Can we find a non-isometry semi-equicontinuous but not equicontinuous homeomorphism on a compact metric space. A class of such maps on distinct compact metric spaces are needed, if exists.
2) If $f$ is an equicontinuous homeomorphism on a compact metric then $f$ must be an isometry?

A: 2) A family $\mathcal F$ of functions between metric spaces $(X,d)$ and $(X',d')$ is uniformly equicontinuous, if for every $\epsilon>0$ there exists $\delta>0$ such that $d(x,y)<\delta$ implies $d'(f(x),f(y))<\epsilon$ for all $x,y\in X$ and all $g\in \mathcal F$. So a homeomorphism $f$ of a space $(X,d)$ is semi-equicontinuous iff a family $\hat f^+=\{f^n:n\ge 0\}$ is uniformly equicontinuous and is equicontinuous iff a family $\hat f=\{f^n:n\in\Bbb Z\}$ is uniformly equicontinuous.
Uniform equicontinuity can be naturally defined for uniform spaces. Namely, a family $\mathcal F$ of functions between uniform spaces $(X,\mathcal U)$ and $(X',\mathcal U')$ is uniformly equicontinuous, if for every $U'\in\mathcal U'$ there exists $U\in\mathcal U$ such that $(f\times f)(U)\subset U'$ for all $g\in\mathcal F$.
It is easy to check that a family $\mathcal F$ of functions between metric spaces $(X,d)$ and $(X',d')$ is uniformly equicontinuous iff $\mathcal F$ is uniformly equicontinuous with respect to uniform spaces $(X,\mathcal U_d)$ and $(X',\mathcal U_{d'})$, where $\mathcal U_d$ and $\mathcal U_{d'}$ are the uniformities induced by metrics $d$ and $d'$, respectively. That is a base of $\mathcal U_d$ is $\{U_n:n\in\Bbb N\}$, where $U_n=\{(x,y)\in X\times X: d(x,y)<1/n\}$ for each $n\in\Bbb N$, and, similarly, a base of $\mathcal U_{d}$ is $\{U'_n:n\in\Bbb N\}$, where $U'_n=\{(x,y)\in X'\times X': d'(x,y)<1/n\}$ for each $n\in\Bbb N$.
It is easy to check that a topology induced by the uniformity $\mathcal U_d$ on the set $X$ is the same as a topology $\tau_d$, induced by the metric $d$ on $X$.
At last we came to a key point of this answer. If $X$ is a compact space then there exists a unique uniformity $\mathcal U$ on $X$, inducing the topology of space $X$, see, for instance, Theorem 8.3.13 from "General topology" by Engelking below. On the other hand, there can be many metrics on $X$ inducing its topology. We can construct them as follows. Let $(X,d)$ be any metric space and $h:X\to X$ be any continuous function. For each $x,y\in X$ put $d'(x,y)=d(x,y)+|h(x)-h(y)|$. It is easy to see that a function $d'$ is a metric on $X$. Since $d'(x,y)\ge d(x,y) $ for each $x,y\in X$, a topology $\tau_{d'}$ induced on $X$ by $d'$ is stronger than a topology $\tau_d$ induced on $X$ by $d$. On the other hand, let $x\in X$ be any point and $\epsilon>0$ be any real number. Since the function $h$ is continuous at $x$, there exist $0<\delta\epsilon/2$  such that $|h(x)-h(y)|<\epsilon/2$ for each $y\in X$ such that $d(x,y)<\delta$. Then $d'(x,y)<\epsilon$. Thus $\tau_{d'}$ is weaker than $\tau_d$, so $\tau_{d'}=\tau_d$.
We can conclude that if $X$ is a compact metrizable space and $f$ is a homeomorphism of $X$ then whether $X$ is equicontionuous does not depend on a metric inducing the topology of the space $X$, but
whether $X$ is an isometry depends on this metric and holds only in special cases.


text:
Q: Asymptotics of a series involving cos integral functions I'm looking for the asymptotic expansion( or value ) of the following function
\begin{equation}
F[y,t] =  \sideset{}{'}\sum_{n \in \mathbb{Z}}\text{Ci}\big[\frac{n^2}{t}\big] - \text{Ci}\big[\frac{(n+y)^2}{t}\big], \quad t \in [0, \infty), \,\, y \in [0, 1]
\end{equation}
where the sum is performed for all nonzero integers and $\text{Ci}$ is the cos integral function
\begin{equation}
\text{Ci}(x) = -\int_x^{\infty} \frac{\cos t}{t} dt
\end{equation}
I plot the alternative form of the function at $y = \frac{1}{2}$
\begin{equation}
F[y = \frac{1}{2}, t] = \sum_{n=1}^{\infty} 2\text{Ci}\big[\frac{n^2}{t}\big] - \text{Ci}\big[\frac{(n+0.5)^2}{t}\big] - \text{Ci}\big[\frac{(n-0.5)^2}{t}\big]
\end{equation}
using Mathematica.

The general pattern of these figures is that the function goes up and then has a damping process and finally converge to a fixed value at large $t$. My truncation is performed for $n \gg t$; it seems that beyond $n \gg t $, extra terms only increase the fuzziness of the curve, not the asympototic value.
I tried to approximate it using Euler-Maclaurin formula.
Let $f(n ) = 2\text{Ci}\big[\frac{n^2}{t}\big] - \text{Ci}\big[\frac{(n+y)^2}{t}\big] - \text{Ci}\big[\frac{(n-y)^2}{t}\big]$
then
\begin{equation}
  F[y, t] = \lim_{N\rightarrow \infty} \int_1^{N} f(x) dx + \frac{1}{2}[ f(1) + f(N)] + \frac{1}{12}[f'(N) - f'(1)] \\- \frac{1}{720}[f^{(3)}(N) - f^{(3)}(1)] + \cdots
\end{equation}
Keeping up to the first derivative term, I have
\begin{equation}
  F[y, t] \sim - 2\text{Ci}[\frac{1}{t}] + (\frac{1}{2} + y ) \text{Ci}[\frac{(1+y)^2}{t}] + (\frac{1}{2} - y ) \text{Ci}[\frac{(1-y)^2}{t}] \\- 2 \Big( \int_1^{1+y} + \int_1^{1-y} \Big) \cos \frac{u^2}{t}du
\end{equation}
However this function is very smooth at large $t$. It seems that I have to keep all the corrections at $n=1$ to have a reasonable estimation.
There are several questions I want to ask about the asymptotic behavior

*

*Does
\begin{equation}
\lim_{t\rightarrow \infty} F[y,t]
\end{equation}
exist?

*If the asymptotic value does exist, then is there some sort of series expansion available for the large $t$?
Thanks.

Edit:
Let me fill in the gaps in user Jack D'Aurizio's solution of asymptotic value(credit belongs to him).
First make a simple change of variable from $u$ to $v$: $u = \frac{v^2}{t}$
\begin{equation}
  -\sum_{n\in\mathbb{Z}}'\int_{n^2/t}^{(n+y)^2/t}\frac{\cos u}{u}\,du = -2\sum_{n\in\mathbb{Z}}'\int_{n}^{n+y}\cos(\frac{v^2}{t})\frac{dv}{v}
\end{equation}
The integral becomes an integration on $\mathbb{R}$ with standard measure and the integrand function
\begin{equation}
-2\cos(\frac{x^2}{t})\big[\sum_{n\in\mathbb{Z}}' \chi_{[n,n+y]}(x) \big]
\end{equation}
where $\chi(x)$ is the characteristic function.
Take $t$ to be an integer sequence, since
\begin{equation}
\Big|2\cos(\frac{x^2}{t})\big[ \sum_{n\in\mathbb{Z}}' \chi_{[n,n+y]}(x)  \big]\Big| \le 2( \sum_{n\in\mathbb{Z}}' \chi_{[n,n+y]}(x)  )
\end{equation}
and the later is integrable( by using the  Weierstrass product for the sine function )
\begin{equation}
2\sum_{n\in\mathbb{Z}}'\int_{n}^{n+y}\frac{dv}{v}=2\sum_{n\in\mathbb{Z}}'\log\left(1+\frac{y}{n}\right)=2\log\prod_{n\geq 1}\left(1-\frac{y^2}{n^2}\right)=2\log\left(\frac{\sin(\pi y)}{\pi y}\right).
\end{equation}
the dominated convergence theorem claims that
\begin{equation}
\lim_{t\rightarrow \infty} F[y,t] = -\int_{\mathbb{R}} dx\, \lim_{t\rightarrow \infty} 2\cos(\frac{x^2}{t})\big[ \sum_{n\in\mathbb{Z}}' \chi_{[n,n+y]}(x)  \big] = -2\log\left(\frac{\sin(\pi y)}{\pi y}\right)
\end{equation}

A: So we want to study the behaviour for a large $t$ of:
$$ \sum_{n\in\mathbb{Z}}'\int_{n^2/t}^{(n+y)^2/t}\frac{\cos u}{u}\,du = 2\sum_{n\in\mathbb{Z}}'\int_{n}^{n+y}\cos(v^2/t)\frac{dv}{v}$$
that by the dominated convergence theorem and the Weierstrass product for the sine function approaches:
$$ 2\sum_{n\in\mathbb{Z}}'\int_{n}^{n+y}\frac{dv}{v}=2\sum_{n\in\mathbb{Z}}'\log\left(1+\frac{y}{n}\right)=2\log\prod_{n\geq 1}\left(1-\frac{y^2}{n^2}\right)=\color{red}{2\log\left(\frac{\sin(\pi y)}{\pi y}\right)}.$$


text:
Q: How can I pick up all the titles and articles with scrapy? I'm currently on scraping some web information.
I don't know why but it just doesn't work fine.
It would be appreciated if someone could correct my code.
This is just an example but what I'd like to do here is from the starting URL, visit all the articles listed on it, and pick up the title and article from each.
(all the articles come the way like http://www.bbc.com/sport/tennis/42610656)
Here is my code below.
Thanks so much for your help!
# -*- coding: utf-8 -*-
import scrapy
from myproject.NLP_items import Headline
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor

class BBC_sport_Spider(CrawlSpider):
    name = 'sport'
    allowed_domains = ['www.bbc.com']
    start_urls = ['http://www.bbc.com/sport/']
    allow_list = ['.*']

    rules = (
        Rule(LinkExtractor( allow=allow_list), callback='parse_item'),
        Rule(LinkExtractor(), follow=True),
    )

    def parse(self, response):

        for url in response.xpath('//div[@id="top-stories"]//a/@href').extract():
            yield(scrapy.Request(response.urljoin(url), self.parse_topics))

    def parse_topics(self, response):

        item=Headline()
        item["title"]=response.xpath('//div[@class="gel-layout__item gel-2/3@l"]//h1').extract()
        item["article"]=response.xpath('//div[@id="story-body"]//p').extract()

        yield item

`

A: To quote the scrapy docs:

When writing crawl spider rules, avoid using parse as callback, since
  the CrawlSpider uses the parse method itself to implement its logic.
  So if you override the parse method, the crawl spider will no longer
  work.

So, by overwriting the parse method, you're invalidating the rules you've defined.
Also, allow=['.*'] in a link extractor is a no-op, and so is a follow=True in a rule without a callback. If you want your rules to both parse an item and follow links, simply specify both a callback and follow instead of creating two rules.
Another problem is the parse method itself. The xpath inside it is selecting links from a div which doesn't exist (although a section with that id does).
However, if you're already using a CrawlSpider, you should specify an appropriate rule instead of overwriting parse in the first place.
And finally, I just want to note that scrapy.contrib.spiders and scrapy.contrib.linkextractors are deprecated; you should be using scrapy.spiders and scrapy.linkextractors instead.


text:
Q: VLookup to return MAX value from multiple hits I tried to vlookup the max value of available Qty against the material in another sheet which has below format. some one who can correct the way I work will be of much help.
What I tried but doesn't work
=INDEX('[Report.xlsb]Stock Report'!$L:$W,MATCH(D19,'[Report.xlsb]Stock Report'!$L$1:$L$9837,0),MAX(12))

WB-1

WB-2

A: If the table with available quantity is in cells A1 to B12 then:
=vlookup(C3,A$1:B$12,2,0)

Assuming the first case CH244G is in cell C3

A: To retrieve the maximum value for each material, you could use a MAXIFS formula like this:
=MAXIFS('WB-2'!B:B,'WB-2'!A:A,'WB-1'!A2)

The first conditions is the range in which you're trying to find the maximum (i.e., the available quantity).  The second condition is the criteria range that lines up with the max range (i.e., the material on WB-2).  The third condition is the criteria (the material on WB-1).
It works the same as a SUMIFS, but returns only the maximum value instead of the sum. Similarly, MINIFS returns only the minimum value.
Also, note that the criteria and sum range are reversed for the SUMIF vs SUMIFS.  If you're accustomed to the SUMIF, it's easy to get mixed up when you switch to SUMIFS, MAXIFS, or MINIFS.


text:
Q: Retag Request [vc++] -> [visual-c++] It seems that:

*

*[vc++] (466)

would be more clearly expressed as

*

*[visual-c++] (1,697)

A: Just some more...
[msvc] (172)
[visual-studio] [c++] (639)
[visual-c++-2005] (54)
[visual-c++-2008] (11)
[visual-c++-2010] (3)
[visual] [c++] (2)

(all of those counts are also searching -[visual-c++]).