text:
Q: Error LNK 2019 Unresolved external symbol I have read several related  post on stackoverflow but couldn't relate the solutions with the problem in my code. Description of error is
1>CAN.obj : error LNK2019: unresolved external symbol "public: __thiscall CLogObjectCAN::CLogObjectCAN(class CString)" (??0CLogObjectCAN@@QAE@VCString@@@Z) referenced in function "void __cdecl `dynamic initializer for 'd_obj''(void)" (??__Ed_obj@@YAXXZ)

why compiler throwing this error ?, i am not good in OOP, trying to modify some existing mode.
CAN.cpp
#include "BaseLogObject.h"
 #include "LogObjectCAN.h"
CString s2( "version" );
CLogObjectCAN *d_obj = new CLogObjectCAN(s2);
CBaseLogObject *obj = d_obj;

static int config_print_error(int error, int channel) {
    CString Header= "";
    obj->vLog_Embaserror(Header, "EMBAS");
}

BaseLogObject.h
class CBaseLogObject {
public:
    CBaseLogObject(CString omVersion);

    ~CBaseLogObject();
virtual void vLog_Embaserror(CString& omHeader, char* mHeader);
};

BaseLogObject.cpp
#include "BaseLogObject.h"
CBaseLogObject::CBaseLogObject(CString omVersion):m_omVersion(omVersion) {
    vResetValues();
}
void CBaseLogObject:: vLog_Embaserror(CString& omHeader, char* mHeader) {
    omHeader = "***EMBAS ";

}

LogObjectCAN.h
#include "BaseLogObject.h"
class LogObjectCAN: public CBaseLogObject {
public:

void vLog_Embaserror(CString& omHeader, char* mHeader);
public:
    CLogObjectCAN(CString omVersion);
    ~CLogObjectCAN();
}

LogObjectCAN.cpp
#include "LogObjectCAN.h"
    CLogObjectCAN::CLogObjectCAN(CString omVersion):CBaseLogObject(omVersion) {
        // Initialise the filtering block
        m_sFilterApplied.vClear();
        m_pasControllerDetails = NULL;
        m_nNumChannels = 0;
    }
    void CLogObjectCAN::vLog_Embaserror(CString& omHeader, char* mHeader) {
        if(strcmp(mHeader, "EMBAS")== 0) {
            CBaseLogObject::vLog_Embaserror(omHeader, "driver");
            omHeader += CAN_Embas;
            omHeader += L'\n';
        }
    }


text:
Q: Can't load XmlReader into XDocument I'm trying to load an XmlReader into an XDocument for easier manipulation. The XML is well formed and valid (I double checked). When I try and load it into the XDocument, I get an InvalidOperationException

The XmlReader state should be EndOfFile after this operation.

the code to load this is
public void ReadXml(System.Xml.XmlReader reader)
{
    var doc = XDocument.Load(reader);
}

I've included a sample of the XML that causes the problem. I can serialize and deserialize this class without a problem, but not load it. Any ideas?
<?xml version="1.0" encoding="utf-8"?>
<ForestView xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Forest>
 <TreeNodeView>
  <Level>Master</Level>
  <ID>39476b1f-e2f8-4d76-b82e-a5166899ad43</ID>
  <Name>Black Mesa</Name>
  <ServerIPAddress>127.0.0.1</ServerIPAddress>
  <ServerPortNumber>8000</ServerPortNumber>
  <ClientIPAddress>NA</ClientIPAddress>
  <ClientPortNumber>4000</ClientPortNumber>
  <Nodes>
    <Level>Server</Level>
    <NodeID>062c3e03-235d-4d7d-9b60-c6228c9cc89e</NodeID>
    <Name />
    <ServerIPAddress>127.0.0.1</ServerIPAddress>
    <ServerPortNumber>5000</ServerPortNumber>
    <ClientIPAddress>127.0.0.1</ClientIPAddress>
    <ClientPortNumber>4000</ClientPortNumber>
  </Nodes>
  <Nodes>
    <Level>Intermediate</Level>
    <NodeID>9bafdc9e-771e-42cf-8f03-e7e75a67a6d1</NodeID>
    <Name>Jen</Name>
    <ServerIPAddress>127.0.0.1</ServerIPAddress>
    <ServerPortNumber>8001</ServerPortNumber>
    <ClientIPAddress>127.0.0.1</ClientIPAddress>
    <ClientPortNumber>8000</ClientPortNumber>
    <Nodes>
      <Level>Terminal</Level>
      <NodeID>72509141-0ab8-45c1-8042-30afb233b4a8</NodeID>
      <Name>Mary</Name>
      <ServerIPAddress>127.0.0.1</ServerIPAddress>
      <ServerPortNumber>0</ServerPortNumber>
      <ClientIPAddress>127.0.0.1</ClientIPAddress>
      <ClientPortNumber>8001</ClientPortNumber>
    </Nodes>
   </Nodes>
  </TreeNodeView>
 </Forest>
</ForestView>

A: Quite late answer, in case somebody is having the same issue.
You can fix it by using ReadSubtree() on the reader, like:
public void ReadXml(System.Xml.XmlReader reader)
{
     var doc = XDocument.Load(reader.ReadSubtree());
}

A: This error implies that there is extra data after the reader has loaded what it thinks is an XML document.  Please verify that your XML file contains no data after the final closing element and that the XmlReader is initialized to read from the root element or start of the file, and nothing else.

A: Another late answer, but I ran into a problem with the reader.ReadSubtree() workaround and this ended up working for my situation. The basic approach is reading into a string, then calling XDocument.Parse():
XDocument doc;
var textReader = reader as XmlTextReader;
if (textReader != null)
{
    var xml = textReader.ReadOuterXml();
    doc = XDocument.Parse(xml);
}
else
    doc = XDocument.Load(reader);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Input::has for radio button value in if statement laravel So i got this form in a page for my laravel project where my form does a get request to the url.

        <input name="BalanceType" type="radio" value="pos">
        Positiv

        <input name="BalanceType" type="radio" value="neg">
        Negativ

        <input name="BalanceType" type="radio" value="null">
        Noll

Ive understood that if you gonna have radio buttons then their name better be the same but with different values if you want to check and uncheck the others.
Now what i use my radio buttons for is filtering different type of users and their balance if its negative, positive or null.
Now im trying to figure out what i should write in my if statement in my controller. Before i tried checkboxes and used if(Input::has('name')) and so on. This worked but that was only for checkboxes with different names, now i want to use radio buttons.
My question is, how do i check if a radio button with a specific type of value is checked like i did with checkboxes and Input::has?
My controller:
public function balanceCheck()
{
    $user = Auth::user();
    $users = Auth::user()->school->users()->orderBy('id', 'DESC')->get();

    if()
    {
        $users = Auth::user()->school->users()->where('balance', '>', 0)->orderBy('id', 'DESC')->get();
    }
    if()
    {
        $users = Auth::user()->school->users()->where('balance', '<', 0)->orderBy('id', 'DESC')->get();
    }
    if()
    {
        $users = Auth::user()->school->users()->where('balance', '=', 0)->orderBy('id', 'DESC')->get();
    }

    return View::make('admin.overview', ['user' => $user, 'users' => $users]);
}

Thanks in advance

A: if You want to only check the radio button status i.e it check or not than try like this
    if(isset($_POST['BalanceType'])){
        $radio_input=$_POST['BalanceType'];
        if($radio_input =="some value"){
         //do some thing.....
        }elseif($radio_input =="some other value"){
         //do some thing else.....
        }else{
              //the last condition goes here
             }
     }

A: Like suggested above, you can do a simple check in you controller. To be more Laravel-like style you can do
$balanceType = Input::has('BalanceType') ? Input::get('BalanceType') : null;

if ($balanceType == 'pos') {
    $users = Auth::user()->school->users()->where('balance', '>', 0)->orderBy('id', 'DESC')->get();
} elseif ($balanceType == 'neg') {
    $users = Auth::user()->school->users()->where('balance', '<', 0)->orderBy('id', 'DESC')->get();
} elseif ($balanceType == 'null') {
    $users = Auth::user()->school->users()->where('balance', '=', 0)->orderBy('id', 'DESC')->get();
}

this should accomplish what you need but this is not a recommended approach to go with at all. See, very quickly your controller will start to look like a mess. With all those if statements, checks if to do that or that. It's not a controller job. Instead you could delegate a piece of work that needs to be done to some other classes that are more likely to be responsible for doing this. For example, in Laravel world it's common to have Repositories.
Think of repository as a class that interacts with you models. It may does different DB queries and fetch whatever you need, leaving  the controller nice and clean with only one line of code to invoke the appropriate method on your repository class. It's not to mention, that later you could reuse the code from your repository, if you need exact same query in a different part of your app. For example, for your scenario, you might have a UserRepository class.
Create a class in the app/Repositories/UserRepository.php
<?php

namespace Repositories;

class ArticleRepository
{

    /**
     * @var User
     */
    protected $model;

    /**
     * @param User $model
     */
    public function __construct(User $model)
    {
        $this->model = $model;
    }

    public function getByBalanceType($balanceType)
    {
         if (! $balanceType) return null;
if ($balanceType == 'pos') {
    $users = $this->model->school->users()->where('balance', '>', 0)->orderBy('id', 'DESC')->get();
} elseif ($balanceType == 'neg') {
    $users = $this->model->school->users()->where('balance', '<', 0)->orderBy('id', 'DESC')->get();
} elseif ($balanceType == 'null') {
    $users = $this->model->where('balance', '=', 0)->orderBy('id', 'DESC')->get();
}
        return $users;
    }
}

After that in your controller you could inject this repository in constructor.
public function __construct(UserRepository $userRepository)
{
    $this->userRepository = $userRepository;
}

ANd then, your balanceCheck method would look
public function balanceCheck()
{
    $user = Auth::user();
    $users = Auth::user()->school->users()->orderBy('id', 'DESC')->get();
     $balanceType = Input::has('BalanceType') ? Input::get('BalanceType') : null;
    $users = $this->userRepository->getByBalanceType($balanceType);
    return View::make('admin.overview', ['user' => $user, 'users' => $users]);
}

but of course you can go with first approach, it's much simpler, easier to use and more clear, probably. But once you get to maintain large apps with lots of stuff going on, you'll quickly mind the significance of the latter approach.


text:
Q: Python - Maintain Folder Structures while Zipping I've got an extremely specific use-case, where I've got multiple folders in a single directory, each of which as subfolders and files, so on and so forth. I need to be able to zip all of those top-level folders into the same archive, while preserving ALL folder / path structure.
For example, if the original folder structure was like this:
/topLevel
   - /directory1
      - /directory1_subfolder
         - /subfolderOfSubfolder
            -/file.txt
         - /file.txt
      - /directory1file.txt
   - /directory2
      - /directory2_subfolder
         - /file.txt
      - /directory2file.txt

I would want it to look EXACTLY like that in the zip archive.
I was using this code I modified from a different StackOverflow post, but it doesn't seem to work for my use-case:
archive = ZipFile('archive_name.zip', 'w')
try:
    for folderName, subfolders, filenames in os.walk(PATH + "/assets"):
        for filename in filenames:
            #create complete filepath of file in directory
            filePath = os.path.join(folderName, filename)
            print(YELLOW + "BUILD: " + GREEN + filePath + RESET)
            # Add file to zip
            archive.write(filePath, basename(filePath))

    for folderName, subfolders, filenames in os.walk(PATH + "/data"):
        for filename in filenames:
            #create complete filepath of file in directory
            filePath = os.path.join(folderName, filename)
            print(YELLOW + "BUILD: " + GREEN + filePath + RESET)
            # Add file to zip
            archive.write(filePath, basename(filePath))

    for folderName, subfolders, filenames in os.walk(PATH + "/modules"):
        for filename in filenames:
            #create complete filepath of file in directory
            filePath = os.path.join(folderName, filename)
            print(YELLOW + "BUILD: " + GREEN + filePath + RESET)
            # Add file to zip
            archive.write(filePath, basename(filePath))

    for folderName, subfolders, filenames in os.walk(PATH + "/scripts"):
        for filename in filenames:
            #create complete filepath of file in directory
            filePath = os.path.join(folderName, filename)
            print(YELLOW + "BUILD: " + GREEN + filePath + RESET)
            # Add file to zip
            archive.write(filePath, basename(filePath))

    for folderName, subfolders, filenames in os.walk(PATH + "/settings"):
        for filename in filenames:
            #create complete filepath of file in directory
            filePath = os.path.join(folderName, filename)
            print(YELLOW + "BUILD: " + GREEN + filePath + RESET)
            # Add file to zip
            archive.write(filePath, basename(filePath))
except Exception as err:
    print(YELLOW + "BUILD:" + RED + " <ERROR> " + SPECIALDRIVE + str(err) + RESET)

It just jumbles all of the files together
like this
Print output looks correct, for the most part.
Does anyone have any suggestions on how I can get Python to maintain my folder's structures? Thanks in advance!


text:
Q: Context of using Object Storage Can someone please give me a solid use case example (in terms of performance/scalability/reliability) that an Object Storage FS should be used over Block Storage FS?
I am so confused since PM wants us to use MinIO in a company's project, but didn't give reasons for why are we should use it without any obvious pros?
I have read below posts, but I don't think these resolve my query.
What is Object storage really?
Difference between Object Storage And File Storage

A: Block storage is a traditional disk. In the old days, you would walk down to the computer store, buy a Hard Disk Drive that has a specific amount of storage (eg 1TB), plug it into the computer and then use it for storage. If it runs out of disk space, you had to delete files or buy additional disks.
This type of storage is called 'Block Storage' because the disk is divided into many blocks. The Operating System is responsible for managing what data is stored in each block and it also maintains a directory of those files. You'll see terms like FAT32 or exFAT for these storage methods.
Computers expect to have this type of directly attached disk storage. It's where the computer keeps its operating system, applications, files, etc. It's the C: and D: drives you see on Windows computers. When using services like Amazon EC2, you can attach Block Storage by using the Amazon Elastic Block Store service (Amazon EBS). Even though storage is virtual (meaning you don't need to worry about the physical disks), you still need to specify the size of the disk because it is pretending to be a traditional disk drive. Therefore, you can run out of space on these disks (but it is fairly easy to expand their size).
Next comes network-attached storage. This is the type of storage that companies give employees where they can save their documents on the network instead of a local disk (eg the H: drive). The beauty of network-attached storage is that it doesn't look like blocks on a disk -- instead, the computer just says "save this file" or "open this file". The request goes across the network to a file server, which is responsible for storage the actual data on the disk. This is a much more efficient way to store data since it is centralized rather than on everybody's computer and it is much easier to backup. However, your company still needs to have disk drives that store the actual data.
Then comes object storage which has become popular with the Cloud. You can store files in Amazon S3 (or MinIO, which is S3-compatible) without worrying about hard disks and backups -- they are the job of the 'cloud'. You simply store data and somebody else worries about how that data is stored. It is typically charged via pay-as-you-go, so instead of buying expensive hard disks up-front, you just pay for the amount of storage used. The data is typically automatically replicated between multiple disks so it can survive the failure of disk drives and even data centers. You can think of cloud-based block storage as unlimited in size. (It isn't actually unlimited, but it acts like it is.)
Services like S3 and MinIO also do more than simply store the data. They can make the objects available via the Internet without having to run a web server. They can have fine-grained permissions to control who (and what) can access the data. Amazon S3 is very 'close' to other AWS services, making it very fast to use data in Amazon EC2, Amazon EMR, Amazon RDS, etc. It's even possible to use query engines like Amazon Athena that allow you to run SQL commands to query data stored in Amazon S3 without needing to load it into a database. You can choose different storage classes to reduce cost while trading-off access speed (like the old days of tape backup). So think of Object Storage as 'intelligent storage' that is much more capable than a dumb disk drive.
Bottom line: Computers expect to have block storage to boot and run apps, but block storage isn't a great way to manage the storage of large amounts of data. Object Storage in the Cloud is as simple as uploading and downloading data without having to worry about how it is stored and how to manage it -- that is the cloud's job. You get to spend your time adding value to your company rather than managing storage on disk drives.


text:
Q: PHP session.cookie_domain not setting PHPSESSID for localhost project URLs only I'm trying to set the cookie domain for local URLs such as http://local-myproject and http://en.local-myproject, etc:
ini_set('session.cookie_domain', '.local-myproject');

But when I check whether the PHPSESSID cookie was written for this domain, it is missing. Only when I remove this line does the cookie appear. But, I want to be able to share the cookie across subdomains. Does my browser (Chrome and FF) not like this value .local-myproject as a cookie domain? Does it have to be a valid URL? e.g. local-myproject.com (I could always create these for all my projects in /etc/hosts)


text:
Q: Storing data into a file for one time and avoid any changes after running the code again My code
Here I take a name from a user and save it to a file, my purpose is to give that name an index (Out) and save it into a file, so that each time I run the code, I will still have the same name and index(not new values). So how can I do that?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class h_main {
  public static void main(String[] args) {
    contact[] table = new contact[3]; //Create an object of contact class
    int tablesize = 3;

    // Input from user

    //**Inserting from user**//
    Scanner reader = new Scanner(System.in); // Reading from System.in
    System.out.println("Enter a name: ");
    String names = reader.nextLine();

    // Save the inserted name inside a table array with an index Out(from the hash function)

    int Out = calc_hash(names, tablesize);
    table[Out] = new contact();
    table[Out].Name = names;
    System.out.println(Out);

    // Writing

    for (int i = 0; i < table.length; i++) {
      FileWriter fWriter = null;
      BufferedWriter writer = null;
      try {
        fWriter = new FileWriter("text.txt");
        writer = new BufferedWriter(fWriter);
        writer.write(table[i].Name);
        writer.write(table[i].phone);
        writer.newLine();
        writer.close();
      }
      //   System.err.println("Your input of " + table[i].Name.length + " characters was saved.");
      catch (Exception e) {
        System.out.println("Error!");
      }

      // Reading

      // The name of the file to open.
      String fileName = "text.txt";

      // This will reference one line at a time
      String line = null;

      try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader = new FileReader("text.txt");

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        while ((line = bufferedReader.readLine()) != null) {
          System.out.println("Name: " + line);
        }

        // Always close files.
        bufferedReader.close();
      } catch (FileNotFoundException ex) {
        System.out.println(
          "Unable to open file '" +
          "text.txt" + "'");
      } catch (IOException ex) {
        System.out.println(
          "Error reading file '" +
          "text.txt" + "'");
        // Or we could just do this:
        // ex.printStackTrace();
      }
    }
  }

  //**Generate hash function**//
  public static int calc_hash(String names, int table_size) {
    int i, l = names.length();
    int hash = 0;
    for (i = 0; i < l; i++) {

      hash += Character.getNumericValue(names.charAt(i));
      hash += (hash << 10);
      hash ^= (hash >> 6);
    }
    hash += (hash << 3);
    hash ^= (hash >> 11);
    hash += (hash << 15);
    if (hash > 0) return hash % table_size;
    else return -hash % table_size;
  }
}

Class contact
    public class contact {
    String Name ;
    int phone ;
}

A: Have the file not exist when you run the program for the first time. After you do, use the existence of the file to determine whether the program has been run before or not. Your code could look like this:
import java.nio.file.*;
import java.util.stream.*;

public class Main {

    public static void main(String[] args) {
        // It's recommended to follow Java naming and style conventions:
        // Class names always begin with an uppercase letter
        Contact[] table = new Contact[3];
        String fileName = "text.txt";

        Path file = Paths.get(fileName);
        // Check for persistence file:
        if(Files.exists(file)) {
            // If all you need to do is print each line, try this:
            try {
                Files.lines(file).forEach(l -> System.out.println("Name: " + l));
            } catch(IOException e) {
                System.err.println("Error reading data file!");
            }
        } else {
            // Take data input
            Scanner scanner = new Scanner(System.in);
            // ...

            // When program is terminated, save everything:
            try(BufferedWriter writer = Files.newBufferedWriter(file)) {
                // use writer to write data...
            } catch(IOException e) {
                System.err.println("Error writing data file!");
            }
        }

    }

}


text:
Q: Delphi Berlin 10.1 FireDac For OSX I have Fire-Monkey application on Delphi. App was created few years before, i don't know the version of XE it was used. I use Delphi Berlin 10.1
I need to manage possibility to run app on OS X. Application contains FireDac and it can't build for OS X.
I have the next output:
[dccosx Fatal Error] E2202 Required package 'FireDACDb2Driver' not found

I was trying to create other simple application for OS X. And i've got it. All steps are needed to deploy to OS X are included here.
I've read article: this
But when i test connection i have password error exception.
Any idea?


text:
Q: Angular 4 router loses params when refreshing page When i am using router link, the router finds the page and renders it
but when i am trying to refresh the page or re enter from the url, it fails and gives me this error:
Error: Cannot match any routes. URL Segment: 'project'
I've searched a lot before asking here but couldn't find an answer.
The link i am using:
http://localhost:4200/#/project/5
This is my router configuration:
export const routes: Routes = [
    { path: '', component: UserHomepageComponent },
    { path: 'signin', component: SigninComponent },
    { path: 'signup', component: SignupComponent },
    { path: 'userHomepage', component: UserHomepageComponent },
    { path: 'project/:project', component: ProjectComponent }
];

the link that does work:

{{project.id}} - {{project.description}}

Any ideas?

A: Your code should be just

{{project.id}} - {{project.description}}

Also i see that you have # in the path, so when you refresh it may cannot find the matching routes!
change your app.module without these,
{provide: LocationStrategy, useClass: HashLocationStrategy}


text:
Q: ¿Por que en mi input tipo text que formatea los numeros ingresados ej: "1000" a "1.000,00" al actualizarlo se borra todo o conserva 2 o 3 valores? Este vendria ser mi codigo, lo que quiero lograr es que si una persona al ingresar un valor "1000" al darle tab o salir del campo se formatee a "1.000,00" y si la persona se equivoco de valor ingresado que pueda modificarlo por ejemplo que pueda borrar un 0 de esos mil "1.00,00" y pueda introducir cualquier otro valor "1.200,00" y se conserve la convertibilidad sin que se le borre lo anterior ingresado.
Este es mi código:
<input id="moneda" type="text" onkeyup="allowOnlyNumbers(this)" onblur="currencyFormatte(this, 2)">

function allowOnlyNumbers(input){
  const regexCurrency = new RegExp('[^0-9,.]');
  const regexMultipleChars = new RegExp('[,.]{2}');
  if(regexCurrency.test(input.value)){
    input.value = input.value.replace(/[^\d.,]+/g, '');
  }
  const decimales = input.value.split(",", 2)[1];
  const cantidadComas = input.value.match(/,/g) != null ? input.value.match(/,/g)?.length : 0;
  const cantidadPuntos = input.value.match(/\./g) != null ? input.value.match(/\./g)?.length : 0;
  if((cantidadComas != undefined && cantidadComas > 1) || (cantidadPuntos  != undefined && cantidadPuntos > 1))input.value = input.value.slice(0, -1);
  if((cantidadComas != undefined && cantidadComas == 1) && (cantidadPuntos  != undefined && cantidadPuntos == 1)) input.value = input.value.slice(0, -1);
  if(regexMultipleChars.test(input.value)) input.value = input.value.slice(0, -1);
  if(cantidadComas != undefined && cantidadComas == 1 && decimales.length > 2 ) input.value = input.value.slice(0, -1);
}

function currencyFormatte(input, maxLength){
  const entero = input.value.split(/[,.]/g, 2)[0];
  let formattedValue = input.value;
  if(input.value == "0")
  {
    formattedValue = "0";
  }else if(input.value != "" && entero.length > 0 && !input.value.includes(",")){
    formattedValue = Number(input.value).toLocaleString('de-DE', {minimumFractionDigits: maxLength, maximumFractionDigits: maxLength});
  }
  else if(input.value != "" && entero.length > 0 && input.value.includes(",")){
    formattedValue = Number(input.value.replaceAll(".","").replace(",", ".")).toLocaleString('de-DE', {minimumFractionDigits: maxLength, maximumFractionDigits: maxLength});
  }
   return input.value = formattedValue;
}

A: Para convertir en el formato requerido basta con hacer lo siguiente:
function format(txt){
  txt.value= Number(txt.value).toLocaleString("es-ES", {minimumFractionDigits: 2});
}

Lo complejo es validar, sobre todo al volver al input porque, por ejemplo "12.344,34" no es un número valido en javascript, así que al regresar hay que limpiarlo. Además nunca sobra poner algunas validaciones
Aquí una demo con 3 funciones:
1.- format que se ejecuta cuando se pierde el foco del control (evento blur)
Aquí se formatea el número usando toLocaleString
2.- clean Limpia el formato anterior a un formato valido numéricamente en Javascipt, es decir sin separador de miles, y con el separador de decimales como un punto
3.- GetValidNumber Convierte en valor del input en un número y lo retorna, y si no puede retorna null. Adicionalmente agregué que mostrara un borde rojo si no era posible convertirlo a número.

function format(txt){
 let numero = GetValidNumber(txt);
 if(numero){
    txt.value= numero.toLocaleString("es-ES", {minimumFractionDigits: 2});
 }
}

function clean(str){
  return str.replace(".","|").replace(",",".").replace("|","");
}

function GetValidNumber(txt){
 let numero = Number(clean(txt.value));
 if(Number.isNaN(numero)){
  txt.setCustomValidity("Número no valido");
  return null;
 }
 txt.setCustomValidity("");
 return numero;
}
input:invalid{
  border-color:red;
}
<input type="text" onblur="format(this)">


text:
Q: How to use .so file in Android code to use the native methods I have libmath.so file which have native methods in it. I need to call the native methods in my android code. I have created a sample android application and added the libmath.so inside libs/armeabi folder, Then ran "Right-click mouse" -> Android Tools -> Add native support. Now the following files with below content are created inside jni folder of the application.
Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE    := libmath
LOCAL_SRC_FILES := libmath.cpp
include $(BUILD_SHARED_LIBRARY)

libmath.cpp
#include <jni.h>

When I run the Project as android application it shows as follows in the console :-
17:58:41 **** Build of configuration Default for project math ****
"F:\\Vinay\\Softwares\\android-ndk-r10d\\ndk-build.cmd" all
[armeabi] Compile++ thumb: math <= libmath.cpp
[armeabi] StaticLibrary  : libstdc++.a
[armeabi] SharedLibrary  : libmath.so
[armeabi] Install        : libmath.so => libs/armeabi/libmath.so
17:58:53 Build Finished (took 11s.695ms)

Here is the code how I am loading the library:-
public class MathJni {
static {
    System.loadLibrary("math");
}
public native String calc(String paramString);

}
public static final MathJni math = new MathJni();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String s= math.calc("help");

    }

Once after running the android application when I launch the application through emulator I am getting the below error.
02-06 07:38:36.900: D/dalvikvm(831): Trying to load lib /data/app-lib/com.example.math-2/libmath.so 0xb3cd0848
02-06 07:38:36.900: D/dalvikvm(831): Added shared lib /data/app-lib/com.example.math-2/libmath.so 0xb3cd0848
02-06 07:38:36.910: D/dalvikvm(831): No JNI_OnLoad found in /data/app-lib/com.example.math-2/libmath.so 0xb3cd0848, skipping init
02-06 07:38:37.540: W/dalvikvm(831): No implementation found for native Lcom/example/math/MathJni;.calc:(Ljava/lang/String;)Ljava/lang/String;
02-06 07:38:37.540: D/AndroidRuntime(831): Shutting down VM
02-06 07:38:37.550: W/dalvikvm(831): threadid=1: thread exiting with uncaught exception (group=0xb3a20ba8)
02-06 07:38:37.570: E/AndroidRuntime(831): FATAL EXCEPTION: main
02-06 07:38:37.570: E/AndroidRuntime(831): Process: com.example.math, PID: 831
02-06 07:38:37.570: E/AndroidRuntime(831): java.lang.UnsatisfiedLinkError: Native method not found: com.example.math.MathJni.calc:(Ljava/lang/String;)Ljava/lang/String;
02-06 07:38:37.570: E/AndroidRuntime(831):  at com.example.math.MathJni.calc(Native Method)
02-06 07:38:37.570: E/AndroidRuntime(831):  at com.example.math.MainActivity.onCreate(MainActivity.java:16)

What can be the possible reason for this error.

A: if you have written no C++ code and only prebuilt .so files to use directly from Java, you don't have to use the NDK.
Simply drop the .so file inside your project, under libs/<abi> for an eclipse project - under jniLibs/<abi> for a gradle project.
Here what you did was to create a libmath NDK module with an almost empty content. When you built your project, the NDK generated a new libmath.so file with nothing from your initial library. So delete all your jni files and folders, copy your former .so files back to libs/<abi>, and run your project again.
If you run into other issues, verify that your libmath.so implements jstring com_example_math_MathJni_calc(JNIEnv* env, jobject* obj), or check what you should declare native in the Java side to use your lib, with the right package name and signature (if there was a documentation that came along with your .so files, it should state that).


text:
Q: Seeking advice on using QGLWidget in Qt4 I'm new here, and have a question about opengl in Qt4, which I've been learning over the last few months.
Particularly, I'm seeking advice on the best way to compose a scene in a good object-oriented fashion using the QGLWidget. I'd ideally like every item in my scene to be sub-classes of a super 'Entity' class. Then in my main QGLWidget I can sort the entities and render them accordingly.
I noticed though that certain openGL functions (like bindTexture) need to be called from the QGLWidget (or the widget's QGLContext). At the moment I'm passing a pointer to the QGLWidget that controls my main viewport to each entity and storing it so that I can gain access to those functions. Is this a good idea?
Any advice would be gratefully received, or even directions to good websites/books that might be of help. I've got the Blanchette/ Summerfield book but the OpenGL section is quite short and most of the examples on the Qt website are pretty simplistic.
Thanks,
Dan

A: I agree with Vime: You're building a scene graph, and there are a number of classical approaches for designing its object hierarchy. Check out "3D Game Engine Design," by Dave Eberly, for details on one such engine, and look at OGRE for another example.
Since only one GL context can be active at a time on a particular thread, consider storing the QGLWidget pointer as a static class member to save effort:
class MyGLWidget : public QGLWidget {
    // ...
public:
    static inline MyGLWidget *GetActiveWidget() {
        return ms_activeWidget;
    }
protected:
    static __declspec(thread) MyGLWidget *ms_activeWidget = 0; // uses MSVC extension
    inline void SetActiveWidget() {
        ms_activeWidget = this;
    }
};

void MyGLWidget::paintGL() {
    SetActiveWidget();
    // ...
}

Then in your entity classes you can simply call MyGLWidget::GetActiveWidget() on the few occasions when you need to call QGLWidget member functions, and not need to copy a (probably invariant) pointer all over the place.

A: You are building something that is usually called "scene graph". In our engine scene graph objects need no access to QGLWidget. It's enough if you create your OpenGL objects inside void initializeGL() and render everything inside void paintGL().
There is a slightly higher level Qt/OpenGL example called Boxes. It can be found from qt/demos/boxes folder in Qt 4.6 installation.


text:
Q: Both Standby and ambient are Same in Android In Android smart watch,If device is not interactive then watch will enter from Interactive Mode to Ambient Mode
In this Google link https://www.youtube.com/watch?v=Rwshwq_vI1s,they have explained only App StandBy and Doze mode
My Query here is Android Wear App flow will be from Interactive -> Ambient -> StandBy
or
Both App Standby and Ambient is Same?

A: Ambient Mode and App Standby are not the same, ambient mode allows your app to keep running on the foreground while staying visible to the user, and if your app is running on the foreground it will not enter to the stand by mode, see next paragraph:

App Standby allows the system to determine that an app is idle when the user is not actively using it. The system makes this determination when the user does not touch the app for a certain period of time and none of the following conditions applies:

*

*The app has a process currently in the foreground (either as an activity or foreground service, or in use by another activity or
foreground service).

As you can see the ambient mode allows you to stay on the foreground thus not allowing to enter Stand By, it's worth noting that to be able to use the Ambient Mode the user has to enable the option Always on screen on the device.


text:
Q: Converting written numbers in text into a sum using for loops Hi all I am completing an on-line exercise where I have to create a program that reads several paragraphs of text. All numbers (written in text) has to be added together and a sum shown at the end.
I have several questions if you guys dont mind answering as I have researched this quite a bit.
This is just an example of the text that is used:
eg  Just remember that you're standing on a platform at twelve o'clock and there are
        five trains that run every hour on nine tracks. A train can go as fast as two hundred miles
        an hour. One of millions of billions...
I am using the StringTokenizer so each word is read individually.
From research I have learnt to create  arrays that represent each word (please see code example), this is so the words are easily represented into ints. Though i have also create variables for each of the numbers, this is prob not required though I do not understand how Java can represent a word to its significant number. (again please see code).
Though my biggest problem is how would I go about combining words like two hundred and eigthy one = 281 using a loop.
Any advice would be greatly appreciated, I know this code is far from perfect as I am continuing to learn though online material and books.
class wordsToNumberAdder

{
    public static void main()
{

    String str = "Just remember that you're standing on a platform at twelve o'clock and there are
    five trains that run every hour on nine tracks. A train can go as fast as two hundred miles
    an hour. One of millions of billions... ";

    StringTokenizer st = new StringTokenizer(str);

String[] digits = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
String[] tens = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
String[] teens = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
String[] power = {"hundred","thousand","million","billion"};

int one = 1, two = 2, three = 3, four = 4, five = 5, six = 6, seven = 7, eight = 8, nine = 9;
int twenty = 20, thirty = 30, forty = 40, fifty = 50, sixty = 60, seventy = 70, eighty = 80, ninety = 90;
int ten = 10, eleven = 11, twelve = 12, thirteen = 13, forteen = 14, fifthteen = 15, sixteen = 16;
int eighteen = 18, nineteen = 19, thirty = 30, hundred = 100, thousand = 1000;
long billion = 1000000000;

double result = 0;
double group = 0;

while (set.hasMoreTokens()) {
        String word = set.nextToken();

for (int x = 0; x < power.length; i += 3) {

            if (word.equals(power[i])) {
            group = group * Math.pow(10, i);
            result = result + group;
            group = 0;
        }
    }

A: To me there are two sub-problems here: parsing the input into a collection of number phrases ("two hundred and four". etc.) and translating those number phrases into actual values to sum.
There's no reason not to use a map for the word to value parsing. So instead of all those fields, try this out:
private static final Map<String, Long> NUMBER_MAP;
static {
  final Map<String, Long> map = new HashMap<String, Long>();
  map.put("one", 1L);
  map.put("two", 2L);
  map.put("three", 3L);
  ...
  map.put("hundred", 100L);
  map.put("hundreds", 100L);
  ...
  map.put("billion", 1000000000L);
  map.put("billions", 1000000000L);
  NUMBER_MAP = Collections.unmodifiableMap(map);
}

Couple of things about this: first, it's immutable so none of these mappings can change, and it is good practice to minimize mutability in your code. I also added plurals of several words to ease parsing. There might be a more elegant way of handling these plurals, but I kept it simple. I also have everything as longs for simplicity, too.
Now, for the parsing. Using a StringTokenizer is a good start, but you're not doing much with it. Here is how I would implement the parsing:
public static void main(final String[] args) {
  final StringTokenizer tokenizer = new StringTokenizer(paragraph.replace(".", " ").toLowerCase());
  final StringBuilder phrase = new StringBuilder();
  final Set<String> numberSet = NUMBER_MAP.keySet();

  while (tokenizer.hasMoreTokens()) {
    final String token = tokenizer.nextToken();

    if (numberSet.contains(token)) {
      if (phrase.length() > 0) {
        phrase.append(" ");
      }
      phrase.append(token);
    } else if (!IGNORED_WORDS.contains(token)) {
      processPhrase(phrase.toString());
      phrase.setLength(0);
    }
  }

  processPhrase(phrase.toString());
}

So what have I done here? First, I'm sanitizing the input string to handle periods and capitals. That way we can parse a sentence like "One Hundred." Then I use a StringBuilder to efficiently build the number phrases. If the next token (word) is in the set of keys to our numbers (e.g. "eighteen" or "hundred") I add it to the current phrase, preceded by a space if it's not the first word in the phrase. IGNORED_WORDS is an (immutable) set that just contains the String "and". This lets us parse "one hundred and ten", for example.
So what about the transformation of phrases to numbers? The loop that you wrote above doesn't make much sense to me. What is i? What is x? What this a typo? The general approach that I used was to consider two words at a time. If there's only one, then that's easy and we are done. If there's two, though, we have to consider their order. Take "nine hundred" for example. Because the second value (100) is greater than the first (9), we'll multiply them together and add them to the total sum. If the previous calculated value is greater than the current one, we just add them. That way, parsing "twelve thousand two hundred" looks like:
12 < 1000 : current sum = 12 * 1000 = 12000
2 < 100 : current sum += 2 * 100 = 12000 + 200 = 12200

I did not test it too much, but you can see my implementation of it here.
Addendum
Maps are really cool in any programming language. Maps are a one-to-one (bijection) function: the keys in a Java map are the domain of the function, and the values the keys are mapped to are the range. You can extract the set of all keys with map.keySet(), and the values with map.values() (where map is an instantiated Map variable).  An even more powerful feature is the following:
for (Map.Entry<K, V> entry : map.entrySet()) {
  // loop over all entries in the map
}

This is really an iterator over each mapping in the map, and you can get the key and the value on each iteration.
Anyways, if we have a map variable, and go map.keySet(), we get a Java Set of all the keys in that map. In the instance of this post, this Set would include the strings "one", "two", ... "billions". To put it in other words, if I had a collection of statements "A maps to B", and asked for the keySet, I would get all the 'A's in those statements.
So view NUMBER_MAP as a mapping from English numbers (keys) to mathematical numbers (values). Starting from the English number in the paragraph, I wanted to get the mathematical number. To do this, I compared the value from the paragraph to the keys from the map.


text:
Q: PHP - Notice: Undefined index: submenu I'm trying to create an menu with submenus.
I created two tables on my database, here the data:
Menu table -
menu_id
front
back
url
menu_friendlyname
name
modules active

Submenu table -
submenu_id
menu_id url
submenu_name
modules

I'm doing a specie of MVC, but with my own rules, here the model:
I'm calling two tables here
    $query = ("SELECT DISTINCT name, menu_id
      FROM menu
      INNER JOIN submenu USING(menu_id)");

    $array = db_array($query, 'a+');
    if (!empty($array)) {
        printMenu($array);
        return true;
    } else {
        return false;
    }
}

And I'm calling the view here, as you can see, I'm trying to show the submenus
function  printMenu($array){

echo '
';
var_dump($array);
echo '
';
foreach($array as $key => $values){

echo '
';

echo '
';
echo $values['name'];
echo '
';

echo '
';

foreach($values['submenu'] as $k => $v){
echo '';
echo $v['submenu'];
echo '';

}

echo '

';

}
}

And is giving me this error:
Notice: Undefined index: submenu
Warning: Invalid argument supplied for foreach()

I did a var_dump too
array(5) {
  [0]=>
  array(2) {
    ["name"]=>
    string(5) "admin"
    ["menu_id"]=>
    string(1) "1"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(4) "user"
    ["menu_id"]=>
    string(1) "2"
  }
  [2]=>
  array(2) {
    ["

name"]=>
        string(22) "permissions_management"
        ["menu_id"]=>
        string(1) "3"
      }
      [3]=>
      array

(2) {
    ["name"]=>
    string(10) "job_offers"
    ["menu_id"]=>
    string(1) "5"
  }
  [4]=>
  array(2) {
    ["name"]=>
    string(12) "applications"
    ["menu_id"]=>
    string(1) "6"
  }
}

Maybe the error is from the array

A: You don't have a "submenu" key in your values sub-array. The only keys you have there are name and menu_id. That's why you are getting an undefined index error.

A: Before your iteration, also check if $values['submenu'] presents or not.
if(isset($values['submenu']) && $values['submenu'] != '') {
    foreach($values['submenu'] as $k => $v){
      echo '';
      echo $v['submenu'];
      echo '';
    }
}

A: Your query should be:
SELECT menu_id, name, submenu_name
FROM menu
INNER JOIN submenu USING (menu_id)
ORDER BY menu_id, submenu_id

Then the function to print the menus should be:
function  printMenu($array){
    echo '
';
    var_dump($array);
    echo '
';

    $last_menu = null;
    foreach($array as $values){
        if ($values['menu_id'] !== $last_menu) {
            if ($last_menu !== null) {
                echo '
';
            }
            echo '
';
            echo '
';
            echo $values['name'];
            echo '
';
            $last_menu = $values['menu_id'];
        }
        echo '
';
        echo '';
        echo $v['submenu_name'];
        echo '';
    }
    if ($last_menu !== null) {
        echo '
';
    }
}


text:
Q: Why is it better to use Vagrant instead of sharing the VM's Disk itself? I was searching for the best way to distribute a development environment to my team and found Vagrant.
After some reading and testing, here is what I can say about it

Pro:
Automates the process of creating a new VirtualBox VM (for a new user).
Con:
Nullifies the only pro I found by requiring the new user to learn a new tool.

The learning curve is way more time expensive than actually copying the VDI and configuring a new VirtualBox VM tu use it.
(It is not that great as well, but is still higher than learning a new tool.)
I definitely didn't understand why using Vagrant makes the process of distributing a development environment so different than just creating a normal VirtualBox VM and sharing the disk.
Maybe I'm missing a point here, can anyone enlight me?

A: I can only speak from my own experience: the learning curve is well worth it.
As a programmer, I love being able to set up separate isolated environments for development, testing, and deployment.
Sure, you can copy the VDI around and whatever, but it's easier-- in my opinion-- to execute a few command line programs and it's all ready to go.  It just seems dirty to me to copy around VDIs or other types of images.
Also, I can make packaged up vagrant boxes that I can send to my coworkers or distribute on the Internet.

A: There are a lot more advantages to vagrant than just that:

*

*100% reproducible environments, everywhere the same.

*Can be stored in source control (git/svn/...) and versioned.

*Saves diskspace. This can be important on laptops, I right now have 92 Vagrantfiles on my system, not all created. Imagine them all being full blown 20gb vm's...

*Experimentation becomes trivial. A quick vagrant init precise64, vagrant up, try some stuff, vagrant destroy, vagrant up, retry some stuff, vagrant destroy - and done.

It requires some discipline not to install required packages manually or updating the common Vagrantfile when doing so, but once you have a workflow worked out, it's simply brilliant. I find

A: I think the major advantage of Vagrant is that it let's you have one base package that can be re-configured for different purposes covering dev, testing, management, operations, etc. simply by changing the manifest/cookbook. It's just more convenient to share and start up.
Less major, but still nice is that it lets you start over effortlessly. I know you can use snapshots in VirtualBox, but sometimes, it becomes annoying to keep going back and forth between them. With Vagrant, you can start a box, test some things, destroy it. Than you can start again, the same box, test something. You can start twice the same VM easily, and test slightly differently in each, destroy them.
Also check out the answer here: https://superuser.com/questions/584100/why-should-i-use-vagrant-instead-of-just-virtualbox
EDIT: In my first answer, I was thinking of Packer, not Vagrant, my mistake.

A: We are discussing the same question in the office... Right now, btw!
When I first got in touch with vagrant, I was sceptic, but the advantages I could see, beyond personal opinion is:

*

*you can start from a common configuration and automatize many "forks", without a snapshot-chaining (what is a big pain when you need to delete one snapshot or two, I might say);

*the process of cloning (packing) a machine is way faster than export appliance;

*using vagrant to setup a machine still makes you able to use VBox iface, so no problem to make a start point based on Vagrant's features and let the teammates decide if they will use it or not;

*as said, automatization.

We are still making some tests... Now talking about particular opinion, to me the main point is replication and the fact that packing and unpacking is faster than exports.


text:
Q: Python json.dumps formatting I am trying the reverse of the operation in Parsing json.dumps - Python
I have a data frame in which the row has the format:
stopLoss  takeProfit   price    id
154.79     151.79      153.784  0

I want to format the output in a JSON of the format
{
"trades" : [{
         "stopLoss": 154.79,
        "takeProfit": 151.79,
        "price": 153.784,
         "id: :0
        }]

}

using json.dumps on the row yields a JSON, but the [ ] after the "trades" are missing. Like shown below:
{
"trades" : {
         "stopLoss": 154.79,
        "takeProfit": 151.79,
        "price": 153.784,
         "id: :0
        }

}

How can I ensure that the [ ] are included?

A: It dumps exactly the structure you pass in. If the value of the trades key is a list of dicts instead of a single dict, you get the output you want. But this has nothing with JSON to do really; it simply depends on what data you have in the argument to json.dumps().
If your code looks like
trades = csvreader.next()
j = {'trades': trades }
json.dumps(j)

then you want to change to
j = {'trades': [trades]}

A: If x is a Pandas dataframe like the one you describe:
   stopLoss  takeProfit    price  id
0    154.79      151.79  153.784   0
1    254.79      151.79  153.784   1

You can try
json.dumps(x.to_dict(orient='records'))

This gets you almost there:
[{"stopLoss": 154.79, "takeProfit": 151.79, "price": 153.784, "id": 0},
 {"stopLoss": 254.79, "takeProfit": 151.79, "price": 153.784, "id": 1}]

To get what you need just create a dictionary:
json.dumps({ 'trades' : x.to_dict(orient='records') })


text:
Q: ffmpeg many single audio files streaming with node.js and ionicframework I'm trying to make mobile app that can play audio files, but, that audio files are big, more than 100 mb, and I don't want save this file into the device, I want make a stream to this file into the browser.
I'm building a prototype only with ionicframework and phonegap plugins this is my github of the project:
https://github.com/cmarrero01/famvoice
My server is in node.js, so my first intent was make the streaming of the audio file with node.js to the  audio tag, something like this:
app.get('/record/:userId/:playListId/:recordName',function(req,res){

    var userId = req.params.userId;
    var playListId = req.params.playListId;
    var recordName = req.params.recordName;
    if(!userId || !playListId || !recordName){
        res.end();
        return;
    }

    var path = "./records/"+recordName;

    if (!params.fs.existsSync(path)) {
        res.end();
         return;
    }

    res.setHeader("content-type", "audio/mpeg");
    var stream = params.fs.createReadStream(path, { bufferSize: 64 * 1024 });
    stream.pipe(res);
}

And in the ionic html the audio tag:
<audio controls preload="none" type="audio/mpeg" autoplay>
<source ng-src="{{audioPlay | trustAsResourceUrl}}" />
</audio>

This is was a bad, bad, bad Idea, when I add the src to the audio tag, this wait to download all file to start playing it, so this is really an streaming, this is the same that I download the file an run it.
So, my second thought was ffmpeg, ffserver. I install ffmpeg, and I run ffserver with this config file:
Port 8090
BindAddress 0.0.0.0
MaxHTTPConnections 2000
MaxClients 1000
MaxBandwidth 1000
CustomLog -

<Feed feed1.ffm>
        File /tmp/feed1.ffm
        FileMaxSize 200K
        ACL allow 127.0.0.1
</Feed>

<Stream status.html>
        Format status
        ACL allow 127.0.0.1
        ACL allow localhost
        ACL allow 192.168.0.0 192.168.255.255
</Stream>

<Stream test.mp3>
    Feed feed1.ffm
    Format mp2
    AudioCodec libmp3lame
    AudioBitRate 128
    AudioChannels 1
    AudioSampleRate 44100
    NoVideo
</Stream>

And then run the next command:
ffmpeg test.mp3 http://IP:PORT/feed1.ffm

This command send to the feed the audio file test.mp3, and if you access to the url: http://IP:PORT/test.mp3 you can listen.. BUT, HERES IS MY BIG PROBLEM...
My Problems are:

*

*The ffmpeg send the file to the feed, when the the process finished if you can try to access to the that url, you can't listen anything and the URL is stay loading.

*Is suppouse that the user can select a file to listen, how I make to stream a specific file to a spefic user and not change stream for all users. I suppouse that I need one feed per user?

*Exist some way to send the stream to node.js and node.js send it to the app with the correct codecs and stuff?.
If the ffmpeg is not the best way, what it is?
Thanks.


text:
Q: Objects not sorted after creation Core Data SwiftUI At the beginning on the app install, I create some objects, but they are not sorted after creation on the UI, I have to close the app and open it so they are displayed correctly. This is the code:
import SwiftUI

struct ContentView: View {

@FetchRequest(
    entity: ProgrammingLanguage.entity(),
    sortDescriptors: [
        NSSortDescriptor(keyPath: \ProgrammingLanguage.id, ascending: true)
    ]
) var languages: FetchedResults<ProgrammingLanguage>

@Environment(\.managedObjectContext) var managedObjectContext

var body: some View {

    NavigationView {
        VStack {
            List(languages, id: \.self) { language in
                Text(language.name ?? "Unknown")
            }
        }
    }
    .onAppear{

        for i in 1...5 {
            let language = ProgrammingLanguage(context: self.managedObjectContext)
            language.name = "\(i) SwiftUI"
            language.creator = "Some text"
            do {
                try self.managedObjectContext.save()
            } catch {
            }
        }

    }
}
}

How can I make it be sorted automatically after creation? Also when created for the first time that part of the screen appears blank, it seems as the UI is not aware of Core Data changes.

A: The problem seems that it is just not assigned in the provided code, because naming attribute by id means noting in CoreData (and by default remains 0), so at least with added below it is updated & sorted properly (in testing model id is Int32, but it is not important)
for i in 1...5 {
    let language = ProgrammingLanguage(context: self.managedObjectContext)
    language.id = Int32(i)           // << here !!
    language.name = "\(i) SwiftUI"

Tested with Xcode 11.4 / iOS 13.4


text:
Q: Searching for SciFi book where a battle android gets rediscovered by scavengers I read a book a few years back and I can't seem to find it again.
What I remember about the story:

*

*In the beginning a couple of scavengers land on a moon or asteroid to scavenge an old military facility

*there is one scavenger team and one lone scavenger who fight over the goods

*a still functional combat android reactivates and starts to hunts the scavengers

*I believe the combat android looked like a woman

*the combat android kills the scavenger team and leaves with the lone one

The only other thing i can remember is that at some point the android goes into a tar lake which has an old battlefield under it to get its hands on materials for repairs.
That's pretty much all I can remember. Would be great if somebody could help me out.

A: Ok. That's a bit embarrassing. Just found the book in my Amazon Kindle library. Looks like I bought, read and forgot about it.
It was:
My Outcast State (The Maauro Chronicles Book 1)
by Edward McKeown
https://www.goodreads.com/book/show/25739499-my-outcast-state

Looks like there's even a second book out now.


text:
Q: SHA1 with salt on windows phone 7 I have some some time now reshearchd how to encode a password to SHA1 with a salt.
The is the code i used on my web application part, but it will not work on a phone environment.
public class Password
{
    private string _password;
    private int _salt;

    public Password(string strPassword, int nSalt)
    {
        _password = strPassword;
        _salt = nSalt;
    }

    public string ComputeSaltedHash()
    {
        // Create Byte array of password string
        ASCIIEncoding encoder = new ASCIIEncoding();
        Byte[] _secretBytes = encoder.GetBytes(_password);

        // Create a new salt
        Byte[] _saltBytes = new Byte[4];
        _saltBytes[0] = (byte)(_salt >> 24);
        _saltBytes[1] = (byte)(_salt >> 16);
        _saltBytes[2] = (byte)(_salt >> 8);
        _saltBytes[3] = (byte)(_salt);

        // append the two arrays
        Byte[] toHash = new Byte[_secretBytes.Length + _saltBytes.Length];
        Array.Copy(_secretBytes, 0, toHash, 0, _secretBytes.Length);
        Array.Copy(_saltBytes, 0, toHash, _secretBytes.Length, _saltBytes.Length);

        SHA1 sha1 = SHA1.Create();
        Byte[] computedHash = sha1.ComputeHash(toHash);

        return encoder.GetString(computedHash);
    }

    public static int CreateRandomSalt()
    {
        Byte[] _saltBytes = new Byte[4];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(_saltBytes);

        return ((((int)_saltBytes[0]) << 24) + (((int)_saltBytes[1]) << 16) +
            (((int)_saltBytes[2]) << 8) + ((int)_saltBytes[3]));
    }

    public static string CreateRandomPassword(int PasswordLength)
    {
        String _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789!\"#¤%&/()=?$+-_.,;'*";
        Byte[] randomBytes = new Byte[PasswordLength];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(randomBytes);
        char[] chars = new char[PasswordLength];
        int allowedCharCount = _allowedChars.Length;

        for (int i = 0; i < PasswordLength; i++)
        {
            chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
        }

        return new string(chars);
    }
}

A: Silverlight and Windows Phone 7 do not have an ASCIIEncoding.  I suggest you use the UTF8Encoding instead.  If you are certain that your passwords are always within the ASCII range then this encoding will work the same as the ASCIIEncoding would of had it been present.
If on the other hand you cannot guarantee that passwords are always within the ASCII range then you would need to make sure both ends hash using the UTF8Encoding to ensure generated hashs are the same.


text:
Q: Найти клиентов которые не покупали ничего SQL CREATE TABLE Customers (
  id int NOT NULL PRIMARY KEY IDENTITY (1, 1),
  CustomerName nvarchar(15) UNIQUE,
  Address nvarchar(20),
  City nvarchar(20),
  Country nvarchar(20)
)
CREATE TABLE Orders (
  id int NOT NULL PRIMARY KEY IDENTITY (1, 1),
  CustomerId int NOT NULL,
  FOREIGN KEY (CustomerID) REFERENCES Customers (id),
  EmployeeID int NOT NULL,
  FOREIGN KEY (EmployeeID) REFERENCES Employees (id),
  OrderDate date,
  ShipersID int NOT NULL,
  FOREIGN KEY (ShipersID) REFERENCES Shipers (id)
)

INSERT INTO Customers
  VALUES ('Begt', 'rht', 'Berlin', 'Germany'), ('Uuu', 'ththj', 'Kyiv', 'Ukraine')
INSERT INTO Orders
  VALUES (2, 1, '2017-11-4', 2), (1, 2, '2018-4-12', 1), (2, 3, '2018-3-24', 3)

SELECT
  Customers.CustomerName
FROM Customers
JOIN Orders
  ON Customers.id <> Orders.CustomerId
ORDER BY CustomerName

так не проходит выводит всех

A: SELECT
  c.CustomerName
FROM Customers c
LEFT JOIN Orders o ON c.id = o.CustomerId
WHERE o.CustomerId IS NULL
ORDER BY CustomerName

Вам нужен LEFT JOIN и проверка на отсутствие покупателя в таблице заказов (Orders ).

A: Или так
SELECT
  CustomerName
FROM Customers
WHERE id NOT IN (SELECT CustomerId FROM Orders)

Но вариант с left join лучше.


text:
Q: Symfony2 - Issue getting correct id to show/{id} I have a view page which is passed all my active alerts.  On each displayed row, I have a show button so you can see the individual alert
{% for alert in alerts %}

        {{ alert[0].id }}
        {{ alert[0].alertStatus }}

            <input type="button" value="Show" data-url="{{ path('NickAlertBundle_show', {id: alert[0].id}) }}" onclick="show_alert( {{ alert[0].id }} )" id="show"/>

{% endfor %}

So when the button is clicked, the javascript function show_alert is called.
function show_alert(id){
    alert(id);
    $.ajax({
        type: "POST",
        url: $("#show").attr('data-url'),
        data: {id: id},
        success: function(data) {
            if(data){

            }else{
                alert("Unknown Error!");
            }
        },
        error:function(){
            alert(id);
        }
    });
}

Now I do an alert at the top of that function, and that alert always displays the correct id.  I think the problem is with the url part of the ajax call.  It calls the data-url which should be correct.  This is what it should be calling
NickAlertBundle_show:
    pattern:  /show-alert/{id}
    defaults: { _controller: NickAlertBundle:Alert:show }
    requirements:
       _method:  GET|POST
       id:  \d+

So this should then call the controller action
public function showAction(Request $request, $id)
{
    var_dump($id);
    if($request->isXmlHttpRequest())
    {
        $id = (int)$request->request->get('id');
    }

    return new JsonResponse('test');
}

At this point though, the var_dump in this action always outputs the id of the last added alert, and not the selected alert.  And when I display the alert, it always displays the latest added alert.
So what is causing it to get the latest alert id instead of the selected id?  As I say, it initially gets the correct id, but at some point this changes.
Thanks

A: You shouldn't declare duplicated ids, like id="show" in your template, better use class or declare your ids like id="show_1 ... n"


text:
Q: Numbering sections as 1A, 1B, 2A, 2B, etc I use scrartcl. I would like the sections to be numbered 1A, 1B, 2A, 2B, etc. I would like subsections etc. to be numbered 1A.1, 1A.2, etc. the idea is to present theory in the "A" sections and examples in the "B" sections.
Please ask if more clarity is needed.

A: You can define appropriate commands for introducing the two types of sections:
\documentclass{scrartcl}
\newcommand{\sectionA}{\renewcommand{\thesection}{\arabic{section}A}\section}
\newcommand{\sectionB}{\edef\thesection{\arabic{section}B}\addtocounter{section}{-1}\section}

% This part is necessary when hyperref is needed
\usepackage{hyperref}

\newcounter{Hsection}
\renewcommand{\theHsection}{\thesection}
\newcounter{Hsubsection}
\renewcommand{\theHsubsection}{\thesection.\arabic{subsection}}
% end of hyperref part

\begin{document}
\tableofcontents

\sectionA{First, theory}
\subsection{One}
\subsection{Two}

\sectionB{First, examples}
\subsection{One}
\subsection{Two}

\sectionA{Second, theory}
\subsection{One}
\subsection{Two}

\sectionB{Second, examples}
\subsection{One}
\subsection{Two}

\end{document}

As you see, one has to do some adjustments when hyperref is loaded. Add all the desired options to it, of course.

A: If you're just considered sectional headings, then you can use \sections, \subsections and \subsubsections with the following counter redefinitions way:
\renewcommand{\thesection}{\arabic{section}}
\renewcommand{\thesubsection}{\thesection\Alph{subsection}}
\renewcommand{\thesubsubsection}{\thesubsection.\arabic{subsubsection}}

The above changes the numbering scheme representation for sections to \arabic (actually, the default), subsections to \Alph (for theory and examples) and subsubsections to \arabic (also, the default). It also makes sure that the display conforms to your requirements in terms of concatenation.


text:
Q: Dynamic binding of table column and rows I'm having troubles getting dynamic binding of both my table columns and rows to work.
Suppose I have two models, one holding the table column info:
    var aColumnData = [
        {
            columnId : "col1"
        },
        {
            columnId : "col2"
        },
        {
            columnId : "col3"
        },
        {
            columnId : "col4"
        },
        {
            columnId : "col5"
        }
    ];

and one with the data:
var aData = [
    {
        col1 : "Row 1 col 1",
        col2 : "Row 1 col 2",
        col3 : "Row 1 col 3",
        col4 : "Row 1 col 4",
        col5 : "Row 1 col 5"
    },
    {
        col1 : "Row 2 col 1",
        col2 : "Row 2 col 2",
        col3 : "Row 2 col 3",
        col4 : "Row 2 col 4",
        col5 : "Row 2 col 5"
    }
];

I then set the model :
    var oModel = new sap.ui.model.json.JSONModel();
    oModel.setData({
        columns : aColumnData,
        rows    : aData
    });

I then create my table in the view:
    var oTable = new sap.ui.table.Table();

    var oColumnTemplate = new sap.ui.table.Column({
        label : "{columnDesc}",
        template : new sap.ui.commons.TextView().bindProperty("text", "<this_should_be_dynamic_but_how?>")
    });

    oTable.bindColumns("/columns", oColumnTemplate);
    oTable.bindRows("/rows");

The part that bugs me is the binding to the current column in the TextView template; this should be dynamic ("col1", "col2", etc) and done on the fly -- that's what bindings are for anyway I assume -- but I can't get it to work...
I guess I'm missing something simple and trivial, but I'm a bit lost now...
Any help is highly appreciated!
==============================
EDIT: I got it to work by iterating through the columns array and using the addColumn() method:
    jQuery.each(aColumnData, function(i, v) {
        oTable.addColumn(new sap.ui.table.Column({
            label : v.columnDesc,
            template: new sap.ui.commons.TextView().bindProperty("text", v.columnId)
        }));
    });

...but I was hoping there would be a more cleaner approach using the bindColumns() / bindRows() approach:

A: I have done something similar before using factory functions see jsbin example for similar example to yours
var oTable = new sap.ui.table.Table({
    title: "Table column and data binding",
    showNoData : true,
    columnHeaderHeight : 10,
    visibleRowCount: 7
});
oTable.setModel(oModel);
oTable.bindColumns("/columns", function(sId, oContext) {
    var sColumnId = oContext.getObject().columnId;
    return new sap.ui.table.Column({
        id : sColumnId,
        label: sColumnId,
        template: sColumnId,
        sortProperty: sColumnId,
        filterProperty: sColumnId
    });
});
oTable.bindRows("/rows");

you could use 2 globally named models in this scenario, one for the metadata one for the data
eg
sap.ui.getCore().setModel(oMetaModel, 'meta');
sap.ui.getCore().setModel(oDataModel, 'data');
..
oTable.bindColumns("meta>/columns" function...
oTable.bindRows("data>/rows");

Heres an example jsbin example of dynamic columns based on OData metadata


text:
Q: Using fetch to log/output json values I'm trying to fetch values from JSON, see below. I need the values for the very last "year", "month", "day", "cycle", "trend" in the object
{"co2":[{"year":"2012","month":"1","day":"1","cycle":"392.92","trend":"391.50"},
...
,{"year":"2022","month":"2","day":"20","cycle":"418.63","trend":"416.80"}]}

I've tried the following script, but it logs [object Object]. Any ideas? Thanks in advance.

    async function loadnums() {
        const response = await fetch('https://global-warming.org/api/co2-api');
        const nums = await response.json();
        console.log(nums);
    }
    loadnums();


text:
Q: Delegate event in vue Im trying to delegate an avent from one instance to another.
I have a toolbar on the top of the page with a button like this

<button v-on:click="add" class="btn btn-default" type="submit"> Ny</button>

This add event working in this vue instance
var toolbarApp = new Vue({
    el: '#toolbar',
    data: {

    },
    methods: {
        add: function (event) {
            alert('lol');
        }
    }
});

But now i want to attach this add event to another instance like this
var contactApp = new Vue({
    mixins: [toolbarApp],
    el: '#contact',
    data: {
        showGrid: true,
        showForm: false,
        editMode: false
    },
    created: function () {
        this.getContacts();
    },
    methods: {
        getContacts: function () {
            $.getJSON(this.apiGrid, function (data) {
                this.contacts = data;
            }.bind(this));
        },
        add: function (event) {
            alert('hej');
        }
    }
});

But i cant attach this because of diffrent instance. Is it any way to do this?
Have also tried with mixedin with no luck.
Thanks in advice

A: what you are trying to do is not unique, there's even a title for it "Event bus"
EventBus = new Vue();

var toolbarApp = new Vue({
    el: '#toolbar',
    data: {

    },
    methods: {
        add: function (event) {
            EventBus.$emit('add-something', this.somevar);
        }
    }
});

then in your other instance:
var contactApp = new Vue({
    mixins: [toolbarApp],
    el: '#contact',
    data: {
        showGrid: true,
        showForm: false,
        editMode: false
    },
    created: function () {
        this.getContacts();
        EventBus.$on('add-something', function(somevar) {
            // do cool stuff, like this.getContacts...
        });
    },
    methods: {
        getContacts: function () {
            $.getJSON(this.apiGrid, function (data) {
                this.contacts = data;
            }.bind(this));
        },
        add: function (event) {
            alert('hej');
        }
    }
});

Definition:
Sometimes you need a quick and easy solution to pass data between Vue.js components.
For an application with simple architecture it's enough to communicate between components using events. For this we can create a quick solution and implement EventBus. EventBus allows us to emit an event in one component and listen for that event in another.
https://medium.com/@andrejsabrickis/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate-between-vue-js-components-cdc11cd59860


text:
Q: How to upload a file in android using AsyncTask I am just a beginner at Android so this question might be stupid. PLease help me out of this.
I am working on an App which requires data to be uploaded on the server. The data could be text, image or a video. I tried to use the following link
http://developer.android.com/reference/java/net/HttpURLConnection.html
and also
http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106
However I ended up being even more confused. How do I send the data into the server using the ASyncTask doinbackgound method.
Thanks.

A: I suggest you use a REST Client for your networking needs. They allow easy use of Async Http Requests and even easer exception handling.
These are some the most notable REST Clients available out there:

*

*Retrofit

*ION

*Android-Query


text:
Q: Changing provisioning profile after replacing rejected binary? So my first official application got rejected as it was crashing on iOS 4.0 for which my application was not even made for (I didn't even check the option for iOS 4 tested). Now after resolving the bug I need to upload my application to the store. Should I create a new APP ID and a new distribution profile or just a new distribution provisioning profile for it?

A: You use the same ID, the same profile. Nothing to change at all. Just fix the bug and upload again.


text:
Q: Monodroid - Handling Click events inside ListAdapter rows I have a ListView with an ArrayAdapter set to it, and each row in the adapter contains four buttons that need to receive and handle click events. Normally in Android I would call SetOnClickListener on each button when I create the cell, but Mono gives the ability to set event handlers for the Click event instead. It looks like there's some weirdness to this in Mono though, because I run into one of two issues depending on where I set the event handler.
ArrayAdapter GetView Example 1:
View tweetCell = convertView;
if (tweetCell == null) {
    tweetCell = ((LayoutInflater)Context.GetSystemService (Context.LayoutInflaterService)).Inflate (Resource.Layout.TweetCell, null);

    tweetCell.FindViewById (Resource.Id.btn_moveTweet).Click += (object sender, EventArgs e) => MoveTweet (GetItem(position));

    tweetCell.FindViewById (Resource.Id.btn_unfavoriteTweet).Click += (object sender, EventArgs e) => UnfavoriteTweet (GetItem(position));

    tweetCell.FindViewById (Resource.Id.btn_hideTweet).Click += (object sender, EventArgs e) => HideTweet (GetItem(position));

    tweetCell.FindViewById (Resource.Id.btn_shareTweet).Click += (object sender, EventArgs e) => ShareTweet (GetItem(position));
}

Here, my event handler only gets set once per button (good!), but the position value is wrong most of the time. I'm wondering if the conversion from Mono to Android code is causing GetItem(position) to use the same value for position every time (the value that position is set to when the cell is first created). This code would work totally fine in normal Android.
ArrayAdapter GetView Example 2:
View tweetCell = convertView;
if (tweetCell == null) {
    tweetCell = ((LayoutInflater)Context.GetSystemService (Context.LayoutInflaterService)).Inflate (Resource.Layout.TweetCell, null);
}
tweetCell.FindViewById (Resource.Id.btn_moveTweet).Click += (object sender, EventArgs e) => MoveTweet (GetItem(position));

tweetCell.FindViewById (Resource.Id.btn_unfavoriteTweet).Click += (object sender, EventArgs e) => UnfavoriteTweet (GetItem(position));

tweetCell.FindViewById (Resource.Id.btn_hideTweet).Click += (object sender, EventArgs e) => HideTweet (GetItem(position));

tweetCell.FindViewById (Resource.Id.btn_shareTweet).Click += (object sender, EventArgs e) => ShareTweet (GetItem(position));

This method does cause the click event to be fired for the correct position, but it sets a new event handler every time the row is recycled. This causes click events for lots of rows at the same time. A workaround for this method would seem to be to keep references to the event handlers and remove them before setting them again inside GetView, but this seems extremely inelegant.
Is there a better method for handling click events inside ListView items in Monodroid?

A: i know its an old thread, but it has a lot of votes and is still marked as unanswered
It is only logical that the scenarios that you described happens! It has nothing to do with mono whatsoever. It has to do with the convertview. This is what the documentation says on convertview:

convertView - The old view to reuse, if possible. Note: You should
  check that this view is non-null and of an appropriate type before
  using. If it is not possible to convert this view to display the
  correct data, this method can create a new view.

Example 1:
In your first example the convertView will be null the first time and the events will be set. Then the next time the GetView method is called the convertview may or may not be null. If it is not null it will use the old view with the events still attached! So this means that the event with the position parameter are still from a previous view!
Example 2:
This example will work as expected but it is not very efficient like you mentioned. It has to locate the controls every time the FindViewById method is called.
Solution:
The solution for this performance problem is to implement the viewholder pattern.
First you create a class that will hold your views:
private class MyViewHolder : Java.Lang.Object
{
  public Button MoveTweet { get; set; }
  public Button ShareTweet { get; set; }
  public Button UnfavoriteTweet { get; set; }
  public Button HideTweet { get; set; }
}

Now you can use this viewholder in your code
public override View GetView (int position, View convertView, ViewGroup parent)
{
  MyViewHolder holder;
  var view = convertView;

  if(view != null)
    holder = view.Tag as MyViewHolder;

  if (holder == null) {
    holder = new MyViewHolder ();
    view = activity.LayoutInflater.Inflate (Resource.Layout.OptimizedItem, null);
    holder.MoveTweet = view.FindViewById<Button> (Resource.Id. btn_moveTweet);
    holder.ShareTweet = view.FindViewById<Button> (Resource.Id. btn_shareTweet);
    holder.UnfavoriteTweet = view.FindViewById<Button> (Resource.Id. btn_unfavoriteTweetTweet);
    holder.HideTweet = view.FindViewById<Button> (Resource.Id. btn_hideTweet);
    view.Tag = holder;
  }

  holder.MoveTweet.Click += (object sender, EventArgs e) => MoveTweet (GetItem(position));
  holder.UnfavoriteTweet.Click += (object sender, EventArgs e) => UnfavoriteTweet (GetItem(position))
  holder.HideTweet.Click += (object sender, EventArgs e) => HideTweet (GetItem(position));
  holder.FavoriteTweet.Click += (object sender, EventArgs e) => ShareTweet (GetItem(position));

  return view;
}

For more information on this check out: https://blog.xamarin.com/creating-highly-performant-smooth-scrolling-android-listviews/

A: I had similar problems too. Apparently, I will avoid solution 2. Moreover, I observe the problem in solution 1 only happened on Android 2.3.
This is how I fixed the problem.
I keep a reference to the ListView in the adapter, say _listView. Then, in your GetItem() method (Don't miss the position variable. Its value is a mystery), call _listView.GetPositionForView((View)sender) to get the correct position.

A: Try with this code:
    void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)
    {
        var listView = sender as ListView;
        var item = items[e.Position];

        //init your data...

        tweetCell.FindViewById (Resource.Id.btn_moveTweet).Click += (object sender, EventArgs e) => MoveTweet (item);
    }


text:
Q: Git is not recognized from TFS build step? I have recently installed Git onto a Dev Server that is our Dev TFS Build agent (Server 2012 R2). When I run a command line git through remote connection, it shows git commands. However, when I run a command line build step on the TFS website, git is not a recognized command. I checked the env path variables and they're fine.
Later, I tested by making my personal computer a build agent. The build step does succeed and it recognizes git. What is the difference with the server?

A: Restart the build agent so it picks up changed path environment variable.

A: Most probably you will have to restart the agent so that the new PATH variable(which will contain git's bin dir) is loaded.
Please note that if you are running the agent from a command prompt, you will have to restart the command prompt as well

A: Thanks for the help in figuring out the problem. Restarting is the correct way to go for most, but I do not have the power to do so.
Here is my solution: Make a batch file build step and include
"PATH %PATH%; (Path to Git)"
This basically appends the git directory to the environment variable of the current session. Then I am free to use git commands in the batch file.


text:
Q: Solving the error TypeError: __init__() takes 1 positional argument but 2 were given I am very new to programming. Here is my simple code below
class BaseClass(object):
    def __init__(self):
        self.value = 10

        def add(self):
            c = self.value + 10
            print("the sum is:")
            print(c)

class InheritingClass(BaseClass):
    pass

x = InheritingClass(BaseClass)

I am working on inheritance with python. When I run this script I get this error
Traceback (most recent call last):
  File "F:/python/classes_01.py", line 20, in <module>
    x = InheritingClass(BaseClass)
TypeError: __init__() takes 1 positional argument but 2 were given

Does any one have an idea on this.
Thank you very much

A: You do not need to pass BaseClass to the constructor. Simply do
x = InheritingClass()

A: Just create the InheritingClass object with:
x = InheritingClass()

Why? Because the super class is already specified in the class definition:
class InheritingClass(BaseClass):
    pass

so it's not necessary to specify it again.

A: When you coded the line:
class InheritingClass(BaseClass):

you were indicating that Inheriting class inherits from BaseClass (i.e. is a sub-class of). You did not give any information about how to create an instance of InheritingClass. That information is in the init method.
In this case, InheritingClass inherits its __init__ method from BaseClass, where there are no user supplied inputs specified/required. Just use
x = InheritingClass()

to create an instance of InheritingClass, the same way you would use
x2 = BaseClass()

to create an instance of BaseClass

A: Like it's already been said, just write x = InheritingClass()
Remember: Every method of a class has at least 1 parameter, and that's self.
That's why you always have to write self in the method definition of a class. But when you
call the function you don't have to pass self to the function:
class A:
    ...
    def foo(self):
        print "bla"

    ...

#call foo
a = A()
a.foo() # self is implicitly there

A: value has to be added to the arguments of the constructor method of
__init__.
Also you should have declared the value not as an instance but as a class variable. It would've helped with code readability


text:
Q: What is inside Callback queue (debugger)? I would like to know how is it possible to know the content of the callback queue.
For example, if you consider the following Javascript code :
<script>
    console.clear();
    setTimeout( function () {console.log("Hello ")},5000);
    console.log("What is inside Callback Queue ? ");
</script>

Is there a mean to print the content of the callback queue to the console ?
If not possible in such that way, is it possible with a debugger by adding a break point to the line console.log("What is inside ...?"); (I tried with Firefox debugger but I did not manage to do it)
Or another solution ?
Thanks for answer.

A: The performance tab of the browser's developer tools contains all the informations needed. Do the following:

*

*Filter markers : function call (only to avoid a lot of
informations)

*Start Recording

*Reload (CTRL + R)

*Stop Recording (With my example, when Hello is printed to the console)
In the waterfall, Click on the mark that appears after 5000ms (with my example) and useful informations are displayed in the right pane.

A: While I'm not sure what your final goal is, you can wrap the function you're calling with the following wrapper function, which prints to the log whenever a function is being enqueued:

function wrapper(func) {
  console.log(`'${func.name}' was enqueued`);
  return func;
}

function foo() {
  console.log('Hello')
}

setTimeout(wrapper(foo), 5000);

You can use a similar mechanism to maintain an array that'll contain all the functions that are currently waiting.


text:
Q: angular ui router named view state overriding another named view I have a project with 2 ui-view div:

The main state login is successfully loaded in both:
$stateProvider
    .state("login", {
      url: "/login",
      views: {
        'agent-station': {
          templateUrl: "login.html"
        },
        'routingConfig': {
          templateUrl: "loginrc.html"
        }
      }
    })

The problem arises when I click in one link which URL updates only one of the ui-views. The ui-view referenced by that URL is successfully updated, but the other ui-view becomes blank. So for example if I click on Test 1 AG link on the plunker example the Test 1 Agent station state is updated but the Login Routing Config state becomes a blank page.
My main suspicion is the following line:
$urlRouterProvider.otherwise("/login");

But I'm not sure why it becomes blank instead of showing the login page for Routing Config ui-view.
What could be the problem?
Here is my plunker:
Angular Named Views Test


text:
Q: Android Studio not detected my usb device - ubuntu Android device is not detected in android studio after updating it from 2.1.4 to 2.2.3 on Ubuntu, previously it was working fine. Even I tried with previous version still its not detecting.
I have already enabled usb debugging. I tried MTP and PTP too nothing works for me.
android device is connected to computer
bhanuchand@bhanuchand-X550CC:~$ lsusb
Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 004: ID 04f2:b40a Chicony Electronics Co., Ltd
Bus 001 Device 006: ID 13d3:3362 IMC Networks Atheros AR3012 Bluetooth 4.0 Adapter
Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 011: ID 2717:1218
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Bus 003 is my device redmi 1s which doesn't have any description
adb device
bhanuchand@bhanuchand-X550CC:~$ adb devices
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
976fc0d9    device

it showing nothing
 enter image description here
PS: sorry for my english

A: install device driver on Ubuntu and restart the system..
make sure you select MTP is selected

A: It is because, I'm running studio on ubuntu 32-bit version. Android studio Developers stopped supporting 32-bit versions. To get it worked downgrade your build version to 21 or below in gradle and rebuild the project (download if it needed).

A: This command is to install the mainstream device driver, can not find the driver can also be manually added in /etc/udev/rules.d/51-android.rules
$ wget -S -O - http://source.android.com/source/51-android.rules | sed "s/<username>/$USER/" | sudo tee >/dev/null /etc/udev/rules.d/51-android.rules; sudo udevadm control --reload-rules


text:
Q: how to retrieve multiple values from single column using AND operator I want to grab user_id when there is a match found for two values in meta_value column. For example, if there exist a record for "tagowner" and another values is "999"  in meta_value column only.
I tried using IN operator as :-
SELECT * from wp_usermeta where meta_value IN ('tagowner',999);

but this is also displaying results for other group also. I just need results  only for "tagowner" and "999" .
Thanks

A: meta_value are non numeric type.
SELECT *
FROM   wp_usermeta
WHERE  meta_value IN ( 'tagowner', '999' );

A: If you need user_ids for where both rows are present, you may use EXISTS or self join:
SELECT * FROM wp_usermeta t1
WHERE meta_value = 'tagowner'
AND EXISTS (SELECT 1 FROM wp_usermeta t2
            WHERE t2.meta_value = '999'
            AND t1.user_id = t2.user_id )

example: sqlfiddle


text:
Q: Can we increase the priority of the Garbage collection thread in java As we know in java we have a priority levels for threads, and Garbage collector is a thread with lowest priority. So i wanted to know whether for a particular java application can we have its Garbage collector to be more prioritized so that it may increase the memory management for that application.

A: There are a lot of command line switches which determine garbage collection behaviour in Sun's JVM.
It gets a little complicated, but they're documented here:
http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html

A: Basically you want the garbage collector to consume as few system resources as possible, and unless you have very good reason to do otherwise you should leave the system default settings as your adjustments may very well be invalidated by a JVM change or upgrade.
Hence I advise that you do not tinkle with the garbage collection settings.  If you have very good reason to do so, please edit your question accordingly.

A: Do not rely on priority of a daemon thread to get a job done. Say java has 10 level of thread priority but when it maps to native OS thread (say Solaris which has 170 levels of priority) the priority is remapped. Moreover Windows NT has this peculiar habit of increasing thread priority indeterministically by each CPU cycle. Trying to control the flow of app using thread priority can lead to portability issues.
For further details refer this SO question
Depending upon the implementation of JVM higher priority threads may still preempt lower priority threads in time slicing scheme. The addition of time slicing mixes up the processing among threads of the same priority; on a multiprocessor machine, threads may even be run simultaneously. Unfortunately, this feature can lead to differences in your application's behavior.


text:
Q: Runge-Kutta code not converging with builtin method I am trying to implement the runge-kutta method to solve a Lotka-Volterra systtem, but the code (bellow) is not working properly. I followed the recomendations that I found in other topics of the StackOverflow, but the results do not converge with the builtin Runge-Kutta method, like rk4 method available in Pylab, for example. Someone could help me?
import matplotlib.pyplot as plt
import numpy as np
from pylab import *

def meurk4( f, x0, t ):
    n = len( t )
    x = np.array( [ x0 ] * n )

    for i in range( n - 1 ):

        h =  t[i+1] - t[i]

        k1 = h * f( x[i], t[i] )
        k2 = h * f( x[i] + 0.5 * h * k1, t[i] + 0.5 * h )
        k3 = h * f( x[i] + 0.5 * h * k2, t[i] + 0.5 * h )
        k4 = h * f( x[i] + h * k3, t[i] + h)

        x[i+1] = x[i] + ( k1 + 2 * ( k2 + k3 ) + k4 ) * 6**-1

    return x

def model(state,t):

    x,y = state

    a = 0.8
    b = 0.02
    c = 0.2
    d = 0.004
    k = 600

    return np.array([ x*(a*(1-x*k**-1)-b*y) , -y*(c - d*x) ]) # corresponds to [dx/dt, dy/dt]

# initial conditions for the system
x0 = 500
y0 = 200

# vector of time
t = np.linspace( 0, 50, 100 )

result = meurk4( model, [x0,y0], t )
print result

plt.plot(t,result)

plt.xlabel('Time')
plt.ylabel('Population Size')
plt.legend(('x (prey)','y (predator)'))
plt.title('Lotka-Volterra Model')
plt.show()

I just updated the code following the comments. So, the function meurk4:
def meurk4( f, x0, t ):
        n = len( t )
        x = np.array( [ x0 ] * n )

        for i in range( n - 1 ):

            h =  t[i+1] - t[i]

            k1 = h * f( x[i], t[i] )
            k2 = h * f( x[i] + 0.5 * h * k1, t[i] + 0.5 * h )
            k3 = h * f( x[i] + 0.5 * h * k2, t[i] + 0.5 * h )
            k4 = h * f( x[i] + h * k3, t[i] + h)

            x[i+1] = x[i] + ( k1 + 2 * ( k2 + k3 ) + k4 ) * 6**-1

        return x

Becomes now (corrected):
def meurk4( f, x0, t ):
    n = len( t )
    x = np.array( [ x0 ] * n )

    for i in range( n - 1 ):

        h =  t[i+1] - t[i]

        k1 = f( x[i], t[i] )
        k2 = f( x[i] + 0.5 * h * k1, t[i] + 0.5 * h )
        k3 = f( x[i] + 0.5 * h * k2, t[i] + 0.5 * h )
        k4 = f( x[i] + h * k3, t[i] + h)

        x[i+1] = x[i] + ( k1 + 2 * ( k2 + k3 ) + k4 ) * (h/6)

    return x

Nevertheless, the results is the following:

While the buitin method rk4 (from Pylab) results the following:

So, certainly my code still is not correct, as its results are not the same of the builtin rk4 method. Please, someone can  help me?

A: You are doing a very typical error,see for instance How to pass a hard coded differential equation through Runge-Kutta 4 or here Error in RK4 algorithm in Python
It is either
k2 = f( x+0.5*h*k1, t+0.5*h )
...
x[i+1]=x[i]+(k1+2*(k2+k3)+k4)*(h/6)

or
k2 = h*f( x+0.5*k1, t+0.5*h )

and so on, with x[i+1] as it was, but not both variants at the same time.

Update: A more insidious error is the inferred type of the initial values and in consequence of the array of x vectors. By the original definition, both are integers, and thus
x = np.array( [ x0 ] * n )

creates a list of integer vectors. Thus the update step
    x[i+1] = x[i] + ( k1 + 2 * ( k2 + k3 ) + k4 ) * (h/6)

will always round to integer. And since there is a phase where both values fall below 1, the integration stabilizes at zero. Thus modify to
# initial conditions for the system
x0 = 500.0
y0 = 200.0

to avoid that problem.


text:
Q: Downloading JSON data using R in Tableau I want to use data from an openFDA API, which is in JSON format, in Tableau so that when the data changes Tableau can also update the visualization when refreshed. I tried to use R code inside Tableau but I am getting an error message. The code I am using is:
SCRIPT_INT('library(jsonlite);
fda<-fromJSON("https://api.fda.gov/drug/label.json?search=effective_time:[20090601+TO+20140731]&count=effective_time");
fda<-fda$results;
fda<-fda[,2]')

and the error message I am getting:
"STRING_INT is being used with(string), did you mean (string, ...)?"

Any suggestions on how to fix this error?
In R, it works fine as shown below:
library(jsonlite)
fda<-fromJSON("https://api.fda.gov/drug/label.json?search=effective_time:[20090601+TO+20140731]&count=effective_time")
fda<-fda$results;
fda<-fda[,2]
class(fda)
head(fda)


text:
Q: iOS - AccessoryView changes the size of custom separator I have a grouped tableview and at first I wanted to remove the top and bottom separator. I looked around and found a solution that worked great form me. It was by adding a UIView to the bottom of the cell to act as the separator. Now it looks amazing. But the problem I faced is when I set the AccessoryView of the cell , because for some reason when I select the cell , my custom separator change its width . Here's a representation of the problem :
this is when not selected

this is when selected :

Note that the custom separator already has constraint .
Any suggestions please ?
Edit:
Here's how I set the accessoryView :
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if let cell = tableView.cellForRow(at: indexPath) as? TableViewCell {
            let label = UILabel()
            label.text = "x"
            label.sizeToFit()
            label.font = UIFont.systemFont(ofSize: 13, weight: .medium)
            if(cell.accessoryView == nil){
                cell.accessoryView = label
            }else{
                cell.accessoryView = nil
            }

        }
    }

that's it and everything else is just a simple tableview with rows and section , I also set the separator to none in storyboard.
Edit 2 :
This is the separator constraints :

A: You need to change your trailing constraint. Instead of ContentView add trailing constraint to cell. Remove trailing constraint on separator view and add constraints as in image.

A: In iOS 13+, I had to change the code to draw bottom border on the cell instead of the cell's contentView. I do it in awakeFromNib in the Cell class.
override func awakeFromNib() {
    super.awakeFromNib()
    addBorder(borderType: .bottom)
}

func addBorder(borderType: BorderType, width: CGFloat = 1.0, color: UIColor = .darkGray) {
        // figure out frame and resizing based on border type
        var autoresizingMask: UIView.AutoresizingMask
        var layerFrame: CGRect
        switch borderType {
        case .left:
            layerFrame = CGRect(x: 0, y: 0, width: width, height: self.bounds.height)
            autoresizingMask = [ .flexibleHeight, .flexibleRightMargin ]
        case .right:
            layerFrame = CGRect(x: self.bounds.width - width, y: 0, width: width, height: self.bounds.height)
            autoresizingMask = [ .flexibleHeight, .flexibleLeftMargin ]
        case .top:
            layerFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: width)
            autoresizingMask = [ .flexibleWidth, .flexibleBottomMargin ]
        case .bottom:
            layerFrame = CGRect(x: 0, y: self.bounds.height - width, width: self.bounds.width, height: width)
            autoresizingMask = [ .flexibleWidth, .flexibleTopMargin ]
        }

        // look for the existing border in subviews
        var newView: UIView?
        for eachSubview in self.subviews {
            if eachSubview.tag == borderType.rawValue {
                newView = eachSubview
                break
            }
        }

        // set properties on existing view, or create a new one
        if newView == nil {
            newView = UIView(frame: layerFrame)
            newView?.tag = borderType.rawValue
            self.addSubview(newView!)
        } else {
            newView?.frame = layerFrame
        }
        newView?.backgroundColor = color
        newView?.autoresizingMask = autoresizingMask
    }


text:
Q: URL signing using SHA256 key I'm bulding an application using Doctrine ORM and for some reason I need to put a DQL query in a URL. I know.  It's sound like very bad idea but... what if I'll sign URL? I was thinking about something like this:
If my URL is:
http://example.com/api/?sql=SELECT%20e%20FROM%20SomeEntity
I can hash this url with some secret:
$hash = hash('sha256', $url.$someLongSecretToken);
And finally my URL will be looks like this:
http://example.com/api/?sql=SELECT%20e%20FROM%20SomeEntity&hash=5639543ff649aa1b799a99d7cbf509a850de5cb31835a22ee7a927560ce33c60
And after it, just before execute DQL I can remove hash parameter from URL, hash URL again and compare hash form URL with just calculated one. If hashes are same it means that this URL is generated by the server and is not modified.
Is this solution secure? For me as long as sha256 is secure and $someLongSecretToken will be long enough this solution should be secure but I have bad feeling about this ;)

A: No, this is not secure. If a collision attack is found against SHA256, the hash will be able to be faked.
To fix it, replace the hash with a HMAC:
hash_hmac('sha256', $url, $someLongSecretToken);

Definitely use a timing safe comparison:
if (hash_equals($signature, hash_hmac('sha256', $url, $secret))) {
    // It's good
}