Display data from text file in html using httpclient

Question: I am working on an angular project. I have a text file which that is red using node js. The content is then stored in a url. I need to apply an http get method to get the data from the server and display it on the client side.
I tried the following code but when I hit the button I don't get the file data displayed. What is the problem?
src/app/file.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ConfigService {
    constructor(private http: HttpClient) {}
    getFile() {
        return this.http.get('http://localhost:3000/hello');
    }
}

src/app/app.component.html

    <button (click)="getFile()">get data</button>

Answer: You have a few problems. First, you're not subscribing to the Observable, so nothing is going to happen. Second, you also need to handle the Observable, you're not. Third, you have not defined a place to inject the data once received.
...

    @Injectable()
    export class ConfigService {
        data = {};

        constructor(private http: HttpClient) { }

        getFile() {
            this.http.get('http://localhost:3000/hello').subscribe(result => {
               this.data = result });
        }

    }

then you need somewhere to display it,

    <button (click)="getFile()">get data</button>

{{ data }}

Comment: JDunken I tried your code but I got two problems. The first one is that I can't initialise the variable data outside of the Class. And secondly I don't get any data displayed in the front page of my application.
Comment: sorry, my mistake, that should have been inside the class. Edited answer.
Comment: Even when I moved data inside the class, I still don't get any data displayed. I don't know if something is missing in the code.
Comment: If you have a simple example that can help me on stackblitz or any other online editor please send it. Thank you.
Comment: I can't use stackblitz or similar at work due to security settings. If you have one let me know and I can take a look later.


Criando pasta que não apaga ao desinstalar para salvar backup - Flutter

Question: Estou desenvolvendo um sistema de backup usando path_provider, com o seguinte código.
  // Busca o local que esta o arquivo
  Directory documentsDirectory = await getApplicationDocumentsDirectory();
  final path = join(documentsDirectory.path, 'base.db');
  File sourceFile = File(path);
  List<int> content = await sourceFile.readAsBytes();

  // Define diretório que o arquivo de backup será salvo
  final targetDir = await getExternalStorageDirectory();
  final targetDirFolder = Directory('${targetDir.path}/Backup/');

  final targetPath = join(targetDir.path, 'backup-driive.db');
  File targetFile = File(targetPath);
  await targetFile.writeAsBytes(content, flush: true);

Com esse código consigo salvar o backup nesta pasta: "/storage/emulated/0/Android/data/br.com.app.combustivel/files/arquivodebackup.db", porem quando o aplicativo é desinstalado essa pasta é removida e não serve de nada o "backup", de qual forma posso salvar esse arquivo na pasta do armazenamento interno do celular onde não é apagado, andei pesquisando porem não achei nada.
Comment: Você tem que mudar a pasta onde está salvando o backup, quando o app é desinstalado o android remove a pasta br.com.app.combustivel e tudo que estiver nela. Outra alternativa seria configurar o auto backup, https://developer.android.com/guide/topics/data/autobackup
Answer: Você pode salvar na pastar Downloads do Android. Veja abaixo como salvar um arquivo nessa pasta. Lembrar que essa pasta é livre, o usuário terá acesso e poderá apagar o backup. Você poderá nomear o arquivo com o nome do seu app e data do backup.
Veja no link original
Dependências
dio: ^3.0.0
path_provider: ^1.3.0
simple_permissions: ^0.1.9
file_utils: ^0.1.3

Permissões
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Código
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:async';
import 'package:simple_permissions/simple_permissions.dart';
import 'package:file_utils/file_utils.dart';
import 'dart:math';

void main() => runApp(Downloader());

 class Downloader extends StatelessWidget {
 @override
 Widget build(BuildContext context) => MaterialApp(
       title: "File Downloader",
      debugShowCheckedModeBanner: false,
      home: FileDownloader(),
      theme: ThemeData(primarySwatch: Colors.blue),
     );
 }

class FileDownloader extends StatefulWidget {
@override
_FileDownloaderState createState() => _FileDownloaderState();
}

class _FileDownloaderState extends State<FileDownloader> {

final imgUrl = "https://images6.alphacoders.com/683/thumb-1920-683023.jpg";
bool downloading = false;
var progress = "";
var path = "No Data";
var platformVersion = "Unknown";
Permission permission1 = Permission.WriteExternalStorage;
var _onPressed;
static final Random random = Random();
Directory externalDir;

@override
void initState() {
  super.initState();
  downloadFile();
}

Future<void> downloadFile() async {
  Dio dio = Dio();
  bool checkPermission1 =
      await SimplePermissions.checkPermission(permission1);
  // print(checkPermission1);
  if (checkPermission1 == false) {
    await SimplePermissions.requestPermission(permission1);
    checkPermission1 = await SimplePermissions.checkPermission(permission1);
  }
  if (checkPermission1 == true) {
    String dirloc = "";
    if (Platform.isAndroid) {
      dirloc = "/sdcard/download/";
    } else {
      dirloc = (await getApplicationDocumentsDirectory()).path;
    }

    var randid = random.nextInt(10000);

    try {
      FileUtils.mkdir([dirloc]);
      await dio.download(imgUrl, dirloc + randid.toString() + ".jpg",
          onReceiveProgress: (receivedBytes, totalBytes) {
        setState(() {
          downloading = true;
          progress =
              ((receivedBytes / totalBytes) * 100).toStringAsFixed(0) + "%";
        });
      });
    } catch (e) {
      print(e);
    }

    setState(() {
      downloading = false;
      progress = "Download Completed.";
      path = dirloc + randid.toString() + ".jpg";
    });
  } else {
    setState(() {
      progress = "Permission Denied!";
      _onPressed = () {
        downloadFile();
      };
    });
  }
}

@override
Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(
      title: Text('File Downloader'),
    ),
    body: Center(
        child: downloading
            ? Container(
                height: 120.0,
                width: 200.0,
                child: Card(
                  color: Colors.black,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      CircularProgressIndicator(),
                      SizedBox(
                        height: 10.0,
                      ),
                      Text(
                        'Downloading File: $progress',
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                ),
              )
            : Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(path),
                  MaterialButton(
                    child: Text('Request Permission Again.'),
                    onPressed: _onPressed,
                    disabledColor: Colors.blueGrey,
                    color: Colors.pink,
                    textColor: Colors.white,
                    height: 40.0,
                    minWidth: 100.0,
                  ),
                ],
              )));
  }

Comment: Pelo que entendi você salva os dados através do `Dio`, que faz um download de um aquivo, mas no caso da pergunta, é um arquivo local que ele quer fazer backup, ele não vai conseguir usar o `Dio`. E outra, você setou fixo o caminho `"/sdcard/download/"` nem sempre o usuário vai ter um _sdCard_...
Comment: A resposta seria para salvar na pasta downloads como opção para que o backup não seja removido. Ele pode usar o `"plugin ext_storage 1.0.3"` e a achar a pasta do downloads.
`ExtStorage.getExternalStorageDirectory();`
Comment: Entendi, seria interessante então você ter citado tal package em sua resposta também... Mas é um bom exemplo para ele seguir!
Answer: Você já tentou utilizar o comando getLibraryDirectory()?
De acordo com o que está descrito no fonte do package, esse comando retorna um diretório que serve para armazenar dados persistentes e para backups, sendo que também é invisível para o usuário.

/// Path to the directory where application can store files that are persistent,
/// backed up, and not visible to the user, such as sqlite.db.
///
/// On Android, this function throws an [UnsupportedError] as no equivalent
/// path exists.
Future<Directory> getLibraryDirectory() async {
  final String path = await _platform.getLibraryPath();
  if (path == null) {
    return null;
  }
  return Directory(path);
}

Comment: Vou tentar daqui a polco atualizo aqui
Comment: Acabei me esquecendo de atualizar, mas essa solução no android lança um erro, de acordo com a documentação só funciona em dispositivos IOS.


mat-table sorting não funciona no Angular

Question: Estou tentando fazer sorting das minhas colunas com o material table sorting, porém  eu clico no sort e não acontece nada.
Meu template:

    <ng-container matColumnDef="indice">
       indice
       {{element.indice}}
    </ng-container>

    <ng-container matColumnDef="tipo">
       Tipo
       {{element.tipo}}
    </ng-container>

    <ng-container matColumnDef="data">
       Data
       {{element.data}}
    </ng-container>

    <ng-container matColumnDef="usuario">
         Usuario
         {{element.usuario}}
    </ng-container>

    <ng-container matColumnDef="acao">
       Ação
       {{element.acao}}
    </ng-container>

    <ng-container matColumnDef="detalhes">
       Detalhes

    </ng-container>

Meu ts:
colunasTabela:string[] = ['indice', 'tipo', 'data', 'usuario', 'acao', 'detalhes']

  dadosTabela:any[] = [
    {indice: 1, tipo: 'Exclusão', data: '11/09/2018', usuario: 'Renato', acao: 'Exclusão de operador', detalhes: 'Detalhe xxxxx'},
    {indice: 2, tipo: 'Edição', data: '15/02/2019', usuario: 'Jessica', acao: 'Edição de produto', detalhes: 'Detalhe xxxxx'},
    {indice: 3, tipo: 'Exclusão', data: '11/09/2018', usuario: 'Renato', acao: 'Exclusão de operador', detalhes: 'Detalhe xxxxx'},
    {indice: 4, tipo: 'Exclusão', data: '11/09/2018', usuario: 'Renato', acao: 'Exclusão de operador', detalhes: 'Detalhe xxxxx'},
  ];

  @ViewChild(MatSort) sort: MatSort;
  dataSource = new MatTableDataSource(this.dadosTabela);

  constructor() {
    this.dataSource.sort = this.sort;
  }

Estou importando no meu modulo tanto o MatSortModule quanto o MatTableModule, no app.module também, ambos depois do browser module/commom module...
Alguma ideia?
Answer: Olá!
Tente realizar a seguinte alteração, ao invés de instanciar o sort dentro do constructor utilize o mesmo dentro do ngAfterViewInit(). Realizei esta alteração aqui e a mesma atendeu corretamente. Verifique também seu app.module e veja se o mesmo está importando corretamente o MatSortModule.
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatSort, MatTableDataSource } from '@angular/material';

@Component({
  selector: 'app-tabela',
  templateUrl: './tabela.component.html',
  styleUrls: ['./tabela.component.scss']
})

export class TabelaComponent implements OnInit {

  colunasTabela: string[] = ['indice', 'tipo', 'data', 'usuario', 'acao', 'detalhes'];

  dadosTabela: any[] = [
    {indice: 1, tipo: 'Exclusão', data: '11/09/2018', usuario: 'Renato', acao: 'Exclusão de operador', detalhes: 'Detalhe xxxxx'},
    {indice: 2, tipo: 'Edição', data: '15/02/2019', usuario: 'Jessica', acao: 'Edição de produto', detalhes: 'Detalhe xxxxx'},
    {indice: 3, tipo: 'Exclusão', data: '11/09/2018', usuario: 'Renato', acao: 'Exclusão de operador', detalhes: 'Detalhe xxxxx'},
    {indice: 4, tipo: 'Exclusão', data: '11/09/2018', usuario: 'Renato', acao: 'Exclusão de operador', detalhes: 'Detalhe xxxxx'},
  ];

  @ViewChild(MatSort) sort: MatSort;
  dataSource = new MatTableDataSource(this.dadosTabela);

  constructor() {}

  // tslint:disable-next-line:use-life-cycle-interface
  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }

  ngOnInit() {
  }

Espero ter ajudado :)


Deadlocks in Groovy shell evaluations

Question: I am using Groovy 1.7.8. and have written a Groovy DSL which I execute concurrently on different domain objects.
Of late, I have started facing deadlocks under heavy concurrency when DSLs are compiling/executing concurrently.
I am compiling/executing Groovy DSL at runtime using:
Script s = compileScript(dsl)
def binding = new Binding()
binding.setVariable("domainObj", domainObj)
s.setBinding(binding)
s.run()

def Script compileScript(String dsl) {
    def scriptText = getScriptText(dsl)
    def conf = new CompilerConfiguration()
    conf.setScriptBaseClass(GroovyViewExecutionBase.class.getName())
    new GroovyShell(conf).parse(scriptText)
}

Below is the thread dump of deadlocked threads, looking at the thread dumps I feel that Groovy is deadlocking internally when we concurrently compile/execute scripts at runtime.
Deadlock-Participant-1:
at java.beans.PropertyDescriptor.getReadMethod(PropertyDescriptor.java:158)

- waiting to lock <0x00007f41a3363960> (a java.beans.PropertyDescriptor)

at java.beans.Introspector.processPropertyDescriptors(Introspector.java:683)

at java.beans.Introspector.getTargetPropertyInfo(Introspector.java:615)

at java.beans.Introspector.getBeanInfo(Introspector.java:407)

at java.beans.Introspector.getBeanInfo(Introspector.java:164)

- locked <0x00007f41a3358c28> (a java.lang.Object)

at groovy.lang.MetaClassImpl$15.run(MetaClassImpl.java:2940)

at java.security.AccessController.doPrivileged(Native Method)

at groovy.lang.MetaClassImpl.addProperties(MetaClassImpl.java:2938)

at groovy.lang.MetaClassImpl.initialize(MetaClassImpl.java:2921)

- locked <0x00007f429f011268> (a groovy.lang.ExpandoMetaClass)

at groovy.lang.ExpandoMetaClass.initialize(ExpandoMetaClass.java:463)

- locked <0x00007f429f011268> (a groovy.lang.ExpandoMetaClass)

at org.codehaus.groovy.reflection.ClassInfo.getMetaClassUnderLock(ClassInfo.java:166)

at org.codehaus.groovy.reflection.ClassInfo.getMetaClass(ClassInfo.java:182)

at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.getMetaClass(MetaClassRegistryImpl.java:210)

at org.codehaus.groovy.runtime.InvokerHelper.getMetaClass(InvokerHelper.java:751)

at groovy.lang.GroovyObjectSupport.<init>(GroovyObjectSupport.java:32)

at groovy.lang.Script.<init>(Script.java:40)

at groovy.lang.Script.<init>(Script.java:37)

at flipkart.cms.views.core.GroovyViewExecutionBase.<init>(GroovyViewExecutionBase.groovy)

at Script1.<init>(Script1.groovy)

at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)

at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)

at java.lang.reflect.Constructor.newInstance(Constructor.java:513)

at java.lang.Class.newInstance0(Class.java:355)

at java.lang.Class.newInstance(Class.java:308)

at org.codehaus.groovy.runtime.InvokerHelper.createScript(InvokerHelper.java:408)

at groovy.lang.GroovyShell.parse(GroovyShell.java:743)

at groovy.lang.GroovyShell.parse(GroovyShell.java:770)

at groovy.lang.GroovyShell.parse(GroovyShell.java:761)

at groovy.lang.GroovyShell$parse.call(Unknown Source)

at cms.views.core.GroovyDSLViewComputer.compileScript(GroovyDSLViewComputer.groovy:85)

==================
Deadlock-Participant-2:
    at java.beans.Introspector.getPublicDeclaredMethods(Introspector.java:1277)
- waiting to lock <0x00007f41a3358c28> (a java.lang.Object)

at java.beans.Introspector.internalFindMethod(Introspector.java:1312)

at java.beans.Introspector.findMethod(Introspector.java:1383)

at java.beans.Introspector.findMethod(Introspector.java:1363)

at java.beans.PropertyDescriptor.getReadMethod(PropertyDescriptor.java:179)

- locked <0x00007f41a3363960> (a java.beans.PropertyDescriptor)

at groovy.lang.MetaClassImpl.applyPropertyDescriptors(MetaClassImpl.java:2215)

at groovy.lang.MetaClassImpl.setupProperties(MetaClassImpl.java:1995)

at groovy.lang.MetaClassImpl.addProperties(MetaClassImpl.java:2950)

at groovy.lang.MetaClassImpl.initialize(MetaClassImpl.java:2921)

- locked <0x00007f42a12972b8> (a groovy.lang.ExpandoMetaClass)

at groovy.lang.ExpandoMetaClass.initialize(ExpandoMetaClass.java:463)

- locked <0x00007f42a12972b8> (a groovy.lang.ExpandoMetaClass)

at org.codehaus.groovy.runtime.HandleMetaClass.replaceDelegate(HandleMetaClass.java:66)

at org.codehaus.groovy.runtime.HandleMetaClass.setProperty(HandleMetaClass.java:91)

at org.codehaus.groovy.runtime.InvokerHelper.setProperty(InvokerHelper.java:179)

at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.setProperty(ScriptBytecodeAdapter.java:483)

at flipkart.cms.views.core.GroovyViewExecutionBase.setupAttrProperties(GroovyViewExecutionBase.groovy:60)

at flipkart.cms.views.core.GroovyViewExecutionBase$setupAttrProperties$0.callCurrent(Unknown Source)

at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:44)

at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)

at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:149)

at cms.views.core.GroovyViewExecutionBase.computeView(GroovyViewExecutionBase.groovy:32)

==================
Any ideas how I can fix/workaround this?
Answer: Posted this on groovy-user forum and looks like the deadlocks are caused because of synchronization issues in java 6's java.beans.Introspector class which apparently have been fixed in Java 7. Also received a backport of these classes for java 6 and am testing the backported classes to reproduce the deadlocks.
More details here:
http://groovy.329449.n5.nabble.com/Groovy-deadlocks-when-executing-DSL-from-GroovyShell-td5709889.html

Deadlocks in Groovy shell evaluations


In parallel.for share value more then one

Question: Here is problem.
long sum = 0;
Parallel.For(1, 10000, y => { sum1 += y;} );

Solution is ..
Parallel.For<int>(0, result.Count, () => 0, (i, loop, subtotal) =>
{
    subtotal += result[i];
    return subtotal;
},
(x) => Interlocked.Add(ref sum, x)
);

if there are two parameters in this code. For example
long sum1 = 0; long sum2 = 0;
Parallel.For(1, 10000, y => { sum1 += y; sum2=sum1*y; } );

what will we do ? i am guessing that have to use array !
int[] s=new int[2];
Parallel.For<int[]>(0, result.Count, () => s, (i, loop, subtotal) =>
{
    subtotal[0] += result[i];
    subtotal[1] -= result[i];
    return subtotal;
},
(x) => Interlocked.Add(ref sum1, x[0])
//but how about sum2 i tried several way but it doesn't work.
//for example like that
//(x[0])=> Interlocked.Add (ref sum1, x[0])
//(x[1])=> Interlocked.Add (ref sum2, x[1]));

);
Comment: I don't understand what this question is actually asking. Can you clarify?
Answer: I'm not sure that I can solve your problem, because I don't really know what it is. But there's a good reason that Parallel.For doesn't easily support accumulators like this: because it's ridiculous to attempt to parallelize a simple operation with side-effects.
Parallel.For is for parallelizing relatively expensive operations that don't have side effects that depend on each other. A regular for loop (or Accumulate) is the right thing to do here.
Comment: how can we add share variables while using "parallel.for".
It is very easy to understand in this case one share variable in above code. But more then one in this case how to do ?
There is one method that "locked" in C#.
example:

static readonly object stateLock = new object();

 lock (stateLock)

                {
                    variable1
                    variable2
                }
But i thought it is not good way to handle this problem.
Comment: Sharing variables with `Parallel.For` should be trivial--ordinary closures do that just fine. *Updating* variables is what's tricky, but the point is that if you're updating shared variables you really should think about something other than `Parallel.For`.
Comment: Also i think we can use any parameters on "type of parameter". So i used a massive type of int. But you are telling that the side-effects is ridiculous. Am i was thinking wrong ?
Comment: @user, I could answer your question better if you gave me a concrete example of what you're trying to do. Adding up a bunch of numbers in a loop is a poor usage of `Parallel.For`, and the syntax problems that you're having seem to reflect this.
Comment: Here is ...
private int sum1=0,sum2=0;
...
for(int i=0;i<loop;i++)
        {
            {
                sum1 += (pop1[i].getRating());
                sum2 += (pop2[i].getRating());
            }
        }
...
that's it.
Answer: See Microsoft's sample on thread local variables, for information on updating globals in a parallel for.
Answer: Just expand expression such way:
(x) => { Interlocked.Add(ref sum1, x[0]); Interlocked.Add(ref sum2, x[1]); }


Blues Scale Notes - major 6th?

Question: I've typically always played a blues scale in C as:
C Eb F Gb G Bb
However, in a book I'm reading, the author lists the blues scale for C as:
C D Eb E F Gb G A Bb
Improvising over this new scale definitely gives me a more full sound, and I can get a sense where the second and major third fit in - however, the A always sounds like it takes the sound away from bluesy. Are major 6ths typically only used as passing tones when playing the blues, or should I focus more on this when the harmony shifts from I to IV or V?
Answer: What people usually mean by "blues scale" is the scale that you already knew, i.e. a minor pentatonic scale with an added b5 ("blue note"). What the author of that book refers to as blues scale is actually more like a collection of notes, all of which can be used over a blues progression. The difference with the standard blues scale is that not all of those notes will sound equally good over all three basic chords of the progression (I7, IV7, V7).
With the standard blues scale, even though some notes are pretty dissonant over some chords, none of them sounds really wrong to our ears in a blues context. Even the b5 can always be played as a passing tone. However, the other scale contains notes that would sound really wrong (if played as target notes) over certain chords. E.g. the note E simply sounds wrong over the IV7 chord (F7) because it clashes with the b7 of that chord (Eb), and not in a bluesy way but in a bad way.
There are two ways how you can understand that collection of notes referred to as "blues scale" by the author. It can be seen as the union of the notes of the standard blues scale and the notes of the major pentatonic scale:
blues scale: C Eb F Gb G Bb
major pentatonic: C D E G A
=> C D Eb E F Gb G A Bb
Equivalently, you can arrive at those notes by filling up the C mixolydian scale with the two blue notes from the blues scale (the b3 and the b5):
C mixolydian: C D E F G A Bb  +  Eb Gb => C D Eb E F Gb G A Bb
Again, I wouldn't actually call those notes a scale, because there is no chord over which you can really play that scale. They are rather a collection of notes all of which can be useful at a certain moment in a blues progression. But then you could as well write down the chromatic scale and call it a blues scale, because if you know how to, you can play all 12 notes and make them sound good over a blues progression.
To answer your question about the major 6th, the A in the case of C major: it is not only a passing tone, it actually can be used over all 3 chords. Over the one it is a 13, over the IV it is the 3rd, and over the V it is the 9th. One way to use it, is to distinguish the I from the IV in your solo: you could play some motif over the I containing a Bb (and no E, because this won't work over the IV). Then you repeat that motive over the IV chord, but you exchange the Bb for the A. In this way you make the transition from I to IV very clear. But that's not the only use of the major 6th, because - as mentioned before - it is a valid tension for both I and V chords as well. One example: Larry Carlton start his solo over BP blues on the major 6th (he bends to it from the 5). Check it out here.
Comment: Love this answer, it's rare to see someone who actually understands the blues talk about "blues scales", and a treat to read!  I would probably call it a 6th not a 13, because it's more often used that way, but that's certainly picky. I'd agree with the 9th though (it's not a second)
Comment: Last para: is there a reason you call it 13th rather than 6th (the A over a C scale)?
Comment: @Tim: In that context I view it as a tension over the C7 chord. Then it's usually played above the 7th, so technically it becomes a 13.
Comment: thanks. If it's played on a different instrument, but only a tone away from that b7th note, I suppose it's technically a 6th, but you wouldn't do it on the same instrument. Thus 13th is a better name, generally.
Answer: Two blues scales exist generally. Minor blues as in C, Eb, F, Gb, G, Bb. Major blues as in C, D, Eb, E, G, A. Often players will mix the sets of notes in their playing.
The minor blues is probably used more in guitar playing, due to the pattern of notes easily found because of the way guitars are tuned. The whole solo in Stevie Wonder's Sir Duke is major blues.
The E serves well to sweeten up a line over a C chord; the A works the same over an F chord. I've often wondered what happened to B to go over the dominant G chord.
After all this, any of the twelve notes can fit into a blues (or any other) song. Using the blues notes from ,say, C work over C, but when the chord changes to F, the F blues notes will fit well. Of course, some are the same, but others have a better fit. As in there's no F in C blues, but it's there in F blues: and works well over an F chord!
So, over a typical three chord blues, particularly a major blues, any of the notes from Cmaj/min;Fmaj/min;G maj/min blues scales could be used. That covers, at a guess, all available notes! One wouldn'd use an E over C minor, etc, though.
Comment: Another way to think about this is playing a blues scale built from the tonic (minor blues), and a blues scale  built from the 6th (major blues). Less things to memorize for some. Note that the C major blues scale contains the same notes as the A minor blues scale (A is the 6th of C). Also interesting to hear the difference - the blues scale built from the 6th sounds more "in" the key than the one built from the tonic.
Comment: @MikeHildner - rather like the major and relative minor, then.
Answer: The problem with answering the question "what notes are in the blues scale" is that the archetypal bluesy sound comes from bending and inflecting the notes within certain ranges, so any attempt at defining a blues scale in terms of the 12-note scale is only going to be an approximation.
When soloing, I personally play the blues scale on the guitar as a pseudo-pentatonic something like this:

C
a whole range of notes around Eb, covering the range down to D and up to E.
F, bending up a little (maybe not as far as Gb)
G
Bb, with scope to bend up a little (but maybe more like a quarter tone - not as far as B)

So I don't personally play it with an A in. However, Blues is often about finding "the space between", and I wouldn't deny that with all that flexibility I've outlined (which already allows some major tonality) for that you couldn't add the A and move a little more towards major.
When you get a chord change to F or G (from tonic C) in blues, it's often much more like a transposition to F or G, so you are shifting your whole scale around, not just changing the chord; and yet there are often nods to western harmony too. Again, the space between!

Blues Scale Notes - major 6th?


Derive the distribution of the fraction ${\sum{x_i}}\Big/{\sqrt{\sum{x_i^2}}}$

Question: Suppose ${X_i}$ follows the standard normal distributon N(0,1), what is the distribution of  $\frac{\sum{x_i}}{\sqrt{\sum{x_i^2}}}$
Comment: Assuming $X_i$'s are independent, the vector $\left(\frac{X_i}{\sqrt{\sum X_i^2}}\right)_{1\le i\le n}$ is uniformly distributed on the surface of a unit sphere. So you are looking for the distribution of sum of the components of this vector. Where do you need this?
Comment: Welcome to CV. If this question relates to a class exercise, please see https://stats.stackexchange.com/tags/self-study/info and add the tag to modify the question accordingly.
Comment: That this is a uniform distribution on the sphere is shown at https://stats.stackexchange.com/questions/7977.  The distribution of the components is derived at https://stats.stackexchange.com/questions/85916.  These two threads together therefore (fully) answer the question.
Answer: Hint: you can rewrite $\sum x_i^2 = \bar{x}^2 + \sum (x_i -\bar{x})^2$.
Note that the terms $n\bar{x}^2$ and $\sum (x_i -\bar{x})^2$ are independent chi-squared distributed variables.
Then you can rewrite $Y = \frac{\sum{x_i}}{\sqrt{\sum{x_i^2}}}$ as
$$\begin{array}{}
Y^2 &= &\frac{\left(\sum{x_i}\right)^2}{{\sum{x_i^2}}}\\
&=& \frac{n^2\bar{x}^2}{\bar{x}^2+{\sum{(x_i-\bar{x})^2}}}\\
&=& \frac{n}{1/n+{\left(\sum{(x_i-\bar{x})^2}\right)/(n\bar{x}^2)}}\\
\end{array}$$
And this term in the denominator ${\left(\sum{(x_i-\bar{x})^2}\right)/(n\bar{x}^2)}$ follows an F-distribution
So we have that $n/Y^2-1/n$ follows a F-distribution.
Possibly this can be simplified further (edit: and as Henry noted in the comments you can 'turn it into' a beta distribution. Or... $Y^2$ follows a beta distribution.)
Comment: $Y$ seems to be a symmetric Beta distribution relocated and rescaled to have mean $0$ and variance $1$ (might that be called a *standardised symmetric Beta distribution*?)
Comment: @Henry you are right you can simplify it to a beta distribution. The beta distribution and F-distribution [are related](https://en.m.wikipedia.org/wiki/F-distribution#Properties_and_related_distributions). My answer was mostly to give the hint to rewrite $\sum x_i^2 = \bar{x}^2 + \sum (x_i -\bar{x})^2$.
Answer: Some empirical assertions if there are $n$ terms and $Y_n = \frac{\sum_1^n{X_i}}{\sqrt{\sum_1^n{X_i^2}}}$  with the $X_i$ iid $N(0,1)$:

$Y_n$ has expectation $0$ and variance $1$

$Y_n$ has support on $[-\sqrt{n},\sqrt{n}]$ (unless $n=1$, in which case the support is just $\{-1,1\}$)

The density for $Y_n$ on its support is proportional to $(n-y^2)^{(n-3)/2}$

In particular if $n=3$ this is a uniform distribution; if $n=4$ it is a Wigner semicircle distribution; if $n=2$ it is a version of the arcsine distribution

$\frac{Y_n}{\sqrt{n}}+\frac12$ has a Beta distribution with parameters $\alpha=\frac{n-1}{2}$ and $\beta=\frac{n-1}{2}$; perhaps $Y_n$ could be called a standardised symmetric Beta distribution

As $n$ increases, the distribution of $Y_n$ converges to a standard normal distribution

If $Z_{i,n} = \frac{{X_i}}{\sqrt{\sum_1^n{X_i^2}}}$  with the $X_i$ iid $N(0,1)$ then $Y_n =\sum_1^n Z_{i,n}$ and, as StubbornAtom commented,
the vector $\mathbf Z_{n}$ is uniformly distributed on the surface of a unit hypersphere. $Z_{i,n}$ has the same distribution as $\frac{Y_n}{\sqrt{n}}$, so with mean $0$ and variance $\frac1n$ supported on $[-1,1]$
Comment: This density $(n-y^2)^{(n-3)/2}$ is not of a beta distribution, but the density of a variable that is the square root of a variable that follows a beta distribution. https://en.m.wikipedia.org/wiki/Kumaraswamy_distribution#Relation_to_the_Beta_distribution
Comment: @SextusEmpiricus it does have a relocated rescaled beta distribution: if you let $w=\frac{y}{2\sqrt{n}} + \frac12$ you would get $(n-y^2)^{(n-3)/2}=(4n)^{(n-3)/2} w^{(n-3)/2}(1-w) ^{(n-3)/2}$ which is proportional to the density of a beta distribution
Comment: Many thanks to @Henry. I'm working on standardizing portfolio weighting and this is confusing me. Thanks and I'm new to this community.


Where to Download java-ee.jar?

Question: Where does the Jar file come from?  I expected it to be either a part of the JDK or Eclipse.  That expectation proved to be wrong.
Answer: Sun/Oracle is providing a java-ee.jar - which contains only the Java EE APIs and does not contain any method bodies - that you can use to compile against it (from the java.net maven repository):

For Java EE 5: http://download.java.net/maven/1/javaee/jars/javaee-api-5.jar
For Java EE 6: http://download.java.net/maven/2/javax/javaee-api/6.0/javaee-api-6.0.jar

If you want to execute some Java EE code, you'll need a Java EE application server, they provide an implementation of the Java EE APIs. For example, for Java EE 6, there is GlassFish.
Comment: @Kayser: You should typically be adding the dependency as a provided dependency in your POM:  ` javax
javaee-api 6.0 provided `  or  ` javax.j2ee j2ee 1.4 provided `
Comment: How can i add the java-ee dependency in my pom?
Answer: if you want javaee-api-7.jar, use maven dependency
<code><dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
</dependency>
</code>
or you can download from here
Comment: This is the correct and recommended solution according to the best practices. Simple and functional. Thanks.
Answer: Download Glassfish or JBOSS or another Java EE app server.  They all have it.
Comment: It's better to include the dependency as suggested in other answers, then you can swap between Glassfish, TomCat, JBoss without having to check your code is compatible.
Comment: No, it'll be a problem if the app server includes the JAR and there's a conflict.  Better yet - don't use Java EE anymore.  Go with Spring Boot.  It's almost 2018.  Java EE is dead.

Where to Download java-ee.jar?


How to add Timestamp value in SQL Server 2005 by using LINQ

Question: My database table have a Timestamp column named as inTime and i am using LINQ for insert, update data in SQL server. Now i want to add the timestamp value in my database but i don't know how to insert?
<code> spaBL.attendance obj = new spaBL.attendance();
            obj.FK_employeeId = 1;
            obj.inTime =[what to write here??]
</code>
inTime is of timestamp type.
Answer: Timestamp as in SQL Server Timestamp data type?
;) If I got a cent every time someone did not read the documentation and thought that is a TIME STAMP I would be more rich than bill gates.
Timestamp data time has NO TIME INFORMATION IN IT. It is a running version number, legacy to Sybase SQL Server where SQL Server from Microsoft originated and a totally borked design.
So, no, you CAN NOT SET THAT FIELD, sorry, and it has no usable value except to see whether it changed (then the row was updated).
The documentation is explicitly clear on that, even if some people think reading is maybe a lost art:
http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Is a data type that exposes automatically generated, unique binary
  numbers within a database. timestamp is generally used as a mechanism
  for version-stamping table rows.

There is no way for you to set it. CHange your LINQ setup to not update this column.
Answer: Timestamp values are auto generated by the server on inserts. You should insert rows to the table without supplying a value for the timestamp column. Sql server will then generate the value for the column.
Note the columns of type timestamp does NOT contain values that can be parsed as a DateTime. The idea behind timestamp columns is that they can be used to check if a row has been updated between fetching the row and trying to update the row with new values.
Answer: You do not provide values for columns with a Timestamp (Rowversion) data type. SQL Server will provide a value for you automatically (and it won't be a datetime value). Therefore you do not need to be concerned with having Linq To SQL insert a Timestamp value for you. In fact, you cannot do it. SQL Server will do it for you. You can however, retrieve the value of a Timestamp column. I believe the corresponding C# type will be System.Data.Linq.Binary.
How to add Timestamp value in SQL database by using LINQ
hope it helps
Answer: You cannot update a timestamp. See here. And indeed, as TomTom indicated, it doesn't contain actual time information.


Upload de arquivos (sempre em pastas diferentes)

Question: Gostaria de saber se é possível (e como eu poderia fazer) eu criar um sistema de upload onde sempre que eu subir um arquivo, ele vá para uma pasta diferente (sempre), e me mostre (ou grave) o caminho que ele gerou. É possível fazer isso?
Motivo: Sempre gero propostas em PDF que ficam com 10MB, então gostaria de ao invés de enviar para o cliente anexo, envio o link para ele fazer download da proposta. Contudo, um cliente não pode ver a proposta do outro, por isso gostaria de sempre fazer o upload para uma pasta diferente.
O código que tenho de base é esse:
    <?php
    $pasta = "/pasta/onde/o/arquivo/sera/salvo";
    $dest = $pasta."/".$file_name;
    if(!move_uploaded_file($file, $dest)) {
    echo "Não foi possível enviar o arquivo!";
    } else {
       echo "Arquivo enviado com sucesso!";
    }
    ?>

Comment: Você usa alguma biblioteca para gerar o pdf? Geralmente, é preciso especificar onde o arquivo será salvo, assim sendo bastaria criar um padrão para nomenclatura, mas pode variar de biblioteca pra biblioteca.
Comment: Provavelmente esse não é o método mais seguro de controlar o acesso aos arquivos, visto que , mesmo que você use nomes não padronizados , é possível que eventualmente eles sejam expostos...
Answer: Aqui fica uma ideia de como poderias fazer:
<?php

   // Pasta de upload
   $updir =  "/upload/";

   // criar pasta random .../upload/RANDOM/
   $finaldir = $updir . md5(openssl_random_pseudo_bytes(23)) . "/";

  if (!is_dir($_SERVER['DOCUMENT_ROOT'] . $finaldir)) {
     mkdir($_SERVER['DOCUMENT_ROOT'] . $finaldir);
  }

  // nome ficheiro
  $file = $finaldir . $_FILES["file"]["name"];

 // salvar ficheiro upload para a pasta
 copy($_FILES['file']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . $file);

 //Salvar em base dados
 $sql = "INSERT INTO tabela (ficheiro, user) VALUES ('".$file."', 'xpto')";
 mysql_query($sql);

 ?>

Comment: Nota: ao user `uniqid`, devera' usar a flag `$more_entropy = true`. Se a flag for `false`, o valor retornado sera o tempo actual em microsegundos - ou seja, nao garante unicidade.
Comment: O metodo `mt_rand` nao garante unicidade, o que parece ser um requisito do OP.
Comment: ok uniqid() tambem dá ------ Ja Agora: The output generated by the sprintf() and mt_rand() calls is identical to com_create_guid() results.
Comment: Pronto melhor ainda: openssl_random_pseudo_bytes()
Answer: Para garantir um nome uniquo, basta usar um guid (globally unique identifier) para gerar o nome da pasta, e depois guardar la' o ficheiro.
string com_create_guid ( void )

Fonte: http://www.php.net/manual/en/function.com-create-guid.php
Answer: Pra sua necessidade eu faria o seguinte:
Criaria as pastas no padrão:

ano
mes
dia
hora minuto segundo (tudo junto)
nome do cliente (slug => sem caracteres especiais e minusculo)

Então ficaria assim:
    /2014/01/31/092631/fulano-de-tal/arquivo.pdf

Acho mais organizado do que criar um hash do tipo:
    /19090d9f0e92wd0920e90d9f029d09/arquivo.pdf

Answer: Tenho uma aplicação em PHP que faz o upload de ficheiros gerados automaticamente por postos clientes e, para que se faça um download seguro, criei um "token" único  à semelhança do que já foi dito e depois tenho uma tabela que gere os downloads. Esta tabela guarda o token do ficheiro, cria um link para download (tenho todos os ficheiros na mesma pasta referenciados na bd) e tem uma data/hora associada ao download que estabelece um tempo limite para o fazer (no meu caso de 2 dias).
Uma estrutura de pastas por cliente só faz sentido se os ficheiros tiverem de ser acedidos de outra forma (FTP por exemplo), senão basta ter um registo com o nome do ficheiro na base de dados.
Answer:
Motivo: Sempre gero propostas em PDF que ficam com 10MB, então gostaria de ao invés de enviar para o cliente anexo, envio o link para ele fazer download da proposta. Contudo, um cliente não pode ver a proposta do outro, por isso gostaria de sempre fazer o upload para uma pasta diferente.

Nesse caso, o que você precisa é das duas uma:

Implementar um controle de acesso, exigindo por exemplo que o cliente entre com uma senha antes de baixar o arquivo;
Usar um token aleatório e difícil de adivinhar (unguessable), ou alternativamente o hash do [conteúdo do] próprio arquivo

O caso 1 a primeira vista parece inconveniente para o usuário - e é mesmo - mas passa uma boa impressão: é mais fácil convencer um cliente [leigo em questões de segurança] que seu arquivo está "protegido" por meio de uma senha do que explicando para ele que a "chance de alguém sem o link adivinhar o token é muito próxima de zero" (e você vai ouvir a pergunta: "mas e se alguém descobrir?").
No segundo caso, você pode usar um valor aleatório - talvez um GUID/UUID - como as outras respostas sugeriram, mas também pode fazer um hash (ex.: SHA-256) do conteúdo do arquivo. A vantagem nesse segundo caso é que, se o mesmo arquivo for carregado duas vezes no servidor, somente uma única cópia do mesmo precisa ser armazenada. Sim, eu sei que "um cliente não pode ver a proposta do outro", mas se as duas forem iguais, que diferença faz? (i.e. não há nenhuma informação que mostre que outro cliente também tem acesso ao mesmo arquivo)
Answer: Acho bem útil mudar as pastas, mas acredito que você poderia fazer esse procedimento de uma maneira mais dinâmica.
Poderia gerar o PDF já direto no PHP e setar a header do mesmo, existem classes como o MPDF que facilitam esse procedimento. Segue um link de um tutorial.
Assim, você poderia economizar espaço em seu servidor.


How to save multiple data into local json file with Codable in Swift

Question: I am doing iWatch app and I am tracking 4 minutes walk for Heart rate multiple data for each second.
I am getting data and I have to save it to local json file.
I am trying to add data to Codable, but, I am getting only single data.
I am new to Swift.
Following is required format.
{   "items" : [
    {
      "endDate" : "2019-12-11",
      "HeartRate" : "82 BPM",
      "startDate" : "2019-12-11"
    },
    {
      "endDate" : "2019-12-11",
      "HeartRate" : "79 BPM",
      "startDate" : "2019-12-11"
    }   ] }

Below is my data in main class.
    func workoutBuilder(_ workoutBuilder: HKLiveWorkoutBuilder, didCollectDataOf collectedTypes: Set<HKSampleType>) {
              guard let hrType = HKQuantityType.quantityType(forIdentifier: .heartRate),
              let distanceType = HKQuantityType.quantityType(forIdentifier: .distanceWalkingRunning) else {
                  return
          }
          if collectedTypes.contains(hrType) {
              if let hrQuantity = workoutBuilder.statistics(for: hrType)?.mostRecentQuantity() {
                  // We want to have BPM
                  let hrUnit = HKUnit(from: "count/min")
                  let hr = Int(hrQuantity.doubleValue(for: hrUnit))
              //    print("HR: \(hr)")
                self.bpmLabel.setText(String(hr))

                let jsonData = HealthItem.init(endDate: formattedDateFromString()!, HeartRate: String(hr), startDate: formattedDateFromString())
                print("jsonData \(jsonData)")
   }
}

struct codable class
struct HealThInfo: Codable {
    let items: [HealthItem]?
}

struct HealthItem: Codable {
    let endDate: String?
    let HeartRate: String?
    let startDate: String?
}

But, It is saving only single data, Not multiple data.

jsonData HealthItem(endDate: Optional("2020-02-04"), HeartRate:
  Optional("87"), startDate: Optional("2020-02-04"))
Comment: Your shown code only prints out a `HealthItem`. Can you show the code that "saves" it?
Comment: I am not yet saving it into local json file, I got stuck over formating itself. Once this gets fixes, Then I can save it into local json file
Comment: You are saving HealthItem data. HealthItem is a single object. You should append HealthItem to 'items' of  'HealThInfo' and save 'HealThInfo'
Answer: You can use bellow function
func getArrayViaCodable<T : Codable>(arrDict : [[String : Any]]) -> [T]? {
    if let jsonData = try?  JSONSerialization.data(
        withJSONObject: arrDict,
        options: .prettyPrinted
       ){
       do {
           let posts = try JSONDecoder().decode([T].self, from: jsonData)
            return posts
       } catch {
            print(error)
            return nil
       }
   } else {
        return nil
   }
}

Now use like
if let dictresponse = responsedata as? [String: Any] {
    if let itemArray = data["items"] as? [[String: Any]] {
        let arrHealthInfo : [HealThInfo] = getArrayViaCodable(arrDict: itemArray)
    }
}

Comment: I am taking data in loop from delegate method which will get call 6 minutes continuously. I did not get that from your code
Answer: collectedTypes is an array of type HKSampleType. You should iterate over collectedTypes in order to get all data. Hope it helps you.
Comment: No, I did not get you
Comment: Can you have solution for my issue? my issue with codable class
Answer: You never are using the HealThInfo object.
let jsonData = HealthItem.init(endDate: formattedDateFromString()!, HeartRate: String(hr), startDate: formattedDateFromString())
let healtInfo = HealThInfo() // maybe load from disk with previous data?
healtInfo.items.append(jsonData)
print("jsonData \(healtInfo)")


Is Organic Groups 7.x ready for production?

Question: I am about to build a community and planned on using organic groups. I was using drupalmodules.com to download modules, and I noticed that that the reviews for organic groups 7.x are terrible. http://drupalmodules.com/module/organic-groups. Is anyone using organic groups 7.x, and what are your experiences with it?
Comment: The last review was made in April 22, 2012, and a lot has happened with OG since then. OG is complex and if you haven't used it before in D7 it really takes some time to get your head around it. I have used the OG 2 for production and it works pretty okay. Had some issues before but they seem to have been resolved.
Answer: I've used OG6 in the past and am starting to use OG7 now for a website.  I'd say in general, both with the 6 and 7 versions that the learning curve in figuring out how to use Organic Groups can be steep for a newbie, since it's a complicated module with a lot of features, and a lot of related, supporting modules like OG menu, OG Extras, etc.
Give yourself time to play with all of those.  Don't expect to setup your perfect site in a day if you've never used it before.  It may be that the 6 folks who reviewed the module on the site you referenced had such expectations.  Also, those are 6 reviews out of over 24,000 sites currently using OG.  :-)
My recommendation: do your own testing and make up your own mind before believing a review 100%.  Some of those reviews are probably quite valid, but OG is a useful module and may be able to do everything you want for your site.


Prove that the subgroup $H$ is normal in the group $G$

Question: where $3|H| = |G|$ is odd
Attempt: Set $a$ in $H$ and $b$ in $G$ such that $bab^{-1}$ is not in $H$. Let $f\colon H\rightarrow \mathbb{Z}_2$ such that $f(a) = 0$ for $abH = bH$, $f(a) = 1$ for $abH = b^2$H. I need to prove that  $f$ is a homomorphism and $f(H) = {0}$. How do I do this?
Comment: Note that $|G:H| = |G|/|H| = 3$, and since $|G|$ is odd, $3$ is the smallest prime dividing $|G|$. There is a general theorem that if $p$ is the smallest prime dividing $|G|$, and $|G:H| = p$, then $H$ is normal. Try proving that.
Answer: Just slightly modify your arguments: $H$ is a subgroup of index $3$, it has three cosets, say $H, xH, yH$. Define $F\colon G\rightarrow S_3$ by
$$F(g)=
\begin{pmatrix}
H & xH & yH\\
gH & g(xH) & g(yH)
\end{pmatrix}.
$$
Check that it is a homomorphism.
Where the elements of $H$ will go? For $h\in H$,
$$F(h)=
\begin{pmatrix}
H & xH & yH\\
hH & h(xH) & h(yH)
\end{pmatrix}
=
\begin{pmatrix}
H & xH & yH\\
H & h(xH) & h(yH)
\end{pmatrix}
=\begin{pmatrix}
xH & yH\\
h(xH) & h(yH)
\end{pmatrix}.
$$
So the image $F(h)$ is either identity or a $2$-cycle.
If $F(h)$ is $2$-cycle, then $2$ divides $|F(h)|$ and $|F(h)|$ divides $|h|$, which divides $|G|=odd$, contr.
So $H$ is in $\ker(F)$. Can $\ker(F)$ be whole $G$? For this, take $b\in G\setminus H$. What is $F(b)$?
$$F(b)=
\begin{pmatrix}
H & xH & yH\\
bH & b(xH) & b(yH)
\end{pmatrix}\neq Identity (why?).
$$
So $H=\ker(F)$ hence normal.
Comment: $|s|$ denotes order of element $s$ in group.


Technique to avoid this parse error? JSON +double quote

Question: We know in JSON  string object we have property and its value as
"Property":"Value"
Suppose my Value contains a double quote, Like "Property": "my country is "uk" "
We know that this is going to give parse error on JSON.parse().
What is the technique to avoid this parse error?
Answer: You can use backslash to escape the double qoute, read more about escape character over here.
Change
"my country is "uk" "

To
"my country is \"uk\" "

Answer: If you're encoding an object into JSON, you can use JSON.stringify():
JSON.stringify({
    Property: 'my country is "uk"'
})
// {"Property":"my country is \"uk\""}

As you can see from above example, the notation \" is used to properly escape double quotes.


How to make redirection in Apache HTTP with Apache Tomcat

Question: I have installed in my Linux server an Apache HTTP Server (the main) and an Apache Tomcat 7 Server.
I want that all requests that are made for projects hosted in Tomcat to be redirected by the Apache HTTP respectively.
I didn't do that until now, so have anyone some thoughts and suggestions on this?
I read something about mod_jk, mod_proxy, mod_jserv.
What is the best choice for my scenario?
Answer: To use mod_proxy, put this in your <VirtualHost>:
ProxyPass /project-one http://127.0.0.1:8080/project-one
ProxyPassReverse /project-one http://127.0.0.1:8080/project-one


Schema for group module

Question: I have installed this module and I assume that this works not only in the regular content type but also in the group module. I was expecting that after enabling the module there is an option to map my group type fields in the manage fields section but none even in the edit setting of the group type.
See RDF Mappings in the Basic Page content type:

Notice this from the module:

Features
RDF UI Map Content Types to Schema.org Types. Map Fields to Schema.org
  properties.

Does the group module supports schema integration? If yes, is there any documentation provided?
Comment: Please **edit** your question to explain what kind of integration you're looking for.
Comment: Added details of my current case.
Answer: The RDF UI module only provides the 'RDF Mapping' local task for nodes at the moment (so not Group entities). See the if statement in this snippet from Drupal\rdfui\Plugin\Derivative\RdfUiLocalTask::getDerivativeDefinitions():
foreach ($this->entityManager->getDefinitions() as $entity_type_id => $entity_type) {
  if ($entity_type->get('field_ui_base_route') && $entity_type_id === "node") {

    $this->derivatives["overview_$entity_type_id"] = array(
      'route_name' => "entity.$entity_type_id.field_ui_fields",
      'title' => $this->t('Fields'),
      'parent_id' => "field_ui.fields:overview_$entity_type_id",
    );

    $this->derivatives["rdf_$entity_type_id"] = array(
      'route_name' => "entity.$entity_type_id.rdf_ui_fields",
      'weight' => 2,
      'title' => $this->t('RDF Mappings'),
      'parent_id' => "field_ui.fields:overview_$entity_type_id",
    );

  }
}

Schema for group module


Does the sign of the numerator matter in the "arctan-angle-line" formula?

Question: So the simplified formula for finding the acute angle between two intersecting lines is:
tan-¹ (m1-m2/1+m1m2)
But what if m2 is larger than m1 and we get a negative numerator? Does the formula still hold?
Comment: Parentheses, please.  You have written the argument as $m1-\frac {m2}{1}+m1m2$, which is not what you mean.
Answer: The right formula is
$$\alpha=\arctan\left|\frac{m_1-m_2}{1+m_1m_2}\right|$$
Let $l_1$ and $l_2$ be two straight lines and $\alpha$ be a measure of the angle between $l_1$ and $l_2$.
Thus, if $l_1||l_2$ then $\alpha=0^{\circ}$;
if $l_1\perp l_2$ then $\alpha=90^{\circ}$;
otherwise, $\alpha$ it's a measure of the small angle between four angles,
which which we get by these lines.
Comment: OP was asking about the sign of the calculation.  If you take off the absolute value bars, it indicates which direction  you are measuring, clockwise or counterclockwise
Comment: @Ross Millikan See please better my answer. I said that the formula, which he try to use is total wrong.
Comment: Thanks, Ross Millikan. It's just that everywhere I look, I see the formula without absolute value bars, so that got me thinking. So without them we get the same answer, just with respect to the direction we measure the angle from?
Comment: @user485842:  The arctan function is odd, so if you change the sign of the argument, you change the sign of the result.  That corresponds to measuring in the other sense.


How to design cross-validation and testing scheme when N is small?

Question: I have a binary classification problem with 60 samples (N=60). 40 are responders (+) and 20 are non-responders (-) to a drug. There will be ~20 measured features (p=20) per sample with which to make predictions. I expect co-linearity between some of the features. If I devote 20 samples to my test set and divide responders and non-responders equally between the training and testing sets, I would get 6-7 responders in the test set. I would perform cross validation to select between LASSO regression models and random forest with a few parameter values for each. Finally, I would train the best model (one standard error rule) on the entire training set, and then apply to the test set.

I understand that N is too small. Is it foolhardy to even attempt classification in this scenario?

Is it permissible or even advisable to over-represent the smaller class (non-responders) in the test set? Perhaps I randomly select 10 responders and 10 non-responders for the test set. I might have more statistical confidence. With only 6 non-responders in the test set, it might be easier for me to get "lucky" or "unlucky". A bad classifier could accidentally perform well or vice versa. If my classifier were to perform well by some metric, how could I be confident that was not due to chance?

Should I use leave-one-out cross validation in this scenario? With 40 samples in the training set and 10 non-responders, I could do 5-folds cross validation and randomly select 2 non-responders and 8 responders for each CV fold. But then I am only training on 30 training samples for each split vs. 39 if I do leave-one-out CV.

I haven't actually done this experiment yet. I am trying to get a sense for whether this kind of a project is worth attempting with such a small N, and if so, what problems I may need to be wary of.
Answer: Cross validation is not the only way to compare different models. Several model selection criteria, such as the Akaike Information Criterion (AIC) or the Bayesian Information Criterion (BIC) can precisely be used to compare different hypotheses when the number of observations is small and all samples need to be used for training. The main concept behind these selection criteria is to penalize the likelihood of a model with its complexity (i.e. with its number of free parameters).
Answer:
I understand that N is too small. Is it foolhardy to even attempt classification in this scenario?

Probably, at least as you propose to proceed.
First, for train/test splits to work well, you need on the order of 20,000 cases. You are very far from that. Your best option is to repeat your entire modeling process on multiple bootstrap samples, treat each bootstrap sample as a training set, and evaluate each model against the entire data set as a test set. Incorporating the "optimism bootstrap" will allow you to evaluate the extent of overfitting. That assesses the quality of your modeling process, which is all you can hope to do with a small sample.
For a binary outcome and an unpenalized model, to avoid overfitting you typically need about 15 members of the minority class per predictor. See Chapter 4 of Frank Harrell's course notes. With 20 in your minority class, that's only 1 or maybe 2 unpenalized predictors.
Penalization via LASSO will tend to retain a similar number of predictors, 1 or 2 in this data set. The particular predictors retained, however, are likely to differ from bootstrap sample to bootstrap sample, particularly with collinear predictors. See Statistical Learning with Sparsity, Section 6.2. There's no assurance that those retained in the model on the full data set will be the "best choices" overall, only that they happened to work on this small data set. Is that OK for your application?
Critically, don't use accuracy as your performance criterion. You should work with probability estimates for as long as possible, using log loss or other strictly proper scoring rules. If you do ultimately have to classify, the choice of probability cutoff should take into account the relative costs of false-positive and false-negative classifications. The (often hidden) default of a cutoff at probability of 0.5 for "accuracy" is only appropriate if those are equally costly, which isn't necessarily true.
As you are still in the study design phase, simulate large numbers of cases based on reasonable assumptions about outcomes, their associations with your 20 features, and the correlations among feature values. See how well you can model your known associations with outcome on samples of size 60. That might be the best way to see whether this modeling attempt really is foolhardy.
You might be better off using you knowledge of the subject matter to do data reduction on the set of features, combining them intelligently into a smaller number of combined predictors, rather than relying on the types of automated procedures you envision. Again, see Harrell's course notes for guidance.
Answer: In addition to the excellent points in Camille's and EdM's answers:
Purpose of the model/study
Whether something sensible can be done or not depends crucially on the purpose of the modeling.
For any kind of real-world application, the random uncertainty on your internal validation results (even with the best resampling) will likely not be useful.
If on the other hand, this is a preliminary study with the purpose of generating a first rough idea to substantiate a grant proposal, that would be perfectly fine.
Random uncertainty in internal validation results
Do a back-of-the-envelope assessment of the situation.
The best resampling cannot get around the fact that you have only 60 cases (forget about hold-out), and only 20 in the smaller class.
Proportions like acurracy, sensitivity, specificity etc. have many disadvantages over the already mentioned proper scoring rules. Right here, however, they have the one advantage that they allow back-of-the-envelope calculations before even preliminary data is available.
(Proper scoring rules can have lower variance than these proportions, but don't expect miracles. Plus, overfitting leading to overconfidence in the predictions, thus predicted probabilities too close to 0 or 1, increases variance uncertainty)
With 20 patients in the negative class, specificity (the probability of correctly recognizing negative class/non-responders) will have 95 % confidence intervals (calculated via Bayes method with uniform prior):

If this uncertainty is (unjustifiably) too large for your purpose, then don't even start experiments now. Instead, you can use such confidence interval estimations to calculate a more sensible number of cases and recruit them.

Note that this includes only random uncertainty that stems from the limited number of cases. Resampling in small-sample-size situations or across optimization processes there will be additional variance due to model instability.

As I said, (strictly) proper scoring rules feature lower variance among their advantages over proportions. However, you may find that you are forced to communicate final internal validation results in the form of proportions, and then you're back to these large confidence intervals.

Looking at the variance of a figure of merit between cross validation folds gives you a funny mix of $\frac{n}{k}$ case-to-case variance and model instability variance.

(avoiding) Data-driven model optimization
These confidence intervals should also give you an idea of how large the observed difference in performance between candidate models should be to allow a data-driven choice. (Remember, choosing between multiple models -> multiple comparisons). The likely conclusion is that you cannot do data-driven model optimization with so few cases. Not even if you switch to a nested resampling strategy, and while AIC, BIC etc. spare you the inner resampling, they also cannot do miracles and will basically tell you that you cannot afford a complex model based on these case numbers.  However, they may be more convenient for formulating a decision strategy for the model complexity that is then evaluated in the resampling.
Other than that, your best bet is to include as much external knowledge as possible and reduce the dimensionality of your data before even looking at it. I.e., avoid the data-driven optimization and replace it by decisions you take.
E.g. if you know you have 3 clinical parameters that are highly correlated, either decide for now to go with one (i.e. decide which one) or if you prefer with their average or sum (or difference for negative correlation) and then swallow the bill for this professional decision.  The cost (in terms of performance) of being undecided will likely be heavier, because data-driven optimization costs sample size...
Or decide to go for the LASSO model using 5 parameters, without looking whether 4 or 6 look better.
The random forest you mention takes yet another strategy, and may be your best bet if you do not have sufficient external knowledge. The rF tries to "average out" model instability. The beauty here is that default parameters often yield a sensible model, so don't even think of optimizing them. If you want to be on the safe side, use more trees though: there you trade of computational resources for a possible gain in predictive performance, but you do not risk worse predictive performance by using more trees.

Leave-one-out
... is almost never advisable since it conflates surrogate model and test case, depriving you of the possibility to check stability of the predictions (there are more disadvantages to LOO, but that alone is sufficient for me to avoid it).
Instead, go for a resampling scheme like bootstrap or repeated k-fold cross validation (say, 50x10-fold or 25x20-fold) that allows you to measure instability, possibly stratified.
Is it permissible or even advisable to over-represent the smaller class (non-responders) in the test set?
Adjusting relative class frequencies is IMHO advisable only if you correct your data to better represent the application-scenario specific relative class frequencies.
All other adjustments, in particular towards better balance in the training data may lead to nice-looking results at the first glance, but that will usually come at the cost of worse performance under application working conditions.
Instead of adjusting relative class frequencies in the test data, it is IMHO better to adjust the resulting figures of merit to application-relevant relative frequencies.

Finally, be happy: I often have to work with smaller sample size and at the same time much higher dimensionality (p in the 100s or 1000s). (But I can typically use repeated measurements and external knowledge about the physics and chemistry behind the data - which makes modelling possible - even if it does not help with the uncertainty of the internal validation)
Comment: Good point about the usefulness of specificity for back-of-the-envelope estimates in the design phase. That plot says a lot. (+1)


ANOVA is significant but also demonstrates non-inferiority

Question: I have data that is looking at comparing a cheap (T) to expensive (V) ultrasound device with the hopes that the cheap is the same as expensive. There was 4 different examiners that used 4 different views to determine the presence of osteophytes. I have used a generalised mixed-effects logistic regression followed by an ANOVA and non-inferiority test.
glmer(OSTEOPHYTES ~ DEVICE + Examiner + VIEW + (1 | ID), data = TVOPL, family = binomial,
                  nAGQ = 10)

The ANOVA is significant for DEVICE (Pr(>|z|) = 0.00514), meaning there is a difference in the two devices (Reject Null hypothesis). However, when I do a non-inferiority (LRT) test:
subset_data <- subset(TVOPL, DEVICE %in% c("V", "T"))
vinno_model <- glmer(OSTEOPHYTES ~ Examiner + VIEW + (1 | ID), data = subset_data, family = binomial(link = "logit"), control = glmerControl(optimizer = "bobyqa"))
tablet_model <- glmer(OSTEOPHYTES ~ DEVICE + Examiner + VIEW + (1 | ID), data = subset_data, family = binomial(link = "logit"), control = glmerControl(optimizer = "bobyqa"))
lrt_result <- anova(vinno_model, tablet_model, test = "LRT")
summary(lrt_result)

It is significant Pr(>Chisq) = 0.00495 determining that the cheap device is noninferior to the expensive device by the specified margin. When I subset the data into each view, it also can come up with the opposite. The ANOVA is not significant, but also not non-inferior. How do I interpret this in terms of results due to conflicting outcomes? Also is it possible to use non-inferiority with the data set including all views, then, ANOVA for each View (A,B,C,D) as I want to know which view is the best.
Answer: Your understanding of a non-inferiority test is wrong, I fear. It has nothing to do with a small p value of a LRT.
In your case, you would specify a margin for the true effect $\theta$ of DEVICE to be "like zero". For instance, 0.02. This leads to traditional hypotheses

$H_o$:   $\theta \le -0.02$ and
$H_1$:   $\theta > -0.02$ (non-inferiority, the thing that you want to show)

Then, you would calculate a lower one-sided 95% CI for $\theta$ and show that it is larger than -0.02. If yes, you would reject $H_o$ in favour of non-inferiority.
Furthermore, you seem to do pairwise comparisons. This will make the non-inferiority consideration much more complicated (as it is completely different from showing superiority, one cannot simply apply a Bonferroni correction or similar).


How to filter array to get only the object and not array in PHP

Question: I'm not even sure what to search for for this question. What I really want is I have an array of objects  like this
array(3) {
  [0]=>
  object(stdClass)#423 (4) {
    ["name"]=>
    string(3) "Blah"
    ["full_name"]=>
    string(10) "/Blah"
    ["id"]=>
    string(32) "BlahBlah"
    ["parent_id"]=>
    string(32) "BlahBlah"
  }
  [1]=>
  object(stdClass)#422 (4) {
    ["name"]=>
    string(8) "Blah1"
    ["full_name"]=>
    string(9) "Blah2"
    ["id"]=>
    string(32) "BlahBlah2"
    ["parent_id"]=>
    NULL
  }
  [2]=>
  object(stdClass)#421 (4) {
    ["name"]=>
    string(4) "Blah3"
    ["full_name"]=>
    string(11) "Blah3"
    ["id"]=>
    string(32) "BlahBlah3"
    ["parent_id"]=>
    string(32) "BlahBlahBlah3"
  }
}

I want to filter to just the object that I want so what I did was
   $found_label = array_filter($labels, function($obj) use($label) {
       return $obj->name === $label;
   });

But then the results I got is this
array(1) {
  [1]=>
  object(stdClass)#422 (4) {
    ["name"]=>
    string(8) "Blah1"
    ["full_name"]=>
    string(9) "Blah1"
    ["id"]=>
    string(32) "BlahBlah2"
    ["parent_id"]=>
    NULL
  }
}

But what I really want is just this
      object(stdClass)#422 (4) {
        ["name"]=>
        string(8) "Blah1"
        ["full_name"]=>
        string(9) "Blah1"
        ["id"]=>
        string(32) "BlahBlah2"
        ["parent_id"]=>
        NULL
      }

Then I have to do this to just get the actual object
$theKey = key($found_label);

return $found_label[$theKey];

I thought they should be a better way of doing this, also I'm new to PHP.
Answer: This:
<?php

$labels = array(
  "0" => (object) array('name' => "name1", "title" => "title1"),
   "1" => (object) array('name' => "name2", "title" => "title2")
);

$label = "name1";

$found_label = array_filter($labels, function($obj) use($label) {
   return $obj->name === $label;
});

print_r($found_label[0]);

Produces:
stdClass Object ( [name] => name1 [title] => title1 )

Answer: You can't do that with array_filter, there is no way to stop it and return only the first result. If you can't use the key to extract the result you want from the array returned from array_filter, you should use a loop. Something like this:
$label = "wantedLabel";
foreach ($labels as $l) {
    if( $l->name === $label ) {
        print_r ($l);
        break;
    }
}


What is the relevance of the fact that the completeness axiom for R needs to be stated in second-order logic?

Question: My logic course points out that most statements of mathematics can be given by first order logic, but that the completeness axiom for R needs to be quantified over sets and so uses second-order logic.
I'm wondering what this implies for the completeness axiom - is it a different kind of mathematical statement to smaller, simpler ones? Does this effect the validity or perceived epistemic value of maths in some way that it wouldn't if this were phraseable in first-order logic?
Wasn't sure whether to put this is in philosophy or maths so sorry if i chose the wrong one!
Answer: First of all, note that we are talking about first- and second-order logic over the signature of $(R, +, -, \times, 0, 1, <)$ of real ordered fields. In this language, the ordered field $\mathbb R$ can be given as the unique structure satisfying the first-order axioms of an ordered field (things like $a + b = b + a$ or $a \neq 0 \to \exists b(ab = 1)$), together with one additional second-order axiom: the axiom of completeness.
When we want to formulate mathematics as a whole, not just the real numbers, in a logical language, this is typically done ZFC (or a similar set theory). This is a first-order theory whose domain is that of all sets. In this language, stating that $\mathbb R$ is complete is an ordinary first-order sentence: quantification over sets is all that first order ZFC sentences do.

I'm wondering what this implies for the completeness axiom - is it a different kind of mathematical statement to smaller, simpler ones?

It is in the basic sense that the completeness axiom for $\mathbb R$ cannot be stated in the first order theory of real ordered fields. One way to see this is that, by Löwenheim-Skolem, all first-order theories with infinite models must have infinite models of all cardinalities, while the only model up to isomorphism of the ordered field axioms + the completeness axiom is the real numbers.
One way of phrasing this is: first-order axioms are too weak to pin down a single infinite model, while second-order axioms are strong enough to do so.

Does this effect the validity or perceived epistemic value of maths in some way that it wouldn't if this were phraseable in first-order logic?

Because of the "in some way", this is a very wide question, but as an attempt at an answer: the vast majority of mathematicians accept some form of first-order set theory as a valid foundation of mathematics. Within that set theory, the completeness axiom is just a first-order sentence, and thus perfectly valid and epistemically sound.


Commerce pick up vs shipping

Question: I've read the documentation, but it doesn't seem to be complete just yet.
I'm using Drupal 9.4 and Commerce Core 8.x-2.31 with a few extra Commerce modules.
I've got a basic question (I think?). How can you get the checkout in a way that the customer can choose between filling in an address and picking up the order at 1 of 2 locations?
When they pick it up at a location, no cost should be added.
There are product variations seeing that we are using SKU numbers for stock and tracing etc.
The customer shouldn't be bothered with extra details, just choose a product and during checkout say 'I want to pay x to send, or pick it up at x or y with no extra cost'.
I have 3 shipping methods, 2 of which add 0 cost to the order, 1 adding the shipping fee.
To add this to the checkout, I saw a question about how the order types and ordertype items are linked to each other.
I'm not sure if this setup needs multiple stores (1 online/ 2 offline), or just have multiple Order item types which the Product variation types link to? (The last option, it seems that you can only enter 1 Order item type per Product variation type, so that doesn't seem like the correct way to go?)
Comment: I found https://www.drupal.org/project/commerce_pickup, this module adds a few options to the shipping method.
But I still cant get a customer to chose between picking something up or getting it sent to them.
Answer: An easy solution would be to use two flat rate shipping methods (Pick up at place x, Pick up at place Y). Flat rates is provided by Commerce Shipping module.
The drawback is that it will require the customer to enter their address. On the other hand, you probably need billing address anyway, so it may be good enough solution.
Comment: Ok, I think I know where you're going with this. But where in the process of the checkout can the customer choose that they want to pick it up?
Thanks for your answer.
Comment: You can create a new shipping method as described in [the docs](https://docs.drupalcommerce.org/commerce2/developer-guide/shipping/create-a-shipping-method). Probably choosing "flat rate" as a plugin and a description that the customers will understand.
Comment: All methods you create in this way will be available for the customer to choose from. Provided you have defined an appropriate checkout flow in /admin/commerce/config/checkout-flows. Also you need to configure in /admin/commerce/config/order-types an order type with workflow "Fulfillment" (or "Fulfillment with validation").
Comment: Indeed, yesterday I fixed the entire flow and used the flat rate as you mentioned. I had forgotten to put the correct setting in the "order types" default, which was "enable shipping for this order type". It was a mess in settings, I thought I had to add a different order type for the different shipping methods, which was wrong ofcourse. I've cleaned out the types and set the correct settings. Thank you very much for the help, @rs211 !
I've created an [issue](https://www.drupal.org/project/commerce_pickup/issues/3308313) about the settings not showing.

Commerce pick up vs shipping