text:
Q: Not able to create Azure Container Instance in the portal with private image I'm trying to create an Azure Container Instance in the portal with a private image. The validation seems to pass but I can't click OK. The button is disabled.
The private registry is an Azure Container Registry in the same subscription.

A: Looks like this was resolved on your own after waiting between attempts. For future reference if you need to deploy a private image from the portal you need to include the hostname of the image like "myprivateregistry/nginx:latest".
We've also improved some error handling so deployment failures should also be easier to troubleshoot.


text:
Q: Qt - I can't select any QListWidget item. They are always auto selected from the top down When I go to select A SINGLE item in my QListWidget, it just selects my item, and all of the ones above it. Also, I would like to know how to get a 'right-click context menu' that I can use when I right click the QListWidget. I'll leave an image and my source code. All help is greatly appreciated. Thank you!

MainWindow:
#include "mainwindow.h"
#include "ui_mainwindow.h"

QString path;
QStringList before;
QStringList suffixes;
QDir folder;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->checkBoxDateOrdered->setEnabled(false);
    ui->checkBoxInverted->setEnabled(false);
    ui->pushButton->setEnabled(false);
    ui->pushButtonClear->setEnabled(false);
    connect(ui->listWidget, SIGNAL(customContextMenuRequested(const QPoint &)), SLOT(showContextMenuForWidget(const QPoint &)));
    ui->listWidget->setContextMenuPolicy(Qt::CustomContextMenu);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::showContextMenuForWidget(const QPoint &pos)
{
    QMenu contextMenu(tr("Context menu"), this);
    contextMenu.addAction(new QAction(tr("Hello"), this));
    contextMenu.exec(mapToGlobal(pos));
}

void MainWindow::check()
{
    ui->listWidget->clear();
    before.clear();
    if (ui->checkBoxDateOrdered->isChecked() && !ui->checkBoxInverted->isChecked())
    {
        before = folder.entryList(QDir::Files, QDir::Time);
    }
    else if (ui->checkBoxInverted->isChecked() && !ui->checkBoxDateOrdered->isChecked())
    {
        before = folder.entryList(QDir::Files, QDir::Reversed);
    }
    else if (ui->checkBoxInverted->isChecked() && ui->checkBoxDateOrdered->isChecked())
    {
        before = folder.entryList(QDir::Files, QDir::Time | QDir::Reversed);
    }
    else
    {
        before = folder.entryList(QDir::Files);
    }
    ui->statusBar->clearMessage();
    ui->statusBar->showMessage(QString::number(before.size()) + " file(s) found. ");
    ui->listWidget->addItems(before);
    suffixGet();
}

void MainWindow::verify()
{
    before.clear();
    check();
    suffixes.clear();
    suffixGet();
    ui->listWidget->clear();
    ui->listWidget_2->clear();
    ui->statusBar->clearMessage();
}

void MainWindow::update()
{
    before.clear();
    check();
    if (ui->listWidget->count() == 0 && ui->listWidget_2->count() > 0)
    {
        ui->pushButtonClear->setEnabled(true);
    }
    else if (ui->listWidget->count() > 0 && ui->listWidget_2->count() == 0)
    {
        ui->pushButtonClear->setEnabled(true);
    }
    else if (ui->listWidget->count() > 0 && ui->listWidget->count() > 0)
    {
        ui->pushButtonClear->setEnabled(true);
    }
    else
    {
        ui->pushButtonClear->setEnabled(false);
    }
}

void MainWindow::makeList()
{

    check();
    suffixes.clear();
    suffixGet();
    ui->listWidget->clear();
    ui->listWidget_2->clear();
    ui->statusBar->clearMessage();
    folder.setPath(path);
    check();
    ui->statusBar->showMessage(QString::number(before.size()) + " file(s) found. " + " Path: " + path);
}

void MainWindow::suffixGet()
{
    ui->listWidget_2->clear();
    QStringList temp;
    QString suffix;
    QString temp2;
    QStringList after;

    for (int x = 0; x < before.size(); x++)
    {
        temp2 = before.at(x);
        temp = temp2.split(".");
        suffix = "." + temp.value(temp.length() - 1);
        suffixes << suffix;
        after << QString::number(x) + suffix;
    }
    ui->listWidget_2->addItems(after);
}

void MainWindow::on_toolButton_clicked()
{
    before.clear();
    suffixes.clear();
    suffixGet();
    path.clear();
    path = QFileDialog::getExistingDirectory(this, tr("Open Directory"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);

    if (path != "")
    {
        makeList();
    }
    ui->lineEdit->setText(path);
}

void MainWindow::on_pushButton_clicked()
{
    before.clear();
    check();
    suffixes.clear();
    suffixGet();
    for (int x = 0; x < before.size(); x++)
    {
        int i = x;
        folder.rename(before.at(x), QString::number(i++) + suffixes.at(x));
    }
}

void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
    before.clear();
    suffixes.clear();
    suffixGet();
    check();
    ui->listWidget->clear();
    ui->listWidget_2->clear();
    if (arg1 == "")
    {
        ui->checkBoxDateOrdered->setEnabled(false);
        ui->checkBoxInverted->setEnabled(false);
        ui->pushButton->setEnabled(false);
        ui->pushButtonClear->setEnabled(false);
        ui->statusBar->clearMessage();
    }
    else if (arg1 != "")
    {
        if (QDir(arg1).exists())
        {
            ui->checkBoxDateOrdered->setEnabled(true);
            ui->checkBoxInverted->setEnabled(true);
            ui->pushButton->setEnabled(true);
            ui->pushButtonClear->setEnabled(true);
            path = arg1;
            makeList();
        }
        else
        {
            ui->statusBar->showMessage("Invalid path!");
        }
    }
}

void MainWindow::on_pushButtonClear_clicked()
{
    before.clear();
    suffixes.clear();
    suffixGet();
    ui->lineEdit->clear();
    verify();
}

Main.cpp:
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

MainWindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QFileDialog>
#include <QMenu>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    void check();
    void verify();
    void update();
    void makeList();
    void suffixGet();

    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_toolButton_clicked();

    void on_pushButton_clicked();

    void on_checkBoxDateOrdered_clicked()
    {
        check();
    }

    void on_checkBoxInverted_clicked()
    {
        check();
    }

    void on_lineEdit_textChanged(const QString &arg1);

    void on_pushButtonClear_clicked();

    void on_listWidget_currentTextChanged()
    {
        update();
    }

    void on_listWidget_2_currentTextChanged()
    {
        update();
    }

public slots:
    void showContextMenuForWidget(const QPoint &pos);

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

redpajama_set_name: RedPajamaStackExchange


text:
Q: Visual Studio PATH Setting Seems to not be Working
Possible Duplicate:
Why can't Visual Studio find my DLL?

I've been trying to use the "VC++ Directories" to set the path to a dll I want to use. I add the path to the "Executable Directories" for the Debug configuration, but when I try to debug the project I get the message saying that the dll cannot be found.
If I copy the dll to the debug folder then debug it works. I'm sure the directory is correct. There must be something I've forgotten to do or did wrong. How do I use the "VC++ Directories" to get the dll?
Any help would be appreciated,
Kevin


text:
Q: alternative to std::optional that can report failure reasons Is there an alternative to std::optional where I don't have to pass the result as a parameter to the function. I want the function to not modify its arguments (to be more pure/immutable).
TL;DR
The problem with std::optional seems to be that we lose information about errors. The function returns a value or something empty, so you cannot tell what went wrong.
using std::optional
std::optional<std::string> doSomething() {
    std::string value;
    int rc = callApi(value);

    if (rc == 0) {
        //do some processing on value
        return value;
    }

    return std::nullopt;
}

//calling the function seems much more pure/cleaner than when passing a result parameter.

without std::optional
int doSomething(std::string& result) {
    std::string value;
    int rc = callApi(value);

    if (rc == 0) { //if no error
        //do some processing on value and set result = value
        result = value;
    }

    return rc;
}

A: It seems like what you're looking for is std::expected.
... it's not actually in the standard already, but:

*

*You can read a recent version of the proposal, P0323 revision 10

*You can use it! Or rather, an implemented of it by the talented Sy Brand / TartanLlama, including some nice extensions which I won't go into.

But - what is it?
Well... in a nutshell: When you want to return either some value, or some kind of failure/error descriptor, you just template those, say into T, E, and those are the template parameters: std::expected<T, E>. And since T and E are disjoint types, you know which of them you got back from the function.
Here's your function, adapted for an error type your API seems to have:
namespace my_api {
using error_t = int;
enum : error_t { success = 0, invalid_input = 1, /* etc. */ };
} // namespace my_api

std::expected<std::string, my_api::error_t> doSomething() {
    std::string value;
    my_api::error_t rc = callApi(value);
    if (rc != success) { return rc; }

    //do some processing on value
    return value;
}

Of course the my_api namespace is not part of my suggestion, it's merely an illustration, since you did not indicate how you would like to communicate errors. Actually, you might even add:
namespace my_api {
template <typename T>
using expected = std::expected<T, error_t>;
} // namespace my_api

and then your function signature becomes:
my_api::expected<std::string> doSomething();

See also: What is std::expected in C++?

A: std::variant is a type-safe union that allows you to return one of a fixed set of types. In this case you'd want a std::variant<std::string, int>
Using std::variant
std::variant<std::string, int>doSomething(){
    std::string value;
    int rc = callApi(value);

    if(rc == 0){ //if no error
       //do some processing on value
       return value;
    }

    return rc;
 }

A: std::optional is not intended to return an error. It is a tool for a very simple concept of "having a value or not". From cppreference:

Any instance of optional at any given point in time either contains a value or does not contain a value.

If you are writing a C++ function and an error is not a part of your business logic (i.e. you are not going to proceed when you receive an error instead of a usable result), just throw an exception. std::runtime_error will suit you fine. Or you can use std::error_code.

*

*Throwing an exception is perfectly fine performance-wise if the error rarelly occurrs.

*Throwing an exception simplifies your procedure logic. Instaed of checking each result for an error code you catch one exception.

A: I'll present three options, though I'm sure somebody will come up with a more clever approach. In short: you could throw an error, you could return an instance of a custom struct or class, or you could use a std::variant.
Option 1: Throw an Error
Here, you can throw the error value (i.e. the return code from callApi) on failure, then wrap any calls to doSomething() in a try ... catch block.
std::string doSomething(){
  std::string value;
  int rc = callApi(value);

  if(rc) throw rc;

  //do some processing on value
  return value;
}

Option 2: Return a Struct
Here, you create a struct that holds both a std::string and a return code; this allows the encoding of both error information and a successfully-returned string.
struct ReturnString {
  std::string value;
  int rc;
}

ReturnString doSomething(){

  ReturnString return_value;
  std::string & value = return_value.value;
  int & rc = return_value.rc;

  rc = callApi(value);

  if(rc) return return_value;

  //do some processing on value
  return return_value;
}

Then, calling code can check the value of rc, process the error appropriately if nonzero, or use the string if 0.
You could even get fancy and use a generic struct, with the type of value being a template parameter. You could additionally add helper functions that check the value of rc to give you the string contents if appropriate. Rather than doing all that, though, you can use something similar that already exists in the standard library:
Option 3: Use a Variant
The std::variant represents a type-safe union, and thus can hold either a return code or a string. Helper functions can be used to determine which one it holds. So, you might do something like:
std::variant<int, std::string> doSomething(){
  std::variant<int, std::string> return_value;

  std::string value;
  int rc = callApi(value);

  if(rc) return rc;

  //do some processing on value
  return return_value;
}

Then, from your calling function, you can check the variant to see which type it holds, and proceed accordingly:
auto v = doSomething();
int rc;
if(std::holds_alternative<int>(v)) {
  rc = std::get<int>(v);
  //Process error accordingly
if(std::holds_alternative<std::string>(v)) {
  std::cout << "String returned was " << std::get<std::string>(v) << std::endl;
}


text:
Q: How to deploy a model having no predict attribute? app.py
from flask import Flask, jsonify, request,render_template
import pickle
app = Flask(__name__,template_folder='template')
# load model
model = pickle.load(open("model.pkl",'rb'))
# app

@app.route('/')
def home():
    return render_template('recommendation.html')
# routes
@app.route('/api', methods=['POST'])

def predict():
    result=request.form
    query_user_name=result["user name"]
    user_input = {'query':query_user_name}
    output_data=model(query_user_name)
    print(output_data)
    # send back to browser
    output ={output_data}
    return f'
{output_data}
<form action="/"><button type="submit">back </button> </form>'

if __name__ == '__main__':
    app.run(debug=True)

I am deploying it using a model made from following function,not a pre-existing model having predict attribute.
def model(user):
    recommended_list=[]
    top_list=[]
    x = data.iloc[data.loc[data.Users == user].index[0],2:]
    similar = np.array([(data.iloc[i,0],weight_factor(x,data.iloc[i, 2:])) for i in range(0,data.shape[0],1)])
    index= np.argsort( similar[:,1] )
    index=index[::-1]
    similar=similar[index]
    neighbours = similar[similar[:,1].astype(float) > 0.6]  #Taking threshold as 0.6
    for i in range(0,len(neighbours),1):
        for j in range(2,len(data.columns),1):
            if data.iloc[data.loc[data.Users == neighbours[i][0]].index[0],j]==1 and data.iloc[data.loc[data.Users == user].index[0],j]==0:
               recommended_list.append(data.columns[j])
    if (len(neighbours)>10):
       for i in range(0,10,1):  #Top 10 neighbours
           top_list.append(neighbours[i][0])
    else:
       for i in range(len(neighbours)):
            top_list.append(neighbours[i][0])
    if user in top_list: #Remove the user of which we are asked to find neighbours,each user is always strongly correlated with itself and its of no use to us.
       top_list.remove(user)
    print(" ")
    print("Top users similar to this user are:")
    print(" ")
    for i in range(0,len(top_list),1):
        print(top_list[i])
    print(" ")
    print("Users similar to this user liked these products too:")
    print(" ")
    recommended_array=np.unique(np.array(recommended_list))
    for i in range(0,len(recommended_array),1):
        print(recommended_array[i])

How to deploy it using flask,my output is not being shown in the window,though on deploying the home page is being shown and input is being taken.

A: your function "model(user)" must return somethings
example:
def model(user):
    # code
    return somethings


text:
Q: c# - common objects among a list of objects I have the following list of list of Person objects
List<List<Person>> setofPersons=new List<Lits<Person>>();

I add items to it like this.
List<Person> firstPersonList=new List<Person>();
Person p1=new Person(100,"James");
Person p2=new Person(200,"Smith");
firstPersonList.Add(p1);
firstPersonList.Add(p2);

setOfPersons.Add(firstPersonList);

List<Person> secondPersonList=new List<Person>();
Person p3=new Person(100,"James");
Person p4=new Person(200,"Smith");
Person p5=new Person(300,"Thomas");
secondPersonList.Add(p3);
secondPersonList.Add(p4);
secondPersonList.Add(p5);

setOfPersons.Add(secondPersonList);

List<Person> thirdPersonList=new List<Person>();
Person p6=new Person(100,"James");
Person p7=new Person(400,"Amy");
thirdPersonList.Add(p6);
thirdPersonList.Add(p7);

setOfPersons.Add(thirdPersonList);

Now I want to find out the common objects among the lists contained in setOfPersons. This comprison should be done by person Id eg : 100,200,300 etc;
I have tried the following.
List<Person> commonPersons = setOfPersons
    .Where(i => setOfPersons.Skip(1).All(x => x.Contains(i)))
    .ToList();

But the problem is that count in commomPersons is always 0;
Can someone help me to fix this ?
EDIT
I have written the following method in Person class
              public int CompareTo(object obj)
              {
                       Person p = (Person)obj;
                       if (p.personId == personId)
                             return 1;
                       else
                             return 0;

               }

Then I changed my LINQ query to the following
              List<Person> commonPersons = setofPersons[0].Where(
                                  i => setofPersons.Skip(1).All(x => i.CompareTo(x))
                              ).ToList();

It now generates a compile time error saying " cannot convert bool to int ".
I'm new to LINQ. Can someone point out where I have gone wrong ?

A: The problem is that there is no way for the computer to know if 2 instances of person class are the same. To tell the .NET Runtime how to do that, make your Person class implement IComparable, and there you can specify how to compare 2 instances of Person class (in your case you would check if the Ids are equal). See here
Correction: You need to implement IEquatable, comparable is for ordering/sorting.

A: IComparable / CompareTo is used for ordering/sorting.  What you should do is override Equals and GetHashCode or implement an IEqualityComparer
A simple equality implementation could look like this, for example:
public override bool Equals(object obj)
{
    var person = (Person)obj;
    return Equals(Id, person.Id);
}

public override int GetHashCode()
{
    return Id;
}

Then your common persons could be found by:
var commonPersons = firstPersonList
    .Intersect(secondPersonList)
    .Intersect(thirdPersonList);

For the intersection of multiple enumerations (e.g. a list of lists), there are more efficient ways of doing this shown in the answers to Intersection of multiple lists with IEnumerable.Intersect()

A: Trying to think in set... to get what you got, you need to:

*

*Flatten all data in the set into a single collection of person, then group them by person.id

*Then group it by the person id

*Finally, filter them to only the groups having the same count as the original set.

Code as follow:
var query = setOfPersons
            .SelectMany(personList => personList.Select(person => person))
            .GroupBy(person => person.Id)
            .Where(group => group.Count() == setOfPersons.Count);

See the final sample here: https://dotnetfiddle.net/gCgNBf

A: What you need to do is flatten the list of lists into a single list. To do so, you can use SelectMany.
The code would look like this:
var commonPersons = setOfPersons.SelectMany(x => x.Where(y => y.Id == 100));


text:
Q: Git how to copy one branch to the master branch I have a repository and I used to work with the master branch myself, now  we got a new employee, we created a new branch for him, and now his branch is stable, how can I copy its content to the master branch ?
I am using bitbucket

A: It sounds like you just want to do a git merge? The process of doing it is described here, but the tl;dr is git checkout master && git merge his-branch


text:
Q: Diferença entre std::map, std::unordered_map, std::flat_map, e qual delas escolher? Qual é a diferença entre as funções da biblioteca map, unordered_map, flat_map, e qual delas utilizar, por exemplo em quesito de performance?

A: Performance é relativo. Performance em que? Em acesso? Em inserção? De que adianta ter performance se a estrutura não faz o que precisa?
Se precisa de um mapa com ordem definida não pode usar um unordered_map.
Se precisa do flat_map e só pode usar a biblioteca padrão, como mostra a pergunta, não tem como já que não está disponível nela. Em geral o pessoal usa a implementação da Boost.
A estrutura de mapa ordenado tem uma performance muito boa em quase todas operações, mas um mapa não ordenado pode ser mais rápido na maioria dos casos, embora não tenha garantias boas e no pior caso (muito raro, quase impossível na prática) pode ser extremamente lento (permite até ataque de DOS).
A (ordered) map geralmente é implementada com uma árvore de busca binária e a unordered_map costuma ser uma tabela de espalhamento.
A flat_map costuma ser uma árvore implementada em cima de um array, o que impede certas garantias em algumas operações (pode ser lento inserir um novo elemento quando a estrutura está cheia, e também não diminui de tamanho automaticamente se for possível), porém permite alguns ganhos no acesso, podendo ter até mesmo a melhor performance possível dependendo de como precisa do dado e como ele está organizado. O acesso linear costuma ser ótimo. A inserção pode ter ganho se também for bem linear. Os ganhos não ocorrem em qualquer conjunto de dados, pode até ficar bem pior.
Enfim, essa estrutura é boa para casos muito raros onde se sabe que os dados são muito lineares, o que quase sempre permitiria o uso de outra estrutura, quem sabe até mesmo um Vector.


text:
Q: C# List, Removing all null values *after* last non-null element I have a list of strings, example(C#):
new List<string> { "string1", null, null "string2", "string3", null, null, null }

I have many of those, all with different amounts of strings and nulls, where every one can be in a different place and the list length is not the same for each list, also not necessarily string list.
How would I remove the remaining null values after the last string, after the last non null value, keeping the null values that are between and in front of?
Thanks!
/Fredman

A: Check your list from last item to the beginning and remove null values until a non null values is reached:
List<string> list = new List<string> { "string1", null, null "string2", "string3", null, null, null };

for(int i=list.Count - 1; i>=0; i--)
{
     if(list[i]==null) list.RemoveAt(i);
     else break;
}

A: To avoid iterating the list twice to determine whether all entries are null (as you are currently doing), I'd suggest a slight tweak of Ashkan's solution:
var list = new List<string> { "string1", null, null, "string2", "string3", null, null, null };

int? firstNonNullIndex = null;

for (int i = list.Count - 1; i >= 0; i--)
{
    if (list[i] != null)
    {
        firstNonNullIndex = i;
        break;
    }
}

if (firstNonNullIndex == null) {
    // Do nothing as per your requirements (i.e. this handles your `All` call)
}
else
{
    list.RemoveRange(firstNonNullIndex.Value + 1, list.Count - firstNonNullIndex.Value - 1);
    // Do whatever you need to do with the `List` here
}

This solution has two main benefits:

*

*A single RemoveRange call is faster than multiple Remove calls

*No need to remove all (or indeed any!) of the elements if they are all null (i.e. this scenario gets much faster)

A: Here's a pretty simple way to remove all trailing null items:
while (items.Any() && items.Last() == null) items.RemoveAt(items.Count - 1);

A: Linq way:
int position = list.IndexOf(
          list.Where(x =>x!=null).OrderByDesc.FirstOrDefault());
return position == list.Count -1 ? list: list.RemoveRange(position+1, list.Count - 1);


text:
Q: How do you perform a segue from a UITableViewCell? In my UITableviewController I have a custom cell with UITableViewCell subClass. This custom cell contains UITextField, I want to perform a segue when Return key of keyboard is pressed, inside this - (BOOL)textFieldShouldReturn:(UITextField *)textField.
How I can create segue in storyboard in this situation? How I can perform segue inside uitableViewCell?

A: *

*Create a protocol method in your custom cell and add delegate property.

*Set your UITableViewController, which contains UITableView with custom cell, as a delegate - do it in tableView:cellForRowAtIndexPath: method.
cell.delegate = self;

*Call your protocol method in custom cell inside textFieldShouldReturn: method.
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.delegate yourMethod];
    return YES;
}

*In implementation of your protocol method in your UITableViewController place code to perform a segue.
- (void)yourMethod {
    // segue code
}

A: Create a segue normally in the storyboard, put a name on this segue (for this example, I'm using @"segue name") and  inside textFieldShouldReturn: call this method:
[self performSegueWithIdentifier:@"segueName" sender:self];


text:
Q: copyField chain I tried to use copyField like a chain but it doesn't seems to work. Here my example:
<copyField source="allfields" dest="metafields1" />
<copyField source="metafields1" dest="metafields2" />
<copyField source="metafields2" dest="metafields3" />

Each field uses a different fieldType.
The problem is that except of allfields and metafields1 the other have no content after indexing. Is solr unable to copy from another copyField? I use solr 3.5.

A: Documentation @ http://wiki.apache.org/solr/SchemaXml#Copy_Fields

The copy is done at the stream source level and no copy feeds into another copy.

Having a copyfield as the source of copyfield tag does not work.
The copyfield source must be an actual field, which has some value and does no cascade.
You can also check http://lucene.472066.n3.nabble.com/does-copyField-recurse-td2450208.html

A: As Jayendra said the copy is done @ stream source level while indexing and you can use this to perform the copy of analyzed text from copy fields.
Steps to arrive @ the solution:
1. Configure the fields (source and dest) and its field type accordingly.

*Write a custom update processor and configure this processor in solrconfig.xml

<requestHandler name="/update" class="solr.UpdateRequestHandler"><lst name="defaults">
             <str name="update.chain">custom_processor_name</str>
</lst></requestHandler>
A.   Look up to this link
B.  In the processAdd() of (A), perform below to obtain the tokenStream for a configured Schema field, analyze and copy the analyzed token stream value into dest field.
Ex:
SchemaField field = req.getSchema().getField(sourceField);

Analyzer anal = sourceField.getType().getAnalyzer();

....
//ToDo: Retrieve tokenStream from source and add it to Destination
....

doc.addField(destFieldToCopy, termBuffer.toString());

To obtain tokenStream check this post


text:
Q: Hardware testing tool/suite I just bought a new core i5 system (assembled) and started installing Windows 7. It was failing for many times and at some point got installed. After that, frequent crashes related to MEMORY. So checked the RAM using memtest86+ and found many errors.I got it replaced with the vendor and now if i install ANY OS, at some point in installation it either freezes completely with no response for hours, or restarts automatically. I tried installing Windows 7, Windows Vista and Ubuntu 9.10.
I tested the new RAM again and found no problems in about 2 passes using memtest86+. I even updated the BIOS using bootable USB and even the problem persists. I am really not sure which hardware is causing trouble. I dont have any OS inside it, so i have to check using bootable CDs DVDs and USB only.
Please advice on how to proceed. Are there any suites/ separate tools for checking integrity of each hardware parts and troubleshoot it? I wanted to confirm which part is problematic before going for replacement.
Thanks a lot!
This is the config: Core i5, MSI P55-GD65, GSKill 2x2GB, Seagate 500GB 7200rpm, CM Extreme 600W PSU, Saphhire Radeon 5770 1GB, LG DVD Writer

A: CM Extreme 600W PSU is not a good PSU for this system. Replace the PSU with a Corsair vx550 / CM Real Power 550W and try. If any of your friends have this PSU try replacing it with the ones mentioned above.


text:
Q: Converting single value colors to LAB using python OpenCV I have an numpy array containing a single pixel/color in floating point RGB. I need to convert this value to LAB, for which I am trying the following:
color = cv2.cvtColor(color.reshape((1,1,3)), cv2.COLOR_RGB2LAB).reshape((3))
Where color is:
array([137.38841, 161.38841,  65.38841], dtype=float32)
The resulting LAB is: [100.   0.   0.]
Which clearly isn;t correct as it should be close to: [62.667494977600484, 22.98637993404601, 46.1397720707445]
How do I convert the value to LAB?

A: You were not reshaping it properly. Use the below code to do that.
import cv2
import numpy as np
bgr = [40, 158, 16]
lab = cv2.cvtColor( np.uint8([[bgr]] ), cv2.COLOR_BGR2LAB)[0][0]
print(lab)  #[145  71 177]

Above code will help of rgb/bgr value is in integer. Since your values are in floating-point, I suggest you go with rgbtolab function found on this link.
https://stackoverflow.com/a/16020102/9320324


text:
Q: yandex smtp doesnt work on codeigniter(digitalocean+ubuntu+serverpilot) I send email on localhost but doesnt work same settings on server(digitalocean+serverpilot).
php's open ssl support is enabled.

php get "Message: fsockopen(): unable to connect to
  ssl://smtp.yandex.com.tr:465 (Connection timed out)

codeigniter framework get :

The following SMTP error was encountered: 110 Connection timed out
  Unable to send email using PHP SMTP. Your server might not be
  configured to send mail using this method.

my code is:
 $config = Array('protocol' => 'smtp','smtp_host' => 'ssl://smtp.yandex.com.tr','smtp_port' => 465, 'smtp_user' => 'info@mydomain.com','smtp_pass' => 'mypass','mailtype'  => 'html', 'charset'   => 'utf-8');

$this->load->library('email');
$this->email->initialize($config);
$this->email->set_newline("\r\n");

$this->email->from('info@mydomain.com', 'test.com');
$this->email->to('testing@yandex.com');
$this->email->subject('test');

$this->email->message('test body');
$this->email->send();
 echo $this->email->print_debugger();

nslookup smtp.yandex.com:

Server:       2001:4860:4860::8844 Address:   2001:4860:4860::8844#53
Non-authoritative answer: smtp.yandex.com canonical name =
  smtp.yandex.ru. Name: smtp.yandex.ru Address: 93.158.134.38
  Name: smtp.yandex.ru Address: 87.250.250.38 Name: smtp.yandex.ru
  Address: 213.180.204.38 Name: smtp.yandex.ru Address: 213.180.193.38
  Name: smtp.yandex.ru Address: 77.88.21.38

and telnet request is work.

A: Your outgoing connection may be blocked by a firewall.
Use tool like tcptraceroute to locate the problem.


text:
Q: Importing a MySQL database Trying to import a MySQL database using PHP-Admin. When I try to import the file backed-up by my host, I get this error message:
SQL query:

DROP TABLE IF EXISTS `wp_commentmeta`

MySQL said: Documentation
#1046 - No database selected

I have also tried to export the database myself, then trying to import that specific file. When I do that, however, I get a completely different error message:
SQL query:

CREATE TABLE IF NOT EXISTS `wp_commentmeta` (
  `meta_id` bigint(20) unsigned NOT NULL,
  `comment_id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `meta_key` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `meta_value` longtext COLLATE utf8mb4_unicode_ci
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

MySQL said: Documentation
#1046 - No database selected

What can I do to resolve this?

A: You need to USE a database. You could edit your file and add the line at the top, something like:
USE databasename;

Some tools will let you set a default database when restoring from backup. If you haven't selected one that could be a problem.
If you haven't created a database you'll need to do that first.

A: You need to select which database you are importing to in your SQL. Your first statement should be:
USE DATABASE `db_name`;

A: You have no database selected.
Find which databases exist
SHOW DATABASES:

and then select one for use
USE `database_name`

You say that you are importing into a new host, so I would assume that you do not already have a database created;
CREATE DATABASE `database_name`

Now you can USE that database you just created; and your queries should now work.


text:
Q: KineticJs: How to scale an Image and keep the position of the attached container? I have an image (the blue box) and ad red rectangle. The image's offset is set to the center of the image to make rotation around the center of the image. The code is similar to the following:
var image = new Kinetic.Image({
x: 200,
y: 100
});
image.offsetX(100);
image.offsetY(50);

var rect = new Kinetic.Rect();

var group = new Kinetic.Group();

group.add(image);
group.add(rect);
layer.add(group);
stage.add(layer);

The stage than looks something like this:

After I rescale the image with
image.scaleX(0.5);
image.scaleY(0.5);

I get the following:

The red rectangle is not attached to the image anymore.
I could do
rect.scaleX(0.5);
rect.scaleY(0.5);

but this would change the size of the rect.
How do I rescale the image and keep the rectangle attached to the same position as before?
Edit:
The following image shows what it should look like after the image scaling. Event after the scaling the red rectangle should be attached to the image.

A: If you want the red rect to be centered in the top-left of the blue image after scaling the image, you will need to listen for changes in the images scaleX and scaleY properties.
You can listen for scaleX / scaleY property changes like this:
image.on("scaleXChange scaleYChange",function(){
    // either scaleX or scaleY has changed on this image
});

Then you can reposition the rect to be centered on the images top-left corner like this:
image.on("scaleXChange scaleYChange",function(){
    var imgX=this.x()-this.offsetX()*this.scaleX();
    var imgY=this.y()-this.offsetY()*this.scaleY();
    rect.position({x:imgX-rect.width()/2,y:imgY-rect.height()/2});
})

Here's a Demo:  http://jsfiddle.net/m1erickson/6H9aK/

A: Do this instead to apply the scaling to both x and y axes at the same time, rather than scaling one first, then the other:
rect.scale({x:0.5,y:0.5});


text:
Q: Pulling a table out of a mess of HTML w/ VBA & Excel 'get the table based on the table's id
Set ieDoc = ieApp.Document
Set ieTable = ieDoc.all.Item("contentBody")

'copy the tables html to the clipboard and paste to teh sheet
If Not ieTable Is Nothing Then
    Set clip = New DataObject
    clip.SetText "
" & ieTable.innerHTML & "
"
    clip.PutInClipboard
    Sheet1.Select
    Sheet1.Range("A1").Select
    Sheet1.PasteSpecial "Unicode Text"
End If

I've played with the code above and know there's a better way.  the "contentBody" includes:

Base Statistics

All I want out of this is the table that is

But because of my lack of knowledge I'm not sure where to start trimming out the excess or if I should try another approach.
For this example the navigation, search and breadcrumb from the website gets pulled into my worksheet.  I've grabbed data before using HTML tags, but only pieces of data and never an entire table and I'm currently left here just shrugging.

A: Basically you can get items by tag name., like described in this link: http://www.vbaexpress.com/forum/showthread.php?t=31831
Dim HTMLdoc As HTMLDocument
Dim TDelements As IHTMLElementCollection

Set HTMLdoc = ieApp.Document
Set TDelements = HTMLdoc.getElementsByTagName("table")

And if you want, you can enumerate through the items:
Dim TDelement As HTMLTableCell
For Each TDelement In TDelements
    'code-code-code-code-code
Next


text:
Q: JS: Javascript validation not working Here is js fiddle
I have done many validation but this time not working i dont know how please help me..
HTML
<form action="" method="post" name="contactformm" onsubmit="return valiadd()">

                                Name
                                <input type='text' name='namee' class='form-control' />

                                <input type='submit' class='btn btn-primary' value='Submit' />

                </form>

Javascript code
function valiadd {
var name = document.contactformm.namee.value;
     if(name==""){
         alert('Please Fill Your Name');
         document.contactformm.namee.focus();
         return false;
     }

     else {
        return true;
     }

 }

A: you just forgot to add brackets after your function name
just change this line :
function valiadd {

with
function valiadd() {

A: You forgot the parentheses in the function, Use the chrome console to detect errors
function valiadd (){
var name = document.contactformm.namee.value;
     if(name==""){
         alert('Please Fill Your Name');
         document.contactformm.namee.focus();
         return false;
     }
        return true;
 }

A: You haven't put braces after function name.
Working fiddle https://jsfiddle.net/55qgqhvz/1/
function valiadd() {
 var name = document.contactformm.namee.value;
 if(name==""){
     alert('Please Fill Your Name');
     document.contactformm.namee.focus();
     return false;
 }

 else {
    return true;
 }

}


text:
Q: performance issue caused by IO? Just curious to get an issue sanity checked  . . .
I'm trying to ascertain whether a performance issue experienced by users is the result of the app, server it sits on or SQL Server.
Looking at perfmon I can see very high Avg. Disk Write Queue. Looking at SQL   ASYNC_IO_COMPLETION and OLEDB are featuring as the more prominent waittypes. These suggest to me that SQL isn't the defining factor in the poor performance.
The presence of CXPACKET waittypes was high, this I believe is the result of parallelism being enabled and high fragmentation of the underlying indexes couple with out of date statistics.
What do others think? What other steps can I take to prove (or disprove) my theory that the disk is slow.
Thanks !

A: There's a few different questions in here:
Q: "Looking at perfmon I can see very high Avg. Disk Write Queue."
That Perfmon counter isn't relevant for SQL Server anymore. SQL Server batches IO operations together, and it's normal to see big jumps here. Instead, check out the counters for Avg Disk Sec/Read and sec/Write. This tells you how fast the storage is responding to your requests. The downside is that it's only at the drive (volume, mount point) level. To get IO stats for specific files, query sys.dm_io_virtual_file_stats. David Pless has a great query here:
Link
Q: "Looking at SQL ASYNC_IO_COMPLETION and OLEDB are featuring as the more prominent waittypes. These suggest to me that SQL isn't the defining factor in the poor performance."
ASYNC_IO_COMPLETION is typically data file writes that happen in the background, asynchronously. When you insert/update/delete stuff, SQL Server has to get the data into the log file immediately - that's WRITELOG waits. It changes the data pages in memory, and then those get cached until later. ASYNC_IO_COMPLETION waits aren't holding up end users. It can indicate slow drive performance for data file writes, but that's a system bottleneck, not an end-user-facing bottleneck.
In my experience, OLEDB is usually caused by performance monitoring tools like Spotlight, SQL Sentry, Idera SQL DM, etc that are running traces and grabbing performance data over the wire.
Q: What do others think? What other steps can I take to prove (or disprove) my theory that the disk is slow.
I've got a video on how to do that here:
http://www.brentozar.com/archive/2011/08/how-prove-its-san-problem-webcast-video/
Short story - IO is probably not your biggest problem based on what you described here.


text:
Q: Sending notification when update event occurs I could swear my code was working until now. I am observing an Item model and want to send an email notification anytime the status column is udpdate and it is set to loaded. To do this I am using the isDirty() method but my code doesn't seem to work as no mail is sent. Here's my code
use App\Notifications\ItemAlert;
use App\User;
use App\Item;

class ItemObserver
{
    public function updated(Item $item)
    {
        // check if product status was updated to loaded
        if ($item->isDirty('status' === 'Loaded')) {

            // notify all users
            $users = User::all();

            foreach ($users as $user) {
                $user->notify(new ItemAlert($user, $item));
            }
        }
    }
}

I need help to get this working.

A: Solved! Apparently isDirty() need a second condition to check which was missing. The correct code was meant to be
public function updated(Item $item)
    {
        // check if product status was updated to loaded
        if ($item->isDirty('status' === 'Loaded') && ($item->status === 'Loaded')) {

            // notify all users
            $users = User::all();

            foreach ($users as $user) {
                $user->notify(new ItemAlert($user, $item));
            }
        }
    }

I hope this helps whoever comes across this solution.


text:
Q: Passing a classname using variable I tried to search this but didn't get the workable solution, I am newbie in Jquery, I was creating multiple choice quiz and I want to disable the radio button for one question once user selects one answer for that I am giving same class name to each input and when I am using the classname in below code I am getting desired result. if class name is q1.
$(document).ready(function(){
           $(".q1 :input").prop("disabled", true);
          });

I want to do this for multiple questions so when I am trying to pass the class name through a variable.
var val1 = $("input[type='radio']:checked").attr('class');

I get the name of class in variable val1 but not sure how to use it in jquery for the above code to work.
Could somebody please help me.  I tried many solutions on the net but nothing worked.

A: If you want to disable all input elements with the classname val1 you can do it like this:
$("." + val1).prop("disabled", true);

Example:

$(document).ready(function() {
  $("input").on("click", function() {
    var val1 = $(this).attr('class');
    $("." + val1).prop("disabled", true);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" class="q1"/>Answer 1
<input type="radio" class="q1"/>Answer 2
<input type="radio" class="q1"/>Answer 3<br>
<input type="radio" class="r1"/>Answer 1
<input type="radio" class="r1"/>Answer 2
<input type="radio" class="r1"/>Answer 3


text:
Q: Get the rolling SUM of one column and bring the result in SQL I have a table with 3 columns:
ID   date           Amount
---------------------------
0    2019-01-25        500
3    2019-02-25       -200
4    2019-02-28        700
5    2019-02-28       -300

I want a query that returns the rolling total of the Amount column in an additional column:
ID   date           Amount     total amount
--------------------------------------------
0    2019-01-25        500              500
3    2019-02-25       -200              300
4    2019-02-28        700             1000
5    2019-02-28       -300              700

This is my query:
   SELECT
       ID,
       TrDate,
       Amount,
       SUM(CONVERT(FLOAT, [Amount])) AS 'total amount'
   FROM
       [Transactions]

A: Use window function SUM(...) OVER(...):
SELECT *, SUM(Amount) OVER(ORDER BY id) total_amount FROM mytable;

Demo on DB Fiddle:
<pre>
ID | date                | Amount | total_amount
-: | :------------------ | -----: | -----------:
 0 | 25/01/2019 00:00:00 |    500 |          500
 3 | 25/02/2019 00:00:00 |   -200 |          300
 4 | 28/02/2019 00:00:00 |    700 |         1000
 5 | 28/02/2019 00:00:00 |   -300 |          700
</pre>

NB : if your version of SQLServer does not support window functions, then you can self-join the table and use aggregation:
SELECT t.id, t.date, t.amount, SUM(t1.amount) total_amount
FROM mytable t
INNER JOIN mytable t1 ON t1.id <= t.id
GROUP BY t.id, t.date, t.amount


text:
Q: C# data reader value repeats multiple times while debugging I am reading data from the SQL server table and inserting the same value in the PostgreSQL\SQL database table. It's a data migration process.
The issue is that the data in the SQL is plain text but I see it in the debugging it shows the same value multiple times in watch (visual studio 2015).
Value displays in SQL server as below:

Data shows in the visual studio debugger:

All migration process works fine but the only table having these type of value does not insert in the PostgreSQL\SQL and will throw an exception.
Exception:
{"22021: invalid byte sequence for encoding \"UTF8\": 0x00"}

Stacktrace:

I don't understand the exact problem here. Can anyone please help me understand the cause and solution to the above issue?

A: I suspect what whatever's displaying the value in SQL Server is just stopping at Unicode code point 0 (U+0000), which is what Windows controls do by default. It looks like Postgres simply doesn't accept that.
I believe you should:

*

*Try to work out why you've got the value like that in SQL Server to start with. (It could well be a bug in whatever code is doing the insert.)

*Determine what you want the data to be. If you actually need the data after U+0000, you'll need to work out whether that means more rows, a different separator etc.

*Either fix the data in SQL Server (e.g. by truncating before the U+0000 in every field) or perform the truncation as part of the migration (depending on how you're doing the migration).


text:
Q: How to handle session in facebook ios sdk Hi I'm working on an app. In the app is possible to sing-in with facebook or not... And in several places of the app you can share stuff on you own timeline.
I followed the scrumptious example that facebook provides, and the log-in is working fine... But when I have to share stuff, I don't know if it's necessary or not to check if the session is active before calling the FBRequestConnection method to post to fb.
What's the best way to handle this? Because all the authentication is made calling an open session method in the delegate so... I have to call this methods from anywhere in the app? How do I go back to the place where I was before calling the authentication method... I'm sure there must be some kind of patron to use, but I can't find which one...
Any idea?
thanks!

A: Use a block of code like this to make sure that the session is open, which is important because if the user isn't, your app will crash. And then you need to have you OpenGraph objects within the FBRequestConnection.
    if (FBSession.activeSession.isOpen) {
        [[FBRequest requestForMe] startWithCompletionHandler:
         ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
             if (!error) {
                 self.nameString = user.name;
                 self.profileImage.profileID = user.id;
                 self.userName = user.username;
                 [self.tableView reloadData];
             }
         }];
    }
}

** For your comment below: **
Okay, then perhaps bring up a UIAlertView asking the user to log into Facebook. If they select yes, then do something like
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
[appDelegate openSessionWithAllowLoginUI:YES];

assuming that your AppDelegate looks like Scrumptious.


text:
Q: Jquery traversing a table (Error: Not a function) $(function(){
  $('.swaction').click(function(event){
    var num = $(this).parent().parent().children().first().children.first().val();
    alert(num);
    event.preventDefault();
  });
})

      Nombre de archivo
      Fecha de creación
      Acciones

   12313242122333
   07/06/2013 10:52:52
   Ver |
       Renombrar |
       Eliminar

I want to get this number: 12313242122333
I tried this: var num =

$(this).parent().parent().children().first().children.first().val();

but Firebug says it's not a function. Any clue on what is wrong? This is the first time I try to traverse the tree.
Thanks!
Error:
TypeError: $(...).parent(...).parent(...).children(...).first(...).children.first is not a function
http://192.168.100.196/printbox/js/js_procesar_escaneos.js
Line 3

A: Use var num = $(this).closest('tr').find('td:first').html(); instead.
jsFiddle example
.val() is for input elements, you want to get the HTML which you'd use .html() for.

A: You can't use .val() on td element, it's for form element. try .text()
$(this).parent().parent().children().first().text();

A: children.first()

You're trying to call the first() method of the children function.
You need to call the children function using parentheses.

A: $(this).closest('tr').find('td:first').html();

Try this.
Use html instead of val


text:
Q: pyproj conversion UTM to lat/long out by 3 deg I am reading UTM point data from a shape file.  The geopandas CRS string associated with the shape file is:
PROJCS["WGS 84 / Falk",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-60],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",10000000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH]]

I convert the point data to lat/long using pyproj:
projn = pyproj.Proj('+proj=utm +zone=21 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs +lon_0=-60')
ylon, ylat = projn(utm_e, utm_n, inverse=True)

This gives me the correct latitude but the longitude is exactly 3 degrees out.  I changed the UTM zone to utm=+20 but now am 3 degress out in the other direction.   I also tried setting the false easting with x_0=500000 and the central longitude with lon_0=-60 but that made no difference.  Finally, I tried setting a projection system using one of the EPSG settings in the CRS string eg
projn = pyproj.CRS.from_epsg(6326)

but that gave the error message CRSError: Invalid projection: epsg:6326: (Internal Proj Error: proj_create: crs not found).  Would appreciate any suggestions as I am new to GIS and finding it difficult to understand projections. An illustration of the problem is shown below:
import pyproj

# Define points to process

well_dict = {}
well_dict['14/09-1']  = [-59.384869, -49.319319, 544706.1998681703, 4536872.299629836]
well_dict['14/09-2']  = [-59.349633, -49.247411, 547331.1995800878, 4544831.399531693]
well_dict['14/10-1']  = [-59.176736, -49.275033, 559882.9998544991, 4541663.299837932]
well_dict['14/13-1']  = [-59.496483, -49.417692, 536519.4998223917, 4525987.899903225]
well_dict['14/05-1A'] = [-59.177950, -49.162275, 559930.8995227005, 4554179.299983081]
well_dict['14/24-1']  = [-59.297611, -49.812692, 550533.2498328319, 4481958.129964017]

# Define projections

projns = {}
projns['base'] = pyproj.Proj('+proj=utm +zone=21 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs +lon_0=-60')
projns['6326'] = pyproj.CRS.from_epsg(6326) #FIXME: gives CRSerror
# projns['6326'] = pyproj.Proj('epsg:6326')
# projns['7030'] = pyproj.Proj('epsg:7030')
# projns['9001'] = pyproj.Proj('epsg:9001')

# Convert UTMs for each well to lat/long using each projection

for well in well_dict:
    xlon, xlat, utm_e, utm_n = well_dict[well]
    print("%-9s  %10.2f %10.2f  %7.3f %7.3f" % (well, utm_e, utm_n, xlat, xlon), end='')

    for pname in projns:
        projn = projns[pname]
        ylon, ylat = projn(utm_e, utm_n, inverse=True)
        print("  %7.3f %7.3f" % (ylat, ylon), end='')

    print("")

EDIT:
After further investigation I found that I should have been using the Transverse Mercator projection, not Universal Transverse Mercator.  If I use:
projns['tmerc'] = pyproj.Proj('+proj=tmerc +lat_0=0 +lon_0=-60 +k=0.9996 +x_0=500000 +y_0=10000000 +datum=WGS84 +units=m +no_defs')

then the points plot in the correct position.

A: Recommendations:

*

*Use Transformer (https://pyproj4.github.io/pyproj/stable/gotchas.html#upgrading-to-pyproj-2-from-pyproj-1)

*The WKT can be used as input directly

import pyproj

wkt = 'PROJCS["WGS 84 / Falk",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",-60],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",10000000],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["Easting",EAST],AXIS["Northing",NORTH]]'
transformer = pyproj.Transformer.from_crs(wkt, "EPSG:4326", always_xy=True)
# Define points to process

well_dict = {}
well_dict['14/09-1']  = [-59.384869, -49.319319, 544706.1998681703, 4536872.299629836]
well_dict['14/09-2']  = [-59.349633, -49.247411, 547331.1995800878, 4544831.399531693]
well_dict['14/10-1']  = [-59.176736, -49.275033, 559882.9998544991, 4541663.299837932]
well_dict['14/13-1']  = [-59.496483, -49.417692, 536519.4998223917, 4525987.899903225]
well_dict['14/05-1A'] = [-59.177950, -49.162275, 559930.8995227005, 4554179.299983081]
well_dict['14/24-1']  = [-59.297611, -49.812692, 550533.2498328319, 4481958.129964017]

# Define projections

# Convert UTMs for each well to lat/long using each projection

for well in well_dict:
    xlon, xlat, utm_e, utm_n = well_dict[well]
    print("%-9s  %10.2f %10.2f  %7.3f %7.3f" % (well, utm_e, utm_n, xlat, xlon), end='')
    ylon, ylat = transformer.transform(utm_e, utm_n)
    print("  %7.3f %7.3f" % (ylat, ylon))

Output:
14/09-1     544706.20 4536872.30  -49.319 -59.385  -49.319 -59.385
14/09-2     547331.20 4544831.40  -49.247 -59.350  -49.247 -59.350
14/10-1     559883.00 4541663.30  -49.275 -59.177  -49.275 -59.177
14/13-1     536519.50 4525987.90  -49.418 -59.496  -49.418 -59.496
14/05-1A    559930.90 4554179.30  -49.162 -59.178  -49.162 -59.178
14/24-1     550533.25 4481958.13  -49.813 -59.298  -49.813 -59.298


text:
Q: How to rewrite the name of key of object in ngFor I have an object like this

What I want to do is show count at specific time.
For now, I have this code and it works fine
  <mat-card *ngFor="let room of roomList; let i = index">
    <mat-card-content>

Room Number: {{room.staticData.rName}}

{{room.occupation[0].timetable.at17.count}}

    </mat-card-content>
  </mat-card>

What I would like to do is to rewrite the line in the p tag room.occupation[0].timetable.at17.count, because at17 is hardcoded right now.
I want to assign variable in my component, a value of variable hour I become from server (it works too) and then I concat it to "at" and assign the whole to this.time
this.time = 'at'++this.hour;

So, would I would like to have is

{{room.occupation[0].timetable.time.count}}

But it doesn't work...
How could I solve this?

A: You should be using it as below,
<mat-card *ngFor="let room of roomList; let i = index">
    <mat-card-content>

Room Number: {{room.staticData.rName}}

{{room.occupation[0].timetable['at'+i].count}}

    </mat-card-content>
  </mat-card>


text:
Q: Not get duplicates in math random I want my index to be a random number that is equal to my questions. I have a list of 33 questions which is indexed from 0-32. I have this idea that I will get random questions everytime with help of my index. This works but I still get duplicates. How do I prevent this?
 @if (questionIndex23 < 10)
        {
            <div class="app-title">
                @Questions[kuken].Category
            </div>

Here I get a random category from my list "question" with help of my index.
public void Hannes()
    {
        Random slump = new Random();
        kuken = slump.Next(1, 32);
    }

This is the method I've written to get random numbers for my index.

A: Shuffle your questions
Random slump = new Random();
Questions = Questions.OrderBy(_ => slump.Next()).ToList();

before displaying them
@foreach(var question in Questions)
{
    < div class="app-title">
        @question.Category
    </div>


text:
Q: Using jQuery, is there a way to set a string equal to itself but with some modification? $('p').text($('p').text().replace('string A', 'string B'));

Looking for a simpler way of doing this. Is there a way to pull and redeclare a string in the same method?

A: You can pass a function to $.text instead of a manual value. That function will receive the old value as one of the arguments. Just return whatever you'd like the new value to be from the function.

$('p').text(function(index, text) {
  return text.replace('Hello', 'Good day');
});

Hello, World!


text:
Q: Can't install python module timeloop on OS X 10.3.7 with Python 2.7.7 I am using an old Mac Mini without internet connection, with OS X 10.3.7 and Python 2.7.7,
and cannot install timeloop with "python setup.py install".
Should timeloop principally work on this system?
Is there maybe any other way to get it work on this rather old machine?
Please don't recommend me to use a newer system: It's a project and I need to use this computer.
I would appreciate your help very much.
what I get is this: Do you see any error message which could help?
$ python setup.py install
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'long_description_content_type'
  warnings.warn(msg)
running install
running bdist_egg
running egg_info
writing timeloop.egg-info/PKG-INFO
writing top-level names to timeloop.egg-info/top_level.txt
writing dependency_links to timeloop.egg-info/dependency_links.txt
reading manifest file 'timeloop.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'timeloop.egg-info/SOURCES.txt'
installing library code to build/bdist.macosx-10.3-ppc/egg
running install_lib
running build_py
creating build/bdist.macosx-10.3-ppc/egg
creating build/bdist.macosx-10.3-ppc/egg/timeloop
copying build/lib/timeloop/exceptions.py -> build/bdist.macosx-10.3-ppc/egg/timeloop
byte-compiling build/bdist.macosx-10.3-ppc/egg/timeloop/exceptions.py to exceptions.pyc
creating build/bdist.macosx-10.3-ppc/egg/EGG-INFO
copying timeloop.egg-info/PKG-INFO -> build/bdist.macosx-10.3-ppc/egg/EGG-INFO
copying timeloop.egg-info/SOURCES.TXT -> build/bdist.macosx-10.3-ppc/egg/EGG-INFO
copying timeloop.egg-info/dependency_links.txt -> build/bdist.macosx-10.3-ppc/egg/EGG-INFO
copying timeloop.egg-info/top_level.txt -> build/bdist.macosx-10.3-ppc/egg/EGG-INFO
zip_safe flag not set; analyzing archive contents...
creating 'dist/timeloop-1.0.2-py2.7.egg' and adding 'build/bdist.macosx-10.3-ppc/egg' to it
removing 'build/bdist.macosx-10.3-ppc/egg' (and everything under it)
Processing timeloop-1.0.2-py2.7.egg
Removing /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/timeloop-1.0.2-py2.7.egg
Copying timeloop-1.0.2-py2.7.egg to /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
Removing timeloop 1.0 from easy-install.pth file
Adding timeloop 1.0.2 to easy-install.pth file

Installed /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/timeloop-1.0.2-py2.7.egg
Processing dependencies for timeloop==1.0.2
Finished processing dependencies for timeloop==1.0.2


text:
Q: @Enumerated(EnumType.STRING) is not working in play. it is still saving integer in Db Code was working file till last month but suddenly after it is throwing error in reading string via DB (for Enum) and it is saving them as int.
Col of Enum in DB is set as varchar(255).
and this problem is occurring for only on one class other class are working fine.
this is code part
@Enumerated(EnumType.STRING)
    private Addr addr;

This is db setting.
addr |varchar(255) | NO | NULL


text:
Q: Guidelines to generate Authorization Code for Credit Card transactions I'm working on a module that will receive the messages in a custom format with all the information required to process the request (Purchase, Cash Disbursement, Balance Inquiry), so in order to compose the response, i have to generate the authorization code (Field 38 - ISO8583), only if the transaction was processed sucessfully.
As i know, it doesn't have to be unique, but i don't know if any other values from the transaction must be used to generate it.
Any advice will be appreciated.

A: I've only ever seen the provider generate the code, its then passed through the middleman (you in this case) and on to the consumer.
I don't think this would be bad practice. It would be one number that you could use to identify the whole series of transactions.


text:
Q: What does "Insufficient system resources..." error mean? This question spans both serverfault and stackoverflow so I just picked this one.
I get the following exception with some simple file copy code.  Its running on Windows Server 2003 x64
Caused by: java.io.IOException: Insufficient system resources exist to complete the requested service
at sun.nio.ch.FileDispatcher.pwrite0(Native Method)
at sun.nio.ch.FileDispatcher.pwrite(Unknown Source)
at sun.nio.ch.IOUtil.writeFromNativeBuffer(Unknown Source)
at sun.nio.ch.IOUtil.write(Unknown Source)
at sun.nio.ch.FileChannelImpl.write(Unknown Source)
at sun.nio.ch.FileChannelImpl.transferFromFileChannel(Unknown Source)
at sun.nio.ch.FileChannelImpl.transferFrom(Unknown Source)
at Tools.copy(Tools.java:473)

public static void copy(FileChannel input, FileChannel output) throws IOException {
    final long size = input.size();
    long pos = 0;
    while (pos < size) {
        final long count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos);
        pos += output.transferFrom(input, pos, count);
    }
}

The thing is the server that is running this code is brand new and super powerful, so I don't understand what system resource it could possibly be running out of.
This looks like the error described here:
http://support.microsoft.com/kb/304101
But I've tried adding the registry edits to increase kernel memory page size, and that didn't help.
What I really don't get is I've seen code that uses FileChannel transferFrom with a lot larger chunks of 50 MB.  I've seen that code work for files well over 1 GB in one chunk.  But the file the server is getting stuck on is just 32 MB!
What is going on here?  Is this a problem with FileChannel or Windows?

A: It may be related to "Bug" ID 4938442: Insufficient System Resources When Copying Large Files with NIO FileChannels.

Evaluation: Not a bug.  This is most likely a file-server (or possibly client)
  configuration issue.
CUSTOMER SUBMITTED WORKAROUND :

*

*Don't use NIO; we'd prefer to avoid this workaround since
  NIO offers a significant performance boost for large files
  (at least when performing local disk-to-local disk copies)

*We can transfer using a smaller number of bytes.  The
  actual number of bytes that may be copied without
  encountering this error seems to differ on Windows XP and
  Windows 2000 server.  Certainly a value of 32Mb appears to
  work.


text:
Q: How to get gmail mails subject in android? I want to control e-mails subjects of spesific people who send mail me. I found some code about it but i don't know how i control subjects of e-mails. Is there anyone to know how can i achieve this? Thanks. Here is the code.
Properties props = new Properties();
//IMAPS protocol
props.setProperty("mail.store.protocol", "imaps");
//Set host address
props.setProperty("mail.imaps.host", imaps.gmail.com);
//Set specified port
props.setProperty("mail.imaps.port", "993″);
//Using SSL
props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imaps.socketFactory.fallback", "false");
//Setting IMAP session
Session imapSession = Session.getInstance(props);

Store store = imapSession.getStore("imaps");
//Connect to server by sending username and password.
//Example mailServer = imap.gmail.com, username = abc, password = abc
store.connect(mailServer, account.username, account.password);
//Get all mails in Inbox Forlder
inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
//Return result to array of message
Message[] result = inbox.getMessages();

A: You did not was looking a friend. You need next:
System.out.println("Subject: " + message.getSubject());


text:
Q: Unit testing a controller with automapper mapping in it I have an asp.net webapi project, in which I have a controller that I want to unit test. In that controller I have a mapping. The controller inherits from a base controller, of which the implementation is:
public class BaseController : ApiController
{
    /// <summary>
    /// AutoMapper Mapper instance to handle all mapping.
    /// </summary>
    protected IMapper GlobalMapper => AutoMapperConfig.Mapper;
}

I now want to unit test the controller. My automapper configuration looks like this:
    public static class AutoMapperConfig
    {
        /// <summary>
        /// Provides access to the AutoMapper configuration.
        /// </summary>
        public static MapperConfiguration MapperConfiguration { get; private set; }

        /// <summary>
        /// Provides access to the instance of the AutoMapper Mapper object to perform mappings.
        /// </summary>
        public static IMapper Mapper { get; private set; }

        /// <summary>
        /// Starts the configuration of the mapping.
        /// </summary>
        public static void Start()
        {
            MapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile<MeldingProfiel>();
                cfg.AddProfile<GebouwProfiel>();
                cfg.AddProfile<AdresProfiel>();
            });

            MapperConfiguration.AssertConfigurationIsValid();

            Mapper = MapperConfiguration.CreateMapper();
        }
    }

How can I unit test the controller that has this automapper mapping in it?

A: My recommendation would be to use Dependency Injection.  Each controller would take a dependency on an IMapper instance, which would be provided by your DI container.  This makes unit testing much easier.
public class MyController : ApiController
{
    private readonly IMapper _mapper;

    public MyController(IMapper mapper)
    {
        _mapper = mapper;
    }
}

Don't use the static AutoMapper instance (e.g. Mapper.Map(...) ) at all.
Here's a sample for getting AutoMapper registered in an Autofac container, which just registers any profiles which have been added to the container.  You won't have to look far to find equivalent samples for any other DI container.
builder.Register<IMapper>(c =>
{
    var profiles = c.Resolve<IEnumerable<Profile>>();
    var config = new MapperConfiguration(cfg =>
    {
        foreach (var profile in profiles)
        {
            cfg.AddProfile(profile);
        }
    });
    return config.CreateMapper();
}).SingleInstance();


text:
Q: SQL server timeouts for some commands for a while just after restoring We have a large web application in asp.net mvc using EF6 and SQL server 2012.
We have two environments: staging and production.
Every time we have a release, we first deploy the exact same code to staging and restore production's db on the server for testing purposes.  That has always worked for us.
Now, when we restore production's db to the staging server we are getting some timeouts on some commands.  What's strange is that after a few hours pass, we stop getting timeouts.

This is the stacktrace of one of the timeouts:
[Win32Exception (0x80004005): The wait operation timed out]

[SqlException (0x80131904): Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
The statement has been terminated.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +388
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +688
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4403
   System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +82
   System.Data.SqlClient.SqlDataReader.get_MetaData() +135
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +6664141
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +6666008
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +577
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +107
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +288
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +180
   Glimpse.Ado.AlternateType.GlimpseDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +847
   System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed) +72
   System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +306
   System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues) +417
   System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() +218

[UpdateException: An error occurred while updating the entries. See the inner exception for details.]
   System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() +537
   System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +627
   System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy) +212
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +263
   System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) +262
   System.Data.Entity.Internal.InternalContext.SaveChanges() +218

[DbUpdateException: An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.]
   System.Data.Entity.Internal.InternalContext.SaveChanges() +291
   *******.Services.DbTransaction.TransactionManager.SaveChanges() in c:\BuildAgent\work\c357fed3de014622\Source\Services\*******.Services\*******.Services\DbTransaction\TransactionManager.cs:28
   System.Web.Mvc.Async.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41() +112
   System.Web.Mvc.Async.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41() +452
   System.Web.Mvc.Async.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41() +452
   System.Web.Mvc.Async.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41() +452
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +15
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +37
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +241
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +19
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +51
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

We have an action filter that calls the context.SaveChanges() method if everything went well on the request (so we don't have to do that manually in every action).  That's why there is no action on the stacktrace, it times out on the SaveChanges() call when the action finished.
There is a lot happening on that request, that's why I'm not showing code, we are doing the usual stuff: updating some rows, inserting new ones, etc.  There are some complex commands in there, but not complex enough for the db to timeout.  And when we run the code on our dev machines with the same production db it runs ok.
The weird thing is that it stops timing out after a few hours.  But we can't risk going to production like that.
Now, I know it's unlikely that you can give me a solution just with the information provided.  But I'd like to know some tips, pointers, advice, where to look, what to check, etc.
Edit
Our server has 12GB of RAM and an Intel Xeon E5-2680 @ 2.80GHz.
Our site is the only thing running there.
Our database is less than 4GB
And we don't get timeout on our dev machines.

A: We finally found what was happening:
We have a seed method that was executed after the migration, that method opened a connection to the database and was also querying some external services that took forever to respond, it kept running for hours and those queries were blocking the insert command.
Thanks to Zdravko's suggestion we were able to find the issue.
We ran exec sp_who2 and found that the insert was being blocked by the seed method's select query.
So, if anyone gets here with a similar problem: what helped us was using the sql profiler and filtering for queries taking longer than 30 sec to find the offending queries and using exec sp_who2 to check if someone is blocking them.

A: Timeouts are most likely due to SQL server rebuilding indexes and other maintenance jobs running after the restore. Those can take significant amount of time on a larger database. Full text search indexes for example take particularly long time to build...


text:
Q: Selenium IDE : How to use pattern checking for a dynamic id using XPath In my website there is a recently uploaded image section.
in this section all recently uploaded images are displayed randomly
using firepath i traced the xpath of that location
//div[@id='udtkbdf50']/a/div[2]/div

so on each time page refresh this  @id='udtkbdf50' value changes ,only one thing is common that is the value is always starting with   u
so i want to use pattern matching technique [regular expression or Globbing Patterns ]
@id='udtkbdf50'  for this value and rest of the path i.e  /a/div[2]/div will remain same.

A: //div[contains(@id,'u')]/a/div[2]/div will work.
UPDATE:
//div[starts-with(@id,'u')]/a/div[2]/div will be more specific.
All d best.


text:
Q: Windows form AximageEdit control event initialization-Mouseup event C sharp In designer i have initialized the mouse up event like below
this.axImgEdit1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.axImgEdit1_MouseUpEvent);
and in code behind , event is written like below.
private void axImgEdit1_MouseUpEvent(object sender, MouseEventArgs e)
but in run time it is throwing error.
event mouse up is not valid on this activeX control
aximageedit also has its own eventargs, but if i write that it throw compile time error like no overload for matches delegate 'system.eventhandler'
how to handle this third party control events in windows form


text:
Q: How to add the commit's description to the discord webhook bot messages? I followed this tutorial to create a Webhook between Github and Discord.
https://support.discordapp.com/hc/en-us/articles/228383668
Everything worked as expected and the bot is updating the chat just fine.
Despite searching in the Docs
( https://discordapp.com/developers/docs/resources/webhook ), I
could not find how to configure the bot so it also displays the commit's description.
I don't really know if this is possible, can someone point me how to handle this?

A: The Discord GitHub webhook does display the first line of the commit which git typically treats as a summary.
The GitHub push webhook publishes a json document containing fields such as head, refs, and a commits array with fields such as message and author.
However, the default Discord webhook expects a simpler json document with just a content field for the message body. This webhook will reject a GitHub push document.
However Discord also provides a special GitHub webhook that understands the payload of the GitHub push webhook. You've set this up but as noted only displays the first line of the commit. There doesn't seem to be any way to customize it.
If you want to display the full commit message, you'll need a custom bot that can receive the GitHub push event, format a new json document in the form expected by the default Discord webhook, and send it to the Discord API.
There is already an app that does this. The developer has abandoned it in favor of the official Discord GitHub webhook but left it running for now. It's easy to integrate and it does display the full commit message. It does require a public GitHub repository however.


text:
Q: Weird outcome of python bitwise operation Anyone could explain? I get really confused by the following outcome. Thanks a lot!
why this doesn't work!???
`i = 2
table[i] = i&1 + table[i>>1] `

the following works
`tmp = i&1
 table[i] = tmp + table[i>>1]`

A: This is because of parens gruopings and & having less precedence: Here's an example of how this works:
2& will not happen until 2+ 2 >> 2
In [569]: 2&2 + 2>>2
Out[569]: 0

Here we use the and in parens first, before adding to 2>>2
In [570]: (2&2) + 2>>2
Out[570]: 1

Here's what the operator precedence looks like for the original operation:
In [571]: 2&(2 + 2>>2)
Out[571]: 0


text:
Q: Why my safe rust code triggers segmentation fault? My safe rust code is listed below:
use std::mem::size_of;

const ROWS_PER_PAGE: usize = PAGE_SIZE / ROW_SIZE;
const TABLE_MAX_ROWS: usize = TABLE_MAX_PAGES * ROWS_PER_PAGE;
const ROW_SIZE: usize = ID_SIZE + USERNAME_SIZE + EMAIL_SIZE;
const TABLE_MAX_PAGES: usize = 100;
const PAGE_SIZE: usize = 4096;
const ID_SIZE: usize = size_of::<u64>();
const USERNAME_SIZE: usize = 32;
const EMAIL_SIZE: usize = 255;

#[derive(Clone, Copy, Debug)]
pub struct Page {
    buffer: [u8; PAGE_SIZE],
}
pub struct Table {
    pub pages: [Option<Page>; TABLE_MAX_ROWS],
    pub num_rows: usize,
}

impl Table {
    pub fn new() -> Self {
        Self {
            pages: [None; TABLE_MAX_ROWS],
            num_rows: 0,
        }
    }
}

fn main() {
    println!("{}", ROW_SIZE);
    let table = Table::new();
    println!("{:p}", &table);
}

Every line in the piece seems like ordinary, but on my MacBook Pro it crashed with 'Segmentation fault'.
$ cargo r
    Finished dev [unoptimized + debuginfo] target(s) in 0.07s
    Running `target/debug/segfault`
295
[1]    68684 segmentation fault
$ rustup show  active-toolchain
nightly-aarch64-apple-darwin (default)

Stranger still, when I copy-paste the code piece into Rust Playground, It said 'Stack overflow'. Where is the cause?
   Compiling playground v0.0.1 (/playground)
   Finished dev [unoptimized + debuginfo] target(s) in 0.82s
   Running `target/debug/playground`

thread 'main' has overflowed its stack
fatal runtime error: stack overflow
timeout: the monitored command dumped core
/playground/tools/entrypoint.sh: line 11:     8 Aborted                 timeout --signal=KILL ${timeout} "$@"

A: Your Table struct is over 5 MB large (TABLE_MAX_ROWS is 1300, Page is 4096 bytes large, so Option<Page> is 4097 bytes, so total size is 5326100 bytes plus 8 for num_rows).
You try to allocate one on the stack. You can't do that, the stack isn't this large. The segmentation fault you get is the attempt to access beyond the bounds of the stack.
You'll want to put some of that on the heap. Probably all of it, though beware that it can be a bit tricky in Rust to create a huge object on the heap (especially in debug mode, the compiler might want to create it on the stack first and copy it over).

A: The playground error is actually describing the same problem as the error from MacOS, but more specifically - the "stack", the memory space reserved for function-local variables that are not static (namely, table) has been filed up. This results in a segfault because the program tries to use more memory regardless, and so steps into pages it doesn't have access to. The OS limits how large the stack can be to much smaller than the total memory capacity, often as little as 1MB, although this is configurable.
So table is allocated on the stack because it is a local variable of main. table in turn is so huge because each Option<Page> (i.e. a flag denoting whether it is present, followed by a whole Page) within the array is laid out directly next to each other in memory, with no indirection or separate allocations as you might be used to in other languages. Within Page, all 4096 u8s are contiguous, and all of the ~1400 (if I did the math right) Pages are contiguous in Table, which means that when you construct a Table, the resulting value is (slightly over) 1400*4096 = 5.46MB of contiguous data. Which you then try to put in a memory region (the stack) much too small for it.
To get around this, you can use Box<Table> instead so that the table's data is instead allocated on the heap, which is allowed to grow basically as large as hardware permits. You may also have to compile your program with --release, because otherwise the table will temporarily exist on the stack when you construct it before placing it in the box, which causes the same problem.
That said, your Table looks suspiciously like it's supposed to be a dynamically-sized array of Pages, in which case you can simply use Vec<Page> which will not only do the same thing, but avoids the problem entirely because Vec puts its items on the heap implicitly.

A: The problem is that your code is trying to put too much data on the stack, causing the stack to overflow. On some platforms a stack overflow will cause a segmentation fault.
The solution is to put the data on the heap:
pub struct Table {
    pub pages: Vec<Option<Page>>,
    pub num_rows: usize,
}

impl Table {
    pub fn new() -> Self {
        Self {
            pages: vec![None; TABLE_MAX_ROWS],
            num_rows: 0,
        }
    }
}

With this change, the code runs in the playgound.


text:
Q: RabbitMQ scheduled message and revoke feature Is it possible to schedule a message using RabbitMQ and also remove the message (which is scheduled to be processed) when certain conditions are met?
We have a requirement where we need to call a external service to get some data. The call is asynchronous. The client calls the API endpoint of the server mentioning the data that it needs. The server just responds back with a acknowledgement that it has received the request from client. Internally the server also starts processing the client request and it will call the client API endpoint with the actual response to the query it received sometime back from the client.
There is a time limit (30sec) till the client needs to wait to get the response from the server. If the client receives response within 30sec then it will proceed with the execution. Even if the client does not receives response from the server in 30sec, it will proceed with other steps.
There are thousands of independent transactions (request and response) happening each second between the client and server. How can the client keep a track of the requests and and response received in the most effective way using RabbitMQ.
Can the RabbitMQ plugin rabbitmq_delayed_message_exchange used for this scenario in which the client will push new messages in a queue along with x-delay header (30sec)? How can the scheduled message be removed from the queue in case the client receives the response from server before 30sec?

A: I'd do the following:

*

*Make the response go through RabbitMQ too (using RPC)

*Make sure that the name of the response queue is also sent as a parameter that is used to route it by some exchange policy (routing key or use header exchange)

*Set up a DLX exchange with the correct policy for 2.

*Set a 30s TTL in the client->server queue

How'd this work in the usual case?

*

*Client creates the reply-to queue

*Client sends the request to the server

*Client consumes from the reply-to queue

*Server consumes the message and posts the response to the reply-to queue

What'd happen with a timeout?

*

*Client creates the reply-to queue

*Client sends the request to the server

*Client consumes from the reply-to queue

*Request message TTL triggers

*RMQ deadletters the request message to the reply-to queue

*Client receives its own request instead of the response


text:
Q: mxnet: how to retrieve the number of example from the DataIter object? After using the mx.io.ImageRecordIter() to load my training examples, is there a way to retrieve the total number of examples from the returned DataIter object ?
Many thanks,

A: Length of the iterator is unknown until you iterate through it.
You could iterate through and count the number of examples but depending on the data set size, this could be a time consuming operation.


text:
Q: How to create a randomly sized list of randomly generated numbers in Haskell I'm new to haskell and I've been trying to figure out this problem for a while now.  I want to generate a list of a random size using randomRIO and have that list be populated with random numbers using randomIO.  I have tried to approach this problem by creating a function which takes in the randomly generated from randomRIO like so:
x <- randomRIO(1,5)
let y = randList x []

the function itself is something like this:
randList :: Int -> IO [Int] -> IO [Int]
randList 0 xs = return [xs]
randList g xs = do
            t <- randomIO
            let a = t:randList (g-1) xs
            return [a]

I'm not sure how to handle the monad IO in a recursive function but this is how I'm thinking of it.  Any help is appreciated thanks!

A: You can use replicateM to repeatedly execute randomIO, generating a new number each time. You call randomRIO once up front to decide on the length of the list:
import Control.Monad (replicateM)
import System.Random (randomIO, randomRIO)

randList :: IO [Int]
randList = do
  len <- randomRIO (1,5)
  replicateM len randomIO

Now, your definition wasn't actually very far off. A couple of things though:

*

*Given that you expect to be able to call randList x [], the second argument of randList clearly is a plain list. Not an IO action of some sort. So your type should be
randList :: Int -> [Int] -> IO [Int]

*In your first pattern match
randList 0 xs = return [xs]

Remember that xs is already a list. So when you do return [xs] you will get an IO [[Int]], a list of lists. What you want here is a plain return xs.

*In your second definition
randList g xs = do
    t <- randomIO
    let a = t:randList (g-1) xs
    return [a]

The expression t:randList ... makes no sense. The right-hand side of : must be a list. randList does not yield a list though, it yields an IO action. What you actually want to do is to treat the second argument of randList (the list) as an "accumulator", which is gradually built up. So you want to generate a number, add it to the accumulator, and then recurse with g decreased by one:
randList g xs = do
    t <- randomIO
    randList (g-1) (t:xs)


text:
Q: Apache.NMS.AMQP 2.0.0 library when publishing is throwing org.apache.qpid.proton.amqp.UnsignedByte cannot be cast to java.lang.byte error I am using Apache.NMS.AMQP library in our .netcore 5 project. We connect to Apache ActiveMQ Artemis as a middle layer for the event driven architecture using AMQP protocol.
There is no issue in consuming messages from the same amqp protocol; but when publishing to a topic, we are getting some errors.
broker URI:
 failover:(amqp://localhost:5672)?transport.startupMaxReconnectAttempts=1&transport.randomize=false
Code:
var _factory = new Apache.NMS.AMQP.ConnectionFactory(_connectURI);

IConnection connection = _factory.CreateConnection(username,password);
ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);

ITextMessage msg = session.CreateTextMessage(stringMessage);
var topicDestination = SessionUtil.GetTopic(session, topic);
connection.Start();`

IMessageProducer publisher = session.CreateProducer(topicDestination);
publisher.DeliveryMode = MsgDeliveryMode.Persistent;
publisher.Send(msg);

Error that I'm getting:

Message ID: xxxx:2:1:1-1 rejected, Description = org.apache.qpid.proton.amqp.UnsignedByte cannot be cast to java.lang.byte

I tried several combinations of sending the same from different methods, added Apache.NMS library on top of it as well. But still no luck.
Anyone have come across this issue?

A: I have used amq broker 7.10 and the issue is sorted in the broker.


text:
Q: Define Extension function on GETx I am trying to define an extension function on GetInterface as
extension FindOrPut on GetInterface {
  S findOrPut<S>(S dependency,{String? tag}){
    if(GetInstance().isRegistered<S>(tag: tag)){
      return GetInstance().find<S>(tag: tag);
    }
    return GetInstance().put<S>(dependency,tag: tag);
  }
}

Which is same as the extension Inst on GetInterface developed by the GETx team. But my code is not working as expected.
Note: If I put the extension function code in the same file where it will be used; It works fine. But if I put the above code in the separate file function not found on Get.

A: I created the FindOrPut extension on GetInterface. Please check the below code it is working fine.
import 'package:amigo/src/controllers/test_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

extension FindOrPut on GetInterface {
  S findOrPut<S>(
    S dependency, {
    String? tag,
    bool permanent = false,
    InstanceBuilderCallback<S>? builder,
  }) {
    if (GetInstance().isRegistered<S>(tag: tag)) {
      return GetInstance().find<S>(tag: tag);
    }
    return GetInstance().put<S>(dependency, tag: tag, permanent: permanent);
  }
}

class ExtensionTesting extends StatelessWidget {
  ExtensionTesting({Key? key}) : super(key: key);

  //TODO: Include your getx controller here with findOrPut function
  final TestController _testController = Get.findOrPut(TestController());

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white30,
      child: Obx(() => Text(_testController.name.value)),
    );
  }
}

For working code please check the extension_method_implementation repo.


text:
Q: Reading excel using Apache POI I am reading .xls and .xlsx using Apache POI through Java.
I have included below jars to my classpath:
 1. poi-3.7-20101029.jar
 2. poi-examples-3.7-20101029.jar
 3. poi-ooxml-3.7-20101029.jar
 4. poi-ooxml-schemas-3.7-20101029.jar
 5. poi-scratchpad-3.7-20101029.jar

Are all jars required to read/write data from/to xls/xlsx files? I think I can exclude poi-examples-3.7-20101029.jar as the name suggests it contains examples. I tried that and it works (I am able read from xls/xlsx). What is the minimal set of jars required to read/write data from/to xls/xlsx files?
I want to keep my project size as small as possible, so appreciate if anyone can focus on this.

A: I think poi-3.7-20101029.jar is enough. :)

A: If you just want to read/write XLS files, then all you need is the main POI jar. If you want to read/write XLSX files, then you also need the two OOXML jars (plus appropriate XML parser dependencies)
You wouldn't normally need to include the examples Jar. The scratchpad jar is needed for PPT, DOC, VSD etc, along with a small number of experimental XLS features (such as charts).


text:
Q: session id changes when using redirect() in View I have a page with a form that I use for site search. The form uses POST verb to submit data to search for. The search results are displayed under the form after it is submitted.
In an attempt to solve the "Page has expired" problem on IE I use the so called PRG pattern (http://en.wikipedia.org/wiki/Post/Redirect/Get). so I return django.shortcuts.redirect() from my view's post() method that redirects to the same URL.
The problem is that in production I see different session ids associated with the GET requests sent after the 302 response. and since I store my form in the session to be able to split the results in to pages, I get inconsistent results.
I run django under apache/mod_wsgi. apache is configured to run at most 3 processes.
It does not happen right after I restart httpd, and it seems that it starts happening after the amount of memory consumed by httpd processes reaches some limit.
I check this by repeatedly pressing the submit button, the form gets populated from the session so I can see the search strings that I have entered. when session changes, the form is returned blank. so, when this starts happening, the form gets successfully populated 2 times in a row, and when I press submit for the third time it returns blank, which means that the server returned new session cookies. this seems to have something to do with the ServerLimit setting.
What is wrong? Any ideas?
thanks
Konstantin

A: Have you tried using a HTTP 303 See Other response instead of a 302?
http://tumblr.jonthornton.com/post/7902581999/preventing-form-re-submission-with-http-303-redirects

A: You are Using Django Sessions App Correct?
If that is the case then it stores the current session ID in a cookie whose name is specified with the setting SESSION_COOKIE_NAME and it defaults to sessionid. Since you are not experiencing this issue in Firefox, I believe it should be safe to assume that your session handling and storage within Django is working fine.
The most likely culprit here is that IE is losing/deleting the sessionid cookie, causing it start a new session after the redirect. A quick google on the subject seems to confirm this.
You can see some related information at:

*

*http://www.persistall.com/archive/2008/01/25/cookies--redirects--nightmares.aspx

*http://jhottengineering.blogspot.com/2009/02/ie-post-and-redirect-errors.html
Now, in order to actually solve your problem. Django does not set a session cookie unless it actually needs too (i.e. If you set Session Data). If the only place you set session data is in the view when you POST, then IE is going to discard the cookie setting the sessionid.
So a quick and simple bandaid would be to just save some junk data (or default values?) to the session during the GET to display the form originally before the POST, that will IE will get the sessionid cookie, and things should work.

A: IE opens a new connection when it gets a 302 redirect.  This is why the 302 solves your page has expired problem. But that also means you are serving a new "session".
You'll need some other mechanism to track the session across the 302 other than being dependent upon the connection.


text:
Q: How to display the value that are caculated from two other metrics in GA4 in an explore report? I can see the count of users with the explore report like this:

However, if I want to check out how much % of users are on mobile or desktop. There is no way to show that.
The current report might have very small and huge values because the visitor of the website is very unstable. But the % of the visitors should be a stable value.
Is it possible to create a metric, that the values in it equals mobile/total?


text:
Q: Having specific htaccess credentials for one URL different from rest of site I'm trying to setup a site so that I a username and password is needed to access the site in general, but for a specific location a different username and password is needed, with the more general username and password not working for that location.
This is from my httpd.conf at present:
<Location "/store/dashboard">
    AuthType Basic
    AuthName "Please Enter Password"
    AuthUserFile /home/user/webapps/blue_webapp/.htpasswd
    Require user blueadmin
</Location>

<Location "/">
    AuthType Basic
    AuthName "Please Enter Password"
    AuthUserFile /home/user/webapps/blue_webapp/.htpasswd
    Require user blue
</Location>

The problem is the second location block seems to override the first. When I change the second location block to require valid-user I can login to the /store/dashboard location with blueadmin, but this also means blueadmin can be used to login to the rest of the site which is not what I want.
How can I fix this?

A: I can't comment so I must send an answer.
The problem is (as far as I know): You wan't to access /store/dashboard
but you need also the right to see / because /store/dashboard is a subdirectory of /.
You can use a subdomain:
/ => example.com
/store/dashboard => dashboard.example.com
Then you can/must use 2 vhosts with own / directory.
But I am not sure.

A:
The problem is the second location block seems to override the first.

Yes.
I feel I must be missing something here, but you simply need to reverse your two <Location> blocks:
<Location "/">
  :
  Require user blue
</Location>

<Location "/store/dashboard">
  :
  Require user blueadmin
</Location>

Now, user blue can access the entire site, except for /store/dashboard. And blueadmin can only access /store/dashboard and not the rest of the site. In other words, "the second location block overrides the first". Which seems to be what you require?
However, a potential problem with this scenario is that blueadmin cannot access any (possibly shared) resources outside of the /store/dashboard URL tree. But I assume this is not an issue in your scenario?