text:
Q: How to keep label results on secondViewController? I am currently working on an app and I am stuck on the following: I have my mainVC (ReceiveInputVC), which after I enter an input, it goes to the secondVC (TimeLeftVC) and it updates all of its labels with results from the inputs received from the mainVC. My question is: How can I, after clicking on the arrow to go back to the mainVC or even if I close the app, when I click on the arrow from the mainVC to go to the secondVC have my labels showing the same values as before the user closed the application or returned to the main screen?
import UIKit

extension UIViewController {

    func hideKeyboard() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }

}

class ReceiveInputVC: UIViewController {

    @IBOutlet weak var hourglassButton: UIButton!

    @IBOutlet weak var whatIsYourAgeField: UITextField!
    @IBOutlet weak var ageToDieField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.hideKeyboard()
    }

    @IBAction func arrowBtnPressed(_ sender: Any) {
        // When pressed should show go to TimeLeftVC and show last result from the first time user entered the inputs, if nothing has been typed yet and no data has been saved an alert should pop up asking the user to enter an input on both fields
    }

    @IBAction func hourglassBtnPressed(_ sender: Any) {

        let checkAgeField: Int? = Int(whatIsYourAgeField.text!)
        let checkDyingAgeField: Int? = Int(ageToDieField.text!)

        if (whatIsYourAgeField.text == "" || ageToDieField.text == "") || (whatIsYourAgeField.text == "" && ageToDieField.text == "") {
            alert(message: "You must enter an input on both fields")
        } else if checkAgeField! < 1 || checkDyingAgeField! > 100 {
            alert(message: "You must enter an age higher than 1 and a dying age lower than 100")
        } else if (checkAgeField! > checkDyingAgeField!) || (checkAgeField! == checkDyingAgeField!) {
            alert(message: "You must enter an age lower than a dying age")
        } else {
            performSegue(withIdentifier: "goToSecondScreen", sender: self)
        }

    }

    func alert(message: String, title: String = "Alert") {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Try Again", style: UIAlertAction.Style.default, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }

    // Passing the data entered from ReceiveInputVC to TimeLeftVC
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "goToSecondScreen" {

            let destinationTimeLeftVC = segue.destination as! TimeLeftVC

            destinationTimeLeftVC.ageReceived = whatIsYourAgeField.text
            destinationTimeLeftVC.ageToDieReceived = ageToDieField.text
        }

    }

}

import CircleProgressBar

class TimeLeftVC: UIViewController {

    var ageReceived: String! // receive whatIsYourAgeField data from ReceiveInputVC
    var ageToDieReceived: String! // receive ageToDieField data from ReceiveInputVC

    @IBOutlet weak var yearsLeftLabel: UILabel!
    @IBOutlet weak var daysLeftLabel: UILabel!
    @IBOutlet weak var hoursLeftLabel: UILabel!

    @IBOutlet weak var progressBar: CircleProgressBar!

    override func viewDidLoad() {
        super.viewDidLoad()
        createResults()
    }

    func createResults() {

        if let userAge = Int(ageReceived), let dyingAge = Int(ageToDieReceived) {

            let yearsLeft = dyingAge - userAge
            let daysLeft = yearsLeft * 365
            let hoursLeft = daysLeft * 24

            // Update UI
            yearsLeftLabel.text = "\(yearsLeft)"
            daysLeftLabel.text = "\(daysLeft)"
            hoursLeftLabel.text = "\(hoursLeft)"

            let percentage = (CGFloat(yearsLeft) / CGFloat(dyingAge)) * 100
            let formatted = String(format: "%.1f", percentage)

            // Update Circle Progress Bar
            progressBar.setHintTextGenerationBlock { (progress) -> String? in
                return String.init(format: "\(formatted)%%", arguments: [progress])
            }

            progressBar.setProgress(percentage/100, animated: true, duration: 4.0)

        }

    }

Project on GitHub: https://github.com/mvvieira95/Time-Life.git

A: You can use Coredata or another data base or user default
User default implementation:
 @IBAction func arrowBtnPressed(_ sender: Any) {
    UserDefaults.standard.set("your input values from text field or ...", forKey: "key")
}

In second view controller get it with
 UserDefaults.standard.string(forKey: "key")

A: You can save and restore states with these methods
application:shouldSaveApplicationState and application:shouldRestoreApplicationStat.
Example:
func application(_ application: UIApplication,
            shouldSaveApplicationState coder: NSCoder) -> Bool {
   // Save the current app version to the archive.
   coder.encode(11.0, forKey: "MyAppVersion")

   // Always save state information.
   return true
}

func application(_ application: UIApplication,
            shouldRestoreApplicationState coder: NSCoder) -> Bool {
   // Restore the state only if the app version matches.
   let version = coder.decodeFloat(forKey: "MyAppVersion")
   if version == 11.0 {
      return true
   }

   // Do not restore from old data.
   return false
}

You can explore the document in https://developer.apple.com/documentation/uikit/view_controllers/preserving_your_app_s_ui_across_launches?language=objc

A: Thanks guys, I came up with a solution:
class ReceiveInputVC: UIViewController {
    @IBAction func arrowBtnPressed(_ sender: Any) {

    let defaults = UserDefaults.standard

    if let _ = defaults.object(forKey: "yearsSaved"), let _ = defaults.object(forKey: "daysSaved"), let _ = defaults.object(forKey: "hoursSaved") {
        performSegue(withIdentifier: "goToSecondScreen", sender: self)
    } else {
        alert(message: "You must first enter an input")
    }

}

class TimeLeftVC: UIViewController {
var ageReceived: String! // receive whatIsYourAgeField data from ReceiveInputVC
var ageToDieReceived: String! // receive ageToDieField data from ReceiveInputVC

@IBOutlet weak var yearsLeftLabel: UILabel!
@IBOutlet weak var daysLeftLabel: UILabel!
@IBOutlet weak var hoursLeftLabel: UILabel!

@IBOutlet weak var progressBar: CircleProgressBar!

override func viewDidLoad() {
    super.viewDidLoad()

    let defaults = UserDefaults.standard

    yearsLeftLabel.text = defaults.object(forKey: "yearsSaved") as? String
    daysLeftLabel.text = defaults.object(forKey: "daysSaved") as? String
    hoursLeftLabel.text = defaults.object(forKey: "hoursSaved") as? String

}

override func viewWillAppear(_ animated: Bool) {
    createResults()
}

func createResults() {

    if let userAge = Int(ageReceived), let dyingAge = Int(ageToDieReceived) {

        let yearsLeft = dyingAge - userAge
        let daysLeft = yearsLeft * 365
        let hoursLeft = daysLeft * 24

        // Update UI
        yearsLeftLabel.text = "\(yearsLeft)"
        daysLeftLabel.text = "\(daysLeft)"
        hoursLeftLabel.text = "\(hoursLeft)"

        // Store Data
        let defaults = UserDefaults.standard

        defaults.set(yearsLeftLabel.text, forKey: "yearsSaved")
        defaults.set(daysLeftLabel.text, forKey: "daysSaved")
        defaults.set(hoursLeftLabel.text, forKey: "hoursSaved")

        // Update Circle Progress Bar
        let percentage = (CGFloat(yearsLeft) / CGFloat(dyingAge)) * 100
        let formatted = String(format: "%.1f", percentage)

        progressBar.setHintTextGenerationBlock { (progress) -> String? in
            return String.init(format: "\(formatted)%%", arguments: [progress])
        }

        progressBar.setProgress(percentage/100, animated: true, duration: 4.0)

    }

}

Having troubles now updating that progressBar when I go back to the view...


text:
Q: How would I make a program that removes all of the letters and the commas after them from a txt document? I have a giant text document that looks sort of like this:
A,1,2,3
B,2,5,3
C,7,9,0
.
.
.

How would I write a program that would make the text document look like this:
1 2 3
2 5 3
7 9 0
.
.
.

(Basically the letters and the commas after the letter are removed, and all commas after the first number change into spaces)

A: You'll want to call the following on each line:
line.split(',')[1:]

This splits the line along the commas, and then slices off the first element.

A: If you're on Linux/Unix you can use basic shell commands, which should be available everywhere:
cut -d "," -f 2- --output-delimiter=" " input.txt > output.txt

If you insist on using Python, you can do:
with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile:
    for line in infile:
        outfile.write(' '.join(line.split(',')[1:]))

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I define express middleware for all routes I am trying to define one global middleware which will work for all routes of my app. I tried some ways but still got some issues.
var _gMDLW = function (req, res, next) {
  if(req.route) console.log('Called route ', req.route.path);
  next();
}

// Working fine and result on _gMDLW is /route1
app.get('/route1', _gMDLW, function (req, res, next) { return res.sendStatus(200); })

var globalRouter = new express.Router()

// Working fine and result on _gMDLW is /view
globalRouter.route('/view')
  .get(_gMDLW, function (req, res, next) { return res.sendStatus(200);})
app.use(globalRouter);

But problem is here
// Error in _gMDLW and getting /list instead of /items/list
var itemRouter = new express.Router()
itemRouter.route('/list')
  .get(_gMDLW, function (req, res, next) { return res.sendStatus(200);})
app.use('/items', itemRouter)

Second Question is is there any way to define/add _gMDLW inside app instead of adding in each route something like app.use(_gMDLW) ?
Thank you

A:
You can use app.all() to resolve this issue

Example
app.all('*', _gMDLW);

function _gMDLW(req, res, next) {
    if (req.path == '/') return next();// redirect to homepage for guest

    next();//authenticated user
}

You can modify it as your requirement


text:
Q: Is there some computational evidence of the $pq$ analog of Serre's conjecture? The $pq$ analog of Serre's conjecture (see "Mod pq Galois representations and Serre's Conjecture"- Khare, Kiming) states that if $\bar{\rho}_1:G_{\mathbb{Q}}\rightarrow \text{GL}_2(\mathbb{F}_p)$ is a mod $p$ Galois representation and $\bar{\rho_2}:G_{\mathbb{Q}}\rightarrow \text{GL}_2(\mathbb{F}_q)$ is a mod $q$ Galois representation, then if $\bar{\rho}_1$ and $\bar{\rho}_2$ are odd, irreducible, ramified at only finitely many primes and of the same "weight", then under some further hypotheses, $\bar{\rho}_1$ and $\bar{\rho}_2$ both lift to Galois representations coming from the same eigenform.
Before Serre made his conjecture (for one prime) there was certainly a lot of computational evidence for it, is there some computational evidence for this conjecture?
It seems that the easiest way to come up with examples of $\bar{\rho}_1$ and $\bar{\rho}_2$ as described would be to take the mod $p$ and mod $q$ representations associated a newform, but such representations don't serve the purpose of producing evidence for the conjecture. One would instead seek to contrive to find $\bar{\rho}_1$ and $\bar{\rho}_2$ that do not arise in this way to find computational evidence.


text:
Q: to run shell script through java I want to run a shell script through java .I am using license generation tool,It can be call with the help of ./LicenseGen.sh command,under it I require to execute another command
create licensekey -x license-input.xml
which create a new licensekey.xml file where license-input.xml is a input file and licensekey is a output xml file how it is posssible in java please help me.
my code is
import java.io.*;
import java.util.*;

public class ProcessExample {

/**
 * @param args
 */
 public static void main(String args[]) throws IOException {

       File file=new File("/opt");
      // List<String> list=new List<String>();
       ProcessBuilder processBuilder = new ProcessBuilder("./LicenseGen.sh");
       processBuilder.directory(file);

        Process process=processBuilder.start();
       //processBuilder.command("create licensekey -x license-input.xml");
       //process=processBuilder.start();
       InputStream is = process.getInputStream();
       InputStreamReader isr = new InputStreamReader(is);
       BufferedReader br = new BufferedReader(isr);

       String line;

       System.out.printf("Output of running %s is:",
          Arrays.toString(args));

       while ((line = br.readLine()) != null) {
         System.out.println(line);
       }

     }
}

A: You can't execute the script directly since it has to be interpreted by a shell like bash.
Note that bash is an executeable.
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "/path/LicenseGen.sh");

A: Use commons cli http://commons.apache.org/cli/
Good luck!

A: I have used JSch extensively for remote login and script executions. I used google Expect4j with Jsch for executing scripts on remote machines in expect mode(send/wait). Since, you have to execute command one after another, you can try this.
It can also be used for local execution that you require. The only worry is that you need to login (into your local machine) for execution.
For jsch, go to http://www.jcraft.com/jsch/
For Expect4j, go to http://code.google.com/p/expect4j/
Thanks.


text:
Q: ¿Cómo eliminar espacios en blanco/vacio que estan de mas en Angular? En Angular desde uninput textpor ejemplo si el usuario escribe:  "La              Historia", con una funcion (o pipe o con lo que sea) quiero que me quite los espacios en blanco/vacios que estan de mas, para que quede de esta forma: "La Historia". En mi caso estoy intentando hacerlo con una función pero no da resultados.
Aca mi formulario en el componente.html donde intento llamar a la función (blur)="cleanUnnecessaryWhiteSpaces(book.name)" para que me retorne la cadena sin espacios en blanco/vacios que estan demas.

<form [formGroup]="form" (ngSubmit)="createBook($event)">

            <input type="text" class="form-control" formControlName="name"
            [(ngModel)]="book.name" placeholder="Nombre de libro"
            (blur)="cleanUnnecessaryWhiteSpaces(book.name)">

Este campo es obligatorio!

El nombre es muy largo!

            <button [disabled]="form.invalid" type="submit" class="btn btn-dark btn-block">Guardar</button>
            <button type="button" class="btn btn-warning btn-block text-white" (click)="resetForm()">Reset</button>

</form>

Aca mi logica en el componente.ts

book = {} as Book

constructor(){
  this.buildForm();
}

 buildForm() {
    this.form = this.formBuilder.group({
      name: ['', [Validators.required, Validators.maxLength(50)]],
      year: ['', [Validators.required, Validators.max(this.year)]],
      author: ['', [Validators.required]],
      category: ['', [Validators.required]],
      editorial: ['', [Validators.required]],
      description: ['', [Validators.required, Validators.maxLength(2500)]],
      quantity: ['', [Validators.required]],
      price: [0, [Validators.required]],
      image: [''],
      state: [true]
    });
  }

cleanUnnecessaryWhiteSpaces(cadena: string){
   const cleanString = cadena.replace(/\s{2,}/g, ' ').trim();
   console.log(cadena);
   return cleanString;
}

A: En lugar de retornar la cadena corregida asígnala a la propiedad book.name.
cleanUnnecessaryWhiteSpaces(cadena: string){
       const cleanString = cadena.replace(/\s{2,}/g, ' ').trim();
       this.book.name = cleanString;
    }

Actualización
Para que la función sea reusable se puede asignar su valor de retorno
desde la plantilla
cleanUnnecessaryWhiteSpaces(cadena: string){
       return cadena.replace(/\s{2,}/g, ' ').trim();
 }

En el blur, asignar lo que retorna la función:
(blur)="book.name = cleanUnnecessaryWhiteSpaces(book.name)">

A: Mi consejo es que te suscribas a los cambios en el formulario:
ngOnInit() { //mejor aquí que en el constructor
  this.buildForm();
  this.form.get('name').valueChanges.subscribe(newValue => {
    const trimmed = newValue.replace(/\s+/g, " ").trim();
    this.form.get('name').setValue(trimmed, {emitEvent: false});
    // emitEvent:false evita un loop infinito aquí
  });
}

A: No es necesario /\s{2,}/ para marcarle después de cuantos espacios en blanco, sólo aplica el operador + para iterar

const text = "LA                         HISTORIA";
console.log( text );

const cleanText = text.replace(/\s+/g, " ").trim();
console.log( cleanText );


text:
Q: SparseMatrix construction in Eigen I am building a sparse linear system with multiple (soft) constraints. I am converting some code which used to build the matrix with boost::ublas, to Eigen. The boost:ublas has a convenient way to create a sparse matrix with known (or estimated) number of non-zeros, and has reasonably fast operator(int row, int col) to update its elements.
The problem is as follows:

*

*Using SparseMatrix::setFromTriplets:
My system has many constraints. As a naive, 'slightly' exaggerated example, let say that I have a 100x100 sparse matrix, with 500 nnz but 1 billion redundant constraints (i.e., the non-zero coeffs are modified a billion times). setFromTriplets requires me to store 1 billion coefficients, most of which will be summed up to form my set of 500 non zero coefficients. That is not really efficient nor memory friendly.
Of course, I can replace my std::vector by an std::map, and perform the accumulation of the constraints manually, but this somehow misses the point of having a sparse matrix class, and that wouldn't be efficient either.

*Using SparseMatrix::insert(i,j,val):
Does not work if the element is already present. My problem is to be able to accumulate coefficients that are already present.

*using SparseMatrix::coeffRef(i, j):
That does work, and would be the function I'm looking for. However it is several orders of magnitude slower than boost::ublas. I am surprised that I did not see a better function for that.
I thought this would be due to the number of non-zeros that is not known in advance, and forces multiple reallocations (which is what happens in practice). However, using SparseMatrix::reserve() has no effect, since it is a function that only works for compressed matrices (a comment in the source says ""This function does not make sense in non compressed mode" before an assert).... and, as the documentation says "the insertion of a new element into a SparseMatrix converts this later to the uncompressed mode".
What is the most efficient way to build a sparse matrix in Eigen while still being able to update its coefficients multiple times ?
Thanks
[EDIT: sample use case: 10x10 matrix with 10 non-zeros. For simplicity, the matrix is diagonal]
SparseMatrix<double> mat(10, 10);
for (int i=0; i<10; i++) {
  for (int j=0; j<1000000; j++) {
    mat.coeffRef(i, i) += rand()%10;
  }
}

=> works, but orders of magnitude slower than the ublas operator() (for bigger matrices and a more realistic setting of course).
std::vector<Eigen::Triplet<double> > triplets(10000000);
int k=0;
for (int i=0; i<10; i++) {
  for (int j=0; j<1000000; j++) {
    triplets[k++] = Eigen::Triplet<double>(i,i,rand()%10);
  }
}
SparseMatrix<double> mat(10, 10);
mat.setFromTriplets(triplets.begin(), triplets.end());

=> not memory friendly...

A: To make insert of coeffRef efficient, you need to reserve enough space using mat.reserve(nnz) where nnz is a Eigen::VectorXi containing the estimated number of non zero of each column. It is better to slightly overestimate these numbers to avoid numerous reallocations/copies. Another complementary trick is to make sure that the first time you access to the element (i,j), this element is the last one of the column j.
If you can easily compute the sparsity pattern, then an alternative is to fill a vector of unique triplet with 0 for the values, and then coeffRef will be fast.


text:
Q: How to send multiple form data with each form has an file attached in postman request There is one API which accepts data in below format, I want to test this API through postman but not sure how to send data in below format in Postman. I tried multiple things in postman but API is not accepting request.
[
  {
    "firstName":"",
    "age":1,
    "image":"This should be actual image"
  },
  {
    "firstName":"",
    "age":1,
    "image":"This should be actual image"
  },
  {
    "firstName":"",
    "age":1,
    "image":"This should be actual image"
  }
]

A: [
  {
    "firstName":"",
    "age":1,
    "image":"This should be actual image"
  },
  {
    "firstName":"",
    "age":1,
    "image":"This should be actual image"
  },
  {
    "firstName":"",
    "age":1,
    "image":"This should be actual image"
  }
]

For above type of request we should send data in below format
In Postman -> Body -> "form-data"
You will find Key-Value columns. Don't give any key and paste above json inside "Value" column first row. Don't give any key. Remove key from above json on which we are supposed to have file.
[
  {
    "firstName":"",
    "age":1
  },
  {
    "firstName":"",
    "age":1
  },
  {
    "firstName":"",
    "age":1
  }
]

In Key column and second row you will have invisible drop down with options "Text", "File". Select "File". In "Value" column 2nd row you will see "Select files" button. Click on that and select the single/multiple files.

This we would be able to send multiple form data with a file in each form.


text:
Q: MySQL not accepting executemany() INSERT, running Python from Excel (datanitro) I HAVE ADDED MY OWN ANSWER THAT WORKS BUT OPEN TO IMPROVEMENTS
After seeing a project at datanitro. I took on getting a connection to MySQL (they use SQLite) and I was able to import a small test table into Excel from MySQL.
Inserting new updated data from the Excel sheet was this next task and so far I can get one row to work like so...
import MySQLdb

db = MySQLdb.connect("xxx","xxx","xxx","xxx")
c = db.cursor()

c.execute("""INSERT INTO users (id, username, password, userid, fname, lname)
VALUES (%s, %s, %s, %s, %s, %s);""",
      (Cell(5,1).value,Cell(5,2).value,Cell(5,3).value,Cell(5,4).value,Cell(5,5).value,Cell(5,6).value,))

db.commit()
db.close()

...but attempts at multiple rows will fail. I suspect either issues while traversing rows in Excel. Here is what I have so far...
import MySQLdb

db = MySQLdb.connect(host="xxx.com", user="xxx", passwd="xxx", db="xxx")
c = db.cursor()

c.execute("select * from users")
usersss = c.fetchall()

updates = []

row = 2 # starting row

while True:
    data = tuple(CellRange((row,1),(row,6)).value)
    if data[0]:
        if data not in usersss: # new record
            updates.append(data)
        row += 1
    else: # end of table
        break

 c.executemany("""INSERT INTO users (id, username, password, userid, fname, lname) VALUES (%s, %s, %s, %s, %s, %s)""", updates)

db.commit()
db.close()

...as of now, I don't get any errors, but my new line is not added (id 3). This is what my table looks like in Excel...

The database holds the same structure, minus id 3. There has to be a simpler way to traverse the rows and pull the unique content for INSERT, but after 6 hours trying different things (and 2 new Python books) I am going to ask for help.
If I run either...
print '[%s]' % ', '.join(map(str, updates))

or
print updates

my result is
[]

So this is likely not passing any data to MySQL in the first place.
LATEST UPDATE AND WORKING SCRIPT
Not exactly what I want, but this has worked for me...
c = db.cursor()
row = 2
while Cell(row,1).value != None:
    c.execute("""INSERT IGNORE INTO users (id, username, password, userid, fname, lname)
    VALUES (%s, %s, %s, %s, %s, %s);""",
      (CellRange((row,1),(row,6)).value))
    row = row + 1

A: Here is your problem:
while True:
    if data[0]:
        ...
    else:
        break

Your first id is 0, so in the first iteration of the loop data[0] will be falsely and your loop will exit, without ever adding any data. What you probably ment is:
while True:
    if data[0] is not None:
        ...
    else:
        break

A: I ended up finding a solution that gets me an Insert on new and allows for UPDATE of those that are changed. Not exactly a Python selection based on a single query, but will do.
import MySQLdb

db = MySQLdb.connect("xxx","xxx","xxx","xxx")
c = db.cursor()
row = 2
while Cell(row,1).value is not None:
    c.execute("INSERT INTO users (id, username, password, \
    userid, fname, lname) \
    VALUES (%s, %s, %s, %s, %s, %s) \
    ON DUPLICATE KEY UPDATE \
    id=VALUES(id), username=VALUES(username), password=VALUES(password), \
    userid=VALUES(userid), fname=VALUES(fname), lname=VALUES(lname);",
    (CellRange((row,1),(row,6)).value))

    row = row + 1

db.commit()
db.close()


text:
Q: progressbar in openGL android I am working to draw progressbar using OpenGL in Android. Is there someone who can suggest. I have been able to draw static images for the bars using OpenGL. I want to fill the color on the bar depending upon the progress.
What I need is how to resize the vertices buffer for the progress? I am trying to take two different vertex buffers. one for drawing the background and other for the progress. Now I want to fill color in the progress buffer and its length should depend on the data recieved.


text:
Q: How to handle dependency source version issues If a project depends on some libraries, there are basically two options available:

*

*Locate the libraries in a well known global path (like /usr/src/linux-headers-4.13.0-1-amd64/

*Copy the sources into the project folder.

Using the global location approach takes minimum space and time (download time). If the dependencies are well versioned (tagged, like v3.1, v3.1.1, etc...), this option just works well.
If our project needs to use the latest commit of the library, versioning is not an option. If we just pull the latest commit into the well known location and let our project use the library, chances are we will be unable to compile our project 6 months later, which is unacceptable.
If we add the dependency as a subproject into our project, we will always be able to compile our project. This is the safest approach. Problem is that if the library is around 100MB, copying sources into the project folder is  just a waste of disk usage, download time etc...
How do the people handle this problem?

A: You can't have your cake and eat it:

*

*either you are going to rely on a stable, versioned library, then reference that (whereever it is located)

*or you are going to rely always on the "latest and the greatest" - then reference a copy of that
Disk space is not really an issue - obviously you need to have at least one local copy of the lib you are using once on your developer machine, it does not make a difference if it is a "proper versioned" code or "head of trunk". And when it is always "head of trunk", you will probably use some version control system like git or svn to get the library, so whenever you update your local copy, you will pull only the changes from the repo, not the "full 100 MB".
However, to make your builds reproducible, with each version of your source code, you should version all dependencies as well together with your source code. If you are using third party libs, you can either

*

*rely on the vendor providing you with exactly the versions you used during  the project, and expect them to provide you with these versions for the next 10 years or so

*or, keep your own copy of each version of the third party libs you used (probably put them in your own source code repo as well). That is the approach I always prefer for professional development, who knows if the library vendor is maintaining his stuff still next week, next month, next year?

A: Here is how you can both have and eat your cake at the same time (see quantum physics):

*

*Maintain your dependencies (libraries) in global locations with their own distributed version control system (git, hg, bazaar, etc.). (See note 1)

*Maintain a dependency version database (a text file) inside the project folder and update it on each build. (Format: MyLibrary commit-hash-or-version)

Project will always use the latest version of the dependencies. If compilation fails at some point (when you try to compile the project 3 years later, for example),

*

*Go and get which version of a dependency was used at the last successful build point

*Create a checkout of the dependency with that hash in a temporary location.

*Point the temporary location as your dependency path in your build process.

Obviously this "return-to-successful-point" process can be easily automated.

Note 1: Dependencies are not meant to be only source codes, they might be simply some tools in binary format. In this case the dependency manager hook should invoke the tool with --version parameter (or what is appropriate for that tool), get the version, append to the dependencies.txt file. Obviously you should be prepared to be able to get the older version of the tool in case you'll need it at some point in the future.


text:
Q: How to load the telerik report in reportviewer? I am trying to load the telerik report on win form where i have a report viewer to show it ... But I am not successfull to load it. I am not getting its code working write. I want to make it on form load .
private void Form1_Load(object sender, EventArgs e)
{
      //Code here to load telerik
}

Any way to load it like crystal report can load
{
    crystalReportViewer1.ReportSource = (@"C:\Users\CrystalReport1.rpt");
}

errors I am getting when I am do this
{
     Telerik.Reporting.TypeReportSource typeReportSource = new Telerik.Reporting.TypeReportSource();
     typeReportSource.TypeName = "Telerik.Reporting.Examples.CSharp.ListBoundReport, CSharp.ReportLibrary";
     this.reportViewer1.ReportSource = typeReportSource;
     reportViewer1.RefreshReport();
}

A: What I normally do is to deign the report inside VS in a class library. I then reference the class library in the application, ASP or Winforms. In your case, Winforms, once you have added your class library to the bin, select the "Report Source" from the report viewer properties and add the report from a path or selecting your class library. Thats it.

For more reference, have a look here.


text:
Q: mysql query: count by column where column > number
Possible Duplicate:
Find duplicate strings in database

im querying a mysql database with php.
I need to know what names are repeated over 375 in the table (it has 375 rows). The table contains 3 columns: id, name, category.
Here is my php code, however it counts with php, and i want it to be made with mysql
$query = "SELECT * FROM user_likes";
//echo $query;
$result = mysql_query($query) or die(mysql_error());

// craete arrays
while($row = mysql_fetch_array($result)){
    set_time_limit(0);
    $like[$row['name']]=$like[$row['name']]+1;
    if($like[$row['name']]==375) $likes375 ++;

}

If someone could help me ill appreciate it.
Thanks!

A: Try this:
SELECT name, count(*) likes
FROM user_likes
GROUP BY name
HAVING COUNT(*) > 375

A: Here's some SQL to count the number of likes per name.
SELECT name, count(*) likes FROM user_likes GROUP BY name;

Here is some SQL to filter for names that have more than 375 likes
SELECT i.name, i.likes
FROM ( SELECT name, count(*) likes FROM user_likes GROUP BY name) i
WHERE i.likes > 375

A: If you mean to find duplicated names:
$query = "SELECT name FROM user_likes GROUP BY name HAVING COUNT(*) = 375";

$result = mysql_query($query) or die(mysql_error());

$names = array();
while($row = mysql_fetch_array($result)){
  $names[] = $row['name'];
}

print_r($names);


text:
Q: Why should usernames be unchangable? I read everywhere (and see in practice) that usernames should not be changeable. When I ask why, 'security' is given as a reason.
I've been searching for a definitive answer as to why changing a username is insecure, but I can't seem to find the answer.
Could any of the security experienced people here answer this question?
Note: if you do not know the answer, please refrain from speculation. I've thought of a number of reasons myself, but I don't know the actual answer, hence the question.
UPDATE:
1: By userId I meant to refer to some sort of unique identifier, be it a database record id or some other unique id. I've been told several times that changing the username is bad for security, even if the username is not the primary/unique identifier for the system itself.
2: I do allow users to change their 'public name'. This is the name that is used to identify the user to the other (non-privileged) users.
for example:

userId: 1234
username: john02
public name: John Jameson
email: j.jameson@dev.null

3: As pointed out by Jason and The Rook, consistency seems the only good reason. I've the feeling this 'best practice' might be a leftover from somewhere in the past when usernames where actually used within the system to uniquely identify users.

A: If you don't allow people to change their usernames then some people are just going to create new accounts.  I don't see any security risk in this,  and many apps including SO allow you to change your name.  If you change the name,  keep the userid (primary key) the same so all of the data links up properly.
The only danger I see is if you can change your name to an account that already exists like 'admin'.

A: There are a number of reasons from a security aspect that you may not wish to allow users to change their names.  However, as an all-out "NEVER do this" - I don't necessarily agree.  But, allowing name changes creates quite a bit of extra work.  If you are going to allow users to change their identities, you have to be very careful due to the reasons below.

*

*Maintaining a consistent user identity. Let's say you run a message board and Troll_1 is on everybody's block list.  If Troll_1 is able to change his or her name, then all those user filters are no good and you have some unhappy users.

*Along with answer number 1, you also want to maintain consistency across your underlying systems. If users are allowed to change names, you have to make sure you check that you either, update every system that that user is using so that he or she does not lose (or gain) permissions into areas they are (or are not) allowed.  Additionally, if a user changes his or her name and a new user wishes to use that name, you may, inadvertently, allow that new user access to the old user's information/data/whatever if you have not done due diligence in updating your systems.

*Depending on what type of system you have, allowing someone to change their user name can make your system prone to abuse from a fraud standpoint. You could have someone switching their name back and forth pretending to be two different people in an attempt to scam someone.  An unaware victim may easily fall for it.  (Sounds stupid, I know, but I have seen people come up with crazier crap.)

Anyway, as I said - I don't believe it's necessarily a bad thing to allow users to change their names.  However, it does create quite a bit more work for you, the developer.  User names now can't be unique IDs in a database and user names now don't necessarily relate to someone (because they can be changed later), so you have to have a different system in place for expressing "uniqueness."

A: I disagree with the premise. There are plenty of big name sites that let you change your username; eBay is one of the first ones that comes to mind.
Edit:
Now that I think about this, and read Rook's answer, I remembered about a place I worked at where you could not create an account with a username that already existed, but you could always change it (later, after registration) to a username that already existed. Unfortunately, at said place, permissions were based on the username... you can see where the security problem lies.

A: It's may or may not be bad for security, but if user IDs are based on user names, it may prove embarrassing. Think, for example, a user Jane Smith (married to Mr Smith) who gets divorced and wants to revert to her pre-marriage name. Every time she logs in to your system, it's reminding her of what was.
Now you could just create a new account, and move any configuration over to that new account. Or you could use something else other than the user name so that a user/login ID can be changed, but that's mapped to some unchanging other ID - like a sequence number or something similar.
You need to have some unchanging ID - at the very least so any auditing that's performed by the targetting system is complete. Creating a new user (thus providing a new user ID) on a name change breaks the audit chain and requires a person to remember that "Oh yes, she was called Jane Smith last year"...

A: Keeping a consistent username is entirely irrelevant if you do two things: have a separate unchangable userid, and properly normalize your database.  The first is important because it means you're not using the username as a database key (or for any other permissions or anything like that, thus dodging many of the issues other posters have brought up).  The second is important because it prevents the fraud-like attacks such as Jason brought up, because when you change your username, it will change on all the old posts and any other place it is displayed.
I see no reason why it matters if you have a separate display name or not, the username can still be changeable without any security problems.  You'll likely want to keep a record of past usernames so that if someone emails you about a lost/hacked account, you can find it, as mentioned by jumpdart.  But surely, you're already tracking past email addresses associated with the account for the same reason, right? :)  I say make them changeable.  The extra effort is negligible, and there are many legit uses.

A: A difficulty arises if users are allowed to switch to names that have been used in the past.  If users are always identified using some identifier that will never change nor be reused, it may be possible to safely and sensibly use a username from a UI standpoint if all transactions record both the identity of the user performing the transaction and the username at the time the transaction was performed.  In that case, something like a message-board post could be labeled "By: SuperCat (as Mighty Kitty)".  Supercat would be the present username of the poster, and Mighty Kitty would be the username the poster had when the post was written.

A: I'd say that not being able to change a name is BAD for security. Especially when the login is an email address. Steam is a perfect example of this... people signed up 5 years ago when they were in high school, with their finalfantazy7rocks@yahoo.com emails. Now they have to continue remembering that email, remembering both the Steam and email passwords, ensuring that no one has gotten access to the email, etc... even when they haven't used the email account in years. Basically it reduces the likelyhood that the login email is actually checked, which makes "forgotten password" emails and etc. less secure.
And you can't just make a new account if real-value items such as games are tied to that account. You're stuck with your name for life.

A: Lots of answers. You probably have it settled by now. Here's my 2 cents:
Don't let people change their names. Not for security or anything, but because it can reflect poorly on your site. People know a user as xxx and they change to yyy, then their reputation can fade as well. Abusive users will just plague your system with constant changes.
URL indexing: If you are indexed like so - www.somewhere.com/user/awesomeGuy then awesomeGuy changes name to stupidGuy then you lose your indexed results and you get 404 errors or some such when google spiders crawl the site. You will benefit more by having username URLs than allowing people to change their usernames. These days, the ability to change your username is not big on the list of "must haves" when people sign up for a site.

Time: Your time is more important than programming useless features like this.

Just my opinion. No security risks though, unless you don't clean your input.


text:
Q: Chained join not filtering as expected I have a related question here:
Generate month data series with null months included?
When I posted I omitted the second join thinking it was trivial and not impact my question - I was wrong there.
SELECT TO_CHAR(activity_tasks.start_date, 'MON') AS month,
EXTRACT(MONTH FROM activity_tasks.start_date) AS month_num,
SUM(cost_planned) FILTER (WHERE activity_tasks.aasm_state IN ('open', 'planned' ) )  AS planned,
SUM(cost_actual) FILTER (WHERE activity_tasks.aasm_state IN ('closed' ) ) AS actual
FROM "activity_tasks"
INNER JOIN "activities"."id" = "activity_tasks"."activity_id"
WHERE "activities"."type" = 'My Type' AND activity_tasks.start_date >= '2020-01-01' AND activity_tasks.start_date <= '2020-12-31'
GROUP BY month, month_num
ORDER BY month_num

Which gets me:
+-------+-----------+---------+--------+
| month | month_num | planned | actual |
+-------+-----------+---------+--------+
| NOV   | 11        | NULL    | 123    |
| DEC   | 12        | 500     | NULL   |
+-------+-----------+---------+--------+

The accepted answer on the related had me try various modifications like adding:
LEFT JOIN activities a
ON a.id = t.activity_id AND a.type = 'My Type'

which results in (not filtering out just My Type):
+-------+-----------+---------+--------+
| month | month_num | planned | actual |
+-------+-----------+---------+--------+
| JAN   | 1         | NULL    | NULL   |
| FEB   | 2         | NULL    | NULL   |
| MAR   | 3         | NULL    | NULL   |
| APR   | 4         | NULL    | NULL   |
| MAY   | 5         | NULL    | NULL   |
| JUN   | 6         | NULL    | NULL   |
| JUL   | 7         | NULL    | NULL   |
| AUG   | 8         | NULL    | NULL   |
| SEP   | 9         | NULL    | NULL   |
| OCT   | 10        | 0       | 0      |
| NOV   | 11        | 125     | 123    |
| DEC   | 12        | 1414    | 0      |
+-------+-----------+---------+--------+

Tried this:
ON a.id = t.activity_id
WHERE a.type = 'My Type'

Which gets me the correct filtered results but I lose the filtered results again:
+-------+-----------+---------+--------+
| month | month_num | planned | actual |
+-------+-----------+---------+--------+
| NOV   | 11        | NULL    | 123    |
| DEC   | 12        | 500     | NULL   |
+-------+-----------+---------+--------+

I am looking for this - the filtered tasks with the 'null' months also:
+-------+-----------+---------+--------+
| month | month_num | planned | actual |
+-------+-----------+---------+--------+
| JAN   | 1         | NULL    | NULL   |
| FEB   | 2         | NULL    | NULL   |
| MAR   | 3         | NULL    | NULL   |
| APR   | 4         | NULL    | NULL   |
| MAY   | 5         | NULL    | NULL   |
| JUN   | 6         | NULL    | NULL   |
| JUL   | 7         | NULL    | NULL   |
| AUG   | 8         | NULL    | NULL   |
| SEP   | 9         | NULL    | NULL   |
| OCT   | 10        | NULL    | NULL   |
| NOV   | 11        | NULL    | 123    |
| DEC   | 12        | 500     | NULL   |
+-------+-----------+---------+--------+

I have tried all types of JOINS for the second join.  Not sure what I am missing here.

A: Realized I need a sub-select like this:
SELECT
  UPPER(TO_CHAR(d.start_date, 'mon')) AS month,
  EXTRACT(MONTH FROM d.start_date) AS month_num,
  SUM(t.cost_planned) FILTER (WHERE t.aasm_state IN ('open', 'planned' ) ) AS planned,
  SUM(t.cost_actual)  FILTER (WHERE t.aasm_state = 'closed') AS actual
FROM GENERATE_SERIES('2020-01-01'::date, '2020-12-01'::date, '1 month') d(start_date)
LEFT JOIN
(
SELECT t.*
FROM activity_tasks t
LEFT JOIN activities a
ON a.id = t.activity_id
WHERE a.type = 'My Type'
) AS t ON t.start_date >= d.start_date and t.start_date < d.start_date + '1 month'::interval
GROUP BY d.start_date
ORDER BY d.start_date


text:
Q: Redhawk rh.sourceVITA49 component usage I'm using Redhawk 2.0.1 on a centos6.5 x64 system. I can fire up a rh.SinkVITA49 component just fine with:
from ossie.utils import sb
dst= sb.launch("rh.SinkVITA49",execparams={"DEBUG_LEVEL":4} )
dst.api()
dst.network_settings.interface="eth3"
dst.network_settings.enable=True
dst.network_settings.ip_address="192.168.0.3"
dst.advanced_configuration.force_transmit=True
siggen = sb.launch("rh.SigGen")
siggen.api()
siggen.connect(dst,usesPortName="dataShort_out")
sb.start()

Which I can validate by checking the packets in wireshark. However, for the receiver rh.SourceVITA49 I have a vita-49 (w VRL) data source coming on port 41001 (verified with wireshark) but I can't receive any data. The setup is:
from ossie.utils import sb
src = sb.launch("rh.SourceVITA49",execparams={"DEBUG_LEVEL":4})
src.api()
src.attachment_override.enabled=True
src.interface="eth0"
src.interface="eth1"
src.attachment_override.ip_address="192.168.2.10"
src.attachment_override.port=41001
src.VITA49Processing_override.enable=True
src.VITA49Processing_override.VRL_frames=True
src.VITA49Processing_override.vector_size=1024
src.advanced_configuration.vita49_packet_size=4136
sb.IDELocation("/usr/local/redhawk/ide/2.0.1/")
plot=sb.Plot()
src.connect(plot,usesPortName="dataShort_out")
sb.start()
src.api()

Which appears to run but there is no data flow and the status is:
>>> src.api()
Component [rh.SourceVITA49]:
Provides (Input) Ports ==============
Port Name       Port Interface
---------       --------------
dataVITA49_in   IDL:BULKIO/dataVITA49:1.0

Uses (Output) Ports ==============
Port Name       Port Interface
---------       --------------
dataUshort_out  IDL:BULKIO/dataUshort:1.0
dataChar_out    IDL:BULKIO/dataChar:1.0
dataDouble_out  IDL:BULKIO/dataDouble:1.0
dataFloat_out   IDL:BULKIO/dataFloat:1.0
dataOctet_out   IDL:BULKIO/dataOctet:1.0
dataShort_out   IDL:BULKIO/dataShort:1.0

Properties ==============
Property Name                   (Data Type)     [Default Value] Current Value
-------------                   -----------     --------------- -------------
interface                       (string)        eth1            eth1
attachment_override             (struct)
  enabled                       (boolean)       False           True
  ip_address                    (string)        127.0.0.1       192.168.2.10
  vlan                          (ushort)        0               0
  use_udp_protocol              (boolean)       True            True
  port                          (long/SL/32t)   12344           41001
connection_status               (struct)
  input_enabled                 (boolean)       None            True
  data_throughput               (double/SD/64f) None            0.0
  input_sample_rate             (double/SD/64f) None            0.0
  input_port                    (ushort)        None            41001
  packets_missing               (ulong)         None            0
  waiting_for_context_packet    (boolean)       None            True
  input_ip_address              (string)        None            192.168.2.10
  input_vlan                    (ushort)        None            0
VITA49Processing_override       (struct)
  VRL_frames                    (boolean)       False           True
  repeating                     (ulong)         1               1
  event_tag_size                (ulong)         0               0
  channel_tag_size              (ulong)         0               0
  data_item_format              (longlong)      3               3 (enum=DataType_int16)
  vector_size                   (ulong)         1               1024
  processing_efficient          (boolean)       True            True (enum=processing_efficient)
  enable                        (boolean)       False           True
  real_complex_type             (long/SL/32t)   1               1 (enum=complexCartesian)
advanced_configuration          (struct)
  vita49_packet_size            (ulong)         1500            4136
  buffer_size                   (long/SL/32t)   4096000         4096000
  poll_in_time                  (ulong)         100             100
  corba_transfersize            (ulong)         0               0

I'm guessing the issue is it is waiting for the context packets before starting the receive? My stream doesn't have context packets so I will have to force that if there's a way. Thanks

A: I'm not very familiar with that component but I believe you are correct in your assumption that it is waiting for a context packet. Looking through the code it appears as though there is a canProcessDataPacket method here
Without the internally set receivedContextPacket boolean set to true, your other option is to set the property VITA49Processing_override.enable to true and to provide the component with a valid SRI push. You could create a dummy component that does nothing but push the proper SRI to the VITA49 component or do this through a REDHAWK service or via the sandbox.


text:
Q: fill() in missing lubridate value from a different column Below is a fictional reproducible example of pick-up and drop-of times of four taxis.
Taxi 1, 2, and 3 unfortunately have a missing in the drop-of time. fortunately, two of these times (for taxi 1 and 3) can be inferred to be at least 1 sec before they pick-up new costumers (these are non-ride sharing taxi, very corona-proof):
(the below df is - in the real use case - the result of a group_by and summarise of another df)
library(dplyr)

x <- seq(as.POSIXct('2020/01/01'),  # Create sequence of dates
         as.POSIXct('2030/01/01'),
         by = "10 mins") %>%
  head(20) %>%
  sort()

taxi_nr <- c(1, 1, 1, 2, 2, 3, 3, 3, 3, 4)

drop_of <- x[c(TRUE, FALSE)]
pick_up <- x[c(FALSE, TRUE)]

drop_of[2] <- NA
drop_of[5] <- NA
drop_of[7] <- NA

df <- data.frame(taxi_nr,pick_up,drop_of) %>%
  arrange(pick_up)

I wish to fill in the NA of taxi 1 and 3, I have tried the following:
df <- df %>%
   fill(drop_of, .direction = "up")

However, this take the below drop-of value instead of the below pick-up value and does not take into account the taxi nr.
I have also thought about:
df <- df %>%
  filter(is.na(drop_of)) %>%
  mutate(drop_of, ov[,+1])

This seems to run into problems with the taxi_nr 2 case, as there is no [,+1] in within the group - or so I believe is the issue. I have tried to add safely(), possibly() and quietly(), but that did not help:
df <- df %>%
  filter(is.na(drop_of)) %>%
  mutate(drop_of, purr::safely(ov[,+1]))

Does anyone have a solution?
ps: once I get the right column for filling in it also needs to be subtracted 1 second and be in the right lubridate formate (d/m/y-h/m/s)
THANKS!

A: You can try to use a temporary variable for it, although it does not look pretty
df <- df %>%
  mutate(temp = ifelse(is.na(drop_of), NA, pick_up)) %>%
  group_by(taxi_nr) %>%
  fill(temp, .direction = "up") %>%
  ungroup() %>%
  mutate(drop_of = ifelse(is.na(drop_of), temp - 1, drop_of),
         drop_of = as.POSIXct(drop_of, origin = "1970-01-01")) %>%
  select(-temp)

And if you need your data in a format d/m/y-h/m/s, you could do that with a format() function (I am not sure if what you described is exactly what you need, but at least you should get the idea)
df <- df %>% mutate(drop_of = format(drop_of, "%d/%m/%Y-%H/%M/%S"))


text:
Q: TKINTER get the position of LABEL in TEXT FRAME I have a TEXT Widget as a FRAME und add LABELS to it. Any way to get the position of the LABEL by clicking it?
Not coordinates but rather position.
Example:
These are 15 different LABELS and I need the position of the LABEL 'different at position 4'.
Result:
4 after clicking 'different' LABEL
import tkinter as tk
from tkinter import *
from tkinter import ttk
import tkinter as tk
import re
import tkinter
from tkinter.tix import COLUMN
from turtle import bgcolor

linelist1 = ['some long text 1 as a label!!!', '@combo@Aa Bb Cc Dd', 'some long text 2 as a label!!!',
 'some long text 3 as a label!!!', '@combo@Ee Ff Gg Hh', 'some long text 4 as a label!!!']
lines_with_combobox = [e for e, s in enumerate(linelist1) if '@combo@' in s]

root = tk.Tk()
root.geometry(f'400x100')
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)

bframe = tk.Frame(root, width=100, height=100, bg='red')
bframe.grid(row=0, column=0)

text = tk.Text(bframe, wrap="char", background=root.cget("background"))
text.pack(fill="both", expand=True)

#def get_position():

for line in range(0, len(linelist1)):
    if line in lines_with_combobox:
        delete_combo_marker = re.split("@combo@", linelist1[line])
        words = delete_combo_marker.pop(0)
        word_as_values = re.split('\s+', delete_combo_marker[0])
        combobox = ttk.Combobox(text, values=word_as_values)
        text.window_create("end", window=combobox)

    else:
        textui = linelist1[line]
        for word in textui.split(" "):
            label = tk.Label(text, text=word)
            #label.bind('<Button-1>', get_position)
            text.window_create("end", window=label)

root.mainloop()

EDIT:
Decided to go with a different solution:
def get_position2( label ):
    x = text.index(str(label))
    print(x.split('.')[-1])

for line in range(0, len(linelist1)):
    if line in lines_with_combobox:
        delete_combo_marker = re.split("@combo@", linelist1[line])
        words = delete_combo_marker.pop(0)
        word_as_values = re.split('\s+', delete_combo_marker[0])
        combobox = ttk.Combobox(text, values=word_as_values)
        text.window_create("end", window=combobox)

    else:
        textui = linelist1[line]
        for word in textui.split(" "):
            label = tk.Label(text, text=word)
            label.bind('<Button-1>', lambda event, label=label: get_position2(label))
            text.window_create("end", window=label)

A: If you want an index you'll need the function called by the click to return the index number.  This can be attached with a function closure as shown below, or with functools.partial if you're more comfortable with that.
I've shown the index incrementing by line.  It could be incremented for each label or whatever is required.  The identifier for the label will need to be identified as the label is created, so that it's known when it's clicked.
Code shown from def get_position to just above root.mainloop()
def get_position( n ):
    """ Returns a function bound to n. """

        def func( e ):  # func will be passed an event.
            print( n )

    return func

ix = 0   # Starting Index

for line in range(0, len(linelist1)):
    if line in lines_with_combobox:
        delete_combo_marker = re.split("@combo@", linelist1[line])
        words = delete_combo_marker.pop(0)
        word_as_values = re.split('\s+', delete_combo_marker[0])
        combobox = ttk.Combobox(text, values=word_as_values)
        text.window_create("end", window=combobox)

    else:
        textui = linelist1[line]
        ix += 1                     # Increment the index for each line.
        for word in textui.split(" "):
            # ix += 1  # OR - Increment index for each label.
            label = tk.Label(text, text=word)
            label.bind('<Button-1>', get_position( ix ) )  # Bind the label to ix
            text.window_create("end", window=label)
    text.insert( "end", '\n' )  # Use this if each 'line' should
                                # be on a different line in the text widget.


text:
Q: return new Promise() not working in Node.js I'm new to the concept of promises, as well as to JavaScript in general. I'm trying to write a function in Node.js that I can pass a URL to a promise of the results.
I have programmed it two ways. The first does not work, in which I can pass the URL to the function. The second does work, in which the URL is statically defined. The first one does not work because the compiler does not think it is a function for some reason that I can't figure out, why?
THIS WAY DOESN'T WORK as the function getJson is not interpreted by Node as a function:
var options = { method: 'GET',
                url: URL,  // This will be dynamically filled by the argument to the function getJson
                headers: { authorization: 'OAuth realTokenWouldBeHere', Accept: 'application/json' } };

var getJson = function(URL){

  return new Promise(function(resolve, reject) {

    request(options, function (error, response, body) {
      if(error) reject(error);
      else {
        resolve(JSON.parse(body));  //The body has an array in the jason called Items
      }
    });
  });  // Edited original post. Had two curly braces }}; here by accident, which was why function was not being recognized
};

getJson.then(function(result) {
  console.log(result.Items); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});

THIS WAY DOES WORK AND I GET BACK AN ARRAY OF ITEMS TO THE CONSOLE. The downside of this is that the URL used is static. The point of what I am trying to do is to chain a bunch of URL's by taking the result of an API, one URL call that then contains he URL of the NextPage of results.
var options = { method: 'GET',
  url: 'http://staticURL',
  headers: { authorization: 'OAuth realTokenWouldBeHere', Accept: 'application/json' } };

var getJson = new Promise(function(resolve, reject) {
  request(options, function(err, response, body) {
    if(err) reject(err);
    else {
      resolve(JSON.parse(body));
    }
  });
});

getJson.then(function(result) {
  console.log(result.Items); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});

A: Try this:
var getJson = function(URL){
  var options = {
    method: 'GET',
    url: URL,
    headers: { authorization: 'OAuth realTokenWouldBeHere', Accept: 'application/json' }
  };
  return new Promise(function(resolve, reject) {

    request(options, function (error, response, body) {
      if(error) reject(error);
      else {
        resolve(JSON.parse(body));
      }
    });
  }};
};

And then you can call it:
getJson(theDynamicURLGoesHere).then(function(result) {
  console.log(result.Items); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});

A: getJson.then(...)

in your first code block is not correct.  It needs to be:
getJson(someURL).then(...)

because in that first code block, getJson is a function so you have to call it to execute it and you need to pass it the desired argument.

In your first code block, getJson is a function that returns a promise when you call and execute the function so you have to call the function in order to get the promise.  In the second code block, getJson is already a promise so you can call getJson.then(...).

A: getJson() is a function, so you need to call it with ():
getJson(URL).then(onFulfilled, onRejected);

The important thing to note is that a promise is an object, you create a new promise using a constructor. Don't try to use a promise as a function - a promise immediately starts executing, .then() just registers an event handler so you're notified when the promise changes state.


text:
Q: Asynchronous Socket Read Issue I am having a program which uses tcp socket Asynchronous call to receive the protocol header which is 8 bytes.  When processing the ReadCallBack() [async call back],it uses synchronous  read to get the payload messages then process it.
My question is Whether ReadCallback method is thread safe. I am using normal dictionary to process those payload. Does it affect that dict in any mean?

A: Everything is effectively thread-safe if it is in isolation; the important question is: what else is going on? What else is accessing (read or write) the dictionary? If nothing, then you should be fine - the callback will be invoked (which depending on the specific API being used, and the data available in the buffer, could be either on the thread issuing Read..., or on a completion-port thread), and then presumably you'll do some work with the dictionary before doing something else (read/write/close).
If, however, other threads are accessing the dictionary, then the question is impossible to answer without specific code.


text:
Q: How to remove all entries (delete data) from root / in Firebase? I'm trying to reset the database programatically from Swift. I want to achieve the same result as in the Firebase console, clicking the red X on the name of the database (root path)

A: The Firebase API reference for Objective-C has two methods that seem to be relevant:

*

*Firebase.removeValue

*Firebase.removeValueWithCompletionBlock:block
The latter allows you to supply a callback to call after the removal has been completed.


text:
Q: How to renewenvironment that wrap the base environment? I would like to add wrap something around an existing environment.
Consider an existing environment sphinxVerbatim, I would like to renew this environment by adding something before and after that environment call. I could write this, but obviously it doesn't work:
\renewenvironment{sphinxVerbatim}[1]
    {\begin{code}\begin{sphinxVerbatim}{#1}}
    {\end{sphinxVerbatim}\end{code}}

In context, I would like to wrap my code environment around an existing environment named sphinxVerbatim:
\newtcolorbox{code}{breakable,enhanced,arc=0mm,colback=lightgray!5,colframe=lightgray}

Sphinx generates some code such as:
\begin{sphinxVerbatim}[commandchars=\\\{\}]
\PYG{c+cp}{\PYGZsh{}}\PYG{c+cp}{include} \PYG{c+cpf}{\PYGZlt{}stdio.h\PYGZgt{}}
\end{sphinxVerbatim}

and I would like to redeclare this environment for this sphinxVerbatim to be wrapped inside a \begin{code}...\end{code}.
The main issue I have with sphinxVerbatim is that the frame goes outside from the page area, I want it to be inside with some margin as shown below:

I thought I could simply redeclare sphinxVerbatim...

A: You may benefit from looking at the documentation for Sphinx: https://www.sphinx-doc.org/en/master/latex.html
The section on sphinxsetup mentions the ability to do things like adding a frame, coloring, etc. which should allow you to do the customizations that you like.


text:
Q: Error while running compose up. YAML linter showing no errors I keep getting a service 'image' error when running docker-compose up for my yml file.
I researched online and it seems like it was mostly some formatting error.
I have run my yml through a YAML linter and there are no errors.
version: '3.5'
services:
  server:
  image: postgrest/postgrest
  ports:
    - "3000:3000"
  links:
      - db:db
  environment:
      PGRST_DB_URI: postgres://app_user:password@db:5432/app_db
      PGRST_DB_SCHEMA: public
      PGRST_DB_ANON_ROLE: app_user
      depends_on:
      - db
      db:
      image: postgres
      ports:
        - "5432:5432"
      environment:
        POSTGRES_USER: ${POSTGRES_USER:-postgres}
        POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-changeme}
        PGDATA: /data/postgres
      volumes:
       - postgres:/data/postgres

      networks:
        - postgres
      restart: unless-stopped

      pgadmin:
        container_name: pgadmin_container
        image: dpage/pgadmin4
        environment:
        PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4@pgadmin.org}
        PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin}
        volumes :
        - pgadmin:/root/.pgadmin
        ports:
          -"${PGADMIN_PORT:-5050}:80"
        networks:
        - postgres
        restart: unless-stopped

networks:
  postgres:
    driver: bridge

volumes:
    postgres:
    pgadmin:

swagger:
  image: swaggerapi/swagger-ui
  ports:
    - "8080:8080"
  expose:
    - "8080"
  environment:
    API_URL: http://localhost:3000/

Expected would be the images get downloaded and containers get started up
Error is:
 ERROR: In file '.\docker-compose.yml', service 'image' must be a mapping not a string.

A: This issue happens because of indentation.
docker-compose deals with image like a service because of wrong indentation.
I modified your file and start configured containers successfully:
version: "3.5"

services:
        server:
                image: postgrest/postgrest
                ports:
                         - "3000:3000"
                links:
                         - db:db
                environment:
                       PGRST_DB_URI: postgres://app_user:password@db:5432/app_db
                       PGRST_DB_SCHEMA: public
                       PGRST_DB_ANON_ROLE: app_user
                depends_on:
                         - db
        db:
                image: postgres
                ports:
                        - "5432:5432"
                environment:
                        POSTGRES_USER: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4@pgadmin.org}
                        POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-changeme}
                        PGDATA: /data/postgres
                volumes:
                        - postgres:/data/postgres
                networks:
                        - postgres
                restart: unless-stopped
        pgadmin:
                container_name: pgadmin_container
                image: dpage/pgadmin4
                environment:
                        PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4@pgadmin.org}
                        PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin}
                volumes:
                        - pgadmin:/root/.pgadmin
                ports:
                        - "${PGADMIN_PORT:-5050}:80"
                networks:
                        - postgres
                restart: unless-stopped

        swagger:
                image: swaggerapi/swagger-ui
                ports:
                        - "8080:8080"
                expose:
                        - "8080"
                environment:
                        API_URL: http://localhost:3000/

networks:
        postgres:
                driver: bridge

volumes:
        pgadmin:
        postgres:


text:
Q: Can two pulsed electromagnets generate a local net force? I'm an old RPG:er, and in one of my hard sci-fi campaigns I used reactionless EMP drives on the starships. I've described below how I imagined they would work in concept.

*

*Arrange two electromagnets A and B such that when both are switched on, they attract each other.

*Place a non conducting but incompressible material between them, or embed the magnets in the material completely.

*Both electromagnets are constructed such that when switched off, they do not interact with existing magnetic fields.

*Turn on A. As the current starts to flow through the conducting element(s), it's magnetic field starts expanding.

*When the field from A reaches B, turn on B.

*Now the field from A interacts with the field from B, and a force is generated between them.

*But since the field from B has not yet reached A, the force is in one direction only.

*Once the field from B reaches A, switch off both electromagnets.

*Once the field from B has fully passed A, repeat the cycle.

Intuitively this should generate a net local force while emitting an EM field that is stronger in one direction than the other. Global net force should be zero, as the field would interact with other things outside the engine.
I'm sure I'm missing something obvious here, but my Google-fu has failed to bring me any sort of answer or discussion around this. Probably because I don't know the relevant keywords to search for.

A: This is radio antenna with two coaxial coils driven out of phase. It is similar to a
Cubic Quad antenna

except that the latter has one loop powered and the other is a passive reflector. According to NC4FB Figure-4 this has a radiation pattern predominantly in one direction. I guess the system you describe, with suitable spacing and phase shift, would also.
Since EM radiation carries momentum it would produce thrust (although not much).


text:
Q: How to remove an entry from named.conf I have a bind daemon that was used to resolve a domain. But now i want to use another nameserver. I tried to remove the entry for that domain from the named.conf file, removed also the zone file and restarted the daemon. But it seems that there is no effect.
Is there anything i can do more? I am begginer in dns configuration so this may be noob question but i could not find an answer on google.
UPDATE: this is what dig + trace gives
;; global options: +cmd
.                       63224   IN      NS      h.root-servers.net.
.                       63224   IN      NS      d.root-servers.net.
.                       63224   IN      NS      f.root-servers.net.
.                       63224   IN      NS      m.root-servers.net.
.                       63224   IN      NS      e.root-servers.net.
.                       63224   IN      NS      l.root-servers.net.
.                       63224   IN      NS      j.root-servers.net.
.                       63224   IN      NS      b.root-servers.net.
.                       63224   IN      NS      c.root-servers.net.
.                       63224   IN      NS      k.root-servers.net.
.                       63224   IN      NS      i.root-servers.net.
.                       63224   IN      NS      g.root-servers.net.
.                       63224   IN      NS      a.root-servers.net.
;; Received 512 bytes from 193.231.169.2#53(193.231.169.2) in 1 ms

com.                    172800  IN      NS      e.gtld-servers.net.
com.                    172800  IN      NS      c.gtld-servers.net.
com.                    172800  IN      NS      i.gtld-servers.net.
com.                    172800  IN      NS      l.gtld-servers.net.
com.                    172800  IN      NS      g.gtld-servers.net.
com.                    172800  IN      NS      k.gtld-servers.net.
com.                    172800  IN      NS      d.gtld-servers.net.
com.                    172800  IN      NS      a.gtld-servers.net.
com.                    172800  IN      NS      h.gtld-servers.net.
com.                    172800  IN      NS      f.gtld-servers.net.
com.                    172800  IN      NS      b.gtld-servers.net.
com.                    172800  IN      NS      m.gtld-servers.net.
com.                    172800  IN      NS      j.gtld-servers.net.
;; Received 506 bytes from 192.112.36.4#53(g.root-servers.net) in 55 ms

rencontres-selection.com. 172800 IN     NS      nssec.dedibox.fr.
rencontres-selection.com. 172800 IN     NS      sd-18368.dedibox.fr.
;; Received 99 bytes from 192.26.92.30#53(c.gtld-servers.net) in 124 ms

www.rencontres-selection.com. 604800 IN CNAME   rencontres-selection.com.
rencontres-selection.com. 604800 IN     A       88.191.110.117
rencontres-selection.com. 604800 IN     NS      sd-18368.dedibox.fr.
rencontres-selection.com. 604800 IN     NS      nssec.dedibox.fr.
;; Received 145 bytes from 88.191.108.117#53(sd-18368.dedibox.fr) in 43 ms

A: Dan, in the light of what you've said above, here's what I get when I do the same thing:
[madhatter@risby madhatter]$ dig www.rencontres-selection.com
  [...]
;; QUESTION SECTION:
;www.rencontres-selection.com.  IN  A

;; ANSWER SECTION:
www.rencontres-selection.com. 604800 IN CNAME   rencontres-selection.com.
rencontres-selection.com. 604800 IN A   88.191.110.117

;; AUTHORITY SECTION:
rencontres-selection.com. 604800 IN NS  sd-18368.dedibox.fr.
rencontres-selection.com. 604800 IN NS  nssec.dedibox.fr.

;; ADDITIONAL SECTION:
nssec.dedibox.fr.   7200    IN  A   88.191.254.71
sd-18368.dedibox.fr.    86400   IN  A   88.191.108.117

That seems to be what you get.  Can you say why you think your local named is still behaving as if it's authoritative?
Later: from what you've written above, it's possible that your underlying complaint is that the internet is still treating sd-18368.dedibox.fr as authoritative for the domain.
According to the registrar's whois page, the listed name servers for the domain are
Name Server: NSSEC.DEDIBOX.FR
Name Server: SD-18368.DEDIBOX.FR

If you want to stop the internet looking to sd-18368.dedibox.fr you will need to change the glue records at your registrar.  This is not something you can fix via named.conf, it must be done through the registrar.  You will also need to change the NS records listed in the zone file on the master server, which I presume is nssec.dedibox.fr.
Is that any help?


text:
Q: Ruby on Rails 4 find with order and limit equivalent I need very fast to update my app controller to rails 4, but i didn't know how to write all this line in new rails 4 style: with order_by with conditions and with limit, in web i search for fast, and all part's together - didn't find. How could i translate this from rails 3 to rails 4?
in controller i have
@news = Article.find(:all, conditions: { text: "example" }, order_by: "created_at", limit: 4 )

i didn't must to use conditions in 4, only where, but how to append :all, order_by and limit to it? What is a right syntax?

A: From the old ActiveRecord style:
@news = Article.find(:all, conditions: { text: "example" }, order_by: "created_at", limit: 4 )

To the new:
@news = Article.where(text: "example").order(:created_at).limit(4)

A: I think this might do the trick:
@news = Article.where(text: 'example').order(:created_at).limit(4)

A: In Arel (https://github.com/rails/arel) everything can be appended.  The various clauses are described here: http://guides.rubyonrails.org/active_record_querying.html
@news = Article.where(text: 'example').order(:created_at).limit(4)

Note that this returns a query clause that does not actually query the database until you specifically request the data.


text:
Q: Query Sheets sum if NOT match any values in this other range Would like to produce results that are contingent on any of the list of values in one range, not appearing in my other range!
@jpv had a great solution for the OPPOSITE of what i want, in this post: https://stackoverflow.com/a/54763013/12848172
Thanks!


text:
Q: Can variables in memory by made immune to malicious memory editing? Let's say I am making a game and the player's health is stored in a variable float player_hp. While playing the game, a user can open a memory editor like Cheat Engine, do some clever searches through the memory, and find the location of the variable in memory. They can then edit it to be whatever they want, effectively allowing them to cheat.
Is there a fancy way to store my variables that will effectively stop users from maliciously editing them? Should I move them around in memory? Should I encrypt them or hash them?
If it matters, I am primarily using C++.

A: Disclaimer:  I have no experience programming games, only making cheats for them.
Calculate all important variables such as health & ammo server side and replicate that data to the client.  Pickups must also be validated by the server.  If you serverside ammo, we'll just call PickUp(ammoCrate) if it's client sided.
You'll never stop everyone but I think it's important to make it annoying enough for 90% of people to stop trying to cheat.  There's some basic stuff every game should have and then more advanced protections that popular games must have to avoid being destroyed by cheaters.
Encrypt commonly modified values such as health with a basic XOR like algorithm that changes over time.  Change address of the key also and use a pointer to it, make the pointer more than 6 layers deep.  This will force cheaters to make a script and use pattern scanning instead just a cheat table, that will stop most people.
Use IsDebuggerPresent() to detect debuggers being attached and then close the process.  When you do "Find What Accesses" in Cheat Engine that will attach a debugger and if using default options will be detected by IsDebuggerPresent.
This can be hooked and patched, the next step is to manually check the BeingDebugged flag in the Process Environment Block
Get PEB pointer:
PEB* GetPEB()
{
#ifdef _WIN64
return (PEB*)__readgsword(0x60); //64 bit

#else
return (PEB*)__readfsdword(0x30); //32bit
#endif
}

Read the debugger flag:
bool IsDebugFlagSet(PEB* peb)
{
    if (peb->BeingDebugged == 1) return true;
    else return false;
}

If they're hooking IsDebuggerPresent() you can compare the bytes on disk to the bytes in memory at the beginning of the function and compare, or even easier just check the first byte and see if it's a relative jmp (x86 example)
Check for Hooks:
bool IsHooked(char* functionName, char* dllName)
{
    BYTE* functionAddress = (BYTE*)GetProcAddress(GetModuleHandle(dllName), functionName);
    return (*functionAddress == 0xE9);
}

Other tricks:
Hook LoadLibrary() & LDRLoadDLL() and stop them from loading rogue dlls
Scan running processes for memory editors by comparing the image name or image path using CreateToolHelp32Snapshot() against a blacklist
Fill all debug registers so debugger cannot be attached
Beyond these tricks you can use a commercial anticheat or kernel mode driver to protect your game, but the above tips will stop the average person.

A: Two ways to protect your data:
1) Only provide the user with binary files. Compiled code. Don't give them source code.
2) If your game is an online game, store sensitive data server side.
You should research an idea called "encapsulation" for use in designing APIs such that sensitive data is protected.


text:
Q: How call function before route change and when function done change route i wonder how call some function when click to:
<Link to="/">page</Link>

and call some function before before route change.
eg
I'm in component A i'm click some link for going Component B. Route will change but before route change i wan't to play some javascript animation and wan't to wait animation will finish then route will go to component B.
I'm using react-router-4

A: Instead of using <Link /> you can change route programmatically:
<Button
  onClick={
  () => {
      this.myCustomFunction(); // Execute whatever code you need
      this.props.history.push('/');
     }
  }
></Button>

Ref: https://tylermcginnis.com/react-router-programmatically-navigate/

A: I have created a carousel transition effect before by routing all my paths to the same carousel component and in the carousel, each slide represented a page. When the location path changed the carousel component would check the path and slide into the next component. A similar idea could be used for any transition.
<Switch>
    <Route exact path='/' component={Home} />
    <Route exact path='/history' component={Home} />
    <Redirect to="/" />
</Switch>

public render() {
    let locationPath = this.state.locationPath.toLowerCase();

    return (

                        <History />

    );
}

A: You can do this by calling an function when the link is clicked
<Button
  onClick={
  () => {
      this.animateAndExit()
     }
  }
></Button>

and your function will be like this
const animateAndExit = () => {
animationFunction()
setTimeout(redirectionFunction, timeToWait)
}


text:
Q: Qt segfault trying to show 2 dialogs in test application I'm just learning Qt. I reproduced my problem in a simple test application. I created a new project. Added 2 dialogs Dialog1 and Dialog2. I added 2 menu entries to call dialog1 and dialog2.
The main window's header file looks like this:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "dialog1.h"
#include "dialog2.h"

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_actiondialog1_triggered();

    void on_actiondialog2_triggered();

private:
    Ui::MainWindow *ui;
    Dialog1 *mDialog1;
    Dialog2 *mDialog2;
};
#endif // MAINWINDOW_H

The main window's cpp looks like this:
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
      , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

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

void MainWindow::on_actiondialog1_triggered()
{
     if (!mDialog1) {
        mDialog1 = new Dialog1(this);
        mDialog1->setModal(false);
     }
     mDialog1->show();
     mDialog1->activateWindow();
 }

 void MainWindow::on_actiondialog2_triggered()
 {

    if (!mDialog2) {
        mDialog2 = new Dialog2(this);
        mDialog2->setModal(false);
    }
    mDialog2->show();
    mDialog2->activateWindow();
 }

So it is basically as empty as it gets... If I only show one dialog by commenting out the relevant sections it works but as soon as I want to use 2 or more is segfaults. The given dialogs constructor isn't even being called anymore.
I am using:
Qt Creator 4.12.3
Based on Qt 5.14.2 (GCC 5.3.1 20160406 (Red Hat 5.3.1-6), 64 bit)
Built on Jun 16 2020 04:15:35

I don't understand what I'm doing wrong. Can someone please clarify?

A: First, it is not about Qt. It is about your implementation:In  your constructor, I don't see code, which initializes mDialog1 and mDialog2.
So, when go to the slot what is the value of mDialog1 ? It is undefined, especially in Release build.
Here is one of the approaches:
In your constructor, just create the objects:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
  , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    mDialog1 = new Dialog1(this);
    mDialog2 = new Dialog2(this);
}

Then in slot (you don't need to check the pointer):
void MainWindow::on_actiondialog1_triggered()
{
     mDialog1->setModal(false); //Not required, because of show()
     mDialog1->show();
     mDialog1->activateWindow();
 }

Another approach, which creates objects on demand:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
  , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
//Initalize these members
m_dialog1 = nullptr;
m_dialog2 = nullptr;

}

And then:
 void MainWindow::on_actiondialog2_triggered()
 {

if (!mDialog2)
{
    mDialog2 = new Dialog2(this);
    mDialog2->setModal(false);
}
mDialog2->show();
mDialog2->activateWindow();

}


text: Q: How to save logcat messages to new file I am working on a motion event activity. When user touch screen logcat shows some messages. And how can I create a file and save this messages to the file ? Can someone help me in fixing the code. (android studio)


text:
Q: Xamarin Forms - How to write unit test for tabbed pages in xamarin Forms? Can anybody give pointers on how to write automated unit test for tabbed pages in xamarin Forms?
From the documentation provided I have learned that we need to provide automation Id to the control and write the tap command to get focus on the control and input data.
But this doesn't work for tabbed pages. Tried directly giving the tab name and executing tap command, but that doesn't work too.

A: [Test]
public void MyTabTest()
{
    app.Tap(x => x.Marked("Your Tab Title 1"));
    app.Tap(x => x.Marked("Your Tab Title 2"));
    app.Tap(x => x.Marked("Your Tab Title 3"));
}

Also whenever you don't know a command for a UITest the Xamarin TestRecorder is gonna be your best friend.
Hope this works.


text:
Q: Dynamically insert value into cell If TL;DR - Just go down to the EDIT...
I have a spreadsheet with a table - the table is a comparison of two different (but similar) sets of data. So basically 3 columns with the 3rd being the result column with the formula:
=IF(ISBLANK([@[column_name]]),"",IF(COUNTIF([column_name2],[@[column_name]])>0,TRUE,FALSE))
I would like a 4th column that would hold the contents of [@[column_name]] if the result column [@[column_result]] is TRUE, but if the result is FALSE, default it to blank, but some how allow the end user a way that they can populate it with [@[column_name]] if they want.  Or of course they could always manually enter something.
This spreadsheet is going to be used repeatedly, it's more of a template, so the data and row counts will change every time - that's why it's all in a table.
I've thought about maybe having a dynamically generated drop down list that defaults to colmn_name if TRUE and blank if FALSE, but I'm not sure how to do that.  Or maybe a button in the cell if Result is false, that when clicked, disappears and populates the cell with column_name...
Additional Info:
The spreadsheet is basically comparing the fields from two SQL tables and highlighting the differences (there are far more than 3-4 columns, but for the sake of this question, I dumbed it down).  Eventually the data from tableA needs to be mapped to tableB, so I'm using excel to write and format the bulk of the SQL.  There are many tables and many fields that need to be compared.
Also, sorry if this question sucks... I know it does, but I don't really know how to best ask it.

EDIT:
Below is a picture of my spreadsheet. Column M will = column A if columns E-H are true in other words: IF(colsE-H == TRUE) ColM = ColA; ELSE ColM = ""; If there isn't a value in M then the user needs to do some manual investigating, if everything checks out (usually does), then the user will copy/paste A into M.  I would like to have like a dropdown or a button or something that would allow Col M to be populated with Col A's value at the click (two clicks?) of a mouse.

EDIT2: That pic got shrunk a lot.  Here is a link: Screenshot

A: Even with the image (incidentally because of the great quality, I found that more useful than the Screenshot) I am still not entirely clear. It may be that you are after an outer join (not something Excel provides). Also not clear why your last three rows are not in red, nor the significance of your yellow highlighting.
However, it looks as though it would be helpful to identify where column_name does not feature in the list for column_name2.
A VLOOKUP would serve for that:
=VLOOKUP(A18,I:I,1,FALSE)
This will return an error if it does not.
If it does exist, then do field_type, max_length and nullable all match? Easiest to do this 'in bulk' but can be split into four TRUE/FALSE columns (as you have). In bulk an extra column would be helpful (say P). In P18 copied down as required:
=I18&","&J18&","&K18&","&L18
In ColumnOeach NGPROD column_name, field_type, max_length and nullable can then be searched for in ColumnF, with "Col doesn't exist", where that is so:
=IF(ISERROR(VLOOKUP(A18,I:I,1,FALSE)),"Col doesn't exist",VLOOKUP(A18&","&B18&","&C18&","&D18,P18:P34,1,FALSE))

Results in ColumnO should be one of:

*

*The four fields that match (comma separated) [I'd prefer just "blank" where all match but am trying to keep to the spirit of the OP]

*Col doesn't exist [as explained above]

*N/A – ie column_name exists as a column_name2 but one or more of field_type1 / max len1 and nullable1 does not match with field_type2 / max_len2 / nullable2 respectively.
From the above, because the reference is the NGPROD database, ColumM can be populated as below in M18 and copied down as required:
=IF(ISNA(O18),"",IF(O18="Col doesn't exist","",A18))
Then M18:M34 can be validated against a list of A18:A35.


text:
Q: How to pass parameters in Android drawable How to pass arguments in the android drawable.
How to acheive the below mentioned code
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="{colorcode}" />
            <stroke android:width="1sp" android:color="{colorcode}" />
            <corners android:radius="15dp" />
        </shape>
    </item>
</selector>

and then from XML file take this drawable passing values for parameters. Something like
<TextView
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:layout_marginRight="5dp"
    android:layout_weight="1"
    android:background="@drawable/rounded,{colorCode}"
    android:gravity="center"/>

A: You can do it using data binding and BindingAdapter. I will show an example using Kotlin.

*

*To enable data binding add to Your Gradle:

apply plugin: 'kotlin-kapt' // only need when You use Kotlin

...
android {
    ...
    buildFeatures {
        dataBinding = true
    }
    ...
}

*Crete BindingAdapter (I am adding it to MainActivity.kt to simplify code):

import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.databinding.BindingAdapter
import androidx.databinding.DataBindingUtil
import com.myniprojects.teststackjava.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity()
{
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)

        binding = DataBindingUtil.setContentView(
                this, R.layout.activity_main)
    }
}

// Here is binding adapter. It takes 2 colors, background and stroke. If You want more customization add more parameters
@BindingAdapter(value = ["colorStoke", "colorBack"], requireAll = true)
fun setBackground(textView: TextView, @ColorRes colorStoke: Int, @ColorRes colorBack: Int)
{
    val stroke = ContextCompat.getColor(textView.context, colorStoke)
    val back = ContextCompat.getColor(textView.context, colorBack)

    val gd = GradientDrawable()

    // setting background
    gd.colors = intArrayOf(
            back,
            back
    )

    // here change parameters as You want
    gd.gradientType = GradientDrawable.LINEAR_GRADIENT

    gd.shape = GradientDrawable.RECTANGLE
    gd.cornerRadius = 15f;

    // setting stroke width and color
    gd.setStroke(5, stroke)

    textView.background = gd
}

To customize GradeintDrawable check this docs

*In Your MainActivity.xml do this:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <import type="com.myniprojects.teststackjava.R" />
    </data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <TextView
            android:id="@+id/txtVTest"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dp"
            android:gravity="center"
            android:text="TextView Text"
            android:textSize="40sp"
            app:colorBack="@{R.color.color_back}"
            app:colorStoke="@{R.color.color_stroke}"/>

    </FrameLayout>
</layout>

I am importing R to be able to pass resources. (Maybe there is another way without import but I couldn't pass color like @{@color/name} so I just import it). In Your TextView You have to call app:colorBack and app:colorStoke with colors that You want to set as stroke and back.

*Of course in res/values/colors:

<color name="color_stroke">#B71C1C</color>
<color name="color_back">#33691E</color>

*And final effect to show that everything works:

To generate ActivityMainBinding You first have to create a data binding layout. If You added Your dependency correctly to convert fast Your layout to data binding layout use: Alt + Enter ➡ Convert to data binding layout*

So Your layout should look like this:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    </FrameLayout>
</layout>

And now after rebuilding Your project You should get ActivityMainBinding class.

A: ShapeDrawable, GradientDrawable & ColorDrawable are direct subclasses of Drawable. You can explicitly cast your drawable to any of the aforementioned subclasses to invoke methods/property access like setColor(int), .paint like the following:
val drawable: Drawable = (yourDrawable as StateListDrawable).getStateDrawable(0)
when (drawable) {
    is ShapeDrawable -> {
        (drawable as ShapeDrawable).paint.color = ContextCompat.getColor(mContext, R.color.colorToSet)
    }
    is GradientDrawable -> {
        (drawable as GradientDrawable).setColor(ContextCompat.getColor(mContext, R.color.colorToSet))
        (drawable as GradientDrawable).cornerRadius = 2.0F
    }
    is ColorDrawable -> {
        (drawable as ColorDrawable).color = ContextCompat.getColor(mContext, R.color.colorToSet)
    }
}

Points to be noted:
You can use mutate() on this drawable because it returns the same instance of the drawable with the copied constant drawable state. The mutate() method doesn't share its state with any other drawable so it's pretty helpful if you want to keep the drawable as it is & then use it with different states in many places. Here's a great answer to how to use mutate on drawable & save states.
Additionally, as you mentioned in the comments, to change drawable radius too, use cornerRadii which as per the doc in the given embedded link, returns the radii for each of the 4 corners. For each corner, the array contains 2 values, [X_radius, Y_radius]. The corners are ordered top-left, top-right, bottom-right, bottom-left.


text:
Q: Ошибка при запуске Gulp Уже пол дня мучаюсь, все запускается в отдельности кроме BrowserSync.

var gulp    = require('gulp'),
    sass    = require('gulp-sass'),
    browserSync  = require('browser-sync'),
    concat    = require('gulp-concat'),
    uglify   = require('gulp-uglifyjs'),
    cssnano   = require('gulp-cssnano'),
    rename    = require('gulp-rename'),
    del    = require('del'),
    autoprefixer = require('gulp-autoprefixer'),
    csslint   = require('gulp-csslint'),
    shorthand   = require('gulp-shorthand');;

gulp.task('sass', function(){
 return gulp.src('app/sass/**/*.+(scss|sass)')
  .pipe(sass())
  .pipe(autoprefixer(['last 15 versions', '> 1%', 'ie 8', 'ie 7'], { cascade: true }))
  .pipe(csslint())
  .pipe(shorthand())
  .pipe(gulp.dest('app/css'))
  .pipe(browserSync.reload({stream: true}))
});

gulp.task('scripts', function(){
 return gulp.src([
  'app/libs/jquery/dist/jquery.min.js'
  ])
 .pipe(concat('libs.min.js'))
 .pipe(uglify())
 .pipe(gulp.dest('app/js'));
});

gulp.task('css-libs', ['sass'], function(){
 return gulp.src('app/css/libs.css')
  .pipe(cssnano())
  .pipe(rename({suffix: '_min'}))
  .pipe(gulp.dest('app/css'));
});

gulp.task('browser-sync', function(){
 browserSync({
  server: {
   baseDir: 'app'
  },
  notify: false
 });
});

gulp.task('clean', function(){
 return del.sync('dist');
});

gulp.task('watch', ['browser-sync', 'css-libs', 'scripts'], function(){
 gulp.watch('app/sass/**/*.+(scss|sass)', ['sass']);
 gulp.watch('app/*.html', browserSync.reload);
 gulp.watch('app/js/**/*.js', browserSync.reload);
});

gulp.task('build', ['clean', 'sass', 'scripts'], function(){
 var buildCss = gulp.src('app/css/**/*')
  .pipe(gulp.dest('dist/css'));

 var buildFonts = gulp.src('app/fonts/**/*')
  .pipe(gulp.dest('dist/fonts'));

 var buildJs = gulp.src('app/js/**/*')
  .pipe(gulp.dest('dist/js'));

 var buildHtml = gulp.src('app/*.html')
  .pipe(gulp.dest('dist'));

 var buildPhp = gulp.src('app/*.php')
  .pipe(gulp.dest('dist'));
 var buildImg = gulp.src('app/img/**/*')
  .pipe(gulp.dest('dist/img'));
});


text:
Q: How to pass credentials to RESTinstance POST Request in robot framework? Python Code (Working fine):
 credentials = ("key","token")
 verify = False
 if not verify:
     from requests.packages.urllib3.exceptions import InsecureRequestWarning
     requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

response = requests.post(url, auth=credentials, data=json.dumps(payload), headers={'content-type': 'application/json'}, verify=verify)
status = response.status_code

Robot Framework Code:
I would like to duplicate same API testing in robot framework but i am stuck how to pass credentials to the RESTinstance POST method
*** Settings ***
Library         REST    url=https://testhost.com   ssl_verify=${verify}

*** Variables ***
header = {"content-type": "application/json"}

*** Test Cases ***
Test Task
    POST     endpoint=/api/something   body=${payload}   headers=${header}
    Output   response status

ERROR RESPONSE STATUS - 401

A: The auth argument in requests post() method is just a shortcut to http basic authentication.
And it on the other hand is a very simple (hence - basic) one - a header with name "Authorization", with value "Basic b64creds", where b64creds is base64 encoded form of the "user:password" string.
So the flow is quite simple - encode the credentials, and add them as a header. There is only one caveat - python's base64 module works with bytes, where the strings in Robotframework/python3 are unicode, so they have to be converted.
${user}=    Set Variable    username
${pass}=    Set Variable    the_password

# this kyword is in the Strings library
${userpass}=    Convert To Bytes    ${user}:${pass}   # this is the combined string will be base64 encode
${userpass}=    Evaluate    base64.b64encode($userpass)    base64

# add the new Authorization header
Set To Dictionary    ${headers}    Authorization    Basic ${userpass}

# and send the request with the header in:
POST     endpoint=/api/something   body=${payload}   headers=${header}


text:
Q: Possible to remove inherited members or prevent inheritance of certain properties/methods? I'm wondering if it is at all possible to "remove" members/methods from a base class, or rather inhibit them for being inherited?
Say I have a class A that defines a subscript operator and stores the read/writes of that operator in a map object internally. Then I create B which inherits from A. Is there any way I can remove the subscript operator from B, or rather, prevent it from being inherited and thus becoming part of B?
Sorry for being so verbose, but to make it clear, I'm not looking for functionality such as the final keyword, where I want to prevent B from overloading something in A. I'm looking to basically say "B, inherit everything from A EXCEPT X". I figure it's not possible and most likely the answer is going to be "fix/improve your design", just thought there was no harm in asking anyway.

A: Make the function (or the member) that you want to "delete" private, so the derived class will not be able to "see it". There is no other way of physically removing the function from the derived object (as the derived object contains a copy of the base class, in which your function/member is needed), but making it private guarantees that the derived object has no access to it.