text:
Q: how to remember user name and password in django I want to prepopulate a user's user name and password at login like this:

I'm pretty sure I wouldn't save the password to a cookie.
How else would I accomplish this?

A: No, you really, really don't want to do this. There is absolutely no good reason to prepopulate a user's password field
Of course, you can keep them logged in for as long as you like, that's simply a matter of setting the session expiry. But what would be the benefit of prepopulating their password? Just don't do it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Variable from object js as html id From 3 hours I am trying to set id in HTML code as id from object js, I watched few tutorials and I think it should run correct but all time my compiler is treat data-id ="${getCandidate.id}" as a string value what is wrong in that code ;/

// read all candidates from server
function readData() {
    $.ajax({
        url: apiURLGetAllCandidates
            + 'all'
    })
        .done(candidateList => {
            candidateList.forEach(getCandidate => {
                const $element = $(
                    "
" +
                    "
\n" +
                    "
\n" +
                    "            name	\n" +
                    "            surname	\n" +
                    "            age	\n" +
                    "            education	\n" +
                    "            experience	\n" +
                    "
\n" +
                    "
\n" +
                    "            " + getCandidate.name + "	\n" +
                    "            " + getCandidate.surname + "	\n" +
                    "            " + getCandidate.age + "	\n" +
                    "            " + getCandidate.candidateEducation + "	\n" +
                    "            " + getCandidate.experience + "	\n" +
                    "
\n" +
                    "
" +
                    "        <button class='edit-button'>Edit</button>" +
                    "        <button class='delete-button' data-id =\"${getCandidate.id}\">Delete candidate</button>\n" + // place where i have problem
                    "        <button class='detail-button'>Show details</button>" +
                    "
" +
                    "
\n" +
                    "            phone number	\n" +
                    "            email	\n" +
                    "            salary expectations	\n" +
                    "            city	\n" +
                    "
\n" +
                    "
\n" +
                    "            " + getCandidate.phoneNumber + "	\n" +
                    "            " + getCandidate.email + "	\n" +
                    "            " + getCandidate.salaryExpecations + "	\n" +
                    "            " + getCandidate.city + "	\n" +
                    "
\n" +
                    "
" +
                    "            short description	\n" +
                    "
" +
                    "
" +
                    "            " + getCandidate.shortDescription + "	\n" +
                    "
" +
                    "
\n " +
                    "
"
                );

                $CandidateList.append($element);
            });
        });
}

A: Try this putting inside a single quote
<button class='delete-button' data-id ='"+${getCandidate.id}+"'>Delete candidate</button>


text:
Q: Reading excel file stored in hdfs using java I am writing a UDF for Hive using Java. I have to read excel files stored in hdfs and do some processing using udf. I am using poi library for processing.
When we read from hdfs we get  FSDataInputStream but When we create Workbook using POI it needs InputStream Object.
Though code is not giving error at compile time.
FSDataInputStream stream = hdfs.open(new Path(inputFile));
Workbook workbook= new XSSFWorkbook(stream);

But When I create temporary function I get:

Execution Error, return code -101 from org.apache.hadoop.hive.ql.exec.FunctionTask. org/apache/poi/ss/usermodel/Workbook

A: It looks like you didn't add all dependent jars. You need to either build your jar with dependency or add all dependent jars one by one.
Command: hive> add myjar.jar


text:
Q: How to Logout (Go to Base URL) if local Storage doesn't have certain key-value pair in React I am implementing a simple logout functionality if my local storage doesn't have a particular key-value pair and if the value is empty or if the 'token' inside the value is expired.
My current Code: TokenExpired.js
import { isExpired } from "react-jwt";
import { useNavigate } from "react-router-dom";

export const VerifyAccessToken = () => {
    const navigate = useNavigate()
    const Data = localStorage.getItem('Admin Credentials')
    const existanceOfData = Data !== null

    if (existanceOfData) {
        if (Data && Data !== 'undefined') {
            const tokenExpired = isExpired(JSON.parse(Data).accessToken);
            if (tokenExpired) {
                localStorage.removeItem("Admin Credentials");
                navigate('/')
            }
        } else {
            localStorage.removeItem("Admin Credentials");
            navigate('/')
        }
    } else {
        navigate('/')
    }

}

I am using this in My Dashboard Page : Dashboard/Dashboard/js
import "./Dashboard.scss";
import { adminAuth } from "../../helpers/AdminInformation";
import { VerifyAccessToken } from "../../helpers/TokenExpired";

// components ---------------------------------
certain components

import { useEffect, useState } from "react";

const Dashboard = () => {
    const [dashboard, setDashboard] = useState({ received: 0, expected: 0 })
    const token = adminAuth.accessToken;

    useEffect(() => {
        fetch(baseURL + 'api/dashboard/', {
            headers: {
                token: `Bearer ${token}`
            }
        }).then(res => res.json()).then(json => setDashboard(json));
    }, [token])

    VerifyAccessToken();

    return (
        <div className="dashboard">
            content
        </div>
    );
}

export default Dashboard;

Whenever I try to delete that key value after logging in, it shows error:

A: I Found the Answer to my Question:
I figured I need to make my Routes Strong so that there are no warning about my routes in the console
I Created Layout Component for my Dashboard Page & Update Token Expired Code with useEffect(), It worked...
My Updated Code: TokenExpired.js
import { isExpired } from "react-jwt";
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";

export const VerifyAccessToken = () => {
    const navigate = useNavigate()
    const Data = localStorage.getItem('Admin Credentials')
    const existanceOfData = Data !== null

    useEffect(() => {
        if (existanceOfData) {
            if (Data && Data !== 'undefined') {
                const tokenExpired = isExpired(JSON.parse(Data).accessToken);
                if (tokenExpired) {
                    navigate('/')
                }
            } else {
                navigate('/')
            }
        } else {
            navigate('/')
        }
    }, [Data, existanceOfData, navigate]);
}


text: Q: How to resolve EXC_BAD_Acess on setToolbar: method to set NSToolbar to window? I am trying to set NSToolBar to my window with setToolBar: method but its causing crash. As parameter to method is not nil & window to which toolbar to be set is also not nil. Thanks!


text:
Q: How to match a word to a number in Stata? I have a list of 2505000 data points (in Data Editor) (although the numbers within are between 1-6680 - each number repeats itself 375 times, so that's why I get 250500 fields in this particular column labeled "id").
What I need is to match a word to each of the numbers - ideally batches of numbers: e.g., "cats" to numbers 1,2,56,45,67,55 and "dogs" to 3,59,46,68,11 and then other phrases to other numbers (numbers between 1-6680).
These words should be in a new column (whatever name) and simply correspond with the numbers in column "id".
Can anyone advise on how to do it? Thanks
Clarification:
In my data editor, data is listed in column one ("id"):

The data goes all the way down to field 2505000:

The important thing to note, however, is that the data between the fields 1 and 2505000 is limited to numbers (in "id" column) from 1 to 6680. Each number appears there 375 times - i.e. 375*6680=2505000.
Now, what I need is to create a new variable where words correspond to specific numbers in the "id" variable:

dog equals 3138, 3076, 2851
cat equals 1579, 1449
auto 1810, 2351, 353
...and so on for other words and number combinations.


text:
Q: Updating UILabel Text resets storyboard? I came across a weird scenario, that I just can't figure out on my own.
I started a little test scenario, with an almost empty iOS Single View Application and a storyboard. The story boards contains a label and single UIView, 10x10, just for presenting the issue. Of course they have the appropriate IBOutlets assigned and connected:
@property (nonatomic, weak) IBOutlet UILabel *label;
@property (nonatomic, weak) IBOutlet UIView *dot;

In the (void)viewDidLoad method I start a timer and add it to the run loop like that:
- (void)viewDidLoad {
    [super viewDidLoad];

    NSTimer * timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

In the (void)doSomething method I do the following:
-(void)doSomething {
    // Lets move the dot to the right a bit further
    _dot.center = CGPointMake(_dot.center.x+1, _dot.center.y);

    // About every ten steps, update the label with the current
    // X position, to better show the problem
    CGFloat moduloResult = (float)((int)_dot.center.x % (int)10.0);
    if(moduloResult <= 0)
        _label.text = [NSString stringWithFormat:@"%f", _dot.center.x+1];
}

So basically, I change the center of the little 10x10 dot-view every time by  1, and every 10th time I update the label to show the current X position. For that matter it doesn't even matter with what I update the label text, it's just important that it changes. And I only change the text every 10 times to better show the problem here.
If I run that code the dot moves just as intended to the right, but then when I update the label text, the dot view gets reset and jumps back to it's original position. So updating my label text resets my other views on the Storyboard, which totally confuses me.
Can someone reproduce that or even explain it?
Thanks all, in advance :)
Alex

A: I was able to reproduce described behaviour, here is why it is happening:

*

*By default, position of elements is determined by auto generated AutoLayout constraints

*When changing position of dot you are only updating it's current frame, not underlying constraints

*Changing the text of UILabel possibly changes size of UILabel's content, so it's frame needs to be recalculated. Here entire layout is recalculated based on constraints, thus also reseting frame of the dot.

For resolving, I'd suggest to properly specify AutoLayout constraints and updating them instead of position directly.

A: That was pretty much it, the AutoLayout constraints pushed the view always back to it' original place, which kind of makes sense I guess, that's what the AutoLayout is supposed to do.
So, since I wanted my litte 10x10 dot-view to move around the screen (for practicing purposes, I changed my code. I try to explain it, lack of reputation just currently keeps me from posting the appropriate images.
I made two custom AutoLayout constraints, telling it to keep the view always 120px from the left of the superview and 100px from the top of the superview. I also specified the constraint for a fixed width and height of each 10. Since for a valid constraint you need the combination of x and y as well as height and width (at least as far as I understand it).

                  -
                  |
                  | Constraint *n* from top
                  |

                  |------|
  Constraint      | view |
  *n* from left   | _dot |
|---------------  |------|

Then I created two IBOutlets for the two Constraints:
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *c1X;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *c1Y;

I changed my (void)doSomething method to this:
-(void)doSomething {

    // Lets move the dot to the right a bit
    // further by changing its Constraint
    _c1X.constant++;

    // About every ten steps, update the labe with the current
    // X position, to better show the problem
    CGFloat moduloResult = (float)((int)_dot.center.x % 10);
    if(moduloResult <= 0)
        _label.text = [NSString stringWithFormat:@"%f - %f - %f", _c1X.constant, _dot.center.x, _dot.center.y];
}

It works, the changing of the constraint instead of the actual view now moves the view over the screen. If this is best practice, I don't know. If I wouldn't have tried it for practice purposes, following a aged tutorial, I wouldn't come up with that in the first place.
In the hopes this might help one day. Any comments or improvements are welcome :)
Alex

A: This seems to be an old question but it bothered me too.
I was puzzled at the fact that changing the text in UILabel in the bottom of the visual hierarchy makes the whole storyboard to re-layout.
More than that, having some Android development background I never witnessed such behavior in Android with the (analogous) TextView. You change the text in it how you wish -- never updated the higher levels of the UI.
But the answer by @Jakub Vano made me to realize one thing:
The TextView in Android has always fixed width and height and there is no way the updating of the text inside the view would change its borders.
On the contrary, the iOS' UILabel can be left with self-formatting width and height based on the text in it.
Unfortunately, even fixing the width and height in the storyboard doesn't solve the issue: updating the text still fires the request to re-layout everything.
I found the solution in using CATextLayer -- it does not impact the layout and you can put there any text you want. But the price for that is that you have to take care about everything programmatically, keeping in mind you deal with real pixels, not dots, like so:
            let mScale = UIScreen.main.scale

            indicatorLeft = CATextLayer ()
            indicatorLeft.fontSize = FONT_SIZE * mScale
            indicatorLeft.string = "text in CA layer"
            indicatorLeft.foregroundColor = UIColor.white.cgColor
            indicatorLeft.shadowColor = UIColor.gray.cgColor
            indicatorLeft.isHidden = false
            indicatorLeft.contentsScale = mScale

            indicatorLeft.frame = CGRect(x: 0, y:  0,
                                 width: VIEW_WIDTH * mScale, height: VIEW_HEIGHT * mScale )

            leftView.layer.addSublayer(indicatorLeft)


text:
Q: Programa de loteria Buenas noches estoy comenzando mis andadas con python (soy principiante), estoy desarrollando un script para un progama de lotería, pero no para generar los números aleatoriamente sino con algunas fuciones.
Primero extraigo con parsefeed los siete últimos sorteos, analizo los números repetidos, la media aritmética de cada sorteo, los que han salido una vez en siete sorteos, los que no han salido, etc.
En base a esto elijo una combinación de números probables y genero todas las combinaciones posibles:
    def generador():
        a = [1, 4, 7, 12, 15, 21, 23]
        combinations = list(itertools.permutations(a, 6))
        a = str(combinations)
        return a

Ahora bien, no sé cómo aplicar algunas de las condiciones que quiero implementar:

*

*Me gustaría seleccionar todas aquellas combinaciones dentro de un rango de la media aritmética. He utilizado el módulo stats.mean(combinacion()) para generar la media aritmética de las combinaciones individualmente pero dada la lista que me genera la función permutation(), ¿Cómo podría hacer para seleccionar sólo aquellas combinaciones que estén dentro de un rango de media aritmética (por ejemplo 20)?, e.g.: La combinación 5,7,12,26,29,41 cumpliría la condición porque su media aritmética es 20, el resto de combinaciones que no la cumplen se descartarían.

*Quiero seleccionar sólo aquellas combinaciones cuya diferencia entre número sea de 1 o 2. ¿Cómo podría hacerlo? e.g.: La combinación 1,25,28,31,40,49 no presenta diferencias entre alguno de sus números de 1 o 2, por lo tanto se descartaría. La combinación 1,3,14,34,37,40 presenta una diferencia de 2 entre el 1 y el 3, por lo que sería seleccionada. La combinación 2,14,16,25,30,45 presenta una diferencia de 2 entre el número 14 y 16, por lo tanto sería seleccionada.

*Seleccionar sólo aquellas combinaciones que presenten uno o dos números contiguos, e.g.: La combinación 2,15,16,26,29,34 contiene al 15 y al 16 que son números contiguos, por lo tanto sería seleccionada. La combinación 2,15,23,27,30,34 no presenta números contiguos, por lo tanto no sería seleccionada.
Muchas gracias,
Un saludo.

A: Tu enfoque tiene importantes problemas de consumo excesivo de memoria. Primero, la cantidad de permutaciones que se pueden llegar a generar crece de forma desorbitada a medida que tienes más números "elegibles". Y el problema aparece en que tú usas list() para convertir en una lista todas las permutaciones halladas.
Esto es muy ineficiente ya que muchas de esas combinaciones las vas a descartar luego, por lo que no tiene sentido consumir toda esa memoria guardando combinaciones que no vas a querer al final.
Por si fuera poco, después vuelves a convertir la lista completa en una cadena, usando str(). No veo el sentido de hacer esto, ya que la función podría retornar directamente la lista. Convertirlo a cadena va a llevar mucho tiempo y va a requerir otra vez mucha memoria.
Pero es que ni siquiera necesitas retornar la lista con los resultados si usas un enfoque basado en generadores. Estas son funciones que en lugar de return contienen yield y en vez de retornar listas, "retornan" (con yield) los elementos de uno en uno.
Basándose en esta idea podrías hacer una función que:

*

*Llame a itertools.permutations() para generar todas las permutaciones una a una (sin convertirlas en una lista)

*Cada permutación generada se mira si pasa o no cada uno de tus test (puedes tener funciones aparte que implementen esos test)

*Si algún test falla, se pasa a la siguiente combinación (usando continue)

*Sólo si todos los test han pasado, se "retorna" (con yield) esa combinación.

Esta sería la implementación (aunque faltan las funciones que hacen los test):
def generador(elegibles):
    for combinacion in itertools.permutations(elegibles, 6):
       if not promedio_es(combinacion, 20):
          continue
       if not presenta_saltos(combinacion):
          continue
       if not hay_dos_seguidos(combinacion):
          continue

       # Si pasa todos los test, la retornamos
       yield combinacion

Las funciones que faltan recibirían una sola combinación y retornarían True si pasan el test correspondiente. Por ejemplo, la más simple, sería así:
def promedio_es(combinacion, valor):
   return (sum(combinacion)/len(combinacion) == valor)

De momento te dejo que pienses cómo podrían implementarse el resto de las condiciones. Pregunta de nuevo si te atascas.
Una vez los test estuvieran implementados, lo que tendríamos sería un generador que se puede usar en un bucle, por ejemplo para mostrar todas las combinaciones que hayan pasado los test, así:
a = [1, 4, 7, 12, 15, 21, 23]
for numeros in generador(a):
   print(numeros)

Si quieres también puedes crear una lista con los resultados:
todas_las_validas = list(generador(a))

por si luego quieres usar algún mecanismo para extraer una de esas combinaciones de la lista. No obstante, en lo posible, evita crear esta lista si no vas a necesitar todos sus elementos, para evitar consumo innecesario de memoria.

A: Una forma de evitar pasar una lista de números que hacen tu algoritmo predecible es generar los números de forma aleatoria.
Te dejo un código de apoyo de como hacerlo:
import secrets, string

def NumeroAleatorio(digitos):
    "Genera numeros aleatorios del tamaño indicado"
    return "".join(secrets.choice(string.digits) for i in range(digitos))

# Generacion de 10 numeros de 2 digitos aleatorios
numeros = [NumeroAleatorio(2) for i in range(10)]


text:
Q: Why my parameterless ctor fires with Unity? I have a ViewModel called TopMenuViewModel. It has 2 constructors: one without parameters and one with Parameters that should be pushed from Unity.
When I waht to use the viewmodel, injection isn't working and default parameterless ctor is called (not the injected one) so I canot use dependencies. Why and How? :-)
Here is the ViewModel:
public class TopMenuViewModel
{
    public int unreadMessagesCount { get; set; }
    public PersonnelAMEntity personnel { get; set; }
    IList<DocumentTypeEntity> quickDocumentTypes { get; set; }

    private readonly IPersonnelAMBusiness _IPersonnelAMBusinessRepo;
    private readonly IDocumentBusiness _IDocumentBusinessRepo;
    private readonly IMessageBusiness _IMessageBusinessRepo;

    [InjectionConstructor]
    public TopMenuViewModel(IPersonnelAMBusiness personnelRepo, IDocumentBusiness documentRepo, IMessageBusiness messageRepo)
    {
        _IPersonnelAMBusinessRepo = personnelRepo;
        _IDocumentBusinessRepo = documentRepo;
        _IMessageBusinessRepo = messageRepo;
    }

    public TopMenuViewModel() {}

    internal void SetMenuFor(int matricule)
    {
        // Get personnel
        this.personnel = _IPersonnelAMBusinessRepo.GetAll(matricule);

        // Get message number
        unreadMessagesCount = _IMessageBusinessRepo.GetUnreadReceivedMessages(this.personnel).Value.Count;

        // Get QuickDocumentTypes
        quickDocumentTypes = _IDocumentBusinessRepo.GetAllQuickDocumentTypes(SessionManager.visibilityUnit).Value;
    }
}

Here is how it is called:
public ActionResult TopMenu()
{
    TopMenuViewModel model = new TopMenuViewModel();
    model.SetMenuFor(SessionManager.matricule);
    return PartialView("~/Views/Shared/_TopMenu.cshtml", model);
}

When I call SetMenuFor, I got a 'System.NullReferenceException' on _IPersonnelAMBusinessRepo.
Here is the UnityConfig (it is read by compiler because I can breakpoint on it (fired thanks to UnityMvcActivator) ) :
public static void RegisterTypes(IUnityContainer container)
{

    container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
    container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
    container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
    //container.RegisterType<AccountController>(new InjectionConstructor());
    container.RegisterType<AccountController>(new InjectionConstructor(typeof(IPersonnelAMBusiness)));

    // Business Layer DI
    container.RegisterType<IAMLogBusiness, AMLogBusiness>();    // No dependencies
    container.RegisterType<IAuditBusiness, AuditBusiness>();    // No dependencies
    container.RegisterType<ICockpitStatBusiness, CockpitStatsBusiness>();    // No dependencies
    container.RegisterType<IDistributionListBusiness, DistributionListBusiness>();  // No dependencies
    container.RegisterType<IEmailBusiness, EmailBusiness>();    // No dependencies
    container.RegisterType<INatureBusiness, NatureBusiness>();  // No dependencies
    container.RegisterType<IProfessionBusiness, ProfessionBusiness>();  // No dependencies
    container.RegisterType<IReportingBusiness, ReportingBusiness>();    // No dependencies
    container.RegisterType<IRequeteBusiness, RequeteBusiness>();    // No dependencies
    container.RegisterType<ISocieteBusiness, SocieteBusiness>();    // No dependencies
    container.RegisterType<ITopicBusiness, TopicBusiness>();    // No dependencies
    container.RegisterType<IUserBusiness, UserBusiness>();  // No dependencies
    container.RegisterType<IUnitBusiness, UnitBusiness>();    // No dependencies
    container.RegisterType<IDocumentBusiness, DocumentBusiness>();  // No dependencies
    container.RegisterType<IInstallationBusiness, InstallationBusiness>();  // Unit(V) dependencies
    container.RegisterType<IAnomalyBusiness, AnomalyBusiness>();    // Audit(V), Installation(V) dependencies UNIT
    container.RegisterType<IPersonnelAMBusiness, PersonnelAMBusiness>();    // Anomaly(V), profession(V), user(V), audit(V), Unit(V) dependencies
    container.RegisterType<IMessageBusiness, MessageBusiness>();    // Personnel(V), Document(V) Unity(V) dependencies

    // Set resolver
    DependencyResolver.SetResolver(new UnityDependencyResolver(container));

}

A: When you use following code in controller action:
TopMenuViewModel model = new TopMenuViewModel();

you don't actually create ViewModel instance via Unity Container. You create it with C# new operator calling parameterless constructor.
To make the ViewModel instance created via Unity do the following:
1.Inject instance of ViewModel into your controller constructor:
private readonly TopMenuViewModel _viewModel;

public YourController(TopMenuViewModel viewModel)
{
    if (viewModel == null)
    {
        throw new ArgumentNullException(nameof(viewModel));
    }

    _viewModel = viewModel;
}

Note that there should be no other constructors in the controller.
2.Remove TopMenuViewModel instance creation in TopMenu() action and use injected instance saved in _viewModel field:
public ActionResult TopMenu()
{
    _viewModel.SetMenuFor(SessionManager.matricule);
    return PartialView("~/Views/Shared/_TopMenu.cshtml", _viewModel);
}

3.Remove parameterless constructor from TopMenuViewModel class. As NightOwl888 noted, having multiple constructors with DI is an antipattern that should be avoided.
Now when ASP.NET MVC receives request, it will create instance of controller via Unity, because you set UnityDependencyResolver as DependencyResolver. Unity will resolve instance of TopMenuViewModel passed to constructor including all its inner dependencies.


text:
Q: Merge two dictionaries that have dictionaries as key values Merge two dictionaries of dictionaries
My question is similar to this one, but the answers don't produce the right result (for me?).
Take these dictionaries:
a = {'a': {'a': 1}}
b = {'a': {'b': 2}}

I want to produce:
c = {'a': {'a': 1, 'b': 2}}

Using the answers from the quoted question, these all produce:
c = a.copy()
c.update(b)

>>
c == {'a': {'b': 2}

Consider that a and b might be more complex than this, for example:
a = {'a': {'aa': {'aaa': 1}, 'bb': {'bbb': 2}}}
b = {'a': {'bb': {'aaa': 1}, 'bb': {'bbb': 2}}}

A: In this case you can use
>>> a['a'].update(b['a'])
>>> a
{'a': {'a': 1, 'b': 2}}

Element in dictionary is also dictionary, so you can treat that element as dictionary.
As for more complex example I don't know what result should be. But in general, you can access elements in element as dictionary in nested for loops.


text:
Q: Unable to type alias a specialised generic enum Given the following:
use std::fmt::Debug;

#[derive(Debug)]
enum A<T: Debug> {
    X,
    Y(T),
}

#[derive(Debug)]
struct B;

type C = A<B>;
// use A<B> as C; // Does not compile

I can use it as:
fn main() {
    let val0 = A::X::<B>;
    let val1 = A::Y::<B>(B);
    println!("{:?}\t{:?}", val0, val1);
}

But then for more than one generic parameter (or if A, B etc were much longer names then to alias it I tried the following but it doesn't compile:
fn main() {
    let val0 = C::X;
    let val1 = C::Y(B);
    println!("{:?}\t{:?}", val0, val1);
}

with errors:
src/main.rs:656:16: 656:20 error: no associated item named `X` found for type `A<B>` in the current scope
src/main.rs:656     let val0 = C::X;
                               ^~~~
src/main.rs:657:16: 657:20 error: no associated item named `Y` found for type `A<B>` in the current scope
src/main.rs:657     let val1 = C::Y(B);

As also noted i am unable to use use to solve the problem. Is there a way around it (because typing the whole thing seems to be cumbersome) ?
rustc --version
rustc 1.9.0 (e4e8b6668 2016-05-18)

A:
Is there a way around it (because typing the whole thing seems to be cumbersome)?

You can specify C as the type of the variable so you can use A::X or A::Y without explicit specifying the type parameter:
let val0: C = A::X;
let val1: C = A::Y(B);


text:
Q: What are the reasons for ng-disabled not to work when used in a button I have a Angular form where i am doing validation. And i want the form to be not submit-able if any required fields are empty and validation fails. The form give bellow.
<form name="userForm" novalidate>
    <fieldset ng-disabled="data.externalUserDisable">

NewUser

                UsernameEmail
                <input class="form-control" type="email" id="username" name="username" ng-model="user.Username" ng-model-options="{'update On': 'blur'}" ng-disabled="(!data._editMode && !(user.Status === 'NotVerified' || user.Status === 'ActivationPending'))" ng-maxlength="256" required>

                    FirstName
                    <input class="form-control" type="text" id="firstName" name="firstName" ng-model="user.FirstName" ng-maxlength="64" required>

                    LastName
                    <input class="form-control" type="text" id="lastName" name="lastName" ng-model="user.LastName" ng-maxlength="64" required>

                MasterEngagement
                <input type="text" name="masterEngagement" ng-model="user.MasterEngagementId" ng-if="!data.externalUserDisable" typeahead="engagement.EngagementId as engagement.EngagementName for engagement in getLocation($viewValue)" typeahead-on-select='onSelect($item, $model, $label)'
                       typeahead-loading="loadingLocations" typeahead-editable="false" typeahead-input-formatter="formatLabel($model)" typeahead-template-url="customTemplate.html" typeahead-wait-ms="500" class="form-control" ng-disabled="singleEngagementAdmin !== '0'" required>
                <input type="text" name="masterEngagement" ng-model="user.MasterEngagementName" ng-if="data.externalUserDisable" class="form-control" ng-disabled="singleEngagementAdmin !== '0'" required>

            ...

                <button ng-if="data.urlId === 'new'" type="submit" class="btn btn-primary btn-lg pull-right ladda-button" data-style="expand-left" ng-save-in-progress ng-disabled="{{ userForm.$invalid }}" ng-click="insert()" translate>Save</button>
                <button ng-if="data.urlId !== 'new'" type="submit" class="btn btn-primary btn-lg pull-right ladda-button" data-style="expand-left" ng-save-in-progress ng-disabled="userForm.$invalid || (!superUser && user.Superuser)" ng-click="update()">Update</button>
                Cancel

    </fieldset>
</form>

The use of ng-disabled to disable the save button is correct. But the button is not disabled. The button is not disabled when the form loads and even for the validation errors the button is not disabled.
I have checked the userForm object and the $invalid value is true and $valid valus is false.
What i would like to know is what are the reasons for this to happen.? What could be the possible causes?
Update
The output form printing the userForm..
{
  "$error": {
    "required": [
      {
        "$validators": {},
        "$asyncValidators": {},
        "$parsers": [],
        "$formatters": [
          null
        ],
        "$viewChangeListeners": [],
        "$untouched": true,
        "$touched": false,
        "$pristine": true,
        "$dirty": false,
        "$valid": false,
        "$invalid": true,
        "$error": {
          "required": true
        },
        "$name": "username",
        "$options": {
          "update On": "blur",
          "updateOnDefault": true
        }
      },
      {
        "$validators": {},
        "$asyncValidators": {},
        "$parsers": [],
        "$formatters": [
          null
        ],
        "$viewChangeListeners": [],
        "$untouched": true,
        "$touched": false,
        "$pristine": true,
        "$dirty": false,
        "$valid": false,
        "$invalid": true,
        "$error": {
          "required": true
        },
        "$name": "firstName",
        "$options": null
      },
      {
        "$validators": {},
        "$asyncValidators": {},
        "$parsers": [],
        "$formatters": [
          null
        ],
        "$viewChangeListeners": [],
        "$untouched": true,
        "$touched": false,
        "$pristine": true,
        "$dirty": false,
        "$valid": false,
        "$invalid": true,
        "$error": {
          "required": true
        },
        "$name": "lastName",
        "$options": null
      },
      {
        "$validators": {},
        "$asyncValidators": {},
        "$parsers": [
          null
        ],
        "$formatters": [
          null,
          null
        ],
        "$viewChangeListeners": [],
        "$untouched": true,
        "$touched": false,
        "$pristine": true,
        "$dirty": false,
        "$valid": false,
        "$invalid": true,
        "$error": {
          "required": true
        },
        "$name": "masterEngagement",
        "$options": null
      }
    ]
  },
  "$name": "userForm",
  "$dirty": false,
  "$pristine": true,
  "$valid": false,
  "$invalid": true,
  "$submitted": false,
  "username": {
    "$validators": {},
    "$asyncValidators": {},
    "$parsers": [],
    "$formatters": [
      null
    ],
    "$viewChangeListeners": [],
    "$untouched": true,
    "$touched": false,
    "$pristine": true,
    "$dirty": false,
    "$valid": false,
    "$invalid": true,
    "$error": {
      "required": true
    },
    "$name": "username",
    "$options": {
      "update On": "blur",
      "updateOnDefault": true
    }
  },
  "firstName": {
    "$validators": {},
    "$asyncValidators": {},
    "$parsers": [],
    "$formatters": [
      null
    ],
    "$viewChangeListeners": [],
    "$untouched": true,
    "$touched": false,
    "$pristine": true,
    "$dirty": false,
    "$valid": false,
    "$invalid": true,
    "$error": {
      "required": true
    },
    "$name": "firstName",
    "$options": null
  },
  "lastName": {
    "$validators": {},
    "$asyncValidators": {},
    "$parsers": [],
    "$formatters": [
      null
    ],
    "$viewChangeListeners": [],
    "$untouched": true,
    "$touched": false,
    "$pristine": true,
    "$dirty": false,
    "$valid": false,
    "$invalid": true,
    "$error": {
      "required": true
    },
    "$name": "lastName",
    "$options": null
  },
  "title": {
    "$validators": {},
    "$asyncValidators": {},
    "$parsers": [],
    "$formatters": [
      null
    ],
    "$viewChangeListeners": [],
    "$untouched": true,
    "$touched": false,
    "$pristine": true,
    "$dirty": false,
    "$valid": true,
    "$invalid": false,
    "$error": {},
    "$name": "title",
    "$options": null
  },
  "employeeNumber": {
    "$validators": {},
    "$asyncValidators": {},
    "$parsers": [],
    "$formatters": [
      null
    ],
    "$viewChangeListeners": [],
    "$untouched": true,
    "$touched": false,
    "$pristine": true,
    "$dirty": false,
    "$valid": true,
    "$invalid": false,
    "$error": {},
    "$name": "employeeNumber",
    "$options": null
  },
  "userInfo": {
    "$validators": {},
    "$asyncValidators": {},
    "$parsers": [],
    "$formatters": [
      null
    ],
    "$viewChangeListeners": [],
    "$untouched": true,
    "$touched": false,
    "$pristine": true,
    "$dirty": false,
    "$valid": true,
    "$invalid": false,
    "$error": {},
    "$name": "userInfo",
    "$options": null
  },
  "timeZone": {
    "$viewValue": "W. Europe Standard Time",
    "$modelValue": "W. Europe Standard Time",
    "$validators": {},
    "$asyncValidators": {},
    "$parsers": [],
    "$formatters": [],
    "$viewChangeListeners": [],
    "$untouched": true,
    "$touched": false,
    "$pristine": true,
    "$dirty": false,
    "$valid": true,
    "$invalid": false,
    "$error": {},
    "$name": "timeZone",
    "$options": null
  },
  "culture": {
    "$viewValue": "en-US",
    "$modelValue": "en-US",
    "$validators": {},
    "$asyncValidators": {},
    "$parsers": [],
    "$formatters": [],
    "$viewChangeListeners": [],
    "$untouched": true,
    "$touched": false,
    "$pristine": true,
    "$dirty": false,
    "$valid": true,
    "$invalid": false,
    "$error": {},
    "$name": "culture",
    "$options": null
  },
  "policy": {
    "$validators": {},
    "$asyncValidators": {},
    "$parsers": [],
    "$formatters": [],
    "$viewChangeListeners": [
      null
    ],
    "$untouched": true,
    "$touched": false,
    "$pristine": true,
    "$dirty": false,
    "$valid": true,
    "$invalid": false,
    "$error": {},
    "$name": "policy",
    "$options": null
  },
  "masterEngagement": {
    "$validators": {},
    "$asyncValidators": {},
    "$parsers": [
      null
    ],
    "$formatters": [
      null,
      null
    ],
    "$viewChangeListeners": [],
    "$untouched": true,
    "$touched": false,
    "$pristine": true,
    "$dirty": false,
    "$valid": false,
    "$invalid": true,
    "$error": {
      "required": true
    },
    "$name": "masterEngagement",
    "$options": null
  }
}

A: Actually everything works fine for button tag, check this demo: http://plnkr.co/edit/fJoq7RLrDNYMxYwh6bPq?p=preview
The issue in your case is the ng-if directive which creates an inner scope, but form is declared in the parent scope. And in this case, to disable the button based on the form you have, you need to access it from parent.
Simplified it would be like this:
<button type="submit" ng-disabled="$parent.userForm.$invalid">Save</button>

Edit:
Having two ng-if means you have to go up with two parent scopes in this case, in the original code, having one ng-if access to invalid property is via $parent.userForm.$invalid, with two ng-if is
<button type="submit" ng-if="data.urlId === 'new'" ng-disabled="$parent.$parent.userForm.$invalid">Save</button>

This can be avoided by using ng-show or ng-hide instead of ng-if, the difference is that the first two don't create inner scopes, while each ng-if will create its scope inside its parent. If you change both ng-if into ng-show, then the button will work with your original ng-disabled="userForm.$invalid".


text:
Q: Unusual error in Eclipse on Ubuntu 14.04 I am using this code to test if my Eclipse is working fine with OpenCV or not.
#include "opencv.hpp"

int main(int argc, char* argv[])
{
    IplImage* img = cvCreateImage( cvSize( 640, 480 ), IPL_DEPTH_8U, 3 );

    cvCircle( img, cvPoint( 320, 240 ), 100, cvScalar( 255, 0, 0 ), 5 );

    cvNamedWindow( "OpenCV Window", CV_WINDOW_NORMAL );
    cvShowImage( "OpenCV Window", img );

    cvWaitKey(0);

    cvDestroyWindow( "OpenCV Window" );
    cvReleaseImage( &img );

    return 0;
}

Now when I build and run it once done with all the formalities of linking with OpenCV Libraries, I get the desired output.
But when I run the project, in the error log it says String index out of range:-7, multiple times!
The plug-in it uses is org.eclipse.cdt.managedbuilder.core
Is there a way I can resolve this and other errors of such kind?
Thanks in advance! :)
EDIT: It runs smoothly, as it should, but also generates these errors in the Error Log.

A: The "Error Log" is not a log of errors for your software, it is a log of errors for eclipse. The org.eclipse.cdt.managedbuilder.core plugin itself experienced some sort of error.  Unless the error is causing some sort of noticeable problem with your eclipse experience, you can safely ignore it.  I typically close that view down entirely unless I am experiencing issues with eclipse.
Warnings and error for your software will be displayed in the "Problems" view.


text:
Q: Refinements of open covers in paracompact spaces For lack of a better term and for this purpose only, let us call a refinement $\mathcal{V}$ of a cover $\mathcal{U}$ faithful if $\mathcal{V}$ can be written as $\mathcal{V}=\{V_U:U\in\mathcal{U}\}$ where $V_U\subseteq U$ for each $U\in\mathcal{U}$.
Does every open cover of a paracompact space have a faithful open refinement that is locally finite?
In other words (and maybe clearer): if, for every open cover $\mathcal{U}$ of a topological space, we demand the existence of such an open and locally finite cover $\{V_U:U\in\mathcal{U}\}$ that $V_U\subseteq U$ for each $U\in\mathcal{U}$, do we get an equivalent or strictly stronger notion than paracompactness?

A: I usually call this a precise refinement, but that may just be me.
The answer is yes. Let $\mathscr{U}$ be an open cover of the paracompact space $X$. Then $\mathscr{U}$ has a locally finite open refinement $\mathscr{R}$. For each $R\in\mathscr{R}$ fix $U(R)\in\mathscr{U}$ such that $R\subseteq U(R)$. For
each $U\in\mathscr{U}$ let $V_U=\bigcup\{R\in\mathscr{R}:U(R)=U\}$, and let $\mathscr{V}=\{V_U:U\in\mathscr{U}\}$. Clearly $\mathscr{V}$ is a precise open refinement of $\mathscr{U}$, so it only remains to show that $\mathscr{V}$ is locally finite.
Fix $x\in X$. $\mathscr{R}$ is locally finite, so there is an open nbhd $G$ of $x$ that meets only finitely many $R\in\mathbb{R}$, say $R_1,\dots,R_n$. Then $G\cap V_{U(R_k)}\ne\varnothing$ for $k=1,\dots,n$, but that's it: if $G\cap V_U\ne\varnothing$, there must be an $R\in\mathscr{R}$ such that $G\cap R\ne\varnothing$ and $U(R)=U$, in which case $V_U=V_{U(R_k)}$ for some $k$.
Note that it is possible that some $V_U$ are empty.


text:
Q: NavigationBar color not changing Android 7 I'm trying to change the color of the bottom navigation bar.
It supposed to be super easy using xml, I've added this lines in values/styles:
<item name="android:navigationBarColor" tools:targetApi="lollipop">@color/navigationBarColor</item>

V21:
<item name="android:navigationBarColor">@color/navigationBarColor</item>

Also tried programatically:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.navigationBarColor));
}

The navigation bar color won't change.  I have a viewpager with 2 fragments, each fragment has a recyclerview in it. My device running Android 7.
Any ideas?


text:
Q: Android: getListView().setTextFilterEnabled(true); not working The method setTextFilterEnabled(true) gives the wrong result. on inputing.. I don't know what is the problem.(It gives the wrong search result).
Here is the complete code of my demo application
public class AndroidCustomListActivity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setListAdapter(new MyAdapter(this,android.R.layout.simple_list_item_1,R.id.textView1,getResources().getStringArray(R.array.names)));
       getListView().setTextFilterEnabled(true);
    }

   private class MyAdapter extends ArrayAdapter<String>
{

    public MyAdapter(Context context, int resource, int textViewResourceId,
            String[] strings) {
        super(context, resource, textViewResourceId, strings);
        // TODO Auto-generated constructor stub
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row=inflater.inflate(R.layout.list_items, parent, false);
        String[] items=getResources().getStringArray(R.array.names);
        String[] items1=getResources().getStringArray(R.array.address);

        ImageView iv=(ImageView) row.findViewById(R.id.imageView1);
        TextView tv=(TextView) row.findViewById(R.id.textView1);
        TextView tv1=(TextView) row.findViewById(R.id.textView2);

        tv.setText(items[position]);

        if(items[position].equals("Tuhin Bhatt"))
        {
            iv.setImageResource(R.drawable.tuhin);
            tv1.setText(items1[position]);
        }

        else if(items[position].equals("Rikhil Jain"))
        {
            iv.setImageResource(R.drawable.ronaldo);
            tv1.setText(items1[position]);
        }

        else if(items[position].equals("David Beckham"))
        {
            iv.setImageResource(R.drawable.davidbeckham);
            tv1.setText(items1[position]);
        }

        else if(items[position].equals("Luis Figo"))
        {
            iv.setImageResource(R.drawable.luisfigo);
            tv1.setText(items1[position]);
        }

        else if(items[position].equals("David Silva"))
        {
            iv.setImageResource(R.drawable.davidsilva);
            tv1.setText(items1[position]);
        }

        else if(items[position].equals("Wayne Rooney"))
        {
            iv.setImageResource(R.drawable.waynerooney);
            tv1.setText(items1[position]);
        }

        else if(items[position].equals("Iker Casillas"))
        {
            iv.setImageResource(R.drawable.ikercasillas);
            tv1.setText(items1[position]);
        }

        return row;
    }

}
}

Everything else is working properly. The code runs perfectly except this Problem....
I know i posted a very long code.. but i thought it might help to pinpoint the problem


text:
Q: Passing the list of values to a python script as arguments inside ansible script I have a python script inside ansible playbook:
---
 - hosts: localhost
   become: yes
   become_method: sudo
   become_user: root
   gather_facts: false
   tasks:
     - name: execute script
       command: ./qwe.py
       register: python_output

     - debug:
          var: python_output.stdout_lines

qwe.py :
#!/usr/bin/python
import subprocess
import os
import json
import ssl
import platform
from requests import get
#import psutil
data = subprocess.Popen(['uname', '-r'], stdout = subprocess.PIPE)
output = str(data.communicate())
a = output[2:len(output)-10]
if "3.10.0-1062.9.1.el7.x86_64" ==  a:
  print(json.dumps({"status":"pass", "kernelVersion":a}))
else:
  print(json.dumps({"status":"fail", "kernelVersion":a}))

b = ssl.OPENSSL_VERSION
if "OpenSSL 1.0.2k-fips  26 Jan 2017" == b:
  print(json.dumps({ "status":"pass","OpenSSLVersion":b}))
else:
  print(json.dumps({"status":"fail", "OpenSSLVersion":b}))

I need to pass these list of values, for example :"OpenSSL 1.0.2k-fips  26 Jan 2017","3.10.0-1062.9.1.el7.x86_64" from outside the script instead of haedcoding it.In this way, i have 15 values I need to pass.
How can we achive it?
Thanks for your help and time!!

A: You have many possibilities.

*

*Template out a .py of file with  your vars/config and import it.

*Template out your complete script.

*Pass the data as a command line argument. Perhaps base64 encoded so you don't deal with as many problems escaping. See the docs for the b64encode filter, and maybe the to_json filters.  Would be easy enough to do command: a.py {{ some_ansible_var | to_json|b64encode }}.

*Write the data out to some kind of delimited temporary file and give the command the path to the temporary file.  Writing out a file with template, use the

*Pass the data via stdin. (You need shell instead of command)

*Set environment variables (see the task argument environment)

*Re-write your script as an ansible module. Then you can have full access to your variables.

Since I am sure this is just a bare bones example, I am not sure which idea would work best in your case.
Keep in mind that if all your software is installed via the distro package management system you could probably get everything you need just from the package_facts module. You may be re-inventing the wheel here.


text:
Q: Can I execute the output of this current query, which is itself a query automatically? Below is my query. The output of this query is a query that I can then execute as needed, but I don't want to continue doing so manually. I used to have this query within a manual process, but I now have the need to generate the output of the query that is generated on demand to send the results over to another DB for reporting purposes. What's the best approach to have the output of this existing query automatically execute? Is there a way I can do so without creating a function?
I appreciate any help in advance. Thanks
with full_query_parts as (
    select distinct
         format(' select first_year."Id"
                       , case ''%2$s'' when ''Table1'' then ''GL'' when
                     ''Table2'' then ''HC'' when ''Table3'' then ''OPP''
                         else ''REV'' end                     as "Resource"
                       , extract(''year'' from "%3$s")   as "Year"
                       , count(*)                        as "TxnCount"
              from %1$s."%2$s"
                  left join (select "Id"
                                  , extract(''year'' from "CreatedAt") as year_0
                         from app."Companies"
                             where "Id"::VARCHAR = split_part(''%1$s'', '''',
                          ''3'') ) first_year on true
                  group by 1, 2, 3'
                  ,table_schema,table_name,column_name) as que
         from information_schema.columns
         where table_schema
             in ( select distinct regexp_replace(
                      'company_schema'||"Id", '[^\w ,]', '', 'g') as company
    from app."Companies" )
    and (table_name = 'Table1' and column_name = 'Date')
    or  (table_name = 'Table2' and column_name = 'Date')
    or  (table_name = 'Table3' and column_name = 'CreatedDate')
    or  (table_name = 'Table4' and column_name = 'CreatedDate')
    or  (table_name = 'Table5' and column_name = 'CreatedDate') )
select string_agg(que,' union all ') from full_query_parts;

Also wanted to confirm the reason why I'm going through information_schema is because not each table exists in each of the company specific schemas in the Postgres DB..

A: Yes you can..!
via psql , output of the query can be executed in automated way by the meta command \gexec.
Here is the example:
postgres# select 'select deptid,deptname from mstdepartment'; \gexec;


text:
Q: Enable FairPlay Streaming in Safari over AirPlay Apple's documentation is unclear on how to enable FairPlay streaming via AirPlay on Safari.
The FairPlay Streaming Programming Guide indicates that for an iOS app you need to enable it on the AVPlayer
player.usesExternalPlaybackWhileExternalScreenIsActive = TRUE

But doesn't indicate on what is required to do this for Safari.
Does anyone know?


text:
Q: C++ - Check if One Array of Strings Contains All Elements of Another I've recently been porting a Python application to C++, but am now at a loss as to how I can port a specific function. Here's the corresponding Python code:
def foo(a, b): # Where `a' is a list of strings, as is `b'
    for x in a:
        if not x in b:
            return False

    return True

I wish to have a similar function:
bool
foo (char* a[], char* b[])
{
    // ...
}

What's the easiest way to do this? I've tried working with the STL algorithms, but can't seem to get them to work. For example, I currently have this (using the glib types):
gboolean
foo (gchar* a[], gchar* b[])
{
    gboolean result;

    std::sort (a, (a + (sizeof (a) / sizeof (*a))); // The second argument corresponds to the size of the array.
    std::sort (b, (b + (sizeof (b) / sizeof (*b)));

    result = std::includes (b, (b + (sizeof (b) / sizeof (*b))),
                            a, (a + (sizeof (a) / sizeof (*a))));

    return result;
}

I'm more than willing to use features of C++11.

A: I'm just going to add a few comments to what others have stressed and give a better algorithm for what you want.
Do not use pointers here.  Using pointers doesn't make it c++, it makes it bad coding.  If you have a book that taught you c++ this way, throw it out.  Just because a language has a feature, does not mean it is proper to use it anywhere you can.  If you want to become a professional programmer, you need to learn to use the appropriate parts of your languages for any given action.  When you need a data structure, use the one appropriate to your activity.  Pointers aren't data structures, they are reference types used when you need an object with state lifetime - i.e. when an object is created on one asynchronous event and destroyed on another.  If an object lives it's lifetime without any asynchronous wait, it can be modeled as a stack object and should be.  Pointers should never be exposed to application code without being wrapped in an object, because standard operations (like new) throw exceptions, and pointers do not clean themselves up.  In other words, pointers should always be used only inside classes and only when necessary to respond with dynamic created objects to external events to the class (which may be asynchronous).
Do not use arrays here.  Arrays are simple homogeneous collection data types of stack lifetime of size known at compiletime.  They are not meant for iteration.  If you need an object that allows iteration, there are types that have built in facilities for this.  To do it with an array, though, means you are keeping track of a size variable external to the array.  It also means you are enforcing external to the array that the iteration will not extend past the last element using a newly formed condition each iteration (note this is different than just managing size - it is managing an invariant, the reason you make classes in the first place).  You do not get to reuse standard algorithms, are fighting decay-to-pointer, and generally are making brittle code.  Arrays are (again) useful only if they are encapsulated and used where the only requirement is random access into a simple type, without iteration.
Do not sort a vector here.  This one is just odd, because it is not a good translation from your original problem, and I'm not sure where it came from.  Don't optimise early, but don't pessimise early by choosing a bad algorithm either.  The requirement here is to look for each string inside another collection of strings.  A sorted vector is an invariant (so, again, think something that needs to be encapsulated) - you can use existing classes from libraries like boost or roll your own.  However, a little bit better on average is to use a hash table.  With amortised O(N) lookup (with N the size of a lookup string - remember it's amortised O(1) number of hash-compares, and for strings this O(N)), a natural first way to translate "look up a string" is to make an unordered_set<string> be your b in the algorithm.  This changes the complexity of the algorithm from O(NM log P) (with N now the average size of strings in a, M the size of collection a and P the size of collection b), to O(NM).  If the collection b grows large, this can be quite a savings.
In other words
gboolean foo(vector<string> const& a, unordered_set<string> const& b)

Note, you can now pass constant to the function.  If you build your collections with their use in mind, then you often have potential extra savings down the line.
The point with this response is that you really should never get in the habit of writing code like that posted.  It is a shame that there are a few really (really) bad books out there that teach coding with strings like this, and it is a real shame because there is no need to ever have code look that horrible.  It fosters the idea that c++ is a tough language, when it has some really nice abstractions that do this easier and with better performance than many standard idioms in other languages.  An example of a good book that teaches you how to use the power of the language up front, so you don't build bad habits, is "Accelerated C++" by Koenig and Moo.
But also, you should always think about the points made here, independent of the language you are using.  You should never try to enforce invariants outside of encapsulation - that was the biggest source of savings of reuse found in Object Oriented Design.  And you should always choose your data structures appropriate for their actual use.  And whenever possible, use the power of the language you are using to your advantage, to keep you from having to reinvent the wheel.  C++ already has string management and compare built in, it already has efficient lookup data structures.  It has the power to make many tasks that you can describe simply coded simply, if you give the problem a little thought.

A: Your first problem is related to the way arrays are (not) handled in C++. Arrays live a kind of very fragile shadow existence where, if you as much as look at them in a funny way, they are converted into pointers. Your function doesn't take two pointers-to-arrays as you expect. It takes two pointers to pointers.
In other words, you lose all information about the size of the arrays. sizeof(a) doesn't give you the size of the array. It gives you the size of a pointer to a pointer.
So you have two options: the quick and dirty ad-hoc solution is to pass the array sizes explicitly:
gboolean foo (gchar** a, int a_size, gchar** b, int b_size)

Alternatively, and much nicer, you can use vectors instead of arrays:
gboolean foo (const std::vector<gchar*>& a, const std::vector<gchar*>& b)

Vectors are dynamically sized arrays, and as such, they know their size. a.size() will give you the number of elements in a vector. But they also have two convenient member functions, begin() and end(), designed to work with the standard library algorithms.
So, to sort a vector:
std::sort(a.begin(), a.end());

And likewise for std::includes.
Your second problem is that you don't operate on strings, but on char pointers. In other words, std::sort will sort by pointer address, rather than by string contents.
Again, you have two options:
If you insist on using char pointers instead of strings, you can specify a custom comparer for std::sort (using a lambda because you mentioned you were ok with them in a comment)
std::sort(a.begin(), a.end(), [](gchar* lhs, gchar* rhs) { return strcmp(lhs, rhs) < 0; });

Likewise, std::includes takes an optional fifth parameter used to compare elements. The same lambda could be used there.
Alternatively, you simply use std::string instead of your char pointers. Then the default comparer works:
gboolean
foo (const std::vector<std::string>& a, const std::vector<std::string>& b)
{
    gboolean result;

    std::sort (a.begin(), a.end());
    std::sort (b.begin(), b.end());

    result = std::includes (b.begin(), b.end(),
                            a.begin(), a.end());

    return result;
}

Simpler, cleaner and safer.

A: The sort in the C++ version isn't working because it's sorting the pointer values (comparing them with std::less as it does with everything else). You can get around this by supplying a proper comparison functor. But why aren't you actually using std::string in the C++ code? The Python strings are real strings, so it makes sense to port them as real strings.

A: In your sample snippet your use of std::includes is pointless since it will use operator< to compare your elements. Unless you are storing the same pointers in both your arrays the operation will not yield the result you are looking for.
Comparing adresses is not the same thing as comparing the true content of your c-style-strings.

You'll also have to supply std::sort with the neccessary comparator, preferrably std::strcmp (wrapped in a functor).
It's currently suffering from the same problem as your use of std::includes, it's comparing addresses instead of the contents of your c-style-strings.

This whole "problem" could have been avoided by using std::strings and std::vectors.

Example snippet
#include <iostream>
#include <algorithm>
#include <cstring>

typedef char gchar;

gchar const * a1[5] = {
  "hello", "world", "stack", "overflow", "internet"
};

gchar const * a2[] = {
  "world", "internet", "hello"
};

...
int
main (int argc, char *argv[])
{
  auto Sorter = [](gchar const* lhs, gchar const* rhs) {
    return std::strcmp (lhs, rhs) < 0 ? true : false;
  };

  std::sort (a1, a1 + 5, Sorter);
  std::sort (a2, a2 + 3, Sorter);

  if (std::includes (a1, a1 + 5, a2, a2 + 3, Sorter)) {
    std::cerr << "all elements in a2  was   found in a1!\n";
  } else {
    std::cerr << "all elements in a2 wasn't found in a1!\n";
  }
}

output
all elements in a2  was   found in a1!

A: A naive transcription of the python version would be:
bool foo(std::vector<std::string> const &a,std::vector<std::string> const &b) {
    for(auto &s : a)
        if(end(b) == std::find(begin(b),end(b),s))
            return false;
    return true;
}

It turns out that sorting the input is very slow. (And wrong in the face of duplicate elements.) Even the naive function is generally much faster. Just goes to show again that premature optimization is the root of all evil.
Here's an unordered_set version that is usually somewhat faster than the naive version (or was for the values/usage patterns I tested):
bool foo(std::vector<std::string> const& a,std::unordered_set<std::string> const& b) {
    for(auto &s:a)
        if(b.count(s) < 1)
            return false;
    return true;
}

On the other hand, if the vectors are already sorted and b is relatively small ( less than around 200k for me ) then std::includes is very fast. So if you care about speed you just have to optimize for the data and usage pattern you're actually dealing with.


text:
Q: Using python code on a local server on Mac OS X, What is the simplest way? I've worked on a python project for GoogleAppEngine and I'm testing it locally using the GoogleAppLauncher and every thing is good till now. But lately I needed to test it on my iPad so I need to enable web sharing on my Mac book and use the local Apache server which I couldn't figure out how, so could please help me with any tutorial or any suggestions to accomplish this.
And to clarify more I've the following url: http://localhost:8095/?title=XYZ which gets me some results about the given title when it gets called locally if the associated python application is run using GoogleApplicationLauncher I need to use this URL on my iPad to get me the same results by sharing the web on my Mac book.
Sorry for the poor description, but I couldn't make more clear.
Any help would be greatly appreciated, and many thanks in advance.

A: When you go to Launch Settings of your app and insert --address=0.0.0.0 into the Extra Flags field, you should then be able to access the app from your iPad (0.0.0.0 stands for "any interface"). Just make sure that that your firewall isn't blocking the connection.

A: why aren't you accessing the app from the the devices local ip address?
something like:
http://192.168.0.3:8095


text:
Q: How can I change Amchart5 graph on @Input() decorator data change in Angular 13 I am using amChart5 graph in a component as child component with angular13 and I am sending data from parent component to child component through input decorator it working fine for first-time load but I can't change/update the chart on @Input() decorator data change.
parent component code

    <mat-card class="div3-left shadow"> <app-stacked-bar-chart></app-stacked-bar-chart> </mat-card>
    <mat-card class="div3-right shadow">

Time(24hr
            format)

        <app-heat-map [graphData]="heatMapData" [uniqueVal]="'5'"> </app-heat-map>
        <mat-icon class="btn" data-bs-toggle="modal" data-bs-target="#exampleModal"
            style="position: absolute;right: 1rem;bottom: .5rem;font-weight: 900;color: grey;"> fullscreen
        </mat-icon>
    </mat-card>

child componenet code
 import { Component, Inject, Input, NgZone, OnChanges, OnInit, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

// amCharts imports
import * as am5 from '@amcharts/amcharts5';
import * as am5xy from '@amcharts/amcharts5/xy';
import am5themes_Animated from '@amcharts/amcharts5/themes/Material';

@Component({
  selector: 'app-heat-map',
  templateUrl: './heat-map.component.html',
  styleUrls: ['./heat-map.component.css']
})
export class HeatMapComponent implements OnInit,OnChanges {
  @Input() uniqueVal: any="5"
  @Input() graphData: any = []

  graphData2:any

  private root: am5.Root | undefined;

  constructor(@Inject(PLATFORM_ID) private platformId:any, private zone: NgZone) { }

  ngOnInit(): void {

  }

  // Run the function only in the browser
  browserOnly(f: () => void) {
    if (isPlatformBrowser(this.platformId)) {
      this.zone.runOutsideAngular(() => {
        f();
      });
    }
  }

  ngOnChanges() {
    function dateToDay(data: any) {
      var dayArr: any = []
      data.forEach((e: any) => {
        function getDayName(dateStr: any, locale: any) {
          var date = new Date(dateStr);
          return date.toLocaleDateString(locale, { weekday: 'long' });
        }

        let day = getDayName(e.utc_dates, "en-US")

        dayArr.push({ "utc_day": day, "utc_hour": e.utc_hour, "sum_data": e.sum_data })

      })
      return dayArr
    }
    this.graphData2=dateToDay(this.graphData)

    console.log("graphdata2",this.graphData2);

    /* Chart code */
    let root = am5.Root.new(`chartdiv${this.uniqueVal}`);
    // Set themes
    root.setThemes([
      am5themes_Animated.new(root)
    ]);

    // Create chart
    let chart = root.container.children.push(am5xy.XYChart.new(root, {
      panX: false,
      panY: false,
      wheelX: "none",
      wheelY: "none",
      layout: root.verticalLayout
    }));

    // Create axes and their renderers
    let yRenderer = am5xy.AxisRendererY.new(root, {
      visible: false,
      minGridDistance: 20,
      inversed: true
    });

    yRenderer.grid.template.set("visible", false);

    let yAxis = chart.yAxes.push(am5xy.CategoryAxis.new(root, {
      maxDeviation: 0,
      renderer: yRenderer,
      categoryField: "utc_day"
    }));

    let xRenderer = am5xy.AxisRendererX.new(root, {
      visible: false,
      minGridDistance: 30,
      opposite: true
    });

    xRenderer.grid.template.set("visible", false);

    let xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
      renderer: xRenderer,
      categoryField: "utc_hour"
    }));

    // Create series
    let series = chart.series.push(am5xy.ColumnSeries.new(root, {
      calculateAggregates: true,
      stroke: am5.color(0xffffff),
      clustered: false,
      xAxis: xAxis,
      yAxis: yAxis,
      categoryXField: "utc_hour",
      categoryYField: "utc_day",
      valueField: "sum_data"
    }));

    series.columns.template.setAll({
      tooltipText: "{sum_data}",
      strokeOpacity: 1,
      strokeWidth: 2,
      width: am5.percent(100),
      height: am5.percent(100)
    });

    series.columns.template.events.on("pointerover", function (event) {
      let di: any = event.target.dataItem;
      if (di) {
        heatLegend.showValue(di.get("value", 0));
      }
    });

    series.events.on("datavalidated", function () {
      heatLegend.set("startValue", series.getPrivate("valueHigh"));
      heatLegend.set("endValue", series.getPrivate("valueLow"));
    });

    // Set up heat rules

    series.set("heatRules", [{
      target: series.columns.template,
      min: am5.color(0xfffb77),
      max: am5.color(0xfe131a),
      dataField: "sum_data",
      key: "fill"
    }]);

    // Add heat legend

    let heatLegend = chart.bottomAxesContainer.children.push(am5.HeatLegend.new(root, {
      orientation: "horizontal",
      endColor: am5.color(0xfffb77),
      startColor: am5.color(0xfe131a)
    }));

    // Set data

    let data = [...dateToDay(this.graphData)]
    console.log("data", data);

    series.data.setAll(data)

    yAxis.data.setAll([
      { utc_day: "Sunday" },
      { utc_day: "Monday" },
      { utc_day: "Tuesday" },
      { utc_day: "Wednesday" },
      { utc_day: "Thursday" },
      { utc_day: "Friday" },
      { utc_day: "Saturday" }
    ]);

    xAxis.data.setAll([
      { utc_hour: "0" },
      { utc_hour: "1" },
      { utc_hour: "2" },
      { utc_hour: "3" },
      { utc_hour: "4" },
      { utc_hour: "5" },
      { utc_hour: "6" },
      { utc_hour: "7" },
      { utc_hour: "8" },
      { utc_hour: "9" },
      { utc_hour: "10" },
      { utc_hour: "11" },
      { utc_hour: "12" },
      { utc_hour: "13" },
      { utc_hour: "14" },
      { utc_hour: "15" },
      { utc_hour: "16" },
      { utc_hour: "17" },
      { utc_hour: "18" },
      { utc_hour: "19" },
      { utc_hour: "20" },
      { utc_hour: "21" },
      { utc_hour: "22" },
      { utc_hour: "23" },
      { utc_hour: "24" }

    ]);

    // Make stuff animate on load
    chart.appear(500, 10);
  }

  ngOnDestroy() {
    this.ngOnChanges()
    // Clean up chart when the component is removed
    this.browserOnly(() => {
      if (this.root) {
        this.root.dispose();
      }
    });

  }

}

A: ngOnChanges triggeres on each changes in the binding AND once in the beginning of the creation of the component.
It comes with a parameter of type SimpleChanges.
If you use that it will give you autocomplete functionality.
the SimpleChanges object contains properties for every binding you have (in your case 'graphData' and 'uniqueVal') with each having four properties: isFirstChange(), currentValue, previousValue and firstChange.
read more here: https://angular.io/api/core/SimpleChanges
perhaps try:
ngOnChanges(changes: SimpleChanges) {
  if(changes.graphData.currentValue) { // <-- this way it only performs if there is a new input from the binding
    this.updateGraph(changes.graphData.currentValue) // <-- contains the new data
  }
}

updateGraph(graphData) {
  // move all your graph update stuff from the ngOnChanges to here
}


text:
Q: TrippleDES without base 64 encoding: Given final block not properly padded I'm trying to encrypt and decrypt a string using TrippleDES algorythm and without using Base64 encoding (my app will be talking to another app that has these requirements). Everything worked beautifully when I was testing stuff using Base64 encoding/decoding, but when I switched to doing it plain-text style (like the app I'm calling requires), everything broke.
I've read this post Given final block not properly padded which says the key is wrong on decoding, but that can't be, because these lines actually pass in the same variables for both the key and transformation:
ecipher = Cipher.getInstance(transformation);
dcipher = Cipher.getInstance(transformation);
ecipher.init(Cipher.ENCRYPT_MODE, key, iv);
dcipher.init(Cipher.DECRYPT_MODE, key, iv);

Also, I've printed out the lengths of both the encoded string and the array, their lengths are multiples of 8.
My output with I'm getting:
originalText: Abcdefgh
number of bites: 16
cryptText: d4167d9e2b3b1b2d1f940bc45099da0a
cryptText.length: 32
cryptText.getBytes().length: 32
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.DESedeCipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)
Java Result: 1

My full code (slightly modified version of this tutorial http://eternusuk.blogspot.com/2008/09/java-triple-des-example.html):
package com.test.encrypt;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import org.apache.commons.codec.binary.Hex;

public class TrippleDESTest
{
    private Cipher ecipher;
    private Cipher dcipher;
    private String algorithm = "DESede";
    private String transformation = "DESede/CBC/PKCS5Padding";
    private String keyPhrase = "123456789012345678901234"; //your keyphrase 24 bit
    private SecretKey key;
    private IvParameterSpec iv;
    private static TrippleDESTest cryptoUtil;
    private String ENCODING = "UTF-8";

    public static TrippleDESTest getInstance() throws Exception
    {
        if (cryptoUtil == null)
        {
            cryptoUtil = new TrippleDESTest();
        }

        return cryptoUtil;
    }

    private TrippleDESTest() throws Exception
    {
            DESedeKeySpec keySpec = new DESedeKeySpec(keyPhrase.getBytes());
            key = SecretKeyFactory.getInstance(algorithm).generateSecret(keySpec);
            iv = new IvParameterSpec(new byte[8]);
            ecipher = Cipher.getInstance(transformation);
            dcipher = Cipher.getInstance(transformation);
            ecipher.init(Cipher.ENCRYPT_MODE, key, iv);
            dcipher.init(Cipher.DECRYPT_MODE, key, iv);
    }

    public String encrypt(String str) throws Exception
    {
            byte[] utf8 = str.getBytes(ENCODING);
            byte[] enc = ecipher.doFinal(utf8);
            System.out.println("number of bites: " + enc.length);
            return Hex.encodeHexString(enc);
    }

    public String decrypt(String str) throws Exception
    {
            byte[] dec = str.getBytes();
            byte[] utf8 = dcipher.doFinal(dec);
            return Hex.encodeHexString(utf8);
    }

    public static void main(String[] args) throws Exception
    {
        TrippleDESTest test = TrippleDESTest.getInstance();
        String originalText = "Abcdefgh";
        System.out.println("originalText: " + originalText);
        String cryptText = test.encrypt(originalText);
        System.out.println("cryptText: " + cryptText);
        System.out.println("cryptText.length: " + cryptText.length());
        System.out.println("cryptText.getBytes().length: " + cryptText.getBytes().length);
        System.out.println("decote text: " + test.decrypt(cryptText));

    }
}// end class TrippleDESTest

Thanks in advance!

A: You are performing the hexadecimal encoding in the wrong order. You need to decode the ciphertext, instead of encoding the plain text in your decrypt method.


text:
Q: In Memory Buffer to store data in java I have a requirement to store data coming from UI into some place that can be processed later. Writing in DB or file is not an option because these will take time.
I need this operation to be asynchronous so that the person does not have to wait for the data to be processed.
JMS is an option but the Queue might get overloaded because the calls are thousands in number.
Is there a way I can write it into a temporary Map or something that can be used later. It need not be synchronized

A: 1) Use an embedded Database which is very fast so there won't be much overhead to it.
You can start with exploring H2 database engine.
This is in-memory+open source. You just need to include a jar in your project.
If data is more, in a longer run synchronized map will
have a performance overhead.
In case of unplanned Sever/application outage, the user entered data may get lost if you store it in a Map.
2) You can use Guava CacheBuilder where you can expire an entry based on time or on maximum size of cache, if using third party library is allowed.
3) You can consider using ConcurrentHashMap if option 1 and 2 doesn't look suitable to you.

A: What is the size of amount? If it is less amount of data, you can solve this by storing in session.


text:
Q: Karatsuba Multiplication for unequal size, non-power-of-2 operands What's the most efficient way to implement Karatsuba large number multiplication with input operands of unequal size and whose size is not a power of 2 and perhaps not even an even number? Padding the operands means additional memory, and I want to try and make it memory-efficient.
One of the things I notice in non-even-number size Karatsuba is that if we try to divide the number into "halves" as close to even as possible, one half will have m+1 elements and the other m, where m = floor(n/2), n being the number of elements in the split number. If both numbers are of the same odd size, then we need to compute products of two numbers of size m+1, requiring n+1 storage, as opposed to n in the case when n is even. So am I right in guessing that Karatsuba for odd sizes may require slightly more memory than for even sizes?

A: Most of the time, length of operands will not be a power of 2. I think this is rare case. Most of the time there will be different lengths of operands. But this will not be a problem for a Karatsuba algo.
Actually, I don't see any problem here. This overhead (odd length) is so light and definitely not a big deal. Problem about different lengths - let's assume, that X = 1234 and Y = 45
So, a = 12, b = 34, c = 0, d = 45
So, after that X * Y = 10 ^ 4 * ac + 10 ^ 2 (ad + bc) + bd
ac = 0;
bd = 34 * 45;
ad + bc = (a + b) * (c + d) - ac - bd = 540;

And, if we assume, that we could multiply 2 digit numbers easily - you could get the answer = 55530. Same, as just multiply 1234 * 45 in any calculator :) So, I can't see any memory issue with different lengths of numbers.

A: You can multiply the numbers by powers of 10 so that each of them have even numbers of digits. Apply karatsuba algorithm and them divide the answer by the the factor of powers of 10 that you multiplied the original 2 numbers to make them even.
Eg: 123*12
Compute 1230*1200 and divide the answer with 1000.

A: To answer your doubt in comments above. Trick is to follow the formula to calculate powers of 10 in case of decimal calculation.
10^2m(A.C) + 10^m((A+B).(C+D)-A.C-B.D) + B.D

m = n/2 + n%2

n is length of number

Refer to wiki it explains in details.


text:
Q: Node callback firing at the same time Consider this:

there can only be one callback firing at the same time

So consider this code:
var http = require("http");
function onRequest(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}

http.createServer(onRequest).listen(8888);

If my application receives a request then OnRequest is called.
If it's only possible to fire one call back at a time then the requests are queued. Is it right?

A: Node.js is designed in such a way that when request arrives it gives the info to callback function and let it handle it and main process waits for next request.
so if you set setTimeout in  onRequest to 10 sec. and make 100 request to server all the request will return you the data after 10 sec not 10,20,30 ...
As node.js is single process application the request will be queued but human thats for very small fraction of time. You can try experimental features such as http://nodejs.org/api/cluster.html to handle request in parallel. Here queuing does not mean that unless reques1 get answered request2 will not be answered but it means that node process will quesing them untill every earlier request gets their callbacks assigned that do not effect your websites performance at all.
read http://book.mixu.net/node/single.html it is one of the most awesome books also
     http://www.nodebeginner.org/
EDIT 1
Node.js request you to write non-blocking code. In case of none blocking code we use callbacks.
Node.js is single threaded application but it behaves like one main important thread and other less-important thread pool.(there are no specific priorities as such).
Eg: An ambulance waits for phone call to come every time.
    when it gets a call it goes to pick up the patient and take him to the hospital.
    while the doctor is performing operation on the patients. Ambulance team does not
    switch off their phone and wait for its first patient to get healthy but
    If they get another call they go to pick up the next guy

    when they were off to receive next guy hospital calls and say first patient is
    healthy and drop him home, ambulance does not leave other guy in pain but complete
    its second task and then drop first guy home.

    so callback was doctorPerformOperation which was put in thread pool
    and
    recieveTheGuy was a blocking operation

So from your code it is very small so it might happen that every response might be after its request but it is also a possibility that out of 5 (almost) simultaneous requests 3rd gets callback assigned before 2nds connection's last 'ack'.
More specific examples
Blocking code
 setTimeout(function() {
   console.log('bye')
 }, 100);

 while(1) {
 }

'bye' will never be printed
None Blocking code
 setTimeout(function() {
   console.log('bye')
 }, 100);

 setInterval(function() {
   console.log('hi');
 }, 100);

bye will be printed after .1 sec but it can be delayed by some nano second if hi were printing at the same instance.
It executes the callbacks when main process is free.
More non-blocking
setTimeout(function() {
   console.log('bye')
 }, 100);

 setInterval(function() {
   console.log('hi');
 }, 50);

setInterval(function(){
   console.log('hello');
},100);

Guess,what will happen with this?
EDIT 2:
I wrote a small code
exports.sample = function (res) {
var tcpsocket = net.createConnection(port, host);
tcpsocket.on('connect', function () {
    tcpsocket.write('query');
    console.log('tcp');
});
tcpsocket.on('data', function (data) {
    res.write(data);
});
tcpsocket.on('end', function () {
    console.log('end');
    res.end();
});
tcpsocket.on('error', function (e) {
   var ret={error:'error'}
   res.end(JSON.stringify(ret));
   console.log('Error occured in tcp socket');
       console.log(e);
});
tcpsocket.on('close', function () {
    console.log('socket close');
    res.end();
});
};

Now the socket I was connecting to was a c socket which writes the data in 10 sec interval 10 times. So each request takes around 100s to finish. as I did not call res.end in 'data' event the browser does not load anything untill full request is completed. If you want to see the data coming in realtime you can use curl for the same url.
Result: When you open 10 tabs same time you will be able to see the data in all tabs in 100sec (not 100s,200s...)


text:
Q: How to count total time of column state for the given status In MySql I have a table device with column for timestamp(long) and for status(boolean):
| ts   | status |
+------+--------+
| 1    |      1 |
| 2    |      1 |
| 5    |      1 |
| 17   |      0 |
| 18   |      0 |
| 26   |      0 |
| 31   |      1 |
| 32   |      1 |
| 37   |      1 |

Need a query to count how long the status was 1.
For the given case it is: (17-1) + (37-31) = 22

A: http://sqlfiddle.com/#!9/e27644/1
First step create a view ordered_status (mysql doesn't support window function like rank ;-( )
(You can skip this view by adding a position column with AUTO_INCREMENT directly in your device table)
create view ordered_status as
select
    count(*) position,
    A.ts,
    A.status
from
    device A
    left join device B on
        A.ts >= B.ts
group by
    A.ts,A.status

Second step, join each row with the next and compute only timestamp delta for status=1, and sum the total :
select
    sum(case
    when A.status=1 then B.ts-A.ts
    else 0
    end)
from
    ordered_status A
    left join ordered_status B on
        A.position+1 = B.position

Or without view : http://sqlfiddle.com/#!9/97b97/1
select
    sum(case
    when A.status=1 then B.ts-A.ts
    else 0
    end)
from
    (select count(*) position, A.ts,A.status
       from device A left join device B on A.ts >= B.ts
      group by A.ts,A.status) A
    left join
    (select count(*) position, A.ts,A.status
       from device A left join device B on A.ts >= B.ts
      group by A.ts,A.status) B on
        A.position+1 = B.position
order by
    A.position

A: Since you can not use window function, the solution is slightly more complicated
select sum(final.ts * final.sign)
from
(
    select device.ts,
           case when status = 1 and (prevstatus is null or prevstatus = 0) then -1  else 1 end sign
    from
    (
        select d1.ts, d2.status, prev.ts prevts, prev.status prevstatus, next.ts nextts, next.status nextstatus
        from (
          select d1.ts,
               d1.status,
               max(d2.ts) prevts
          from device d1
          left join device d2 on d1.ts > d2.ts
          group by d1.ts, d1.status
        ) d1
        left join (
          select d1.ts,
               d1.status,
               min(d2.ts) nextts
          from device d1
          left join device d2 on d1.ts < d2.ts
          group by d1.ts, d1.status
        ) d2 on d1.ts = d2.ts
        left join device prev on prev.ts = d1.prevts
        left join device next on next.ts = d2.nextts
    ) devicePrevNext
    where (status = 1 and (prevstatus is null or prevstatus = 0 or nextstatus is null)) or
          (status = 0 and prevstatus = 1)
) final

demo

A: I would phrase this as "getting the next 0" and using that information for the sum:
select next_ts_0, min(ts) as ts_1, max(ts) as ts_1_end
from (select d.*,
             (select d2.ts
              from device d2
              where d2.status = 0 and d2.ts > d.ts
              order by d2.ts asc
              limit 1
             ) as next_ts_0
      from device d
     ) d
where status = 1
group by next_ts_0;

Then you can add up the results:
select sum(coalesce(next_ts_0, ts_1_end) - ts_1)
from (select next_ts_0, min(ts) as ts_1, max(ts) as ts_1_end
      from (select d.*,
                   (select d2.ts
                    from device d2
                    where d2.status = 0 and d2.ts > d.ts
                    order by d2.ts asc
                    limit 1
                   ) as next_ts_0
            from device d
           ) d
      where status = 1
      group by next_ts_0
     ) d;

Here is the SQL Fiddle for this solution.
An index on device(status, ts) might help.  If performance is an issue, you might need a solution using variables.


text:
Q: Please help. A batch Script that check multiple factors and decide whether to install or not I have been tasked to create a script that checks if .net framework 4.5 is installed before being installing a security program " Heimdal " and if there is no .net install it should install .net and then install Heimdal afterwards. I have tried different solutions but i can't get it to work...
Where have i gone wrong ?
REG QUERY "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client" /s|FIND "4.5"
IF %ErrorLevel% EQU 0 (
    ::echo.>DotNet4.5 already installed.txt
GOTO :Heimdal
) else (
    Start /B /I /WAIT O:\it\Patrick\dotNetFx45_Full_setup.exe /q /norestart
    echo.>DotNet4.5 Installed.txt
GOTO :Heimdal
)
:Heimdal
    IF EXIST "C:\Program Files (x86)\Heimdal"(
    echo.>Heimdal already installed.txt
GOTO :END
) else (
    msiexec /qn /i "O:\it\Patrick\Heimdal.msi" heimdalkey="xxxxx-xxxx-xxx-xxx-xxxxx"
)
:END
    echo.>DotNetAndHeimdalInstalled.txt

A: I'm not sure about further errors in the code but the line
Start /B /I /WAIT O:\it\Patrick\dotNetFx45_Full_setup.exe /q /norestart

can't work. The START command supports either /B or /WAIT as option. Combination of there two switches won't work.


text:
Q: How to sort grouped products without modifying core files The last answer here is exactly what I'm looking for, but I want to do it the clean way:
How to sort associated products in a grouped product
Has anybody a solution to achieve this within the grouped.phtml I rather don't want to open up an own module just for this sorting.
I tried $_associatedProducts = $this->getAssociatedProducts($_product)->addAttributeToSort('entity_id', 'ASC');but that doesn't work.

A: I tested this on 1.9 and you might put this code into a helper but if you look at the code which gets the associated products it eventually calls Mage_Catalog_Model_Product_Type_Grouped->getAssociatedProducts()
The code below sets the order by price and descending.
$_product = $this->getProduct();
$_grouped =  Mage::getModel('catalog/product_type_grouped');
$_storeFilter = $_grouped->getStoreFilter($_product);
$_status = $_grouped->getStatusFilters($_product);

/** @var Mage_Catalog_Model_Resource_Product_Link_Product_Collection $_associatedProducts */
$_associatedProducts = $_grouped
    ->getAssociatedProductCollection($_product)
     ->addAttributeToSelect('*')
     ->addFilterByRequiredOptions()
     //->setPositionOrder()
     ->addStoreFilter($_storeFilter)
     ->addAttributeToFilter('status', array('in' => $_status));

// Add custom filtering here
$_associatedProducts->setOrder('price', 'DESC');


text:
Q: How to nest JSON fields using grok filter in logstash? I receive logs from my Spring Boot App via logback and want to transform several fields to a nested separate json element in using logstash filters. I've done that with the
mutate filter:
filter {
  mutate {
    rename => {
      "appName" => "[app][name]"
      "appNode" => "[app][node]"
      "appStatus" => "[app][status]"
      ... etc
    }
  }
}

and it works (I look at the result in Kibana).
But it's not convienent to list all those fields (which I'm gonna have more than 3). It'd be great to write a regexp (perhaps) which would match fields starting with 'app' and nest them under 'app' element.
I know it's possible to achieve this with ruby and grok filters. I don't have enought time to learn ruby to write a script, so I want to know how can I group it using grok template?


text:
Q: Question about coprime intergers a,b that satisfy sa+tb=n for positive s and t. Let a,b be coprime positive integers, find an integer N (depending on a and b), such that
for any integer n > N it is possible to find integers s, t ≥ 0 satisfying sa+tb = n, but no such s, t exist satisfying sa+tb = N
I conjecture that N is ab-a-b, but I cannot prove it despite considerable efforts. Please help! Thanks.

A: Yes, $N=ab-a-b$.
Each of the numbers $0, a, 2a, \ldots, (b-1)a$ can have some nonnegative multiple of $b$ added to it so the sum is somewhere in the interval $[ab-a-b+1, ab-a]$. Because $a$ and $b$ are coprime, all these sums will be different. (Namely, if $sa+tb=s'a+t'b$ for $s\ne s'$, then $(s-s')a\equiv 0\pmod b$ and since $a$ is invertible modulo $b$ we have $s\equiv s'\pmod b$, but both $s$ and $s'$ are in $[0,b-1]$, so $s=s'$).
By the pigeonhole principe, then, every number between $ab-a-b+1$ and $ab-a$ will be hit, and every larger number can be made by adding an appropriate multiple of $b$.
It remains to show that $ab-a-b$ is not hit. However, if $sa+tb=ab-a-b$, then $s<b-1$ and $sa+(t+1)b=(b-1)a$ which contradicts the observation from above that each number in $[ab-a-b+1, ab-a]$ arises in only one way. So $N$ cannot be hit.


text:
Q: Create DB record return wrong data types Laravel 5.8 In my model I have functions for create and find records.
Model
use Illuminate\Database\Eloquent\Model;

class Charge extends Model
{
    use ChargeMutator;

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->request = $attributes;
    }

    public function add() {
         $result = self::create($this->request);
         return $result;
    }

    public function find($id) {
        $record = self::find($id);
        return $record;
    }
}

And I have a mutator to mutate the values.
<?php

    trait ChargeMutator
    {

        public function getCostAttribute($value)
        {
            return $this->attributes['cost'] = // call function A;
        }

        public function getTotalCostAttribute($value)
        {
            dd(gettype($value));
            return $this->attributes['total_cost'] = // call function A;
        }

        public function setCostAttribute($value)
        {
            return $this->attributes['cost'] = // call function B;
        }

        public function setTotalCostAttribute($value)
        {
            return $this->attributes['total_cost'] = // call function B;
        }
    }

Controller
class ChargesController extends Controller
{
    use ValidateCreditNoteCharges, Messages, ApiResponser;

    public function addCharge(Request $request)
    {
        // $this->validateAddCharge($request);

        $credit_note_charge = new Charge($request->all());
        $get_result = $credit_note_charge->add();

        return $this->createdResponse($get_result);
    }
}

the $request is like this
{
    "name":"TEST",
    "quantity":1,
    "cost":56.00,
    "total_cost":56.00
}

The Problem is:
when I   dd(gettype($value)); in  getTotalCostAttribute

*

*from the add() function the type of total_cost value is string

*from the find() function the type of total_cost value is integer
in the database the data type for total_cost is int(10)
I am not sure why is the type of the return values casted into strings when use create()
I have searched for this for 3 hours now and couldn't find a solution. i need the data type correctly because accoriding to the data type i do different calculations in my calling functions A  and B


text:
Q: Unknown user seen when listing tar file I have here a POSIX tar archive call Debian9.ova.
Interestingly enough, listing it with tar in MacOS High Sierra, shows:
$ tar -tvf Debian9.ova
-rw-r--r--  0 someone someone  5344 26 Feb 13:57 Debian9.ovf
-rw-r--r--  0 someone someone   179 26 Feb 13:57 Debian9.mf
-rw-r--r--  0 someone someone 2113245184 26 Feb 13:59 Debian9-disk1.vmdk

Now the interesting point is, that I do not have a someone user and group.
$ id someone
id: someone: no such user

Listing it with --numeric-owner, it shows as uid 64, and gid 64, which clearly are not present in my system.
$ tar -tvf Debian9.ova --numeric-owner
-rw-r--r--  0 64     64       5344 26 Feb 13:57 Debian9.ovf
-rw-r--r--  0 64     64        179 26 Feb 13:57 Debian9.mf
-rw-r--r--  0 64     64 2113245184 26 Feb 13:59 Debian9-disk1.vmdk

Listing the users in the system does not find a somebody user:
dscl . list  /Users | grep someone

Where is then someone coming from? Is it a tar "feature" when it finds an unknown uid and gid?
PS. In debian just for comparison:
$ tar -tvf a.tar
-rw-r--r-- 64/64          3212 2018-02-27 02:01 dead.letter
$ bsdtar -tvf a.tar
-rw-r--r--  0 64     64       3212 Feb 27 02:01 dead.letter

A:
I have here a POSIX tar archive […]

In a standard format tar archive, the header information for each file contains fields for both a symbolic user and group name and a numeric user and group ID.
As you have seen, tar can list either one set of fields or the other.
With a conformant pax utility one should be able to list these fields altogether: $ pax -o listopt="%(uid)s %(gid)s %(uname)s %(gname)s %L\n" < Debian9.ova
However, I believe that no standard-conformant pax utility currently exists.
Further reading

*

*"ustar header block". pax.  Single Unix Specification.  IEEE 1003.1-2008:2016.

*Tim Kientzle (2016-12-27).  tar.  § 5.  FreeBSD File Formats Manual.


text:
Q: Can the empty set be an index set? I ran into a question, encountered in a computational course.
Could anyone tell me why the empty set $ \emptyset $ can be an index set?
My source is this book

A: If you've seen How I Met Your Mother, you might remember the episode when Barney is riding a motorcycle inside a casino, and when the security guards grab him he points out one simple thing: "Can you show me the rule that says you cannot drive a motorcycle on the casino's floor?".
Mathematics is quite similar. If there's nothing in the rules which forbids it, it's allowed.
Direct your attention to Definition 7.1.9 in that book, it says that an index set is a set of all indices of some family of computable [partial] functions/computably enumerable sets. The empty set is a set of computable functions, and the empty set is exactly its index set.


text:
Q: A alternative to install pairtaghighlighter for geany 1.23.21 I prove to install this plugin following the instructions of this post: HTML pair tag highlight alternative for Geany editor on Ubuntu 14.04
but, when I write
sed -i 's/1.24/1.23/' wscript

it says me this:
fatal: destination path 'geany-plugins' already exists and is not an empty directory.

What can I do?
after
./waf configure --enable-plugins=pairtaghighlighter

it appears me this:
Setting top to                           : /tmp/geany-plugins
Setting out to                           : /tmp/geany-plugins/_build_
Checking for waf version in 1.6.1-1.7.0  : ok
Checking for 'gcc' (c compiler)          : /usr/bin/gcc
Checking for program pkg-config          : /usr/bin/pkg-config
Checking for 'gtk+-2.0' >= 2.16.0        : not found
The configuration failed
(complete log in /tmp/geany-plugins/_build_/config.log)

A: *

*This has nothing to do with the sed -i 's/1.24/1.23/' wscript.
This is an error message from Git. You start the command git clone https://github.com/geany/geany-plugins.git several times. Then Git complains.
Example:
$ git clone https://github.com/geany/geany-plugins.git

Cloning into 'geany-plugins'...
remote: Counting objects: 15302, done.
remote: Compressing objects: 100% (15/15), done.
remote: Total 15302 (delta 1), reused 0 (delta 0), pack-reused 15287
Receiving objects: 100% (15302/15302), 14.59 MiB | 1.17 MiB/s, done.
Resolving deltas: 100% (8708/8708), done.
Checking connectivity... done.

$ git clone https://github.com/geany/geany-plugins.git

fatal: destination path 'geany-plugins' already exists and is not an empty directory.

*Install the gtk2 development library:
sudo apt-get install libgtk2.0-dev

and again:
./waf configure --enable-plugins=pairtaghighlighter


text:
Q: Assignment from void pointer to another void pointer I want to copy the bits from one void * to another void *.
How can I do it?
I tried this:
static void* copyBlock(void* ptr) {
    if (!ptr) {
        return NULL;
    }
    int sizeOfBlock=*(int*)ptr+13;
    void* copy = malloc(sizeOfBlock);
    if (!copy) {
        return NULL;
    }
    for(int i=0;i<sizeOfBlock;i++){
        *(copy+i)=*(ptr+i);
    }
    return copy;
}

but I get: invalid use of void expression

A: You cannot dereference, perform pointer arithmetic, indexing a void pointer because it has no base type or object size.  You must therefore cast the void pointer to the a pointer to the type of the data units you are copying so that the compiler will know the size of the data to copy.
All that said, you'd be better off using:
memcpy( copy, prt, sizeOfBlock ) ;

A: This design (storing block size inside of a block without any struct) seems dangerous to me, but I still know the answer.
*(copy+i)=*(ptr+i);

Here you get the error, because you can't dereference a void pointer. You need to cast it to pointer to something before. Like this:
((char *)copy)[i] = ((char *)ptr)[i];

A: You should use the memcpy function:
memcpy(copy, ptr, sizeOfBlock);

Depending on the compiler settings (you may be compiling as C++ and not as C), you may need to cast the pointers to a char pointer:
memcpy((char *) copy, (const char *) ptr, sizeOfBlock);

Note: The parameter of the function should be const char *ptr, to make sure you don't change the contents of ptr by mistake.


text:
Q: Can you tell docker what network interface to use? I would like to know how can you set up Docker to use a specific network interface.
Thank you

A: If you are talking about setting a default gateway, you would add the --default-gateway=IP_ADDRESS to the docker daemon run command.
It's all in here