Janela fechando automaticamente PySimpleGUI

Question: estou tendo um problema com o PySimpleGUI. O programa está retornando o valor correto no output, porém quando clico no button para que o programa faça os cálculos ele fecha a janela muito rapidamente logo após exibir o output.
Aqui está o código:
import PySimpleGUI as sg

sg.theme('TanBlue')

#layout
layout = [
    [sg.Text("Sexo:", size=(10,0)),sg.Radio("M", "RADIO1",key="masculino"),sg.Radio("F","RADIO1",key="feminino")],

    [sg.Text("Biotipo:",size=(10,0)), sg.Radio("Ectomorfo","RADIO2",key="ecto"),sg.Radio("Mesomorfo","RADIO2",key="meso"), sg.Radio("Endomorfo","RADIO2",key="endo")],

    [sg.Text("Altura(cm):",size=(10,0)), sg.InputText(size=(6,0), key="altura")],

    [sg.Text("Peso(Kg):",size=(10,0)), sg.InputText(size=(6,0), key="peso")],

    [sg.Text("Idade:", size=(10,0)), sg.InputText(size=(6,0),key="idade")],

    [sg.Button("Calcular TMB", size=(10,0)), sg.Exit()],

    [sg.Text("Sua TMB:", size=(10,0)) ,sg.Output(size=(15,0))]
]
#janela
janela = sg.Window("Taxa metabólica basal").layout(layout)
#extrair os dados da tela
Button, values = janela.Read()

masculino = values['masculino']
feminino = values['feminino']
ecto = values['ecto']
meso = values['meso']
endo = values['endo']
altura = int(values['altura'])
peso = float(values['peso'])
idade = int(values['idade'])

if(masculino == True):
    tmb = 66 + 13.7*peso + 5*altura - 6.8*idade
elif(feminino == True):
    tmb = 665 + 9.6*peso + 1.8*altura - 4.7*idade

print(str(tmb)+" Kcal")

Answer: A solução para este problema é simples, o que acontece é que como seu código não tem um loop de while para dar continuidade após realizar uma ação dentro do seu GUI, como por exemplo coletar os dados passados e realizar o cálculo por exemplo ele fecha.
Para resolver isso eu eu adicionei um loop infinito while que acaba quando o GUI é fechado ou o botão Exit é clicado e especifiquei os eventos que ocorrem dentro do programa

Mantive a parte do layout

import PySimpleGUI as sg

sg.theme('TanBlue')

#layout
layout = [
    [sg.Text("Sexo:", size=(10,0)),sg.Radio("M", "RADIO1",key="masculino"),sg.Radio("F","RADIO1",key="feminino")],

    [sg.Text("Biotipo:",size=(10,0)), sg.Radio("Ectomorfo","RADIO2",key="ecto"),sg.Radio("Mesomorfo","RADIO2",key="meso"), sg.Radio("Endomorfo","RADIO2",key="endo")],

    [sg.Text("Altura(cm):",size=(10,0)), sg.InputText(size=(6,0), key="altura")],

    [sg.Text("Peso(Kg):",size=(10,0)), sg.InputText(size=(6,0), key="peso")],

    [sg.Text("Idade:", size=(10,0)), sg.InputText(size=(6,0),key="idade")],

    [sg.Button("Calcular TMB", size=(10,0)), sg.Exit()],

    [sg.Text("Sua TMB:", size=(10,0)) ,sg.Output(size=(100,0))]
]

Segue a parte modificada

Mudei sg.Window("Taxa metabólica basal").layout(layout) da janela para sg.Window("Taxa metabólica basal",layout) tem o mesmo resultado de uma forma mais compacta.

#janela
janela = sg.Window("Taxa metabólica basal",layout)

De acordo com a própria documentação do PySimpleGui o sg.Window tem os parâmetros Title e layout dentro da função sendo: sg.window("Título",layout") a forma mais simples de usar, mas claro que você pode usar também o .layout(layout) assim como você usou.

Primeiramente aqui eu coloquei o loop como dito antes para dar segmento nas ações do usuário enquanto a sua GUI não for fechada.

Mudei o nome do Button para event mas isso não influencia em muita coisa não é só por uma questão de leitura

#extrair os dados da tela
while True:
    event, values = janela.Read()

Aqui embaixo adicionei duas condições relacionadas aos eventos que ocorrem dentro da GUI, sendo eles respectivamente o ato de clicar no botão "Exit" e no "Calcular TMB".

    if event == sg.WIN_CLOSED or event == 'Exit': # if user closes window or clicks cancel
        break

    elif event == "Calcular TMB":
        masculino = values['masculino']
        feminino = values['feminino']
        ecto = values['ecto']
        meso = values['meso']
        endo = values['endo']
        altura = int(values['altura'])
        peso = float(values['peso'])
        idade = int(values['idade'])

        if(masculino == True):
            tmb = 66 + 13.7*peso + 5*altura - 6.8*idade

        elif(feminino == True):
            tmb = 665 + 9.6*peso + 1.8*altura - 4.7*idade

Nessa parte aqui eu troquei o modo de print e coloquei ele para aparecer formatado

O resultado ainda é o mesmo porém desse jeito caso o número seja muito quebrado como por exemplo: 785.99999999999999 o programa só vai deixar vísivel 785.99

        print(f"{tmb:.2f} Kcal")

e por fim coloquei isso aqui para forçar a fechada da janela quando o código todo acabar de rodar.
janela.close()

Espero ter ajudado!
Segue o link para documentação oficial: https://pysimplegui.readthedocs.io/en/latest/
Código completo:
import PySimpleGUI as sg

sg.theme('TanBlue')

#layout
layout = [
    [sg.Text("Sexo:", size=(10,0)),sg.Radio("M", "RADIO1",key="masculino"),sg.Radio("F","RADIO1",key="feminino")],

    [sg.Text("Biotipo:",size=(10,0)), sg.Radio("Ectomorfo","RADIO2",key="ecto"),sg.Radio("Mesomorfo","RADIO2",key="meso"), sg.Radio("Endomorfo","RADIO2",key="endo")],

    [sg.Text("Altura(cm):",size=(10,0)), sg.InputText(size=(6,0), key="altura")],

    [sg.Text("Peso(Kg):",size=(10,0)), sg.InputText(size=(6,0), key="peso")],

    [sg.Text("Idade:", size=(10,0)), sg.InputText(size=(6,0),key="idade")],

    [sg.Button("Calcular TMB", size=(10,0)), sg.Exit()],

    [sg.Text("Sua TMB:", size=(10,0)) ,sg.Output(size=(100,0))]
]
#janela
janela = sg.Window("Taxa metabólica basal",layout)

#extrair os dados da tela
while True:
    event, values = janela.Read()

    if event == sg.WIN_CLOSED or event == "Exit": # if user closes window or clicks cancel
        break

    elif event == "Calcular TMB":
        masculino = values['masculino']
        feminino = values['feminino']
        ecto = values['ecto']
        meso = values['meso']
        endo = values['endo']
        altura = int(values['altura'])
        peso = float(values['peso'])
        idade = int(values['idade'])

        if(masculino == True):
            tmb = 66 + 13.7*peso + 5*altura - 6.8*idade

        elif(feminino == True):
            tmb = 665 + 9.6*peso + 1.8*altura - 4.7*idade

        print(f"{tmb:.2f} Kcal")

janela.close()


Injecting with roboguice on non-activity class

Question: Is there any way to inject custom bindings in a class that's not an activity (a class that doesn't extends RoboActivitiy? Because everytime I try to inject it, I get a NullPointerException when accessing it.
I've solved it getting the injector and doing it by myself... but that's something I don't feel comfortable with.
Thanks!
Answer: If the class isn't itself created through injection, then obtaining the injector is the right (and only) way to do it.  That's how RoboActivity (see onCreate()) does it in the first place.  Objects created through injection get their members Injected by the injector.


CoreData Transformable: Custom Transformer never gets called - NSKeyedArchiver is used instead

Question: I've created a Simple CoreData model with a single Entity with custom transformable attribute:

import Foundation
import CoreData

    extension Entity {

        @nonobjc public class func fetchRequest() -> NSFetchRequest<Entity> {
            return NSFetchRequest<Entity>(entityName: "Entity")
        }

        @NSManaged public var attribute: String?
        @NSManaged public var title: String?
    }

Then, in AppDelegate I try to fetch and then save a single entity:
import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    private lazy var context: NSManagedObjectContext = {
        return persistentContainer.newBackgroundContext()
    }()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let fetch: NSFetchRequest<Entity> = Entity.fetchRequest()

    context.perform {
        print(try! fetch.execute().first?.attribute)
        let entity = NSEntityDescription.insertNewObject(forEntityName: "Entity", into: self.context) as! Entity
        entity.title = "Entity Title"
        entity.attribute = "String attribute"

        try! self.context.save()
    }

    return true
}

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "Europe")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

}

The first time I run the app, I get nil, while the second I get Optional("String attribute"), which seems that the transformation is working correctly.
However, here's my transformer class:
import Foundation

/// Never Called!
@objcMembers public final class MyTransformer: ValueTransformer {

    public override init() {
        super.init()
        fatalError("Nevern gets executed")
    }
    public override class func transformedValueClass() -> AnyClass {
        fatalError("Nevern gets executed")
        print("transformedValueClass")
        return NSData.self
    }

    public override class func allowsReverseTransformation() -> Bool {
        fatalError("Nevern gets executed")
        print("allowsReverseTransformation")
        return true
    }

    public override func transformedValue(_ value: Any?) -> Any? {
        fatalError("Nevern gets executed")
        print("transformedValue")
        guard let string = value as? String else {return nil}
        return string.data(using: .utf8)
    }

    public override func reverseTransformedValue(_ value: Any?) -> Any? {
        fatalError("Nevern gets executed")
        print("reverseTransformedValue")
        guard let data = value as? Data else {return nil}
        return String(data: data, encoding: .utf8)
    }
}

It seems that the CoreData uses NSKeyedArchiver/Unarchiver instead of my custom class. What could be the problem?
This is, obviously, a test project I've set up to figure out how the transformable properties work and to test a bigger issue I'm facing with the real project I'm working on.
Configured project to investigate the issue
Answer: You need to register your ValueTransformer before you use it.
ValueTransformer.setValueTransformer(MyTransformer(), forName: NSValueTransformerName(rawValue: "MyTransformer"))
let fetch: NSFetchRequest<Entity> = Entity.fetchRequest()

For more info refer docs.


How to study auto-correlation of time series when shocks are present?

Question: The time series I want to model has several shocks due to law changes. Basically, I do not have a lot of data that isn't impacted by these shocks/shifts/pulses. Now, I want to study the ACF and PACF of the series- is the auto-correlation still useful for modelling the series knowing that the shocks disturb the "real" data? Also, how do I deal with shocks when I want to study the cross correlation with another time series.
ACF and PACF of the original data:
Comment: In this case you cannot run ACF/PACF directly on the series, you'd have to build a model with shocks in it, then run autocorrelation on errors
Comment: drop the data points with shocks?
Comment: The thing is, the shocks have lags, like a shift or a pulse. i would need to modify several years of data
Comment: Do you mean an Intervention Model ? What is autocorrelation in error used for?
Answer: If you know the date that each law passed, and assume the shocks would occur after that date, you can model the impact of the shocks using a single exponential distribution, with the sample mean being the average impact of each shock.
Answer: Determine best ARIMA model with AICc and RMSE might be of interest. If you know the dates of the shocks then one can form an ARMAX model incorporating any lead and lag effects including dynamic effects. If you don't know the dates of the shocks then you can use Tsay's procedures as outlined here http://docplayer.net/12080848-Outliers-level-shifts-and-variance-changes-in-time-series.html
iN RESPONSE: How to fit a robust step function to a time series? suggests that shocks can be both 1 period events (pulses) or step events . The work of Tsay suggests ways to identify the nature of the Intervention.
If you have a sequence of contiguous pulses they can often be collected/aggregated into a dynamic pulse. This could be evident from a decay pattern.
I prefer to empirically identify the shocks and then to possibly re-parameterize.
If you wish to continue this offline , I will try and help you as it may require some data analysis.
I also have referred readers to Intervention Analysis Coding in R TSA Package ... some caveats   1) it requires the user to specify the arima model AND it doesn't work with user-suggested causals.
AFTER RECEIPT OF DATA:
You sent 54 monthly values for two time series. Here is the plot of the dependent series CA and the user suggested predictor PR . The general approach is called ARMAX modelling
There are a number of issues to be identified via analytics:

Is there seasonality (annual repetitive features) and if so is the seasonal structure autoregressive (SARIMA)or seasonally deterministic ( i.e the need for seasonal dummies )
What differencing or de-meaning is necessary

3.) what is the form of the ARIMA structure
4) Are there unuusal values that need to be dealt with ( THE I'S)
5) Is there evidence of non-constant error variance or non-constant parameters over time in the residuals  ( THE A'S )
6) What is the form of the relationship ( THE X'S )
Using AUTOBOX (a time series package that I have helped to develop ) I obtained answers to these questions in the form of a model that only contained statistically significant parameters and generated a plausible model.
The Actual/Fit and Forecast graph is here   and a less busy Actual and Forecast graph here
The residuals appear to be relatively free of structure   with ACF here
The forecasts for the next 36 period are presented here
The final model is developed through a sequence of interim models much like peeling an onion where model diagnostics ( tests of sufficiency and necessity ) are used to ultimately separate signal and noise   AND here  . The Actual and Cleansed graph is informative about the identified anomalies
The dependent series suffered a number of "shocks" i.e. external policy effects while still being associated with the input series. These shocks were empirically found and as you suggested explicable due to policy changes. The model reflects these external condiderations .
Comment: I know the date of the shocks. Do you know where I can find more information on how to incorporate theses shocks (Methodology)?
Comment: I am finding a lot of information on how to detect shocks but not on how to model them with the method you mentioned.


How to programmatically add a field to a view depending on another field and reorder fields then

Question: I broke a site yesterday using views global php, even if it was working in the preview, so I'm a bit nervious about that php in database and I'm trying to implement the same thing with Views API.
Depending on the key value of a hidden field in the current display, I need to put a custom text. Something like (global php version) :
if( isset($data) && isset($data->field_field_statut_depart) ) {

  switch(  $data->field_field_statut_depart[0]['raw']['value'] ) {

    case 1:
      $text = 'ABC';
      break;
    case 2:
      $text = 'DEF';
      break;
    //and so on

  }
  print $text;
}

I'm trying to build it with hook_views_pre_view(&$view, &$display_id, &$args) but I can't find the required field_statut_depart value in  dpm($view).
Maybe it's not the right hook ?
EDIT : after applying solution described in the answers below (views_post_execute hook) and 12 hours running, I'm facing a strange behaviour : the changes made by  views_post_execute hook are not stable : after clearing caches, they are visible for a while but raw data (without my function applied) is displayed then ! I'm afraid it's still not the right place to do that. Any help is welcome.
Answer: You may want to try the views_post_execute hook.
Otherwise there is a reduced list of hooks used for views rendering at the bottom of the Views Hooks API page.
It is a little hidden but I have used it many times and you may find a solution to your issue there.
Comment: please have a look at the question, savoyard ;) The view does not display the processed data but the raw values after a while !
Answer: Thanks to @kartsims suggestion, this did the trick :
function MODULE_views_post_execute(&$view) {
  if ($view->name == 'foo' && $view->current_display == 'bar') {
    //dpm($view);
    foreach ($view->result as $result) {
      //dpm($result);
      if (isset($result->field_field_statut_depart)) {

        switch($result->field_field_statut_depart[0]['raw']['value'] ) {
          case 1:
            $text = 'ABC';
            break;
          case 2:
            $text = 'DEF';
            break;
          //and so on
        }
        $result->field_field_statut_depart[0]['rendered']['#markup'] = $text;
      }

      if (isset($result->field_commerce_stock)) {

        $result->field_commerce_stock[0]['rendered']['#markup'] = '';

        if($result->field_commerce_stock[0]['raw']['value'] < 6 ) {
          $result->field_commerce_stock[0]['rendered']['#markup'] = $result->field_commerce_stock[0]['raw']['value'].' items remaining';
        }
      }
    }
  }
}


The existence of group isomorphism between Euclidean space.

Question: Is there any group isomorphism for addition $\mathbb{R}^n$ to $\mathbb{R}^m$ where $n\neq m$? I could prove that there exists any vector space isomorphism or smooth map, but I still could not know that if we consider only abelian group structure for the addition of them, then the group isomorphism between them exits or not.
Comment: Do you mean group isomorphism for the addition ?
Comment: Oh, for the addition. Sorry for missing.
Answer: Hint: For vector spaces over $\mathbb{Q}$, you can see the underlying group homomorphism as a $\mathbb{Q}$-linear map. This reduces the problem to seeing if dimensions of the vector spaces over $\mathbb{Q}$ are equal as this is equivalent to the underlying groups being isomorphic. In turn, it is known (facts section) that the dimension of an infinite dimensional vector space over  $\mathbb{Q}$ is the cardinality of the vector set.
Answer: Partial answer:
Assume $n \neq m$ and that $f : \mathbb R^n \rightarrow \mathbb R^m$ is a group isomorphism for addition, i.e. for all $u,v \in \mathbb R^n$, $f(u+v) = f(u) + f(v)$. Then $f$ cannot be continuous.
Indeed, you can easily successively show that for all $u \in \mathbb R^n$, $f(nu) = nf(u)$ for all $n \in \mathbb N$, then for all $n \in \mathbb Z$, then $f(qu) = qf(u)$ for all $q \in \mathbb Q$. Now if $f$ is continuous you have $f(\lambda u) = \lambda f(u)$ for all $\lambda \in \mathbb R$. So $f$ is linear and therefore $n = m$, which is a contradiction.
Here we have also shown that any group isomorphism for addition from $\mathbb R^n$ to $\mathbb R^m$ is a $\mathbb Q$-linear map.
I didn't manage to disprove the statement for non-continuous applications though but I will look into it!


How do I profile disk I/O within a PHP script?

Question: I am running 5 instances of a PHP script using Supervisord.  Running 5 processes is the optimal number to maximize the processing that my PHP script does.  If I run more than 5 or less than 5, I get worse results.
I'm already profiling the PHP script itself with xdebug and webgrind.
I suspect that disk I/O is what's preventing me from running more parallel processes as my CPU and Memory are not maxed out with 5 processes running.  I have 4 virtual cores on an Amazon EC2 instance, and neither Mysqld nor Supervisord are using more than 50% CPU at any given time.
How does one profile disk I/O on a Linux Cent OS machine ( does this sound like the culprit )?
What other bottlenecks should I be looking for?
--SOLUTION--
I was unable to find any simple solutions that gave me very in depth information.  I'm not exactly sure what I'm looking for though, so I apologize for this question and answer being vague.
Comment: Would using plain old `iotop` be an option? That gives you a live view of what processes are accessing the disk.
Comment: I've installed that and tried it out.  Looks like good data, but I'm unclear what to do with the info?  How do I know what my system limits are?
Answer: I would look at iostat -c -n 1 while your script is running and see what is reported in the %util column on the far right. If your hunch is right, then the %util should be close to 100% while your processes are running.
Does this script do any processing that fetches data over the network? That could also be a bottleneck.
Its hard to say more without knowing a little more about what the script does. What is each process doing? How did you determine that 5 is the optimal number of processes?
Comment: It's a crawling/scraping system.  Each script selects the next file from a files table and downloads it if it's not already downloaded.  Then scrapes it and stores various pieces of info like links and meta info. I determined 5 was the optimal # of processes by trying different numbers of processes and tracking how many files per second were being processed.  It maxed at around 2.8 files per second with 5 processes running. I've tried iostat and my %util never goes over 10%. I'll keep digging i guess. Also, I had to use iostat -x 1.
Comment: `yum install sysstat`


Example of a group in which intersection of all non-normal subgroups is non-trivial

Question: What are some examples of a group in which intersection of all non-normal subgroups is non-trivial.
Do I consider abelian or Hamiltonian groups an example for this as they have only normal subgroups, so there does not exist any intersection of non-normal subgroups ? What are some other not so vacuous examples?
Comment: Can you be more precise about what you mean? Do you want the intersection of every pair of non-normal subgroups to be non-trivial?
Comment: @Bungo Intersection of all non-normal subgroups
Answer: In the group defined by the presentation $\langle x,y \mid x^3 = y^4 = 1, y^{-1}xy=x^{-1} \rangle$ (which is isomorphic to the subgroup of $\langle (1,2,3),(1,2)(4,5,6,7) \rangle$ of $S_7$), the only non-normal subgroups are the three Sylow $2$-subgroups, all conjugate to $\langle y \rangle$. Their intersection is the subgroup $\langle y^2 \rangle$ of order $2$.


Laravel query relationship issue

Question: I need to check if inside a relationships there is a given value but i got an error when i try to fetch the variable i need inside the loop. I get  "message": "Undefined variable: cat".
Here is my code
<code>$cate = $request->input('category');
                foreach ($cate as $key => $cat) {
                    $restaurants->with(['categories' => function ($query) {
                    $query->where('name', '==', $cat);
                    }]);
                }
</code>
can someone help me figure out?
Answer: you must use "whereHas" instead of "with" to check if relationship have pass condition:
<code>$cate = $request->input('category');
foreach ($cate as $key => $cat) {
    $restaurants->whereHas(['categories', function ($query) use ($cat) {
       $query->where('name', '==', $cat);
    }]);
}
</code>
and for your questions: import variable to the current scope (the use keyword)
Answer: what is inside your <code>$cate</code> variable ?
and what do you want to do ?
If you want to search your Restaurants matching your given categories in your input, then you should do this :
<code>// assuming your $request->input('category') look like this :

$categories = ['foo', 'bar'];

$restaurants = Restaurant::whereHas('categories', function($query) use ($categories){
    $query->whereIn('name', $categories);
})->get();

</code>
(just for explaining your error, you have to pass you $cat variable to your closure :
<code>$restaurants->with(['categories' => function ($query) use ($cat) {
                    $query->where('name', '==', $cat);
                    }]);
</code>
Answer: you need to just pass the $cat variable to your closure => function ($query) use ($cat)
<code>$cate = $request->input('category');
            foreach ($cate as $key => $cat) {
                $restaurants->whereHas(['categories' => function ($query) use ($cat) {
                $query->where('name', $cat);
                }]);
            }
</code>
use whereHas() to specify additional filters in the relationship.
Show More => https://laravel.com/docs/8.x/eloquent-relationships

Laravel query relationship issue


Como chamar um alertDialog dentro de um fragment?

Question: Não consigo chamar um alertDialog dentro de um fragment. No momento de definir o builder(this) ele retorna erro. Segue código:
public void mostrarMsg(String titulo, String mensagem) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(titulo);
    builder.setMessage(mensagem);
    builder.show();
}

Este código funciona normalmente dentro de uma activity quando é chamado, mas quando é colocado dentro de um fragment retorna erro no 'this'. Qual é a razão e como pode ser solucionado?
Comment: Coloca o GetActivity() que vai servir para isso, ele vai retornar a activity que o fragment esta contido.
Answer: Troque o this por getActivity() que vai resolver seu problema.
A razão disso é que ele espera que você passe um Context ali dentro, uma Activity é um Context, pois ela estende da classe Context, então quando você utiliza o this você está se referindo ao objeto atual, no caso seu Fragment não é um Context.

Veja mais sobre context aqui:
O que é um context no Android?
Comment: Certo, mas como vou chamar este método que está dentro da fragment através de um button que está dentro da mesma? É possível fazer isso pelo java apenas?
Comment: Não entendi, na pergunta você disse que não estava funcionando este código em um `Fragment` e estava apresentado erro no `this`. Para isto basta apenas substituir o `this` por `getActivity()` para obter o `context`da activity.
Comment: Sim... consegui fazer isto.. Agora minha intenção é chamar este método atraves de um button que está no xml do fragment. Agora na verdade a dúvida seria outra rs. Como que posso então, já que consegui criar este método dentro do fragment, coloca-lo no onclick de um button que está dentro da fragment entendeu? Gostaria de fazer isto pelo java e não pelo XML.
Comment: Como é um contexto totalmente diferente da sua pergunta, seria interessante você criar uma nova com essa dúvida do clique, pois não existe nenhuma atualmente no site.
Comment: Ok muito obrigado.


Cmake project with multiple directories and multiple CMakeLists

Question: I have been given some C++ source files, together with a CMakeLists.txt file, which compile to create an executable. I now want to add my own source files to this project. However, I want to keep the original source files, and the original CMakeLists file, separate from the new files.
So, I want my solution to look like this:
/Project
/Project/src
/Project/src/CMakeLists.txt
/Project/src/OriginalSource
/Project/src/OriginalSource/CMakeLists.txt
/Project/src/OriginalSource/Original.cpp
/Project/src/NewSource
/Project/src/NewSource/CMakeLists.txt
/Project/src/NewSource/New.cpp
/Project/build

I want all the source files to then compile into an executable to be placed in the build directory. So my question is, what do I put in the three CMakeLists files, such that src/OriginalSource/CMakeLists.txt just compiles the original sources, src/NewSource/CMakeLists.txt just compiles the new sources, and src/CMakeLists.txt links together all these built sources, and creates an executable?
Comment: Don't you have a CMakeLists.txt at the Project level?
Comment: No, but I could add one (in fact I just have)!
Comment: @dresherjm: You should make that an answer ;). It is also what I use: One CMakeLists.txt and collect source-files from multiple subdirs.
Answer: You could create a convenience library out of your code and then link it to the code you've already got. The idea is explained here.
Please see this link for more details:
http://www.cmake.org/Wiki/CMake/Tutorials/Object_Library
I hope it helps.
Answer: No way to change the executable project in OriginSource without modifying the CMakeLists.txt in it. If you really do not want to modify the original project, you could write a new CMakeLists.txt including old and new sources.
One trick is define new sources in /Project/src/CMakeLists.txt, then include them in /Project/src/OriginalSource/CMakeLists.txt:
set(NEW_INCS ${CMAKE_SOURCE_DIR)/NewSource)
file(GLOB NEW_SRCS ${CMAKE_SOURCE_DIR)/NewSource/*.cpp)


Glissando: white notes or black notes?

Question: I have a question about the glissando:
Does a glissando (on piano) have a meaning of playing just white notes regardless of which key we are in? For example, in F# we have a lot of sharps. If I want an upward-sliding glissando effect from C# through G# (where the G# is ~an octave and a half above the C#), is that properly communicated using a glissando? Would a glissando entail playing all black keys from C# to G#, or would it just entail playing the white keys on the piano?
I have a second question that would be related to this question. So after finding the answer to this question, I'll ask my second question in another post (assuming this response doesn't also answer my second question).
Thanks in advance.
Comment: @AF, I've edited for clarity. Please check to make sure I haven't changed the content at all of your question. In the first large paragraph, did you want the last sentence to say: "Would a glissando entail playing **all keys (black and white)** from C# to G#" or is it correct the way I've edited it?
Comment: Sometimes, you can play the first and/or last note with your other hand, if they are on black keys. That can help to keep the tonality from "wandering" too much when there aren't many white notes in the key signature.
Comment: @jdjazz If the OP's question really was "Would a glissando entail playing all keys (black and white) " the answer is "no, that's not physically possibile for a normal human." Of course with computer playback, you can play any notes you like.
Comment: @alephzero yes, agreed. Just checking to make sure I haven't changed the original content, as this would be an inappropriate edit.
Comment: Technically, gliss on black keys. Practically use white - it doesn't hurt so much.
Comment: @jdjazz seems your edit is OK
Answer: A piano gliss is  usually on white notes, with the back of the middle finger.  Where it needs a specific 'landing point', and it's a black note, it's easy to turn the first finger onto it.
Sometimes 'black note gliss' is requested in the notation.  Sometimes a player decides a black note gliss would be appropriate.  It tends to be very recognizably a pentatonic scale.  This can be a good sound.
But the default gliss is white notes.
Comment: Good answer. You could also note that other variations are possible: Ravel writes glissandos in thirds, and it is possible to do a similar "chromatic" glissando, playing the white notes with thumb and black notes with fingers (or vice versa), not that I've ever seen this written.
Comment: You don't seem to have read my answer!   Yes, there is a default, a white note gliss.  If you just write 'gliss' this is what you will get.  If you want a black note gliss, say so.  Write 'black note gliss'.   If you want something else - well you can ASK for 'D major gliss' or 'Chromatic gliss' but you'll have to tell the player how to do it!   A sequencer could manage it of course, so in these days of computer-generated music maybe it isn't all that silly a question.
Comment: Thanks, so there is no default rule for gliss. for example in classic pieces? Or if Intend to prefer whites to blacks or if I want some notes in the middle to be included in the gliss. how would be the notation rules? How to clarify exactly what I mean on my sheet? How to write I want all the chromatic notes to be played for that specific gliss.? Another question: If for example the music is in F#M, which has lots of sharps, doesn't playing gliss with only white keys seems a lot out of tune or something like that?
Comment: @AF what do you mean by "classic"? Also, I would note that if the gliss is short (just a third or a fourth or so), it's commonly played as a chromatic sequence of all the notes between the beginning and the end ones.
Comment: Is it?  On piano 'gliss' is the name of a particular gesture.  We can also play fast chromatic scales.  But a gliss is where we turn the finger over and slide up (or down).
Answer: On the piano, a glissando is possible on either the white or black keys. In the latter case, it would be an ascending or descending pentatonic scale. I use the back of my fingers. It never hurt me.
On the harp, it is different. The strings can be set by means of the pedals so that a glissando can be done on any scale, diminished-seventh chord, the two whole-tone scales, some dominant sevenths, and some added-sixths chords. Care must be taken, however, not to use the harp glissando to excess. Some harp parts comprise almost entirely zig-zag lines. The late Sir Charles Villiers Stanford used to complain that some composers seemd to imagine that harpists played with brooms instead of fingers.

Glissando: white notes or black notes?


Why can't I modify the contents of this folder when I'm part of the group with full permissions?

Question: dsmith@ip-xx-xxx-xxx-xx:~$ groups dsmith
dsmith sudo py
dsmith@ip-xx-xxx-xxx-xx:~$ sudo chmod -R g+rwxt /usr/local/virtualenvs
dsmith@ip-xx-xxx-xxx-xx:~$ ls -al /usr/local
...
drwxrwxr-x  2 root py   4096 2010-02-17 19:36 virtualenvs
dsmith@ip-xx-xxx-xxx-xx:~$ echo "Hello World" > /usr/local/virtualenvs/test.txt
bash: /usr/local/virtualenvs/test.txt: Permission denied

Answer: You'll need to have read (well, execute at least) on all parent directories, and write access to the file in question.
Also, groups dsmith shows what groups the dsmith user is in; while groups shows what groups the current user is in. You'll need to log in anew if they show different output.
Another thing to check is SELinux; it might be interfering.
Comment: groups returned dsmith sudo. I logged out and logged in as dsmith and it worked. A few steps back I su dsmith so I wonder if switching users instead of logging out and logging in as a different user had something to do with it.
Comment: Another thing to be aware of is that if you add the current user to a new group, that new group won't be recognized until you logout and log back in again - or su to the same user.


Como incluir um recuo ao usar a tecla tab em um textarea?

Question: Tenho um <textarea> que irá funcionar como um pequeno editor de código-fonte.
Queria que, ao pressionar o Tab, incluísse um recuo no texto ao invés de colocar o foco no próximo elemento, que é o comportamento padrão da tecla.
Queria que fosse possível gravar o texto formatado no banco de dados, e ao carregá-lo devolta para o <textarea>, mostrasse os recuos inseridos.
Answer: É só interceptar o keydown quando o keyCode === 9

$('textarea').bind('keydown', function(e) {
    if(e.keyCode === 9) {
        e.preventDefault();
        var inicioDaSelecao = this.selectionStart,
            fimDaSelecao = this.selectionEnd,
            recuo = '\t'; //Experimente também com '    '

        this.value = [
            this.value.substring(0, inicioDaSelecao),
            recuo,
            this.value.substring(fimDaSelecao)
        ].join('');

        this.selectionEnd = inicioDaSelecao + recuo.length;
    }
});

<textarea></textarea>

Você provavelmente vai precisar de um polyfill como este para tornar o código da resposta crossbrowser, já que em algumas versões do IE a seleção de texto é tratada diferente.
Answer: O keyCode do TAB é 9. Adicione um evento ao textarea, para quando o usuário digitar TAB, ele inserir um \t na posição atual do cursor:

document.getElementById('textedit').addEventListener('keydown', function(e) {
    if(e.keyCode === 9) { // TAB
        var posAnterior = this.selectionStart;
        var posPosterior = this.selectionEnd;

        e.target.value = e.target.value.substring(0, posAnterior)
                         + '\t'
                         + e.target.value.substring(posPosterior);

        this.selectionStart = posAnterior + 1;
        this.selectionEnd = posAnterior + 1;

        // não move pro próximo elemento
        e.preventDefault();
    }
}, false);
<textarea id="textedit"></textarea>

  Próximo input:

  <input type="text" id="" />


weighted? proportion (e.g. 1/1 < 10/10)

Question: I was wondering if there was a way to express a proportion but weighting the numerator/denominator size. For example:
Say I have a categorical variable X with 3 possible values: A, B, C and I'm trying to predict effect y (either 1 or 0)
I have 1 case of X = A and y is positive => 1/1
I have 10 cases of X = B and y is positive on five => 5/10
I have 25 cases of X = C and y is positive on all => 25/25
Then:

if I process the feature as "number of positives per category", values A and B would be equivalent.
if I process the feature as a proportion (positives/all), A and C would be equivalent.

None of those is desirable. Is there another way to better encode these?
Thanks!
(Note: the example is illustrative, I need it to generalize to multiple categories)
Comment: Your question is not clear, and example even less so. Could you reformulate it? In particular, how does "I have 1 case of `X = A` and `y` is positive" imply 1/1? What does 1/1 mean here?
Comment: in that case would be 1 example with feature `X = A` and that case is positive (`y = 1`)
Comment: Why then "I have 10 cases of X = B and y is positive on five" implies 1/10? Shouldn't it be 0/5? (0 examples with feature `X = A` and 5 cases positive)?
Comment: @psarka you're right, I corrected it. It's 5/10
Comment: @PabloFernandez This still doesn't make sense to me. If you want an unconditional (you don't know X) prediction of $Y$, you would just use the crude proportion of Y (1 + 5 + 25) / (1 + 10 + 25).
Answer: Try the formula for the posterior mean of a Bernoulli distribution with a beta prior. This is simply $\frac{s + α}{n + α + β}$ where $s$ is the number of succeses, $n$ is the number of trials, and $α$ and $β$ are adjustable prior parameters. For example, if you choose $α = β = 1$, then
 s    n    output
 1    1     .67
 5   10     .50
25   25     .96

Comment: (+1) I've heard of the special case of setting $\alpha = \beta = 1$ as the "+1" estimator, because it's as simple as just adding 1 "success" and 1 failure to your estimate. It surprising how many real world application issues are fixed using this. Also, since the OP asked for a method that generalizes to multiple categories, this is as easy as adding one outcome to each category in the multinomial case.

weighted? proportion (e.g. 1/1 < 10/10)


Where can I download the Windows installer for Drush?

Question: I cannot find the link where to download Drush windows installer.
Can anyone tell me if there is or how to do?
I am using Drupal 8.1 and Windows 7.
Answer: You need to install it using composer as specified here:
https://github.com/drush-ops/drush/blob/master/docs/install.md
After installation, make sure to run and use the drush command inside Git's shell only (the shell environment bundled with Git for Windows)
Comment: thanks for the indication, but I stopped and I have not figured out what is wrong.
I saw the video and I vusto using bash, I will,
I installed git
From the command line I wrote:
git clone --branch master http://git.drupal.org/project/devel.git
Then follow the directions of the site Drush I wrote:
  export PATH = "$ HOME / .composer / vendor / bin: $ PATH"

Any command you write back to me this error:
bash: composer: command not found

What do you suggest me?

thank you
Comment: Installazione - Windows # con l'installer # Questo è il modo più semplice per ottenere Compositore installare sulla vostra macchina. Scaricare ed eseguire compositore-Setup.exe. Sarà installare l'ultima versione Composer e impostare il percorso in modo che si può chiamare compositore da qualsiasi directory nella riga di comando. Nota: Chiudere il terminale corrente. l'utilizzo di test con un nuovo terminale: Questo è importante, dal momento che il PATH solo viene caricato quando il terminale si avvia.
Comment: @Gaetano In Windows, setting PATH environment variables happens via the `SET` command or the GUI by running `rundll32 sysdm.cpl,EditEnvironmentVariables` from command line. Run this command and set the PATH variable there.
Answer: Use Acquia Dev Desktop. Drush is Pre Installed


Equal inner gaps between table-cell columns

Question: I am using savvior.org to create a grid based layout for images and other elements, everything works fine, I am only stuck with adding inner gaps between the .columns.
The outcome is currently as follows:

As you can see the gap is equal but the height of the elements within the row isn't.
I tried to use borders, I manged to get the elements the same height but then the gaps didn't have an equal space...
Note, the gab/padding need to be adjustable.
I have put together a JSFiddle here http://jsfiddle.net/6n0wasjf/4/
Here is the CSS:
/*GRID SYSTEM =================================================================*/
.grid {
    width: 100%;
  margin-bottom: 10px;
  position: relative;
  display: table;
  table-layout: fixed;
  opacity: 0;
}
.grid .grid {
    opacity: 1;
}
.grid:last-of-type {
    margin-bottom: 0;
}

    .grid .column {
      padding: 0 10px;
      display: table-cell;
    }

    .grid .column:first-of-type {
      padding-left: 0;
    }

    .grid .column:last-of-type {
     padding-right: 0;
    }

    /*Columns width settings*/
    .grid .size-1of1 {
      width: 100%
    }
    .grid .size-1of2 {
      width: 50%;
    }
    .grid .size-1of3 {
      width: 33.33%;
    }
    .grid .size-1of4 {
      width: 25%;
    }
    .grid .size-1of5 {
        width: 20%;
    }

Answer: Issue is due to removing padding in .grid .column:first-of-type and .grid .column:last-of-type. It will cause width difference for .column divs.
Instead add negative margin for .grid to remove left and right padding.
.grid {
    ....
   margin-left: -5px;
   margin-right: -5px;
}

Please check the fiddle - http://jsfiddle.net/afelixj/6n0wasjf/5/
Comment: yes.. but the left padding for the first column div, and right padding for last column div will push the content in.
Comment: Don't understand sorry
Comment: In your css there is no margin for grid, and there is no left padding for first column. so it is aligned to the left of the page.  I have added negative margin to the grid which will move grid to left, but added left padding to first column which will push the content to right.
Comment: the whole .grid is moved to the left leaving a gab on the right tho
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/79644/discussion-between-leo-and-afelixj).


How do I create a custom search block?

Question: I want to add in my D7 installation a search field inside a special part of the page, and I don´t want to use the default search block (as it will be harder to theme, this box I have already worked on it).
Naturally, if I just type:
<form><input type="text" placeholder="Search"></form>

it won´t work.
What else does this need to actually act like the default search form in the search block? I know there´s this Custom Search module, but I think that I shouldn´t install yet another module for this simple functionality.
Thanks!!
Comment: is there any functional change to the search box? that is is the search box going to out put some thing different than the default search box. and when you say harder to theme what do you mean?
Comment: Hi!! The search box should output and behave exactly the same as the default search box, I want to completely replace it. I wanted to have a search box at the top (as stackoverflow does), and it´s easier to just paste up there a textbox than configure the search box to appear the way I want. So I thought maybe I should just create another searchbox... Thanks!!
Answer: You could simply call drupal_get_form() on the search form_id, which I think is - either search_block_form or search_form
And use drupal_render() on the returned array.
  print drupal_render(drupal_get_form('search_block_form'));

Though I might be wrong about the drupal_render() part, yet it seems to me since the drupal_get_form() returns an array drupal_render should be used on it.
Also this page might be helpful too - http://data.agaric.com/print-form-such-search-form-anywhere-drupal
Hope that helps.
Answer: I'm not sure why you said the default search box is harder to theme. Drupal can do theme override or form override as you like. If you google, you will see many solutions for this purpose.
Check this Q/A : how to overwrite the search box? and you could also override search-block-form.tpl.php.
Then, you can define which pages the search block to be appeared at the block configuration page admin/structure/block/manage/search/form/configure
OR remove the search block from any region and then you can print the block programmatically where you want. See Placing the contents of a block in any location.
<?php
$block = module_invoke('search', 'block_view', 'form');
print render($block['content']);
?>

Answer: /*
 * create search block
 */

function mymodule_block_info() {
$blocks['my_search'] = array(

'info' => t('My Search Block'),
'cache' => DRUPAL_NO_CACHE,
);
return $blocks;
}
function mymodule_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'my_search':
  $block['title'] = 'MyCustom Search';
  $srchblk = drupal_get_form('mymodule_search_block_form');
  $block['content'] = drupal_render($srchblk);
  break;
  }
  return $block;
}

/* create search form */

function mymodule_search_block_form($form, &$form_state) {
$form['keys'] = array(
'#type' => 'textfield',
'#size' => 15,
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Search',
);
return $form;
}

/*
 * create search result menu callback
 */

function mymodule_menu() {
$items['custom/node/search/%'] = array(
'page callback' => 'mymodule_do_search',
'page arguments' => array(3),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}

/*
 * create form handler
 */

function mymodule_search_block_form_submit($form, &$form_state) {
drupal_goto('custom/node/search/' . $form_state['values']['keys']);
}
 /*
  * create search result callback function
  */

function mymodule_do_search($keys) {
  // set the page title

drupal_set_title('MY search results');
  // get the search results

 $results = module_invoke('node', 'search_execute', $keys );
 return theme('search_results', array('results' => $results));
 }

Answer: This is what I needed:
$block = module_invoke('search', 'block_view', 'form');
print render($block['content']);

How do I create a custom search block?


rank of $A \otimes B$

Question: For two matrices $A$ and $B$, what would be the rank of $A\otimes B$ as a matrix?
Seems to me that $rank(A\otimes B) = rank(A)\cdot rank(B)$. But I don't see an elegant proof...
Answer: Every $m\times n$ matrix $A$ can be reduced, via elementary row/column operations, to the form $D=\operatorname{diag}(I_r,\ 0_{(m-r)\times(n-r)})$, where $r=\operatorname{rank}(A)$. That is, $A=PDQ$ for some invertible matrices $P$ and $Q$. So, $A\otimes B$ can be rewritten in the form of
$$
A\otimes B
=(P_1D_1Q_1)\otimes (P_2D_2Q_2)
=(P_1\otimes P_2)(D_1\otimes D_2)(Q_1\otimes Q_2).
$$
As $P_1\otimes P_2$ and $Q_1\otimes Q_2$ are invertible (their inverses are $P_1^{-1}\otimes P_2^{-1}$ and $Q_1^{-1}\otimes Q_2^{-1}$), they preserve rank. Therefore $\operatorname{rank}(A\otimes B)=\operatorname{rank}(D_1\otimes D_2)$. Now, for diagonal matrices, I think the statement is obvious enough.
Answer: Approach 1 (with matrices). We will use the identity $(XY)\otimes(ZT) = (X \otimes Z)(Y \otimes T)$ which holds for all matrices $X, Y, Z, T$ of suitable size. Notice that from this identity it follows that $X \otimes Y$ is invertible if both $X$ and $Y$ are invertible.
Moving on to the problem. It is known that matrix $A$ can be represented as $A_l A_d A_r$, where $A_l$ and $A_r$ are invertible of appropriate sizes, and $A_d$ has $\mathrm{rank}(A)$ $1$'s on the main diagonal and $0$'s everywhere else. In a similar fashion, represent $B$ as $B_l B_d B_r$. Now we have
$$
A \otimes B = (A_l \otimes B_l)(A_d \otimes B_d)(A_r \otimes B_r).
$$
Matrices $A_l \otimes B_l$ and $A_r \otimes B_r$ are invertible, and $A_d \otimes B_d$ has $\mathrm{rank}(A)\cdot\mathrm{rank}(B)$ 1's on the main diagonal and 0's everywhere else. It is clear then that $\mathrm{rank}(A \otimes B) = \mathrm{rank}(A) \mathrm{rank}(B)$.
Approach 2 (with linear maps). In the language of linear maps, we have two linear maps $f_1: L_1 \to R_1$ and $f_2: L_2 \to R_2$ and their tensor product $f_1 \otimes f_2: L_1 \otimes L_2 \to R_1 \otimes R_2$. We want to show that $\mathrm{rank}(f_1 \otimes f_2) = \mathrm{rank}(f_1) \mathrm{rank}(f_2)$.
Lemma 1. If $f_i$, $g_i$ are linear maps between appropriate spaces, then $$(f_1 \otimes f_2)(g_1 \otimes g_2) = (f_1 g_1) \otimes (f_2 g_2).$$
This follows straight from the definition of the tensor product of maps.
Lemma 2. A linear map $f: L \to R$ is injective iff there is a linear map $g: R \to L$ such that $g f = \mathrm{id}_L$. $f$ is surjective iff there is a linear map $g: R \to L$ such that $f g = \mathrm{id}_R$.
This is an easy exercise.
Corollary 1. If linear maps $f_1: L_1 \to R_1$ and $f_2: L_2 \to R_2$ are injective, so is $f_1 \otimes f_2$.
Proof. By lemma 2, there exist linear maps $g_1: R_1 \to L_1$ and $g_2: R_2 \to L_2$ such that $g_1 f_1 = \mathrm{id}_{L_1}$ and $g_2 f_2 = \mathrm{id}_{L_2}$. From lemma 1 we have
$$
(g_1 \otimes g_2)(f_1 \otimes f_2) = (g_1 f_1) \otimes(g_2 f_2) = \mathrm{id}_{L_1}\otimes \mathrm{id}_{L_2} = \mathrm{id}_{L_1 \otimes L_2}.
$$
Using lemma 2 again we see that $f_1 \otimes f_2$ is injective, qed.
Corollary 2. If linear maps $f_1: L_1 \to R_1$ and $f_2: L_2 \to R_2$ are surjective, so is $f_1 \otimes f_2$.
The proof is similar to corollary 1.
Now we are ready to prove that $\mathrm{rank}(f_1 \otimes f_2) = \mathrm{rank}(f_1) \mathrm{rank}(f_2)$. It is known that there exist vector spaces $M_i$ and maps $g_i: L_i \to M_i$, $h_i: M_i \to R_i$ such that $f_i = h_i g_i$, $g_i$ are surjective, $h_i$ are injective, and $\dim M_i = \mathrm{rank}(f_i)$, for every $i = 1, 2$.
Now we have maps $g_1 \otimes g_2: L_1 \otimes L_2 \to M_1 \otimes M_2$ and $h_1 \otimes h_2 : M_1 \otimes M_2 \to R_1 \otimes R_2$. By corollaries 1 and 2 the former map is surjective and the latter is injective. Now, since $f_1 \otimes f_2 = (h_1 \otimes h_2)(g_1 \otimes g_2)$, we see that its rank is equal to the dimension of the "middle space", i.e.:
$$
\mathrm{rank}(f_1 \otimes f_2) = \dim M_1 \otimes M_2 = (\dim M_1)(\dim M_2) = \mathrm{rank}(f_1)\mathrm{rank}(f_2),
$$
qed.
Comment: Thanks very much. This helps a lot.

rank of $A \otimes B$


Apache Cassandra - Select Operation Timed Out

Question:
Installed --> datastax-community-64bit_2.2.7
Created --> Keyspace = INVENTORY and Tablename = Stocks
Able to pump in total 858 , 469 data records
System error to SELECT total of 858 , 469 data records

SELECT * FROM Stocks;

Unable to execute CQL script on localhost:
[localhost/127.0.0.1:9042] Operation timed out
Here is Cassandra Keyspace and Table script creation:

CREATE KEYSPACE INVENTORY
  WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 1};
USE Inventory;
CREATE COLUMNFAMILY Stocks (
  Id varchar,
  ProductId varchar,
  DealerGroupId varchar,
  SupplierId varchar,
  SerialNo1 varchar,
  SerialNo2 varchar,
  SerialNo3 varchar,
  PIN1 varchar,
  PIN2 varchar,
  PIN3 varchar,
  PIN4 varchar,
  PIN5 varchar,
  PIN6 varchar,
  ExpiryDate varchar,
  GRNId varchar,
  ProvisionedDate varchar,
  ModifiedDate varchar,
  MStockStatusId varchar,
  IsIntermediate varchar,
  ReStockOrderId varchar,
  ReturnRequestId varchar,
  AllocationOrderId varchar,
  PRIMARY KEY ((Id));
Comment: What if I am using Datastax DevCenter 1.5.0 --> an GUI interface to execute SELECT Queries ? Where I can adjust or configure the time out issue ?
Answer: The default client timeout is 10 sec. If you are using CQLSH, you can configure in <code>~/.cassandra/cqlshrc</code>
<code>[connection]
client_timeout = 3600
</code>
Generally, it is not recommended to select all with so many rows.
Hope this helps!
Comment: What if I am using Datastax DevCenter 1.5.0 --> an GUI interface to execute SELECT Queries ?

Where I can adjust or configure the time out issue ?
Comment: I have checked decompiled `com.datastax.devcenter.connections_1.5.0.jar`. It seems that DevCenter doesn't support customizing timeout.
Comment: What if I am using Helenos GUI Cassandra then can it handle customized timed out settings ?

https://sourceforge.net/projects/helenos-gui/
Comment: I checked the source code. https://github.com/tomekkup/helenos/blob/1.5/src/main/java/tomekkup/helenos/dao/model/ClusterConfiguration.java#L80

This tool also has no configuration. But if you want to you can change the source code and build it on your local.

Check Hector client timeout setting https://github.com/hector-client/hector/blob/hector-1.1-0/core/src/main/java/me/prettyprint/cassandra/service/CassandraHost.java#L157
Answer: I received Connection timeout while creating my first Keyspace itself. After lots of testing, i finally came upon a solution - follow the below steps in cqlsh

desc keyspaces --- This will list all system keyspaces present

use system_schema; --- Go to any keyspace, here system_schema

cqlsh:system_schema> CREATE KEYSPACE ksp1
...   WITH REPLICATION = {
...    'class' : 'SimpleStrategy',
...    'replication_factor' : 1
...   }; ------------------- This will create 'ksp1'

cqlsh:system_schema> desc keyspaces
cycling  system_schema  system_auth  system  system_distributed  system_traces

cqlsh:system_schema> use cycling;

Thanks,


I am a singer who has problems with tempo

Question: I'm a singer and I have a decent voice.  But I'm getting really frustrated because I can't seem to get my timing right while singing during live performances.
I have no problem singing along with a CD or singing with others, But when singing live, I don't seem to have a sense of timing.
I've tried metronomes but they don't seem to help at all - and I've also tried tapping out the rhythm but I always mess up, like I skip a beat or got way too fast.  What can I do?
Answer: Can you read music, or,  more importantly do you know the rhythm that you are trying to sing and that is tripping you up? that is to say, do you understand what is going on rhythmically? From my experience as a teacher when students struggle with this it is because they do not understand parts of the rhythm that they cannot feel "naturally."  So, if you cannot read music, even at a level to read just the rhythm and then sing it back I would suggest putting in the time to learn that.  If singing is something you care about than it will be worth it.  You have to be able to break down those small, complicated rhythms so you can rehearse them until they are natural.  This is just one suggestion of course, but I think until you understand what you are trying to do rhythmically it will continue to not work.
I played with a singer who was not trained, if the sound on stage was hard to hear she would struggle with this too so keep in mind that if you are experiencing this at shows, make sure that you can hear everything clearly through the monitors.
Answer: The problem could easily lie with either the way the musicians are playing the music or your inability to hear it and yourself clearly in the monitors.  It may have nothing to do with your ability to keep tempo at all.
Many very talented and gifted vocalist who can sing karaoke or with a backing track they practice with, do just fine - until they try to sing the same song with a live band.
It is a common scenario that I see with singers who try to go from singing to a CD - to singing with a band.  If you are not singing with a band - but rather singing live to a pre-recorded track, skip to the end.
The problem comes in because on a pre-recorded backing track, the musical cues are exactly the same each time you practice singing with them so you get used to exactly where the vocals are supposed to come in.  Also, if you listen to a recording of a particular popular song, and then sing to a karaoke track modeled after that song, you have a reference vocal you can practice with that has the same musical cues that are on the karaoke CD.
By musical cues I mean things like a certain type drum beat, a forceful strum on a particular guitar chord, a certain bass riff, or sax riff.  And with pre-recorded material, you have more opportunity to listen and practice until these cues become automatic.
With a live band, these cues will be completely different and may not always be the same with each performance.  So, whereas on the CD you are used to hearing a particular saxophone riff right before you sing the bridge, maybe the band you are singing with, does not have a sax player so that cue is absent.
And with a live band, it's not as easy to get in as much practice as you can with a CD that you can play while you drive around in your car running errands.
I think you might just need to rehearse more with the band with the way they play the songs you will sing, and ask them to give you stronger musical cues for when the vocals need to come in.  Maybe a symbol crash or a quick four strums on a particular power chord or something that stands out.  And be sure they do it exactly the same each time.
In fact you might need to work with the band to create an arrangement of the music that you can follow and they can play consistently.  Once the band has honed the arrangement and can play it consistently, record it so you will have something to practice to.
If you record it and still need help knowing where the vocals come in, have another band member sing some scratch vocals over the recorded music - just for the purpose of helping you with your timing.  Use that as your "guide-vocal" track to listen to over and over until you can sing along with the guide vocals, and then start practicing singing along with the recording without the vocals.
It is very important that the drummer or percussionist and or bass player (if you don't have a drummer) maintain a consistent rhythm through the entire song.  If you only have a guitar player, having him/her play in a more defined rhythm style may help with your timing. If you are playing the guitar yourself, it's easy to know when to sing.  But if someone else is playing for you, there must be some easy to recognize musical cues to go by.
Finally, and this will apply whether you are singing with a band or singing to a backing track, you must be able to clearly hear the music and your vocals, in a monitor.  I have seen many instances where singers who performed flawlessly in rehearsal, could not keep up at all in a live performance because they could not hear themselves and/or the music in their monitor (or did not have a monitor).
If there is no monitor available (which could be the case if you are performing solo and singing to pre-recorded music), try moving out in front of the PA speakers and face them so you hear what the audience hears, and hopefully everything you need to hear, to keep your timing in sync with the music.
If hearing yourself and the music is not a part of the problem, you might just need more rehearsal time, either with a recording, or the band - or both.  Best of luck to you.  You can do it!
Comment: Inviting lots of feedback - standing in front of speakers!
Comment: @Tim For sure - if you aren't careful where the mic is oriented and what type mic you are using.  I used floor wedges when I provided the PA for my band but I have performed on stage with other bands where they used pole mounted speakers behind the band as the only monitors.  Works as long as you don't pick up the mic and move it around changing the axis as it relates to the speakers.
Answer: Suzanne I have experience with this problem, and a suggestion.
Center your awareness of tempo not in your toes, and not in your thinking process but squarely in your pelvis.
In rehearsal, take time to affirmatively relax your body, taking care to concentrate on your jaw and, to put it delicately, the place where you sit down. Nice and relaxed.
If you are working with a guitarist, ask him/her to play a little in the tempo. You don't have to actually dance - though that would be great - but do sway to the rhythm with your pelvis, increasing your relaxation all the while. This is rehearsal. No one is looking. (Make the guitarist look the other way, if you like.). Don't start singing until you are enjoying the sensation, maybe until you can't stop yourself.
How to translate this into performance? Always take the time to relax beforehand. Think about the songs you are going to sing. Let your pelvis help you keep time as you run down a measure or two in your head. Flow with it. Don't be afraid to move when you perform. Relax, listen, go with the motion.
One of the great things I have learned from my band mates is how to make mistakes. The technique is simple. Make the mistake, but don't dwell on it, apologize or agonize about it. Time and tempo march on. Your mistake is in the past. Forget about it. No one wants to talk about it, they just want to hear you sing. Sing the note, keep the tempo right in front of you. You can do it.
Hope that helps.
Answer: how you fix it:
Start playing the drums. You'll develop rhythm pretty quick. You should be able to feel the phrases coming and going. Drummers know how to time based on 32nd notes for pretty good accuracy.
I began my musical journey with drums, and everything else was easy to grasp after that. Not saying everything was easy, because it's not, but timing and all should become easy.
Also, I told myself that I'm dancing to the music with my hands hitting the drums, and that really helped in the beginning.


Keycloak -- OAuth2 -- Consent Page

Question: Evaluating potentially leveraging KeyCloak to protect APIs --- still wrapping mind around KeyCloak.
Workflow:
1) User access Application A
2) User authenticates to Application A via Keycloak OpenID Connect
3) Application A calls APIs on Platform X -- APIs on Platform X are protected by KeyCloak OAuth2 -- in order to retrieve PII on user (say mail, address, favorite beer)
Question: Can KeyCloak present consent form to user for step 3 above -- i.e. that user agrees that Application A can call Platform X's API to retrieve data on user w.r.t mail, address, favorite beer?
Answer: This depends..
If both Applications are completely separate, but they are both within the same Realm in the same keycloak server, then you can have SSO implemented between apps where you don't need to retrieve info as the tokens received from keycloak will be available for App X with the same content provided to App A. The API will see you as who you are wrt App A. This means that you'll be "automatically logged in".
But, if they are secured with two different Keycloak server instances, then the second application should show the consent message. For example, my Dating website which is secured with Keycloak, asks you to connect to Facebook so it would populate a list of the pages you like to match you with someone... Facebook sign in dialog will pop up for you to sign in, then asks you if you allow App A to see your liked pages and interests.

Keycloak -- OAuth2 -- Consent Page


What was SPX from the IPX/SPX stack ever used for?

Question: Been trying to learn about older networking protocols a bit, and figured that I would start with IPX/SPX.  So I built two MS-DOS virtual machines in VirtualBox, and got IPX communications working (after much trial and error).
The idea being to get several old DOS games to run, link up to a multiplayer match, interact with each game window, and capture the traffic using Wireshark from the host machine.  From this, I got Quake, Masters of Orion 2, and MechWarrior 2 to communicate back and forth.  Doom, Doom2, Duke3d, Warcraft, and several others either buggered up under the VM or just couldn't see the other VM on the IPX network.
What did I discover?  None of the working games used SPX.  Not even Microsoft's NET DIAG used SPX.  They all ran ONLY on top of IPX.  I can't even find SPX examples or use-cases of SPX traffic running over IEEE 802.3 Ethernet II framing.  I did find references that it was in abundant use on token ring, but that's it.
Yet any IPX-aware application that I've hunted down so far usually advertises itself as "IPX/SPX", which seems to be a bit of a misnomer, since it doesn't seem to use SPX.
So what was SPX used for?  Any DOS applications out there that use it which will run under my VM setup?
Edit: I am aware that IPX is to SPX as IP is to TCP (layer 3 to layer 4), so I expected to see an SPX layer underneath the IPX layer in Wireshark when I ran my tests.
Answer: Application examples:

ArcServe Backup Agent for NetWare
Pervasive.SQL v7 NetWare
Lotus Domino Server

SPX (analogous to TCP) was optimised for LANs, and used per-packet NACKs (packets were assumed to be received instead of explicitly acknowledged) and had no concept of a transmission window.
Compare this with TCP, which uses an ACK for every byte; this also implies that you will buffer all the unacknowledged data and re-send after a lost packet.
However, IPX was not suitable for the WAN. For example, it couldn't cope with different frame sizes. I.e. two networks with different frames (say, Ethernet and Ethernet with jumbo frames) couldn't interoperate without a proxy server or some form of encapsulation.
Additionally, packet reordering in WANs is common but it plays hell with SPX (at least with Novell's implementation) causing a lot of spurious NAKs. Note 1

Finally, IPX/SPX supports a maximum of 20 sockets on a single node.  Compare this to TCP, which supports the addressing of thousands of simultaneous sockets.

Note 1: Performance of IPX/SPX and TCP/IP
Comment: Interesting notes and link!  Don't think I can easily run any of the listed applications under my two VMs, though.  I did play with ArcServe briefly at one point as a prior sysadmin -- long enough to hate it.  Any other suggested programs I can maybe find?
Comment: Check out `lwared` or `mars_nwe`, which emulate an NCP file server in linux... maybe you can hook that up to your DOS machines somehow?
Comment: I actually have a NW65 install in a separate VM and I have IPX configured on it, but it seems to only use IPX and not SPX as well.  I have not gotten a proper workstation connection to it, though, so perhaps that might be why.  Wasn't sure if some old DOS LAN games might've used SPX that I could test out.
Comment: Got the MS-DOS clients to talk to the NW VM, but not SPX traffic.  NCP, instead, which I thought ran under SPX -- kinda like how it goes IP --> TCP --> HTTP, I thought it'd be IPX --> SPX --> NCP.  Instead, it appears SPX, NCP, RIP, SAP, and others all behave like layer 4 transport protocols versus application protocols.  Neat!
Comment: I did find a simplistic SPX chat program, SPXDOS.EXE (the archive name).  Can't get it to work, though.  Using the `HELLO.EXE` program from it, it takes as a parameter the connection ID of the target user to chat to, but per WireShark, the sending station calls Function 0x17 on the NCP protocol to get the "internet address" of the target connection -- I assume it wanted the target IPX address -- and instead gets back a reference to the IP address of the NW server and told to use the UDP protocol.  Probably will have to setup an NW3.11 server to make this app work.


Recursively apply grep based on values from multiple columns

Question: I want to grep values from multiple columns and then assign a priority in case there is a conflict. I was able to write a workable code, but it's too repetitive in that I am not really fully utilizing the power of vectorized operation in R. I am looking for a solution with lapply , sapply etc.
I tried dabbling around with lapply but got stuck.
Here are my data:
dput(DF)
structure(list(S6 = c("FED AIR FORCE", "FED AIR FORCE", "FED AIR FORCE",
"FED MARINES", "FED MARINES", "FED MARINES", "FED NAVY", "FED NAVY",
"FED NAVY", "FED NAVY", "FEDERAL", "STATE", "STATE"), S.Name = c("MARINE",
"ARMY", "AIR FORCE", "MARINE", "ARMY", "AIR FORCE", "MARINE",
"ARMY", "AIR FORCE", "NAVY", "NAVY", "AIR FORCE", "FEDERAL"),
    Dept = c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_), Number = c(1, 2, 3, 4, 5, 6, 7, 8, 9,
    10, 11, 12, 12)), .Names = c("S6", "S.Name", "Dept", "Number"
), row.names = c(NA, 13L), class = "data.frame")

Here's my code that's working:
Divisions<-c("Air Force", "Army", "Navy", "Marine")
DF[grep("AIR FORCE",DF$S.Name,ignore.case = TRUE),"Dept"]<-"Air Force"
DF[grep("Army",DF$S.Name,ignore.case = TRUE),"Dept"]<-"Army"
DF[grep("Navy",DF$S.Name,ignore.case = TRUE),"Dept"]<-"Navy"
DF[grep("Marine",DF$S.Name,ignore.case = TRUE),"Dept"]<-"Marine"

DF[grep("AIR FORCE",DF$S6,ignore.case = TRUE),"Dept"]<-"Air Force"
DF[grep("Army",DF$S6,ignore.case = TRUE),"Dept"]<-"Army"
DF[grep("Navy",DF$S6,ignore.case = TRUE),"Dept"]<-"Navy"
DF[grep("Marine",DF$S6,ignore.case = TRUE),"Dept"]<-"Marine"

Commentary: First I read S.Name, if there is a match, I write the match. Then, I read S6, if there is a match, I overwrite it. So, S6 has a priority over S.Name.
Expected Output after running above operations:
dput(DF)
structure(list(S6 = c("FED AIR FORCE", "FED AIR FORCE", "FED AIR FORCE",
"FED MARINES", "FED MARINES", "FED MARINES", "FED NAVY", "FED NAVY",
"FED NAVY", "FED NAVY", "FEDERAL", "STATE", "STATE"), S.Name = c("MARINE",
"ARMY", "AIR FORCE", "MARINE", "ARMY", "AIR FORCE", "MARINE",
"ARMY", "AIR FORCE", "NAVY", "NAVY", "AIR FORCE", "FEDERAL"),
    Dept = c("Air Force", "Air Force", "Air Force", "Marine",
    "Marine", "Marine", "Navy", "Navy", "Navy", "Navy", "Navy",
    "Air Force", NA), Number = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
    11, 12, 12)), .Names = c("S6", "S.Name", "Dept", "Number"
), row.names = c(NA, 13L), class = "data.frame")

I want to be able to vectorize this...i.e. use lapply

Here's what I tried with lapply:
l<-lapply(Divisions,function (x) {sort(unique(append(grep(x,DF$S.Name,ignore.case = TRUE),grep(x,DF$S6,ignore.case = TRUE))))})

Unfortunately, I don't know how to assign priority and feed the values back to the data frame.
I'd appreciate any thoughts.
Answer: We can use str_extract to extract the specific words in 'S6' column from 'Divisions' vector by pasteing the the elements together, then use gsub to change it to camel case by matching a capital letter after a word boundary (\\b) followed by one or more capital letters (([A-Z]+)), captured both as a group, and in the replacement, we use the backreference of the first (\\1) followed by specifying lower case (\\L) for the second backreference (\\2)
library(stringr)
DF$Dept <- gsub("(\\b[A-Z])([A-Z]+)", "\\1\\L\\2", str_extract(DF$S6,
         paste(toupper(Divisions), collapse="|")), perl = TRUE)
DF$Dept
#[1] "Air Force" "Air Force" "Air Force" "Marine"    "Marine"    "Marine"    "Navy"      "Navy"      "Navy"      "Navy"      NA
#[12] NA          NA

If there are NA elements in 'Dept', then change it by applying the same method in 'S.Name'
i1 <- is.na(DF$Dept)
DF$Dept[i1] <- gsub("(\\b[A-Z])([A-Z]+)", "\\1\\L\\2",
     str_extract(DF$S.Name[i1],  paste(toupper(Divisions), collapse="|")), perl = TRUE)
DF$Dept
#[1] "Air Force" "Air Force" "Air Force" "Marine"    "Marine"    "Marine"    "Navy"      "Navy"      "Navy"      "Navy"      "Navy"
#[12] "Air Force" NA

Comment: Thanks. Could you please explain the steps? Also, I find myself really struggling with regular expressions. It would have taken one day for me to come up with what you have above. Do you have any tips on how I can improve my skills with regex?
Comment: @watchtower I updated the post.  Hope it helps.  You can also check http://www.regular-expressions.info/tutorial.html
Comment: Thanks again for your help. Do you think we could do the same using `lapply` i.e. without using regex?
Comment: @watchtower You can loop over the `Divisions` and then assign it, but I would use a `for` loop for assignment.
Comment: Thanks. I wrote this: `l<-lapply(Divisions,function (x) {sort(unique(append(grep(x,DF$S.Name,ignore.case = TRUE),grep(x,DF$S6,ignore.case = TRUE))))})` but I don't know how to substitute values back into the data.frame and assign priority. Any help would be greatly appreciated.


wxPython need to add scrollbar to StaticBox; is this possible?

Question: I have seen similar questions however none have helped me with my specific problem.
I have a bunch of different StaticBoxes on a wx.Panel.  I dynamically add TextFields to one particular StaticBox.  If I add too many, because the BoxSizer is set to wx.VERTICAL (which is what I want), the Panel extends to an ugly look.  Is it possible to add a scrollbar to a StaticBox?  The only scrollable objects I have found are wx.Panel and wx.Window.
Answer: Why don't you put the StaticBox in a ScrolledPanel? That would work perfectly. Here's a simple example:
import wx
import wx.lib.scrolledpanel as scrolled

########################################################################
class MyPanel(scrolled.ScrolledPanel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        super(MyPanel, self).__init__(parent,
                                      style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER)
        self.SetupScrolling()

        box = wx.StaticBox(self, label="Test Box")
        bsizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        for i in range(15):
            txt = wx.TextCtrl(self)
            bsizer.Add(txt, 0, wx.ALL, 5)

        main_sizer = wx.BoxSizer()
        main_sizer.Add(bsizer, 1, wx.EXPAND)
        self.SetSizer(main_sizer)

########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        super(MainFrame, self).__init__(None, title="Static")
        panel = MyPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()

You can use a top level panel and then add a left panel and a right panel as children to the top panel where the right panel would be the scrolled panel instance. That would be one valid approach.
Comment: For some reason I was thinking that a panel was a frame.  Totally screwed me up.  I used a modification of this without setting up the class with the constructor as the TextCtrl's are added dynamically after the mainframe is loaded.  Thank you sir.


Query INFORMATION_SCHEMA.COLUMNS on all databases?

Question: Is there a way to query INFORMATION_SCHEMA.COLUMNS across all databases? It appears that USE db must be specified.
I tried this, but it returns nothing when using PowerShell Invoke-Sqlcmd.
IF DB_ID('db') IS NOT NULL
BEGIN
    SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME LIKE 'BID_BY_CPT_SPECIAL'
    ORDER BY TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,ORDINAL_POSITION
    ;
END

This query is used in a PowerShell script.
$q = @"
DROP TABLE IF EXISTS #Temp;
SELECT DatabaseName=cast('' as varchar(100))
     , TABLE_NAME
     , COLUMN_NAME
     , DATA_TYPE
     , ORDINAL_POSITION
 Into  #Temp
 FROM INFORMATION_SCHEMA.COLUMNS
 Where 1=0

Declare @SQL varchar(max) = '
USE ? ;

Insert Into #Temp
SELECT DatabaseName=''?''
     , TABLE_NAME
     , COLUMN_NAME
     , DATA_TYPE
     , ORDINAL_POSITION
 FROM INFORMATION_SCHEMA.COLUMNS
 WHERE TABLE_NAME LIKE ''BID_BY_CPT_SPECIAL''
 ORDER BY TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,ORDINAL_POSITION
'

EXEC sp_MSforeachdb @SQL

Select * From #Temp
"@

foreach ($db in $DatabaseInstances) {
    $r = Invoke-Sqlcmd -Query $q -ServerInstance $db

=== Update
This query is working with Invoke-Sqlcmd.
$q = @"
DROP TABLE IF EXISTS #Temp;
SELECT DatabaseName=cast('' as varchar(100))
    ,TABLE_NAME
    ,COLUMN_NAME
    ,DATA_TYPE
    ,ORDINAL_POSITION
    ,CHARACTER_MAXIMUM_LENGTH
    ,NUMERIC_PRECISION
    ,NUMERIC_SCALE
    ,IS_NULLABLE
Into  #Temp
FROM INFORMATION_SCHEMA.COLUMNS
Where 1=0

Declare @SQL varchar(max) = '
USE ? ;

Insert Into #Temp
SELECT DatabaseName=''?''
    ,TABLE_NAME
    ,COLUMN_NAME
    ,DATA_TYPE
    ,ORDINAL_POSITION
    ,CHARACTER_MAXIMUM_LENGTH
    ,NUMERIC_PRECISION
    ,NUMERIC_SCALE
    ,IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
 WHERE TABLE_NAME LIKE ''$TableName''
 ORDER BY TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,ORDINAL_POSITION
'

EXEC sp_MSforeachdb @SQL

Select * From #Temp
"@

Answer: Take a look into sp_MSforeachdb
This will collect data into one Temp table.   Personally, I would move your WHERE to the final SELECT
Example
SELECT DatabaseName=cast('' as varchar(100))
     , TABLE_NAME
     , COLUMN_NAME
     , DATA_TYPE
     , ORDINAL_POSITION
 Into  #Temp
 FROM INFORMATION_SCHEMA.COLUMNS
 Where 1=0

Declare @SQL varchar(max) = '
USE ? ;

Insert Into #Temp
SELECT DatabaseName=''?''
     , TABLE_NAME
     , COLUMN_NAME
     , DATA_TYPE
     , ORDINAL_POSITION
 FROM INFORMATION_SCHEMA.COLUMNS
 WHERE TABLE_NAME LIKE ''BID_BY_CPT_SPECIAL''
 ORDER BY TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME,ORDINAL_POSITION
'

EXEC sp_MSforeachdb @SQL

Select * From #Temp

Comment: Be careful using sp_MSforeachdb. It will sometimes skip databases. https://www.mssqltips.com/sqlservertip/2201/making-a-more-reliable-and-flexible-spmsforeachdb/ I have seen this happen myself and never figured out why.
Comment: @SeanLange I've seen that mentioned before.  I have yet to witness it myself.  However, I am keeping this in my toolbox https://www.mssqltips.com/sqlservertip/2201/making-a-more-reliable-and-flexible-spmsforeachdb/
Comment: This works well in SSMS and sqlcmd. But, it returns nothing from `Invoke-Sqlcmd`. Any ideas?
Comment: @JohnCappelletti - It is added to the question. It is all one command.
Comment: @lit Really not a PS guy, but I'll take a harder look into it.
Comment: Here is another great article on this topic from Gianluca Sartori. https://spaghettidba.com/2011/09/09/a-better-sp_msforeachdb/ He references Aaron Bertrand's article but it is the old link.
Comment: I got this to work. I don't know exactly what I did wrong earlier. I will post the working query in the question. Thanks.


Rename directory name having junk characters in AIX

Question: 4000 - LCL**\010**PL CPS Test Bank A
directory name having some junk chars as shown above and I am unable to rename it and unable to go neither  inside this directory nor copy contents
Please help me to rename directory name having junk in AIX/UNIX server
Answer: Use some script like this:
<code>#!/bin/sh

for i in "$@"; do
    To="$(printf '%s' "$i" | tr '\n\r' '_' | sed 's/[^A-Za-z0-9.-_]/_/g')"
    mv -- "$i" "$To"
done
</code>
When call it, use a file-mask as parameter, eg:
<code>./myscript *LCL*
</code>


Please help with the rank-1 matrix eigenvector

Question: Consider the eigenvector problem:
$Aw = \lambda B w$.
If the rank of A is at most 1 (assume B is the full rank matrix), then there is at most one eigenvector corresponding to the nonzero eigenvalue. Is that correct?
If so, what if the problem of $Bw = \lambda A w$? Does this still only has one eigenvector corresponding the nonzero eigenvalue?
Answer: If $B$ is an invertible  matrix, $A w = \lambda B w$ is equivalent to
$B^{-1} A w = \lambda w$, i.e. $\lambda$ is an eigenvector of $B^{-1} A$, and $B^{-1} A$ has the same rank as $A$.  A matrix of rank $1$ can only have at most one nonzero eigenvalue, and the eigenvectors for this eigenvalue form a one-dimensional subspace (it's not correct to say "one eigenvector", because
if $v$ is an eigenvector then so is $t v$ for any nonzero scalar $t$).
Comment: There is no $B A^{-1}$, because $A$ is not invertible (if this is in dimension $> 1$).
Comment: Thanks for the answering. Then what is the rank of $BA^{-1}$?


Let H be a subgroup of G. Let $g_1,g_2\in G$. Prove that the following conditions are equivalent

Question: Let H be a subgroup of G. Let $g_1,g_2\in G$. Prove that the following conditions are equivalent:
i.$g_1H=g_2H$
ii.$Hg_1^{-1}=Hg_2^{-1}$
iii.$g_2\in g_1H$
iv.$g_1^{-1}g_2\in H$
This was a question given in a book. However, I am not been able to get how can we say that i. implies ii.. If $g_1H=g_2H$, then we can say for, $h_1,h_2\in H$, we have $g_1h_1=g_2h_2$ and hence,  $g_2=g_1h_1h_2^{-1}$. Now, $h=h_1h_2^{-1}\in H$ and thus, $g_2=g_1h$ . So, we can say $g_2\in g_1H$. Now, if $g_2=g_1h$, then $g_1^{-1}g_2=h\in H$. So, we can say that, $g_1^{-1}g_2=\in H$. Thus , we see that i.implies iii. and iii. implies iv.. But how to prove i. implies ii. ? Also then if we prove  i. implies ii. , then can we say ii. imples iii. since i. imples ii. ?  How to show that ii. implies iii. ? If we can show that i. implies ii. and ii. implies iii. , I think we can say that all the following conditions are equivalent, right? I think we dont need to show that ii. implies i. (which may not be the case also) as the question asks us to show that i,ii,iii,iv are equivalent .But how to prove it ? I am not quite getting it.
Comment: Which book are you referring to?
Answer: $$g_{1}H=g_{2}H \implies  g_{1}=g_{1}e=g_{2}h \implies g_{1}^{-1}=h^{-1}g_{2}^{-1} $$
So $$\forall k\in H, kg_{1}^{-1}=kh^{-1}g_{2}^{-1}\implies Hg_{1}^{-1} \subset  Hg_{2}^{-1}$$
In the same way u can prove the reverse inclusion.
Comment: @belkam abderrahmane When we proved $g_1^{-1}\in Hg_2^{-1}$, we have $g_1^{-1}\in Hg_1^{-1}$. Now, we know that any two right cosets are either distinct or equal,  so we can directly conclude from there $Hg_1^{-1}=Hg_2^{-1}$. This can be a way , right? But then we need to show ii implies iii , to make it complete , right?
Answer: $(i) \to (iii)$: We have $g_1 H = g_2 H$ which implies that $g_1 h = g_2 \hat h$ for some $h,\hat h \in H$. Then we know that $g_1 h \hat h^{-1} = g_2$, which implies that $g_2 \in g_1H$.
$(iii) \to (iv)$: We have $g_2 = g_1 h$ for some $h \in H$. Hence $g_1^{-1} g_2 = h$ and so $g_1^{-1} g_2 \in H$.
$(iv) \to (ii)$: Note that $H = H (g^{-1}g_2)$ and so $H g_2^{-1} = H g_1^{-1}$.
$(ii) \to (i)$: We have $h g_1^{-1} = \hat h g_2^{-1} \implies g_1 h^{-1} = g_2 \hat h^{-1} \implies g_1 H = g_2H$.
Comment: But shouldn't we prove ii implies iii, also ?
Comment: Not sure, I understand why. Didn't we show equivalence $(i)\to(iii)\to(iv)\to(ii)\to(i)$?
Comment: I can prove i implies ii now, but I really don't get how to prove ii. imples i. ? Thank you!...


Contar Curtidas Firebase Android

Question: Então estou com um projeto aqui de um appblog,

Preciso de ajuda agora pra conseguir contar as curtidas.
<code>    mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");

  }
        });

        viewHolder.mLikeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mProcessLike = true;

                    mDatabaseLike.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {

                              if (mProcessLike ){

                                    if(dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())){

                                        mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
                                        mProcessLike = false;
                                    } else {

                                         mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue("RandomValue");
                                        mProcessLike = false;
                                    }

                        }}

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                }
        });

    }
};
</code>

http://pastebin.com/JKCa4feS
RESOLVIDO
<code>    mDatabaseLike.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Log.e(String.valueOf(dataSnapshot.child(post_key)),dataSnapshot.getChildrenCount() + "");

            for (DataSnapshot snap: dataSnapshot.getChildren()) {
                //Log.e(String.valueOf(snap.child(currentUserId).toString()),snap.getChildrenCount() + "");
                mCurtidas.setText(dataSnapshot.child(currentUserId).getChildrenCount() + "");

            }}
                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
</code>
Comment: Que problema esta tendo?
Comment: Problema nenhum, eu não sei como contar as curtidas, o códiogo ta tudo certo, mais não tem nenhuma linha sobre como contar as curtidas...
Comment: Você vai precisar usar um listener, assim que abrir a activity pra saber se ja foi curtido.

Caso sim, o click retirar, caso não, curte.

No seu print parece que esta funcionando.

Se você esta em duvida sobre a quantidade de curtidas. Você só precisa pegar o "ramo" Likes e fazer um size();
Comment: ok, a parte do botão ta certo, já está clicável.
Comment: Você tem noção de como eu faço isso de modo que conte a .child do firebase?
Comment: Você deve ter uma classe, que encapsula o conteudo do post do blog.
Adiciona uma variavel, que conta os likes. Pode ser um list ou um int mesmo.

https://firebase.google.com/docs/database/android/start/
Answer: Você deve ter uma classe, que encapsula o conteúdo do post do blog.
Adiciona uma variavel, que conta os likes. Pode ser um list ou um int mesmo.
No listener do database, você captura o conteúdo que ta no banco.
<code>   // Read from the database
    myRef.addValueEventListener(new ValueEventListener() {
   @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
    // This method is called once with the initial value and again
    // whenever data at this location is updated.
    SuaClasse  class = dataSnapshot.getValue(SuaClass.class);

    }

    @Override
     public void onCancelled(DatabaseError error) {
    // Failed to read value
    Log.w(TAG, "Failed to read value.", error.toException());
   }
  });
</code>
https://firebase.google.com/docs/database/android/start/

Contar Curtidas Firebase Android


Is it possible to give a language prefix to all the nodes without third-party modules?

Question: I have a site with about 500 pages, all in Hebrew. I want to change all the all paths to include the language prefix.
This would be the first stage in turning this site into a sub-site (with a sub-domain).
Is this possible without third-party modules?
Comment: Pathauto is just for nice URLs. You're talking about changing routes themselves.
Comment: Maybe, this answer will help you ? Here is described the solution for Drupal 8, how to change urls on your site. http://drupal.stackexchange.com/questions/190232/how-do-i-implement-the-equivalent-of-hook-url-inbound-alter/190279#190279
Comment: You can do this by writing [rewrite rule](http://httpd.apache.org/docs/2.0/misc/rewriteguide.html) in the .htaccess file located in the Drupal Root directory. Check [this answer](https://stackoverflow.com/a/29880755).
Comment: Since your requirement is for a sub-site (with a sub-domain), it's better to configure the site with a sub-domain that uses *he* as prefix.
In order to create a multi-site, follow the steps given in the first answer for https://drupal.stackexchange.com/questions/223525/drupal-8-multi-sites-in-subdirectories-not-working.
Answer: These are the rewrite rules to add in the .htaccess file located in the Drupal root directory.
RewriteEngine on
RewriteCond %{REQUEST_URI} !/he
RewriteRule ^(.*) http://www.domain.com/he%{REQUEST_URI} [L,R=301]

Answer: Since you are making this specific to a language prefix, I would suggest using the Language module, since it is part of Drupal core and it's easy to manage.
Enable the Language module, which isn't enabled by default, unless you made your site explicitly multilingual, your content is in Hebrew, but your site default language is English.
You need two languages for the language prefixing to work. On /admin/config/regional/language, add a second language. This will enforce the use of language prefixes.
On /admin/config/regional/language/detection, configure the URL detection method; this should be in fact activated and preceding all other options.
Set the path prefix for the default language to he.
Save and clear the cache. All your Drupal paths now will be prefixed by he.
The existing URLs are still valid. A couple of clicks into navigation and your URLs should be prefixed with he.
Answer: If you wish to have different subdomains for different languages, I think Drupal should be able to detect the language code from the sub-domain and there should be no necessity for adding URL prefixes. You can take the first step by setting up the sub-domain he.example.com and redirecting requests from your main site to the he subdomain until you add other languages and a language selection dialog in example.com (without sub-domains).
Hello! I can see the following solutions:
Solution 1: Altering node paths

Using pathauto (which you do not wish to use) you can set the node prefix to /he/.
Running a one-time script to add a prefix to all node URL aliases and in the future adding the /he prefix manually.

Solution 2: .htaccess
Using .htaccess to re-write all URLs to interpret /he/* URLs as /*. But this might also apply the prefix to other paths - doing this only for nodes might be difficult depending on their existing URLs.
RewriteEngine on
RewriteCond %{REQUEST_URI} !/he
RewriteRule ^(.*) http://www.domain.com/he%{REQUEST_URI} [L,R=301]

NOTE: Code extract copied from Ashish Deynap's answer.
But I've heard that it is better to avoid .htaccess redirects as far as possible because:

The .htaccess might be updated with Drupal versions.
The rules in .htaccess are evaluated for every request! The more rules you have, the more time the server spends evaluating them.

Hope it helps.


How do I programmatically translate a string?

Question: I am working on one custom module to alter the fields labels of user login form for visitors. I created a module to alter the labels in the user login form. The French language is enabled on the setup.
I am trying to translate the field labels on the user login form to French. I am using the following approach in a module.
I have included the namespace with use Drupal\Core\StringTranslation.
After that, I have debugged the $form variable inside hook_form_alter().
From this debugged variable, I am trying to translate the filed label 'E-mail' to French.
function hook_form_alter ({here goes all the parameters of alter hooks}){
  $form['name']['#title'] = t('E-mail');
}

I am not able to see the translated Email field label on the user login form.
Am I missing anything? What should I do to translate the strings using hook_form_alter()?
Comment: Does this answer your question? [Way to programmatically add string translations?](https://drupal.stackexchange.com/questions/214803/way-to-programmatically-add-string-translations)
Answer: you have find and add your translation string here : admin/config/regional/translate
Comment: Thanks, this is working. But If i want to do it by including name space then which one I can include?


Is $C_0^{\infty}(\Omega)\cap H^{m,p}(\Omega)$ dense in $H^{m,p}(\Omega)$?

Question: Let $\Omega\subset\mathbb{R}^n$ be an open set. Let $H^{m,p}(\Omega)$ denote the Sobolev-space of at most $m$ times weakly differentiable functions whose weak derivatives are all $L^p$. Further let $C^{\infty}(\Omega)$ and $C_0^{\infty}(\Omega)$ denote respectively the smooth functions on $\Omega$ in the former case, and those who have compact support in the latter case.
There is a theorem that states that $C^{\infty}(\Omega)\cap H^{m,p}(\Omega)$ is dense in $H^{m,p}(\Omega)$. I'm wondering now if $C_0^{\infty}(\Omega)\cap H^{m,p}(\Omega)$ is dense in $H^{m,p}(\Omega)$.
Is this true or false? Could you please give me hints how to proove it or a link to literature on this?
Thank you in advance.
Answer: In general, it is not. For $\Omega = (0,1)$, how can you approximate the constant function $u=1$ by elements with compact support?
Comment: I don't know how. Do you have a proof that it is not possible to do so?
Comment: Well, in dimension one, $H^1$-functions are continuous.
Comment: I don't see how this helps...
Comment: If a sequence converges in $H^1(a,b)$ then it converges uniformly in $(a,b)$.
Answer: It can't happen in any bounded open set $\Omega$ as the constant function equal to $1$ is in $H^{m,p}(\Omega)\cap C^{\infty}(\Omega)$ for $m,p$, but cannot be approach by a sequence of functions $\{\phi_n\}$ of $C_0^{\infty}(\Omega)$ for the norm $W^{m,p},m\geq 1$. Otherwise, we would have $\nabla\phi_n\to 0$ in $L^p$ so by Poincaré's inequality $\phi_n\to 0$ in $L^p$, a contradiction.


Como pegar o retorno de uma procedure para saber se teve alguma linha afetada?

Question: Minha dúvida é saber se teve alguma linha afetada na execução dessa procedure e armazenar o resultado em uma variável do tipo int.
Caso for = 0, parar o processo.
Caso for > 0, seguir com o processo.
Tenho os seguintes códigos:
Controller:
   public void InserirSaldoBonusExtrato(PCINET.pciPedidos.PedidoVenda pedido)
        {
            try
            {
                Extrato extrato = new Extrato(config);
                extrato.Cliente = pedido.PedCliente;
                extrato.Valor = pedido.PedValor;
                extrato.Ciclo = pedido.PedCiclo;
                extrato.TpOperCodigo = 9;
                extrato.TpOperNome = "Pgtopedido";
                extrato.Descricao = "Pagamento do pedido " + pedido.PedNumero + " com bônus";
                extrato.Indicante = 0;
                extrato.Pendente = "N";
                extrato.InserirSaldoBonusExtrato();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

Model:
 public void InserirSaldoBonusExtrato()
    {
        try
        {
            new ExtratoDB(config).InserirSaldoBonus(this);
        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

Dapper(data):
   public void InserirSaldoBonus(Extrato extrato)
    {

        try
        {
            var db = new Data<Extrato>(config);
            string query = @"sp_InsereSaldoBonusExtrato @Cliente, @Valor, @Ciclo, @TpOperCodigo, @TpOperNome, @Descricao, @Indicante, @Pendente";
            db.Executar(query, extrato);

        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

Answer: Existem dois pontos para verificar:
1. A stored procedure está retornando o número de registros afetados?
Você deve executar a procedure e se certificar que ela retorna o número de registros afetados. Por exemplo, em SQL Server, deve ser setado SET NOCOUNT OFF para executar a procedure, senão não é retornado. Você pode também retornar o valor por si próprio, como por exemplo, em SQL Server usando a variável @@ROWCOUNT que retorna o número de linhas afetadas
2. Está tratando o retorno?
No seu código, a linha que executa a procedure é essa:
db.Executar(query, extrato) mas não vejo o retorno dessa chamada, algo como var total = db.Executar(query, extrato). Se não tratar o retorno assim, ou com um parâmetro de output, mesmo que a procedure retorne você não vai ter esse valor.