Do homomorphism that agree on a generating set agree on entire group?

Question: Let $G_1$ and $G_2$ be a groups and $A\subset G_1$ a subset that generates $G$. Suppose that $f, g : G_1 \to G_2$ be homomorphisms such that $f|_A=g|_A$.
Does this imply that $f = g$?
Comment: Yes, and it is easy to show.
Answer: Hint: if $f\colon G_1\to G_2$ and $g\colon G_1\to G_2$ are homomorphisms, then the subset $H=\{x\in G_1:f(x)=g(x)\}$ is a …


Vue.js 2.0 Lazy Loading

Question: I'm trying to Lazy Load my components in Vue.js 2.0 (in a Laravel 5.3 project).
According to the documentation I should do it like this:
Vue.use(VueRouter);

const Forum = resolve => require(['./Components/Forum/Forum.vue'], resolve);

export default new VueRouter({
    mode: 'history',
    routes: [

        /**
         * Forum
         */

        {
            name: 'Forum',
            path: '/forum',
            component: Forum,
            meta: { requiresAuth: true }
        }
    ]
});

But I get lots of errors:
Uncaught SyntaxError: Unexpected token <
app.js:130 Error: Loading chunk 0 failed.
    at HTMLScriptElement.onScriptComplete (app.js:84)
__webpack_require__.oe @ app.js:130
vue-router.common.js?37ec:80 [vue-router] Failed to resolve async component default: Error: Loading chunk 0 failed.

I'm using Laravel Elixir this is my gulp file:
elixir(mix => {
    mix.webpack('app.js')
        .styles([
            './node_modules/normalize-css/normalize.css',
            './node_modules/nprogress/nprogress.css',
            './node_modules/sweetalert/dist/sweetalert.css'
            ])
        .stylus('app.styl');
});

What am I doing wrong?
Would really help me.
Comment: Anyone Anyone??
Answer: Laravel Elixir does not support Lazy Loading of Vue Components. You have to upgrade to 5.4 where you will get webpack support or you have to use vue-webpack template to build your bundle.

Vue.js 2.0 Lazy Loading


Javascript recursividade

Question: Salve, comecei a ler o livro "Javascript Eloquente" e no capítulo sobre funções de ordem superior me deparei com o seguinte exemplo de um código que calcula os Genes que um indivíduo herdou da familia:
var ANCESTRY_FILE = JSON.stringify([
    {"name": "Carolus Haverbeke", "sex": "m", "born": 1832, "died": 1905, "father": "Carel Haverbeke", "mother": "Maria van Brussel"},
    {"name": "Emma de Milliano", "sex": "f", "born": 1876, "died": 1956, "father": "Petrus de Milliano", "mother": "Sophia van Damme"},
    {"name": "Maria de Rycke", "sex": "f", "born": 1683, "died": 1724, "father": "Frederik de Rycke", "mother": "Laurentia van Vlaenderen"},
    {"name": "Jan van Brussel", "sex": "m", "born": 1714, "died": 1748, "father": "Jacobus van Brussel", "mother": "Joanna van Rooten"},
    {"name": "Philibert Haverbeke", "sex": "m", "born": 1907, "died": 1997, "father": "Emile Haverbeke", "mother": "Emma de Milliano"},
    {"name": "Jan Frans van Brussel", "sex": "m", "born": 1761, "died": 1833, "father": "Jacobus Bernardus van Brussel", "mother":null},
    {"name": "Pauwels van Haverbeke", "sex": "m", "born": 1535, "died": 1582, "father": "N. van Haverbeke", "mother":null},
    {"name": "Clara Aernoudts", "sex": "f", "born": 1918, "died": 2012, "father": "Henry Aernoudts", "mother": "Sidonie Coene"},
    {"name": "Emile Haverbeke", "sex": "m", "born": 1877, "died": 1968, "father": "Carolus Haverbeke", "mother": "Maria Sturm"},
    {"name": "Lieven de Causmaecker", "sex": "m", "born": 1696, "died": 1724, "father": "Carel de Causmaecker", "mother": "Joanna Claes"},
    {"name": "Pieter Haverbeke", "sex": "m", "born": 1602, "died": 1642, "father": "Lieven van Haverbeke", "mother":null},
    {"name": "Livina Haverbeke", "sex": "f", "born": 1692, "died": 1743, "father": "Daniel Haverbeke", "mother": "Joanna de Pape"},
    {"name": "Pieter Bernard Haverbeke", "sex": "m", "born": 1695, "died": 1762, "father": "Willem Haverbeke", "mother": "Petronella Wauters"},
    {"name": "Lieven van Haverbeke", "sex": "m", "born": 1570, "died": 1636, "father": "Pauwels van Haverbeke", "mother": "Lievijne Jans"},
    {"name": "Joanna de Causmaecker", "sex": "f", "born": 1762, "died": 1807, "father": "Bernardus de Causmaecker", "mother":null},
    {"name": "Willem Haverbeke", "sex": "m", "born": 1668, "died": 1731, "father": "Lieven Haverbeke", "mother": "Elisabeth Hercke"},
    {"name": "Pieter Antone Haverbeke", "sex": "m", "born": 1753, "died": 1798, "father": "Jan Francies Haverbeke", "mother": "Petronella de Decker"},
    {"name": "Maria van Brussel", "sex": "f", "born": 1801, "died": 1834, "father": "Jan Frans van Brussel", "mother": "Joanna de Causmaecker"},
    {"name": "Angela Haverbeke", "sex": "f", "born": 1728, "died": 1734, "father": "Pieter Bernard Haverbeke", "mother": "Livina de Vrieze"},
    {"name": "Elisabeth Haverbeke", "sex": "f", "born": 1711, "died": 1754, "father": "Jan Haverbeke", "mother": "Maria de Rycke"},
    {"name": "Lievijne Jans", "sex": "f", "born": 1542, "died": 1582, "father":null, "mother":null},
    {"name": "Bernardus de Causmaecker", "sex": "m", "born": 1721, "died": 1789, "father": "Lieven de Causmaecker", "mother": "Livina Haverbeke"},
    {"name": "Jacoba Lammens", "sex": "f", "born": 1699, "died": 1740, "father": "Lieven Lammens", "mother": "Livina de Vrieze"},
    {"name": "Pieter de Decker", "sex": "m", "born": 1705, "died": 1780, "father": "Joos de Decker", "mother": "Petronella van de Steene"},
    {"name": "Joanna de Pape", "sex": "f", "born": 1654, "died": 1723, "father": "Vincent de Pape", "mother": "Petronella Wauters"},
    {"name": "Daniel Haverbeke", "sex": "m", "born": 1652, "died": 1723, "father": "Lieven Haverbeke", "mother": "Elisabeth Hercke"},
    {"name": "Lieven Haverbeke", "sex": "m", "born": 1631, "died": 1676, "father": "Pieter Haverbeke", "mother": "Anna van Hecke"},
    {"name": "Martina de Pape", "sex": "f", "born": 1666, "died": 1727, "father": "Vincent de Pape", "mother": "Petronella Wauters"},
    {"name": "Jan Francies Haverbeke", "sex": "m", "born": 1725, "died": 1779, "father": "Pieter Bernard Haverbeke", "mother": "Livina de Vrieze"},
    {"name": "Maria Haverbeke", "sex": "m", "born": 1905, "died": 1997, "father": "Emile Haverbeke", "mother": "Emma de Milliano"},
    {"name": "Petronella de Decker", "sex": "f", "born": 1731, "died": 1781, "father": "Pieter de Decker", "mother": "Livina Haverbeke"},
    {"name": "Livina Sierens", "sex": "f", "born": 1761, "died": 1826, "father": "Jan Sierens", "mother": "Maria van Waes"},
    {"name": "Laurentia Haverbeke", "sex": "f", "born": 1710, "died": 1786, "father": "Jan Haverbeke", "mother": "Maria de Rycke"},
    {"name": "Carel Haverbeke", "sex": "m", "born": 1796, "died": 1837, "father": "Pieter Antone Haverbeke", "mother": "Livina Sierens"},
    {"name": "Elisabeth Hercke", "sex": "f", "born": 1632, "died": 1674, "father": "Willem Hercke", "mother": "Margriet de Brabander"},
    {"name": "Jan Haverbeke", "sex": "m", "born": 1671, "died": 1731, "father": "Lieven Haverbeke", "mother": "Elisabeth Hercke"},
    {"name": "Anna van Hecke", "sex": "f", "born": 1607, "died": 1670, "father": "Paschasius van Hecke", "mother": "Martijntken Beelaert"},
    {"name": "Maria Sturm", "sex": "f", "born": 1835, "died": 1917, "father": "Charles Sturm", "mother": "Seraphina Spelier"},
    {"name": "Jacobus Bernardus van Brussel", "sex": "m", "born": 1736, "died": 1809, "father": "Jan van Brussel", "mother": "Elisabeth Haverbeke"}
])

var ancestry = JSON.parse(ANCESTRY_FILE);

var byName = {};

ancestry.forEach(function(person){
    byName[person.name] = person;
});

function reduceAncestors(person, f, defaultValue){
    function valueFor(person){
        if(person == null){
            return defaultValue;
        } else {
            return f(person, valueFor(byName[person.mother]), valueFor(byName[person.father]))
        }
    }
    return valueFor(person);
}

function sharedDNA(person, fromFather, fromMother){
    if(person.name == "Pauwels van Haverbeke")
        return 1
    else
        return (fromFather + fromMother) / 2
}

var ph = byName["Philibert Haverbeke"];
console.log(reduceAncestors(ph, sharedDNA, 0) / 4);

Se vocês observarem a função "valueFor" é uma função recursiva que retorna para a função "f" que faz referência a "sharedDNA". A questão são aquelas duas variáveis da função "sharedDNA" a "fromFather" e "fromMother" essas duas váriaveis aparecem dentro da função com valores como 1, 0.5, 0.125
fromFather = 0.5
fromMother = 0

Mas a função "f" retorna um objeto de pai ou da mãe e não um número decimal
return f(person, valueFor(byName[person.mother]), valueFor(byName[person.father]))

Eu não entendo como "sharedDNA" recebe aqueles números decimais. Se alguém entendeu e poder ajudar agradeço muito.
Answer:
"f" retorna um objeto de pai ou da mãe

Não, os objetos do pai e da mãe são passados como argumentos para valueFor, cujos resultados são passados como argumentos para f. Repare nos parênteses (coloquei uns espaços a mais para facilitar a visualização):
return f ( person, valueFor(byName[person.mother]), valueFor(byName[person.father]) )
         ^    ^    ^                                ^                               ^
         |    |    |                                |                               |__ parênteses que encerra a lista de argumentos de f
         |    |    |                                |
         |    |    |                                |__ terceiro argumento de f
         |    |    |
         |    |    |__ segundo argumento de f
         |    |
         |    |__ primeiro argumento de f
         |
         |__ parênteses que inicia a lista de argumentos de f

Ou seja, f recebe 3 argumentos: o person, o resultado de valueFor(byName[person.mother]) (que é um número) e o resultado de valueFor(byName[person.father]) (que é outro número). Os objetos referentes ao pai e a mãe são passados para valueFor, não para f. O que f recebe é o resultado de valueFor.
E valueFor sempre retornará um número, pois chega uma hora em que uma pessoa não tem mais pai nem mãe cadastrados no array (então person.mother e person.father serão nulos) e ele retornará zero (que é o defaultValue que indicamos ao chamar reduceAncestors). E quando tem pai e mãe, ele retorna o valor de f, passando o resultado do valueFor dos pais destes (e para calcular os valores do pai e da mãe, ele vai chamando recursivamente nos ancestrais destes). Ou seja, no fim valueFor sempre retorna um número.
Comment: Perfeito mano, entendi, nível Jedi você TMJ

Javascript recursividade


How to automatically delete file from runtime in Yii2 that isn't being used for current runtime?

Question: There are so many files created for runtime but may or may not be used for present tasks that occupies unneccessary space. If there's any way to do this either by fiddling around Yii2's own setings or by any other means, please specify those as much as you can?
Answer: You can clear the folder contents. Yii will create the necessary files again.


In this multithreaded java application only one thread seems to be running like a sequential program?

Question: Sorry for lengthy description. If it's too long please tell me how to improve.
I am learning about Java concurrency. This is a scenario I tried to code.
A mother and a child share a bank account. Mother and child are two separate threads and are started from the main thread of the program.
In the run() of both, they perform several bank transactions. For simplicity, the child does only withdraw transactions and mother does only deposit transactions. Each transaction is also a separate thread. Child/Mother have to wait until one transaction is complete to start the next. (wait/notifyAll used for this).
If a withdrawal task tries to withdraw but there is an insufficient balance (balance is 0 initially) then the thread goes to a while loop waiting till the balance becomes greater than withdrawal amount.
Mother sleeps 500ms between each deposit task.
What I expected
Since the mother sleeps between every deposit and the child doesn't sleep during withdrawals it is guaranteed that the child's tasks will enter the insufficient funds while loop. However, since the mother is a separate thread, after waiting 500ms it will deposit some money. Then the child's withdrawal task thread will notice this, get out of the while loop and complete the transaction.
What happens
Child goes to a infinite loop trying to withdraw. Mother's thread does not deposit.
I have a hunch that this is something to do with  wait(). When I call task.wait() from child, it is waiting for this specific instance of Task class to call notify() right? Not all instances of Task class.

public class Test {
    public static void main(String[] args) {
        Account account = new Account();
        new Child("Bob", account).start();
        new Mother("mary", account).start();

    }
}

class Child extends Thread {
    String name;
    Account account;

    public Child(String name, Account account) {
        super("Child");
        this.name = name;
        this.account = account;
    }

    private void transaction(int val, TaskType taskType) {
        Task task = new Task(account, taskType, val);
        task.start();
        synchronized (task) {
            try {
                task.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void run() {
        this.transaction(100, TaskType.WITHDRAW);
        System.out.println("100 WITHDRAW");
        this.transaction(150, TaskType.WITHDRAW);
        System.out.println("150 WITHDRAW");
        this.transaction(200, TaskType.WITHDRAW);
        System.out.println("200 WITHDRAW");
        this.transaction(500, TaskType.WITHDRAW);
        System.out.println("500 WITHDRAW");
    }
}

class Mother extends Thread {
    String name;
    Account account;

    public Mother(String name, Account account) {
        super("Mother");
        this.name = name;
        this.account = account;
    }

    private void transaction(int val, TaskType taskType) {
        Task task = new Task(account, taskType, val);
        task.start();
        synchronized (task) {
            try {
                task.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void run() {
        this.transaction(100, TaskType.DEPOSIT);
        System.out.println("100 DEPOSIT");
        try {
            Thread.sleep(600);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.transaction(150, TaskType.DEPOSIT);
        try {
            Thread.sleep(600);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("150 DEPOSIT");
        this.transaction(200, TaskType.DEPOSIT);
        try {
            Thread.sleep(600);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("200 DEPOSIT");
        this.transaction(500, TaskType.DEPOSIT);
        try {
            Thread.sleep(600);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("500 DEPOSIT");
    }
}

class Task extends Thread {
    private static int id = 0;
    Account account;
    TaskType taskType;
    int val;

    public Task(Account account, TaskType taskType, int val) {
        super("Task");
        this.account = account;
        this.taskType = taskType;
        this.val = val;
    }

    @Override
    public void run() {
        switch (taskType) {
            case WITHDRAW:
                account.withdraw(val, id);
                break;
            case DEPOSIT:
                account.deposit(val, id);
                break;
        }
        id += 1;
    }
}

class Account {
    int balance = 0;

    public synchronized void deposit(int val, int id) {
        this.balance += val;
        this.notifyAll();

    }

    public synchronized void withdraw(int val, int id) {
        while (this.balance < val) {
            System.out.println("Funds insufficient waiting..." + id);

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.balance -= val;
        System.out.println("Withdrawal successful " + id);
        this.notifyAll();
    }
}

enum TaskType {
    DEPOSIT,
    WITHDRAW
}

Update - synchronized on account object instead of task
private void transaction(int val, TaskType taskType) {
    Task task = new Task(account, taskType, val);
    task.start();
    synchronized (account) {
        try {
            account.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Did for both Mother and Child. I'm getting the same output.
Comment: In addition to the other concerns, `System.out.println` is synchronized internally.
Answer: The Mother and Child threads are waiting on the same task object, so they will wake up if you call task.notifyAll(). However, that's not what's happening. It is the account that calls notifyAll when more money is deposited.
The main problem with this implementation is that task is a separate thread. If you still want to keep it that way, then this is what you can do:
First: Account.withdraw waits with a Sleep. Instead, it should use wait(), so when Account.deposit calls notifyAll, it can wake up.
Your Mother and Child threads can wait on task, but then task has to notify them. So at the end of Task.run you should call notifyAll to wake up any threads waiting on the task.
You are essentially using three threads to run a sequential task.
Comment: Hi, did what you suggest. Still getting the same response. Updated code in question.
Comment: I think I see what's wrong. I  changed my answer. The Mother and Child should still wait for Task, but then Task has to wait on Account.
Comment: I understand now. Thank you :)


Componentes para Integration Services - SSIS - Data Flow

Question: Olá! Tenho uma necessidade de desenvolver um componente para o Integration Services (SSIS) -> Data Flow.
Já tenho componentes desenvolvidos para o a área do Control Flow, mas nunca desenvolvi nada para Data Flow. Tentei achar alguma coisa sobre esse tipo de componente na web mas não tive sucesso.
Se alguém souber algum tutorial ou exemplo, agradeço!
Answer: Tente esse tutorial. Está em inglês mas é bem explicado
https://www.mssqltips.com/sqlservertutorial/211/sql-server-integration-services-ssis-data-flow/


Why is my form only redirected sometimes?

Question: I want to have a user register, and be redirected to a node create form. Here's how I'm doing it thus far.
The setup
I have a route, my_module.register that is handled by MyController::register(). It returns the user register form, like so:
class MyController extends ControllerBase {
  public function register() {
    return $this->entityFormBuilder->getForm(User::create([]), 'register');
  }
}

I also have this service, my_module.form_alter_service (just pretend all the implied dependency injection is there):
class MyFormAlterService {

  public function registerFormAlter(array &$form, FormStateInterface $form_state) {
    if ($this->currentRouteMatch->getRouteName() == 'my_module.register') {
      $form['actions']['submit']['#submit'][] = [$this, 'redirectToAddNode'];
    }
  }

  public static function redirectToAddNode(array &$form, FormStateInterface $form_state) {
    $form_state->setRedirect(/* imagine a node form route here */);
  }

}

I have also implemented hook_form_FORM_ID_alter():
function my_module_form_user_register_form_alter(array $form, FormStateInterface $form_state) {
  \Drupal::service('my_module.form_alter_service')->registerFormAlter($form, $form_state);
}

The expected behavior
I fill out the user register form at /my_module/register, hit submit, and am taken to the desired node add form.
What happens instead
I fill out the user register form at /my_module/register and end up on my user edit page.
But then, if I delete that user, clear the cache, and repeat the process with the exact same credentials, it works as expected.
What I know

I am getting debugging output from every part of the process, so I know each part is running.
I am using the exact same pattern for the login form; identical code in the form alter, and that works great.
I can also get debug output from Drupal/user/EventSubscriber/AccessDeniedSubscriber::onException() which redirects authenticated users who are visiting the user.register route to their edit page. So I know that's causing the unwanted redirect, when the unwanted redirect happens.
I tried removing the user.roles:authenticated cache context from the form, and adding user, but that didn't seem to change things.

The actual question(s)
Why is the form initially not respecting the redirect I set in the submit handler? Why does a cache clear change that behavior?
Answer: The cause for the erratic behavior is probably the condition for the current route name in the form alter method. The form is not necessarily built in the same request as the custom controller, it could be served from cache or built in a POST request.
At the moment you have the condition for the route name because the controller invokes the default register form and the form alter doesn't know where it is called from. So you need to make the form distinguishable, for example by a different form handler, a field value in the new entity before you hand it over to the form builder or put the form alter code in a custom form class extending the core user form.
BTW why are you not redirecting by the destination query string you can set on the user register link, then you don't need code?
Comment: Thanks! To answer your question, I wanted users accessing the form on a specific path to be redirected, but to keep the default behavior for the basic login form. I also wanted a way to enforce this behavior, so that users wouldn't get different behaviors if the destination query was lost or altered somehow.


Why does AWS ECS FARGATE not generate log on cloud watch (terraform)?

Question: (I replace sensitive information with XXXXXX, YYYYYY)
1. containerized app
test.py:
import logging
logging.info("wow!!")

Dockerfile:
FROM python:3.10-slim
RUN apt-get update && \
    apt-get -y install git && \
    rm -rf /var/lib/apt/lists/*
COPY test.py /tmp/test.py
CMD ["python", "/tmp/test.py"]

2. Push image on ecr
$ docker push XXXXXXX.dkr.ecr.us-east-1.amazonaws.com/chois-trader:trading-latest

3. terraform
ecs.tf:
resource "aws_kms_key" "chois_trader" {
  deletion_window_in_days = 7
}

resource "aws_cloudwatch_log_group" "chois_trader" {
  name = "chois_trader"
}

resource "aws_iam_role" "chois_trader_task_execution_role" {
  name = "chois-trader-task-execution-role"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ecs-tasks.amazonaws.com"
      },
      "Action": [
        "sts:AssumeRole"
      ]
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "chois_trader_task_execution_role_policy_attachment" {
  role       = aws_iam_role.chois_trader_task_execution_role.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}

resource "aws_iam_role" "chois_trader_task_role" {
  name = "chois-trader-task-role"

  assume_role_policy = jsonencode({
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Principal": {
          "Service": "ecs-tasks.amazonaws.com"
        },
        "Action": "sts:AssumeRole"
      }
    ]
  })
}

resource "aws_iam_policy" "chois_trader_log_policy" {
  name        = "chois-trader-log-policy"
  description = "chois trader log IAM policy"
  policy = jsonencode({
    "Version": "2012-10-17",
    "Statement": [
      {
        "Sid": "1",
        "Effect": "Allow",
        "Action": [
          "logs:CreateLogStream",
          "logs:CreateLogGroup",
          "logs:DescribeLogStreams",
          "logs:PutLogEvents"
        ],
        "Resource": "arn:aws:logs:ap-northeast-2:YYYYYYYYY:log-group:chois_trader:*"
      }
    ]
  })
}

resource "aws_iam_role_policy_attachment" "example_attachment" {
  role       = aws_iam_role.chois_trader_task_role.name
  policy_arn = aws_iam_policy.chois_trader_log_policy.arn
}

resource "aws_ecs_cluster" "chois_trader" {
  name = "chois_trader"

  configuration {
    execute_command_configuration {
      kms_key_id = aws_kms_key.chois_trader.arn
      logging    = "OVERRIDE"

      log_configuration {
        cloud_watch_encryption_enabled = true
        cloud_watch_log_group_name     = aws_cloudwatch_log_group.chois_trader.name
      }
    }
  }
}

# Create a task definition with a container image
resource "aws_ecs_task_definition" "chois_trader_task" {
  family = "chois-trader-task"
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  execution_role_arn       = aws_iam_role.chois_trader_task_execution_role.arn
  task_role_arn = aws_iam_role.chois_trader_task_role.arn
  cpu    = 256
  memory = 512
  container_definitions = jsonencode([
    {
      name  = "chois-trader-task-container"
      image = "XXXXXXXX.dkr.ecr.us-east-1.amazonaws.com/chois-trader:trading-latest"
      log_configuration = {
        log_driver = "awslogs"
        options = {
          "awslogs-group"         = "chois_trader"
          "awslogs-region"        = "ap-northeast-2"
          "awslogs-stream-prefix" = "ecs"
        }
      }
    }
  ])
  volume {
    name      = "service-storage"
  }
}

4. tf apply
$ terraform apply

4. Execute task (AWS console)

After a few seconds, exit with status code 0!

But log not appear at all..

5. Reference

https://www.chakray.com/creating-fargate-ecs-task-aws-using-terraform/
Terraform AWS CloudWatch log group for ECS tasks/containers

Anything i missed?
Comment: Looks like you have a typo in the region you  have specified ap-northeast-2 and looking at your ecr repo you are running it in us-east-1
Comment: @VikramS No. that's not a typo. I intently use us-east repo for reducing cost. I don't think that ECR location is matter now cuz task pulled image and run successfully .
Comment: below config has options = {
          "awslogs-group"         = "chois_trader"
          "awslogs-region"        = "ap-northeast-2"
          "awslogs-stream-prefix" = "ecs"
        }
Answer: Below is our ECS task definition template through which the logs are going through fine. I am guessing there may be issue due to usage of underscore_separated keys instead of camelCase.
"logConfiguration": {
    "logDriver": "awslogs",
    "options": {
      "awslogs-group": "${cw_log_group_name}",
      "awslogs-region": "${aws_region}",
      "awslogs-stream-prefix": "${app_name}-${environment}-log-stream"
    }
},


In Factory.php line 699: The HOME or COMPOSER_HOME environment variable must be set for composer to

Question: I'm trying to deploy Laravel 9 project with github actions. here's my .yml file
 steps:
      - uses: actions/checkout@v3
      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: "8.1"
      - name: Copy .env
        run: php -r "file_exists('.env') || copy('.env.example', '.env');"
      - name: Install Dependencies
        run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist

However, it's failing in composer install with following error:
In Factory.php line 699:

  The HOME or COMPOSER_HOME environment variable must be set for composer to
  run correctly

install [--prefer-source] [--prefer-dist] [--prefer-install PREFER-INSTALL] [--dry-run] [--dev] [--no-suggest] [--no-dev] [--no-autoloader] [--no-progress] [--no-install] [--audit] [--audit-format AUDIT-FORMAT] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--apcu-autoloader-prefix APCU-AUTOLOADER-PREFIX] [--ignore-platform-req IGNORE-PLATFORM-REQ] [--ignore-platform-reqs] [--] [<packages>...]

Error: Process completed with exit code 1.

I've tried this solution, however it's not working.
Server: Ubuntu 18.04
Composer version: 2
Laravel version: 9

Answer: On Ubuntu 20.04 LTS I ran into a similar issue.
The solution that worked for me is running this (ran as non-root):
export COMPOSER_HOME="$HOME/.config/composer";

This allowed me to use composer again, but broke the cache directory.
Hope this helps.


Flutter Model Class

Question: What type of model class is this ?? how can I convert it to a dynamic model class for fetch data from JSON API?? please any suggest me a solution?
i want to make a cart page for my  json API.
import 'package:flutter/material.dart';
import './product.dart';

class Products with ChangeNotifier {
  List<Product> _items = [
    Product(
  id: 'p1',
  title: 'Red Shirt',
  description: 'A red shirt - it is pretty red!',
  price: 29.99,
  imageUrl:
      'https://cdn.pixabay.com/photo/2016/10/02/22/17/red-t-shirt-1710578_1280.jpg',
),
Product(
  id: 'p2',
  title: 'Trousers',
  description: 'A nice pair of trousers.',
  price: 59.99,
  imageUrl:
      'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Trousers%2C_dress_%28AM_1960.022-
 8%29.jpg/512px-Trousers%2C_dress_%28AM_1960.022-8%29.jpg',
 ),
 Product(
  id: 'p3',
   title: 'Yellow Scarf',
   description: 'Warm and cozy - exactly what you need for the winter.',
   price: 19.99,
   imageUrl:
      'https://live.staticflickr.com/4043/4438260868_cc79b3369d_z.jpg',
),
Product(
  id: 'p4',
  title: 'A Pan',
  description: 'Prepare any meal you want.',
  price: 49.99,
  imageUrl:
      'https://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Cast-Iron-Pan.jpg/1024px-Cast-Iron-
  Pan.jpg',
 ),
 ];
 // var _showFavoritesOnly = false;

  List<Product> get items {
  // if (_showFavoritesOnly) {
  //   return _items.where((prodItem) => prodItem.isFavorite).toList();
  // }
 return [..._items];
 }

  List<Product> get favoriteItems {
  return _items.where((prodItem) => prodItem.isFavorite).toList();
 }

  Product findById(String id) {
  return _items.firstWhere((prod) => prod.id == id);
  }

  // void showFavoritesOnly() {
  //   _showFavoritesOnly = true;
      //   notifyListeners();
  // }

  // void showAll() {
  //   _showFavoritesOnly = false;
  //   notifyListeners();
  // }

   void addProduct() {
  // _items.add(value);
  notifyListeners();
  }
  }

I want to use this type model class :-
class Product {
int id;
String productName;
String productDescription;
int categoryId;
int colorId;
int sizeId;
int regularPrice;
int salePrice;
int quantity;
int ratting;
String productImage;
int flag;
int status;
String createdAt;
String updatedAt;

Product(
  {this.id,
  this.productName,
  this.productDescription,
  this.categoryId,
  this.colorId,
  this.sizeId,
  this.regularPrice,
  this.salePrice,
  this.quantity,
  this.ratting,
  this.productImage,
  this.flag,
  this.status,
  this.createdAt,
  this.updatedAt});

 Product.fromJson(Map<String, dynamic> json) {
id = json['id'];
productName = json['product_name'];
productDescription = json['product_description'];
categoryId = json['category_id'];
colorId = json['color_id'];
sizeId = json['size_id'];
regularPrice = json['regular_price'];
salePrice = json['sale_price'];
quantity = json['quantity'];
ratting = json['ratting'];
productImage = json['product_image'];
flag = json['flag'];
status = json['status'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}

Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['product_name'] = this.productName;
data['product_description'] = this.productDescription;
data['category_id'] = this.categoryId;
data['color_id'] = this.colorId;
data['size_id'] = this.sizeId;
data['regular_price'] = this.regularPrice;
data['sale_price'] = this.salePrice;
data['quantity'] = this.quantity;
data['ratting'] = this.ratting;
data['product_image'] = this.productImage;
data['flag'] = this.flag;
data['status'] = this.status;
data['created_at'] = this.createdAt;
data['updated_at'] = this.updatedAt;
return data;
}
}

I know parameter is not same I will make it same but I want to fetch data from Json API.
Answer: In Flutter, there are several ways to fetch data from the internet (e.g. fetching data from JSON API). Some of these where documented in the Flutter official documentation.

Networking & http
Firebase
JSON and serialization

Regarding your question, you can refer on the third bullet for a deeper guide on how JSON works on Flutter. There is a cookbook available to practice and understand well the concept. Check out this blog "Retrieving Json Data in Flutter".

Flutter Model Class


Why does this C substring method not work?

Question: I have this written so far. substring(orig, 3, 3, substr)
Given:
orig = "onetwothree"
should make
substr = "two" ,but it doesn't what am I doing wrong?
void substring(char* source, int start, int length, char* target) {
    int i;
    for(i = 0; i < length; i++) {
        target[i] = source[start + i];
    }
}

Comment: You should make sure so your buffer has enough space to hold the substring and you should also null terminate it after the loop: `target[length] = 0; `
Comment: Seems You are trying to modify a string literal which gives u a Undefined behavior.
Comment: @AlokSave no, the string literal is never modified, only read. the target is modified.
Comment: Don't forget to check `if length > string length`. Also you have to check if the target could hold `length` characters
Answer: You forgot to zero-terminalte the target string.
There also a few extra checks you should have implemeneted. For example, what should happen when the source string ends before length characters are copied?
Additionally, it makes sense to const-qualify the source pointer (const char* source) and use size_t instead of int to represent indices and lengths.
Answer: You forget to add the null-termination character '\0'.
target[length] = '\0';


How to extend section width: 100% using css

Question: I have a section inside width: 1180px; i want to extend this green color div I want to make width: 100% I have tried using vw but not getting but some extra space is coming. can anyone suggest me? Is there any other way to do using CSS.

.wrapper {
  width: 100%;
  position: relative;
  background: #ccc;
}

.inner {
  width: 1180px;
  margin: 0 auto;
  background: pink;
}

.box1 {
  height: 50px;
  background: red;
}

.box2 {
  height: 50px;
  background: green;
  margin-left: calc(-100vw/2 + 100%/2);
  margin-right: calc(-100vw/2 + 100%/2);
  width: 100vw;
}

Comment: why can't you just move it below the box if you want it to be wider?
Answer: You need to reset the margin using media query. Initially you have a negative margin but after 1180px it will be a positive one creating the unwanted space. You also don't need to set width using vw unit. Keeping the default width is enough:

.wrapper {
  width: 100%;
  position: relative;
  background: #ccc;
}

.inner {
  width: 1180px;
  margin: 0 auto;
  background: pink;
}

.box1 {
  height: 50px;
  background: red;
}

.box2 {
  height: 50px;
  background: green;
  margin-left: calc(-100vw/2 + 100%/2);
  margin-right: calc(-100vw/2 + 100%/2);
}
@media all and (max-width:1180px) {
  .box2 {
    margin:0;
  }
}

Answer: You could use negative margin - the only problem with this approach is that if the page gets a vertical scroll, this will add a horizontal scroll as 100vw doesn't take into account the 20px caused by the vertical scroll:

body {
  margin: 0;
}

.wrapper {
  width: 100%;
  position: relative;
  background: #ccc;
}

.inner {
  width: 1180px;
  margin: 0 auto;
  background: pink;
}

.box1 {
  height: 50px;
  background: red;
}

.box2 {
  height: 50px;
  background: green;
  width: 100%;
}

@media screen and (min-width:1180px) {
  .box2 {
    margin: 0 calc(((100vw - 1180px) / 2) * -1);
    width: auto;
  }
}

As I say in my comments, it would be better to just move the green div outside your wrapper
Answer:

.wrapper {
  width: 100%;
  position: relative;
  background: #ccc;
}

.inner {
  width: 1180px;
  margin: 0 auto;
}

.box1 {
  height: 50px;
  background: red;
}

.box2 {
  height: 50px;
  background: green;
}

Answer: Try this:

.wrapper {
  width: 100%;
  position: relative;
  background: #ccc;
}

.inner {
  width: 1180px;
  margin: 0 auto;
  background: pink;
}

.box1 {
  height: 50px;
  background: red;
}

.box2 {
  height: 50px;
  background: green;
  width: 100%;
}


Problema com setlocale no servidor web

Question: Estou com um site online que esta setado o time zone para America/Sao_Paulo e utilizando setlocale para portugues, mas mesmo assim o site onde tenho funções strtime, dão os texto em inglês,  tentei colocar no código a função set time zone mas ainda assim não funcionou.
Alguém consegue me ajudar. Não sei se é algum problema comum ou não, ps: no phpinfo() esta setado para são paulo.
Comment: Possível duplicata de [Como fazer a função date() formatar uma data em português?](https://pt.stackoverflow.com/questions/8317/como-fazer-a-fun%c3%a7%c3%a3o-date-formatar-uma-data-em-portugu%c3%aas)
Comment: Resolvido, o servidor nao aceita portuguese-brazilian, mesmo no manual do php costando que aceita
Comment: Na verdade `setlocale` retorna `false` quando o locale não é reconhecido (e se não me engano, não mostra nenhuma mensagem de erro). E aí o locale não é alterado e ele usa o que já estava configurado antes (e no localhost provavelmente estava português, e no servidor inglês). Verifique o retorno de `setlocale` só pra ter certeza... E [no manual](http://php.net/manual/en/function.setlocale.php#117529) só vi que aceita `Portuguese_Brazilian`, mas só no Windows, nos demais sistemas é pt_BR mesmo
Comment: a data é exibida apenas com números? ex: 14/03/2019
Comment: não são exibidas os textos em ingles, como ex(Thursday)
Comment: Se não me engano, `date` sempre retorna os textos em inglês. O timezone só serve para saber qual a data e hora atual a ser considerada (já que isso varia conforme o fuso horário), e o idioma não tem nada a ver com o timezone. Se quer textos em outro idioma, use [`strftime`](http://php.net/manual/en/function.strftime.php) junto com [`setlocale`](http://php.net/manual/en/function.setlocale.php)
Comment: estou utilziando este setlocale setlocale {(LC_TIME, "portuguese-brazilian");} mesmo assim o strtime ignora
Comment: Não sei se o PHP reconhece "portuguese-brazilian", tem que ser "pt_BR". Veja também se o locale está instalado no servidor: https://stackoverflow.com/q/10909911
Comment: Irei ver se esta instalado, mas o "portuguese-brazilian" funciona, por que pelo menos no localhost ele reconhece, so estou com este problema nos servidor de hospedagem
Comment: @LipESprY não é duplicada, olhei mas não é este este problema
Answer:
"- o servidor nao aceita portuguese-brazilian, mesmo no manual do php costando que aceita"

Feitas algumas pesquisas sobre o setlocale, posso concluir que ele não tem ligação direta ao timezone ou a versão do seu servidor PHP. Mas ele é diretamente dependente do sistema operacional em que está rodando seu servidor PHP!
Como exemplo, meu ambiente de desenvolvimento, com Windows 10 e rodando o PHP através do UniServer Zero XIII, trouxe os seguintes resultados:
// locale string atual:
echo setlocale(LC_TIME, 0); // C
echo setlocale(LC_ALL, 0); // LC_COLLATE=C;LC_CTYPE=Portuguese_Brazil.1252;LC_MONETARY=C;LC_NUMERIC=C;LC_TIME=C

setlocale(LC_ALL, 'portuguese-brazilian');
echo strftime('%A, %d de %B de %Y'); // domingo, 17 de mar�o de 2019

setlocale(LC_ALL, 'portuguese-brazilian.utf8');
echo strftime('%A, %d de %B de %Y'); // domingo, 17 de março de 2019

setlocale(LC_ALL, 'pt_BR');
echo strftime('%A, %d de %B de %Y'); // domingo, 17 de março de 2019

setlocale(LC_ALL, 'pt_BR.utf8');
echo strftime('%A, %d de %B de %Y'); // domingo, 17 de março de 2019

setlocale(LC_ALL, 'pt_BR.iso-8859-1');
echo strftime('%A, %d de %B de %Y'); // Sunday, 17 de March de 2019

setlocale(LC_ALL, 'portuguese');
echo strftime('%A, %d de %B de %Y'); // domingo, 17 de mar�o de 2019

Obs.: teste uma por vez, já que ele considera a última válida caso não encontre!
Charset do HTML: utf8

A própria documentação do PHP recomenda que os usuários de Windows busque a string do local (string locale) no site da Microsoft MSDN:

Dica Usuários do windows encontraram informações úteis sobre as strings de locale no site MSDN da Microsoft. Strings das línguas suportadas podem ser encontradas » aqui as strings de pais/região suportados »  aqui. Sistemas windows suportam códigos de três letras para pais/região especificados por ISO 3166-Alpha-3, que pode ser encontrada em Unicode website. - PHP: setlocale

Mas achei mais conveniente através da Tabela de locais do site Moodle. Que já adianta: não há forma de adicionar novos locais no Windows. Já no Linux é possível instalar novos locais e algumas distribuições já tem todas por padrão. O Moodle, inclusive, explica isso.
Outra questão é que você pode definir várias locale strings de uma só vez e o PHP se encarrega de definir "a que encontrar primeiro".
setlocale(LC_ALL, "pt_BR", "pt_BR.iso-8859-1", "pt_BR.utf-8", "portuguese", ...);

Obs.: isso não quer dizer que ele vai definir a melhor!
Outra recomendação é, se viável, sempre voltar ao padrão depois de exibir sua data com o idioma em questão. Isso vai prevenir possíveis incompatibilidades relacionadas a várias outras funções do PHP. Vide relatos nas User Contributed Notes na documentação do setlocale.
No geral, se você tiver acesso root ao seu servidor, não vai ser difícil encontrar uma opção válida. Caso não tenha, terá de se render ao suporte da empresa que hospeda seu site - que nem sempre atende as expectativas, onde tudo que eles não querem fazer é transformado em "viola a política de segurança".

Problema com setlocale no servidor web


How do I use an equalizer?

Question: So mixing... (audio engineering). When using an equalizer on trackouts/instrument tracks, the general approach is cut out the "bad frequencies" and increase the "good frequencies" to accentuate the instrument track.
What exactly are the bad frequencies? I can sweep across the audio spectrum and a lot of frequencies can sound "bad", so what exactly should I be cutting specifically and to what degree of decibels?
At the same token, what are the good frequencies, how wide should my Q be when accentuating them and to what degree of decibels?
Comment: They're not bad frequencies. They are conflicting. An example would be acoustic guitar. Some are more trebly, some more bassy. But you don't have a dozen acoustics in the studio so if you want it to sound brighter so it stands out more you could EQ it.

Maybe the snare you have doesn't sound 'tight' as you'd like for this particular song ... eq it to make it sound like a different snare. Does doing that make the snare bad?
Comment: What is "Q" in this context? [*Q* factor](https://en.wikipedia.org/wiki/Q_factor)? A measure of the bandwidth of [the bandpass filters in the equalizer](https://en.wikipedia.org/wiki/Equalization_(audio)#Filter_types)? Or something else?
Answer: There is no one way to use an EQ, but there are a few common techniques that people use to EQ, and they can be applied on most sources.
First a few general tips:

Make small changes. EQs are not magic, and they will not instantly improve your recording. They are best for making small tweaks.
Be careful with boosting. It's oftentimes better to attenuate first and then increase the overall gain if necessary.
Try things. Try whatever you want, and learn from it. If you want something to sound in a specific way, that's completely fine. Don't let random people on the Internet tell you what to do

Now, the techniques:

Cutting / Filtering
You may have heard about something like a high-pass or low-cut filter. This concept can be achieved by taking a EQ band and positioning it to "cut" only the lowest frequencies.
If you are recording a violin for example, their lowest string G is just around 190 Hz. Any information below 190 Hz is likely not useful, so you can simply cut it out. If you repeat the same concept on every instrument in the mix, you'll likely increase the total clarity.

You can of course do the inverse to achieve a low-pass filter, but
  this is not as common (especially not with acoustic instruments) as it
  results in more of an effect.

Cleaning
You mention the "bad" frequencies. What you are referring to are frequencies that are especially resonant, compared to the rest of the spectrum. The reason the "bad" frequencies occur can be due to the room they were recorded in, the instrument itself, the playing technique, or a number of other reasons.
The act of removing (attenuating) these frequencies is commonly referred to as cleaning.

Pick the most narrow Q your EQ will allow, max out the gain and scan through the spectrum until you find especially resonant frequencies.

Once you find the most resonant ones, widen your Q and attenuate the problematic frequency and its near range with your gain set to something like -1 to -3 dB.

Note that the resonant frequencies will probably reoccur one octave
  above the last, so it can be useful to start in the low range, and
  then go up by octaves (double the frequency) using a lower gain each time

As for specific values, I gave you a general idea of some of it, but really as I said in the beginning, there are no one-size-fits-all solution in EQing. Play around with different values and see what happens. The most important tool at the end of the day, is your ears.
If it sounds good, it's good.
Comment: Check out this bad boy: https://www.audio-issues.com/music-mixing/all-the-eq-information-youll-ever-need/
Comment: "Pick the most narrow Q your EQ will allow" – _too_ narrow is usually not good for the finding-step, unless it's something like a static hum you want to remove. A width of ½ to 1 octave is generally good. If you make the peak too narrow, then it'll make a bad ringing sound everywhere, which may actually be what the OP's problem was when trying the sweeping.
Comment: @leftaroundabout never had that problem myself but it's certainly good to know that can be an issue, thanks.
Comment: Re *"most narrow Q"* (two instances) and *"widen your Q"*: Don't you mean "most narrow bandwidth (highest Q)" and "widen your bandwidth (lower Q)", respectively? (Ref. *[Relationship between Q and bandwidth](https://en.wikipedia.org/wiki/Q_factor#Relationship_between_Q_and_bandwidth)*)
Comment: @PeterMortensen Fair enough, but Q is quite unintuitive especially for beginners and that's why I phrase it as "most narrow Q". This phrasing along with the image examples makes it unlikely that it will be misunderstood.
Answer: The best way to use an equaliser is not to NEED to use it.
Yes, some instruments share a frequency range, playing them together can sound muddy.  So DON'T play that pair of instruments together.  It's called good orchestration, and it's been part of the composer's art for a thousand years.
You say "the general approach is cut out the "bad frequencies" and increase the "good frequencies" to accentuate the instrument track".   No.  If you're GOING to eq, most of the time you should cut.  Maybe a gentle boost in the 'presence' or 'air' ranges of a vocal.  But generally beware of boosting, particularly of boosting a narrow range.
You might want to cut the low bass, below the range that the anticipated playback system can handle.  Leave it in for the 'club mix' though - but I hope you've got monitors that can tell you what you're getting!
Comment: There are three fundamentally different use cases for EQing. One is to *literally* "equalize", i.e. (mostly) remove unnaturally overemphasized frequencies and (rarely) boost missing ones to make it sound more "natural". The second case is sound design, i.e. make it sound "less natural". For example, a heavy metal kick drum needs to be aggressively EQd in a specific way until it sounds nothing like an actual kick drum anymore. However, that is the sound a kick drum in this genre is supposed to have. Number three is "cleaning up the mix". With a good arrangement, this shouldn't be needed.
Comment: Exactly. Narrow boosts are good for a wah-wah sound, else... not so much.
Answer: The use of EQ is twofold:

to try to give each instrument/part it's own space in the spectrum.

First up - think about what the objective is of a good mix? You want to hear each part that contributes to the musical arrangement, clearly and in it's own space. Of course, you can't do any better than the raw material that you have recorded here! So already part of mixing is thinking about the arrangement. (Years ago, most recording sessions had a specialist arranger - these days arranging and mixing tend to overlap a lot.)
So each musical part (this could be bass, drums, percussion, lead vocal, backing vocals, horns, strings, guitars, keys ... whatever) wants to sit in its own space and be clearly audible. If the arrangement is good this should mostly look after itself but EQ can help. Here are some typical uses:

male lead vocals often get a little boost at around 3-5kHz - known as presence, this helps it "cut through". Other parts that might interfere might get a slight cut at the same frequency.
bass can sound better (especially on smaller speakers) when boosted a bit at around 200-250Hz. This gives a bit of "pop" to the sound.
cymbals might be boosted a bit at around 5-10kHz and up.

and so on. The key here is not to overdo it. Less is more.

To remove any annoying frequencies, or just stuff that shouldn't be there. For instance:

many parts will get a "low cut" at around 125Hz (analogue mixers usually have a dedicated switch for this). This is to remove any low end "rumble" which might not be directly audible but still decreases headroom, and keep the bass end of the mix clean.
a vocal or other part that has some annoying "ring" to the sound - you can use EQ to tune into that part of the spectrum and reduce it.

Basically you use your ears. just beware of overdoing it! On today's DAWs which have almost unlimited EQ and FX, it is all too easy to go overboard, and end up with a mix that sounds really unnatural and awful. The best approach is to try to start with good musical performances well recorded, and then only use EQ to fix what really needs fixing.
Answer:
What exactly are the bad frequencies? I can sweep across the audio spectrum and a lot of frequencies can sound "bad", so what exactly should I be cutting specifically and to what degree of decibels?

There's no general answer to this: it depends on the instrument, the recording system and the room. You want to avoid resonances, where one frequency sounds much louder than the rest because the room acts to amplify this frequency.

At the same token, what are the good frequencies, how wide should my Q be when accentuating them and to what degree of decibels?

Accentuation quickly leads to listening fatigue. Your goal is to make the recording as good a match as possible for a live session in a perfect room.
There's a pitfall here: when you listen to the recording in your studio via loudspeakers, your playback chain includes the loudspeakers and the room they're in. This adds its own coloration, which you may have to compensate for by running an EQ in the playback chain, separate from any EQ that's applied to the recorded tracks.
When you record a live concert, things get more complicated: you need one EQ for the PA system (which is geared to avoiding feedback), and a separate EQ for the recording.

How do I use an equalizer?


Website with Admins that can add/edit articles/pages

Question: Recently, we have launched the website for our Call of Duty clan. However, we would like admins to be able to log in on the page, and allow them to add or edit articles to the homepage or other pages, or edit pages like a member roster.
I'm not expecting very specific answers since this is quite vague i think, but i was wondering what kind of system we should be using for this. I myself have quite some experience with HTML and css, but less with PHP and JS. I can use them, but i don't have the experience to know what system to use for these kind of situations.
Answer: it's easy to answer your question!
I would install Joomla - www.joomla.org. A lot of other clans for Call of Duty use it, and it's really user-friendly to install. (It's also free).
Joomla allows you and other people you choose to upload articles, edit them - all via the Admin section. No programming or PHP experience is necessary.  for install instructions, just search YouTube.com for "Install Joomla".
G'Luck!
Answer: The term for what you're looking for is CMS, or Content Management System. There are a hojillion of these out there, and some of them even with free hosting. Here is a directory for php CMS:
http://php.opensourcecms.com/scripts/show.php?catid=1&cat=CMS%20/%20Portals
DotNetNuke is a popular Windows CMS. Here is a site with free DNN hosting:
http://www.dnn4free.com/
HTH.
Answer: There are a lot of engines out there. Joomla, Wordpress(blog+), Drupal, and etc. If you are looking to blog a lot I would suggest Wordpress.  Basically these are CMS (content management systems).
Answer: It has been mentioned, but I would like to throw in my support for wordpress. Especially if you don't have a ton of experience with web based applications, deployment with most hosting providers is extremely easy.


Fuzzy Logic and membership function of likert scale

Question: I've just started learning about fuzzy logic and I would greatly appreciate your help on this. I have conducted a survey to find the factors that influence cost overrun in residential buildings. The questions were qualitative on a scale of 1 to 6 (1=never...6=always). Then the RII for each factors were calculated and top factors were selected (5 factors).
I'm trying to do some risk assessment using fuzzy logic (I am hoping the end result would be a user input form), however, I am facing difficulties with how to find the membership function of the the 6-scale ranking. I've found some papers, but unfortunately, they don't explain how they did it.
If I wanted to use trapezoidal MF, how should that be written?
Should I have 5 MF for each factor? What would the parameters be?
How can I use the RII and the weights of each factor in the fuzzy approach?
Your help is greatly appreciated!
Answer: This is an incomplete answer proposal: first, could you please describe your problem a bit more, and what you have tried already?
To the question about the number of membership functions, without knowing more, I'd suggest (based on a feeling) that it heavily depends on factors. Do you have natural interpretations for the membership functions? (What have you tried this far?)
A paper
A Fuzzy Decision Making Approach in Evaluating Ferry Service Quality seemed to contain much details.
Another paper also contained quite nice
Measurement and fuzzy scales exposure: identify the problem, fuzzify inputs, construct rules, aggregation, defuzzify, sensitivity analysis.
Have you seen those & do they answer to some of your questions?


Form submission not saved when using a dynamic redirect

Question: I have forms where I use a form alter to set various form fields on the fly.
One of which is the Thank You page field that a user should go to after submitting.
Example $form['submitted']['thankyou_page']['#value'] = 'my_page';
I use the same form for multiple reasons so setting the thank you page to suit.
After setting these (which work fine) I then enter a function to do some processing of the form fields to a CRM.
The final section of this function is like this
try {
    $result = $client->CreateContact($data);
} catch (Exception $e) {
    $result = $e;
}
  my_submit_handler2($values['thankyou_page']); // redirect
}
}

The processing works fine to CRM but my problem is that the form submission (result) doesn't save in Drupal and the auto-emails after submit fail to send too.
The redirect is done like this
function my_submit_handler2($f) {
  drupal_goto($f);
}

So I guess the submission is being interrupted?
How can I do these redirects without affecting the flow of the form submission?
Answer: A form submission handler, as well a form validation handler or a hook to alter a form, should never call drupal_goto() since it outputs a HTTP header and interrupts what Drupal is doing.
The correct way to redirect a form from a form submission handler is setting $form_state['redirect'] in Drupal 7, or calling $form_state->setRedirect() in Drupal 8. The alternative for Drupal 8 is calling $form_state->setRedirectUrl().
For Drupal 7, the following code would redirect the users to node/123?foo=bar#baz.
$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);


No sound from microphone over Remote Desktop (Windows Server 2019)

Question: I'm trying to allow users to properly use video/voice chat software (like Teams) on our Remote Desktop server. Sound playback works fine, but I've been unable to get sound input (microphone input) through to the server.
The sound control panel on the remote server shows my input device as "Remote Audio", but shows no incoming signal when tested. On the local computer, the sound control panel does show a signal, so the mic is working locally, just not over RDP.
Remote server is running Windows Server 2019 Datacenter. Local clients are running Windows 10 or 11.
I have done some research on this issue, here's everything I've already tried:

In the Remote Desktop client, setting Local Resources > Remote audio > Remote audio recording to Record from this computer.
Ensure that both the Windows Audio and Windows Audio Endpoint Builder services are running on both the client and server machines.
Test that the microphone is working locally (as mentioned above).
On the remote server, edited group policy located in Computer Configuration > Administrative Templates > Windows Components > Remote Desktop Services > Remote Desktop Session Host > Device and Resource Redirection. I set Allow audio and video playback redirection and Allow audio recording redirection to Enabled. All other policy options in that folder remain Not configured.
Testing a second client machine.
Testing a second user account on the remote server.

None of the above fixed the problem for me. Any other suggestions?
Answer: When you're connected within your RDP Session, did you check within :
Settings > Privacy , then check within Microphone if the wanted apps are ticked or not.
Comment: Good suggestion. I did not check there. Unfortunately I don't see anything helpful. On the remote server, even Windows itself seems to be getting no mic input (seen via the Control Panel). On the local machine (while RD is connected), nothing with a name similar to "Remote Desktop" appears in either the "apps" or "desktop apps" sections of the microphone privacy settings page.
Comment: Crap... Another idea : if you go to HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control \ Terminal Server \ WinStations \ RDP-TCP, what's the value of fDisableAudioCapture ? (enabled value : 0, disabled value : 1)
Comment: The value of fDisableAudioCapture is 0 on both server and client.


How to prove that sub-level set of spectral radius function is not convex

Question: Let $A \in \mathbb{R}^{n \times n}$ and $\rho(A)=\{|\lambda|_\max : \lambda \text{ is an eigen-value of } A\}$. I am trying to prove that the set
\begin{align*}
B_\alpha=\{A: \rho(A) < \alpha \}
\end{align*}
need not be a convex set in general (for any $\alpha>0$). Can anyone provide a useful hint about how to proceed?
Answer: Note that the $2 \times 2$ matrices $\pmatrix{0 & 0\cr 1 & 0\cr}$ and
$\pmatrix{0 & 1\cr 0 & 0\cr}$ have spectral radius $0$, but their average
has positive spectral radius.


Mostrar / Ocultar o console em uma aplicação em c#

Question: Procurei sobre como mostrar/ocultar o console em uma aplicação em c# nos fóruns em português e não encontrei. Procurando nos internacionais me deparei com várias soluções porém encontrei uma de muito fácil aplicação e gostaria de compartilhar com os demais.
Como ocultar (e mostrar) a janela do console associada com sua própria aplicação console?
Answer: Segue o código:
<code>using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

const int SW_HIDE = 0;
const int SW_SHOW = 5;
var handle = GetConsoleWindow();

// Ocultar
ShowWindow(handle, SW_HIDE);

// Mostrar
ShowWindow(handle, SW_SHOW);
</code>


How to Stop Exchange Server 2003 sending out Mass Spam / Virus Email from Unkown Account?

Question: I'm young and new to the scene, I have been working on a family member's business server. It is an old server and has a few problems but has
a big main one I'm trying to fix now.
I'll try be as clean and concise as I can be in explaining what I need.
The Server Details:
The server is an old box with limited hardware: 50Gb C: Drive With only 1.3Gb free
                     Total Combined Hard Drive Space : 270Gb with 31Gb free
                     Only Has 4Gb RAM memory
                     Has Intel Xeon Processor @ 2.00Ghz
The server also has old software / operating sys: Running Small Business Server 2003 Service Pack 2
                     Running Exchange Server 2003
The Problem:
The Server was recently black listed by our ISP. Upon Calling them they provided no support and said that it should be running fine. All configuration pointed to their connection being the problem so we told the SMTP Virtual Server to create its own connectors using DNS. This fixed our outgoing email problems. However now I see that we have a infected computer that may be sending out mass email.
This is where I start losing track of things about the situation. What happens is in the Exchange server queue we have many connectors to domains that don't exist and the message tracking shows mass emails being sent from our exchange out. Presumably a virus or computer is trying to send spam or send out virus' to other people through our exchange server.
At first it was using a gmail account, I blocked the email account's privilege to send out through the server but then it came back using a different email. Now our queue is clogged more. not just with failed email attempts but all the NDR can't be sent through to a real domain so it sits in the queue too. This has / will lead in blacklisting on our IP as well as our server being clogged up.
I did a test on Mxtoolbox for our mail server and it said that there wasn't an open relay as I thought initially.
Older posts haven't provided instruction that i can't follow, understand or adapt to this server / my problem.
Solution?:

A solution to stop our exchange sending out these mass emails / stop the virus without manually blocking all emails from sending out email other than ones I specify otherwise there will be problems opening new accounts later.
A small explanation As to whats happened so I understand it and can stop it / have knowledge for the future.
And a quick way to remove all the queue when I know no legitimate mail is being sent as there is too many to delete when using the find messages and delete with no NDR inside queues.
Hopefully these things will help me and others in the future to understand and fix what has happened.

Final Notes:
Any help at all will be greatly appreciated and any suggestions on where to look / things to try or do.
I understand I'm not the best admin for mail servers, however i'm doing it for free as we don't have money to spend on IT support but really need the services for the business and I'm doing the best I can.
If Any more detail or information is needed please don't hesitate to ask.
Thanks,
Jesse Hayward.
Answer: After further research and some common sense i managed to find a solution.
If this is happening to you, Go to the system's event viewer. Then filter your events with MSExchangeTransport. Then with authentication. (This needs to have been previously turned on through MSExchange settings). Once done Look to see what user account is being used to authenticate the emails being sent when the spam is going through.
Chances are that this account has an easily guessed password or has let through a virus that has stolen its password. Therefore Disabling the account if necessary or changing the password should hopefully stop the problem from continuing.


Autocomplete box popup not showing in landscape mode in Windows phone 7.5

Question: The autocomplete box displayed when typing the search text in portrait mode, but is not displayed in landscape mode.
Answer: This is a known issue with the Silverlight Toolkit AutoCompleteBox, and that it designed that way in order to match the native experience on the phone, where no autocomplete suggestions come up in landscape mode because of space.
See the Ref here


How to restrict node access based on user roles?

Question: How can I allow only specific nodes to be displayed based on user roles?
Basically, I do not want to allow nodes to be accessed by users of some specific role.
Comment: Not sure why they closed your question, it's a good question. And for anyone who might be interested, I always solve these types of problems by making a custom module and overriding https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access/7 ... full control, no overheads in the form of massive modules, way easier and more reliable.
Comment: @coderama It's a bit broad, without the OP showing what they tried so far. Such questions get broad answers that probably will not help future users.
Answer: What you're talking about is Drupal node access control, which is a huge subject.
The core's built-in support for node access control is rather coarse, and to control access to view a node by role, you must use some sort of node access control module.
There is a page at Drupal.org listing all node access modules, with a capsule review of each.  I suggest you take a look at that page to see if you can find a suitable module to control access based upon roles.
When working with access control, it helps to understand how Drupal access control modules actually work, here is a quick description:

Users granted permission to administer nodes are never restricted by node access control. Users who do not have permission to View published content can never be granted access by a node access module. Only users who have 'access content' and not 'administer nodes' are eligible for the wild world of node access module control.
Node access control in Drupal is as a rule additive. This means that any module doing access control in accordance with the "the Drupal philosophy" should only allow access, not deny it. An administrator who wants to fine tune access to a node must first make sure nobody has access, and then add access grants to anyone that shall have access.

This means that it may be rather cumbersome to restrict access to individual with a module like Content Access, since you must start by denying everyone access, and then add it back to those nodes you don't want restricted.  However, I think it is the best option if you really need to do it node by node. Its primary resolution is content types, but it allows you to override this for single nodes.
Unfortunately, you shall not be able to use Deny access since it only works on content types, with no override for individual nodes.
NB: Using more than one node access module is not recommended.
Note that if you can change your requirements so that you can use content type as your basic unit for node access control, then Deny access would be ideal.   For instance, if you have a role "student" and you want to deny access to nodes with answers, then you can create a content type "Answer" (which can just be a clone of the default "Article") and Deny access will take care of protecting all nodes of the type "Answer" from being viewed by the role "student".
Comment: basically i do not want to allow nodes to be accessed by users of some specific role is this too tough to implement ?
Answer: Have you tried the content access module

This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.
Comment: If you don't need node-based permissions then a simpler module is the [node view permissions](https://drupal.org/project/node_view_permissions) module which controls access based only on content type and user role.
Comment: This module is beta for Drupal 7


Fazer busca de palavra dentro de uma lista e retornar tuplas ordenadas em PYTHON

Question: O algoritmo deve receber uma string, contar quantas palavras iguais e retornar uma lista de tuples com as palavras que mais aparecem na string e quantas vezes ela aparece.
O problema é que nas buscas é palavras que começam iguais ele conta mais vezes. Tipo: "but" e "butter", ele conta but 3X e butter 2X.
"betty bought a bit of butter but the butter was bitter"
Ainda desejo ordenar primeiro pelas palavras que aparecem mais e caso apareçam um numero de vezes igual, pela ordem alfabética das palavras.
Tipo: "falling" e "down", ambas aparecem 4X, por isso na saida ordenar primeiro "down" e depois "falling".
"london bridge is falling down falling down falling down london bridge is falling down my fair lady"
def count_words(s, n):
top_n = []
itens = n
words = s.split()
pref = words
for p in pref:
    cont = 0
    for w in words:
        if w.startswith(p):
            cont+=1
    if (p, cont) not in top_n:
        top_n.append((p, cont))
top_n.sort(key = lambda t:t[1], reverse = True)
#from operator import itemgetter
#sorted(top_n, key = itemgetter(1), reverse = True)
while len(top_n) > itens:
    del top_n[len(top_n)-1]
return top_n

def test_run():
    print count_words("cat bat mat cat bat cat", 3)
    print count_words("betty bought a bit of butter but the butter was bitter", 3)
    print(count_words("london bridge is falling down falling down falling down london bridge is falling down my fair lady", 5))

if __name__ == '__main__':
    test_run()

Answer: def count_words(s, n):
    top_n = []
    itens = n
    words = s.split()
    top_n = dict([])
    for w in words:
        if w not in top_n.keys(): top_n[w] = 0
        top_n[w] +=1
    top_n = list(top_n.items())
    #print(top_n)
    top_n.sort(key = lambda t:(-t[1],t[0]), reverse = False)
    return top_n[:n]

def test_run():
    print(count_words("cat bat mat cat bat cat", 3))
    print(count_words("betty bought a bit of butter but the butter was bitter", 3))
    print(count_words("london bridge is falling down falling down falling down london bridge is falling down my fair lady", 5))

if __name__ == '__main__':
    test_run()

Creio que assim fica mais claro, a idéia aqui é usar as palavras como chaves de um dicionário, fazendo assim a contagem. O problema da ordenação é que você deseja que seja ordenado decrescente pela contagem e de forma crescente pela palavra, o que fiz ali foi transformar o número em negativo -t[1], ordenando primeiramente pela versão negativa do número e depois pela palavra, agora de forma decrescente.
Comment: De uma olhada no `collections.Counter` também -
Answer: from operator import itemgetter
import re

sentence = 'london bridge is falling down falling down falling down london bridge is falling down my fair lady'

def count_words(text):
    words = re.findall(r'\w+', text)
    wordsCount = [(words.count(word), word) for word in set(words)]
    wordsCount.sort(key=itemgetter(1)) #order by word
    wordsCount.sort(key=itemgetter(0), reverse=True) #order by wordcount
    return wordsCount

print(count_words(sentence))

Resultado: [[4, 'down'], [4, 'falling'], [2, 'bridge'], [2, 'is'], [2, 'london'], [1, 'fair'], [1, 'lady'], [1, 'my']]
A função acima utiliza re.findall para localizar as palavras e em seguida realiza a contagem das palavras, retornado na lista wordsCount, uma sequência de listas com cada uma das palavras do texto e o respectivo número de ocorrências. Em sequência utilizamos a função sort para ordenar a lista, primeiro alfabeticamente e em seguida de acordo com o número de ocorrências, destacando-se que a função sort persiste a ordenação alfabética realizada no primeiro passo.
Uma solução bastante legível e em poucas linhas.


Normality is transitive along a chain of index 2 subgroups

Question: Let $G$ be a finite group. Let $G_1$ be a subgroup of $G$ such that $[G:G_1]=2$. Now suppose that $H$ is a normal subgroup of $G_1$ with odd order. Prove that $H$ is a normal subgroup of $G$.
Some remarks/partial progress:

I have shown that if $G$ is a group, $G_1$ is a subgroup of index $2$, and $H$ is a subgroup of odd order, then $H\subset G_1$. I don't think this is relevant to the problem at hand though.

If $H$ is a group of odd order, squaring is injective.

Since $G_1$ in the original problem statement has index $2$, any element $g\in G$ satisfies $g^2 \in G_1$.

If $g\in G$ is in $G_1$, then clearly $gH=Hg$, so it suffices to show our claim for $g\in G\setminus G_1$. Note further than $G\setminus G_1$ is the set of all elements of even order.
Comment: You wrote "suppose that $H$ is a normal subgroup of $G_1$" and "prove that $H$ is a normal subgroup of $G_1$." Please proofread carefully.
Answer: The answer is "no". Take the wreath product $G=C_3\wr C_2$ of order $18$. It has a subgroup $G_1=C_3\times C_3$ of index $2$. The subgroup $G_1$ has several subgroups $H$ of order 3, each of which is normal in the Abelian group $G_1$ but only one of which is normal in $G$.
Comment: I apologize; I intended to include in my problem that $H$ has odd order. Of course, you are absolutely right as my problem is stated. I have upvoted your answer but edited the problem to reflect my intentions.
Comment: I changed the answer. $H$ has order 9. You can replace $C_3$ by any $C_n$ with odd $n$, then the subgroup $H$ will have order $n^2$.
Comment: Which orders of $H$ are possible is a separate question. Clearly $H$ cannot be of prime order. It must have an automorphism of order 2.
Comment: Of course the simplest example is $C_2\wr C_2=D_4$, but in this case $|H|=4$.
Comment: In all these comments $H$ is what the OP calls $G_1$.


Can't connect to mongoDB in docker container

Question: I'm currently working on an api.
When I run my api on my local computer I can connect to MongoDB but when I run it from the docker container, I cannot connect to MongoDB
I tried this to connect to the container :
mongodb://0.0.0.0:27018
and
mongodb://127.0.0.1:27018
I also check if the two containers can communicate together and they can so I don't know how to do it
There is my docker-compose
version: "3.9"
services:
  api:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "3001:3001"
    volumes:
      - .:/app
  mongo:
    container_name: "sell-mongodb"
    image: mongo
    ports:
      - "27018:27017"
    volumes:
      - mongodb-data:/data/db/
volumes:
  mongodb-data:

Comment: Use `docker inspect` to see what the ip of your mongodb container is
Comment: I didn't mention but I also tried using the IP it wasn't working
Comment: You could also set `network_mode: host` under your docker-compose mongo:
Comment: need to use same network in spec of those containers. see networking in docker for more help.
Answer: Use mongodb://mongo:27017.
Use mongo as hostname, because it is the name of your MongoDB service in Docker Compose. By default, Docker enables you to access other containers by this service hostnames.
Do not use 27018 port when connecting from within another container, as it is a port exposed to your host machine. Port 27017 on the other hand should be accessible by default from the internal docker network, i.e. from other containers.
See https://docs.docker.com/compose/compose-file/compose-file-v3/#ports


MVC3 and breadcrumb navigation

Question: I try to create something like breadcrumb navigation using MVC3.
When user go to page he has for example: Home (id = 1), About (id = 2), and Hello (id = 3) links. These links I get from a database. When I click on Home I go to the database and get a  new set of links: Home -- Link1 (id = 3), Link2 (id = 4), etc.
If I not have nothing from database then I show some page content.

Home -- Link1 -- Some Others
Page Content

How can I achieve this?
Answer: We have had success using the MVC SiteMap project  for breadcrumb navigation.  If you cannot make use of this project directly for whatever reason, you could at least take a look at the source code to see how they implemented breadcrumbs.
The method that emits the breadcrumb navigation is: Html.MvcSiteMap().SiteMapPath()
Comment: I've used this project before, love it.

MVC3 and breadcrumb navigation


Contador regressivo não para em Zero

Question: Cronometro regressivo não para quando chega a "0".
Preciso que o cronometro pare quando chegar a "0" e ao clicar no botão "iniciar" o mesmo comece com o valor setado, que é "1 min" e decremente ate "0" novamente. Os Botões de parar e Somar 1 min estão funcionando.
Abaixo segue códigos dos botões:
    this.iniciarCronometro = this.iniciarCronometro.bind(this);
    this.pararCronometro = this.pararCronometro.bind(this);
    this.tempoFormatado = this.tempoFormatado.bind(this);
    this.somarUmSegundo = this.somarUmSegundo.bind(this);
    this.state = {
      contadorSegundo: 0,
      contadorMinuto: 1,
    };
  }

  iniciarCronometro() {
    var intervalId = setInterval(this.somarUmSegundo, 100);
    this.setState({
      intervalId: intervalId,
    });
  }

  pararCronometro() {
    clearInterval(this.state.intervalId);
    this.setState({
      contadorSegundo: 0,
      contadorMinuto: 1,
    });
  }

  somarUmMinuto() {
    this.setState({
      contadorMinuto: this.state.contadorMinuto + 1,
    });
  }

O Código abaixo faz o cronometro funcionar. A forma como ele esta implementado o contador não para quando chega a "0". Preciso que pare quando zerar e quando eu chamar a função iniciar ele comece do valor setado " 1".
somarUmSegundo() {
    let segundos = this.state.contadorSegundo;
    let minutos = this.state.contadorMinuto;

    minutos == 1 || segundos > 0;
    if (segundos == 0) {
      segundos = 59;
      minutos = minutos - 1;
    } else {
      segundos = segundos - 1;
    }

    this.setState({
      contadorSegundo: segundos,
      contadorMinuto: minutos,
    });
  }

Comment: Sua pergunta não está muito clara, tem como apontar mais detalhes?
Comment: @Francisco atualizei o código e coloquei mais informações.
Comment: Cara, agora tem informações demais kk. Se possivel estruture a pergunta seguindo o modelo de [mcve].
Comment: @Francisco atualizado.
Answer: A sua função somarUmSegundo() não faz muito sentido. Tente desta forma:
somarUmSegundo() {
    if (this.state.contadorSegundo == 0) {
        if (this.state.contadorMinuto > 0) {
            this.setState(antigo => ({
                contadorMinuto: antigo.contadorMinuto - 1
                contadorSegundo: 59
            }));
        }
        else {
            clearInterval(this.state.intervalId);
            return;
        }
    }

    this.setState(antigo => ({
        contadorSegundo: antigo.contadorSegundo - 1
    }));
}

Comment: O Código funcionou perfeitamente. Porém quando finaliza a contagem o valor ja retorna para "01:00 min" automaticamente. Preciso que ele fique zerado, só após clicar no button iniciar ele comece a decrementar a partir de "01:00 min". Tentei modificar seu código aqui mas estou com dificuldades.
Comment: Editei a resposta, tenta agr @Philipe

Contador regressivo não para em Zero


Who will decide commentary team in cricket

Question: During international cricket matches who will decide the commentary panel?
Is there any eligibility criteria for that?
When will they announce the list of commentators for the particular series?
Comment: I'm voting to close this question as off-topic because it's about TV, not sport
Comment: @TrueDub Then how about questions found under the [`media`](http://sports.stackexchange.com/questions/tagged/media) tag? Not saying I disagree here, but saying I want to be consistent with the handling of these "media" questions.
Comment: @edmastermind29 I didn't notice that tag, and on investigation this question seems to fit the tag perfectly. I still don't think it's relevant on a sports stack exchange site, but that's a different issue - as things stand this question is ok. I've retracted my close vote.
Comment: broadcaster I think. In my opinion the broadcaster has rights to chose the commentators.
Answer:
During international cricket matches who will decide the commentary panel?

The broadcaster.

Is there any eligibility criteria for that?

No.

When will they announce the list of commentators for the particular series?

When they feel like it.
Comment: Unless it's in India, then it's the BCCI who decides the panel and the list.


store data from txt files in table mysql

Question: I am trying to make a program where I would read data from txt files and store them in tables. The user would give the directory of the files and then would create the table with specific fields.
Then I have to fill the each table with the data that it has. Does anyone could help me how I would do this? The .txt files have data as these that are shown in the image:
The two columns are seperated by tab.
I had tried the code below but I get error:
java.sql.SQLException:at part1.importData(part1.java:31)
    at part1.main(part1.java:16)

The code that I have tried is:
public class notepad {

    public static void main(String args[]) throws Exception {

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = (Connection) DriverManager.getConnection(
                "jdbc:mysql://localhost:3300/mydb", "root", "root");

        String dirpath = "";
        Scanner scanner1 = new Scanner(System.in);
        while (true) {
            System.out.println("Please give the directory:");
            dirpath = scanner1.nextLine();
            File fl = new File(dirpath);
            if (fl.canRead())

                break;
            System.out.println("Error:Directory does not exists");
        }

        try {
            String files;
            File folder = new File(dirpath);
            File[] listOfFiles = folder.listFiles();

            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    files = listOfFiles[i].getName();
                    if (files.endsWith(".txt") || files.endsWith(".TXT")) {
                        List<File> txtFiles = new ArrayList<File>();
                        txtFiles.add(listOfFiles[i]);
                        String[] parts = files.split("\\.");
                        String tablename = parts[0];
                        for (File txtFile : txtFiles) {
                            List sheetData = new ArrayList();

                            try {
                                FileReader in = new FileReader(txtFile);
                                BufferedReader br = new BufferedReader(in);
                                String line = br.readLine();
                                while (line != null) {
                                    System.out.println(line);
                                    line = br.readLine();
                                }
                                in.close();

                            } catch (Exception e) {
                                System.err.println("Error: " + e.getMessage());
                            }
                            showExcelData(sheetData);
                            getCreateTable1(con, tablename);
                            importData(con, txtFile);
                        }
                    }
                }
            }

        } catch (Exception e) {
            System.out.println();
        }
    }

    private static String getCreateTable1(Connection con, String tablename) {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            Statement stmt = con.createStatement();
            String createtable = "CREATE TABLE "
                    + tablename
                    + " ( text VARCHAR(255), price int )";
            System.out.println("Create a new table in the database");
            stmt.executeUpdate(createtable);
        } catch (Exception e) {
            System.out.println(((SQLException) e).getSQLState());
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

    private static void importData(Connection con, File txtFile) {

        Statement stmt;
        String query;
        try {
            stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_UPDATABLE);

            query = "LOAD DATA INFILE '" + txtFile
                    + "' INTO TABLE tablename (text,price);";

            stmt.executeUpdate(query);

        } catch (Exception e) {
            e.printStackTrace();
            stmt = null;
        }

    }

Could anyone help me how I would do it? My difficulty is when I am tring to import the data.
Comment: Please edit your post. You have error in SQL query, that is specific to SQL. It has nothing to do with Java or JDBC. Remote java code, leave only query and retag to MySQL. First try to invoke command from mysql console to get more precise SQL error code.
Answer: The problem is that you trying to pass File to the query, while AFAIK it should be the full path of the file, like:

'C:\temp\data1.txt'

So in this function you should use:
 private static void importData(Connection con, File txtFile) {

        query = "LOAD DATA INFILE '" + txtFile.getAbsolutePath()
                + "' INTO TABLE tablename (text,price);";

, please note this will only work if you're on localhost, for remote server, it would be better to do this in batch insert which means you need to rewrite the whole code.
Comment: I updated my answer, so .getAbsolutePath() could be useful for you.
Answer: Look in command Load Data Infile. That query is not correct. See this http://dev.mysql.com/doc/refman/5.1/en/load-data.html


Are open sets of a product space necessarily given by the Cartesian product of two open sets?

Question: Given two topological spaces $(X,\mathcal U)$ and $(Y, \mathcal V)$, the product topology on $X\times Y$ is that given by the basis $\mathcal B=\{U\times V: U\in \mathcal U, V\in\mathcal V\}$.
But this is a particular topology in $X\times Y$. In general, if we have an open set $Z$ of $X\times Y$, does $Z=U\times V$ for some $U\in\mathcal U$ and $V\in\mathcal V$?
Comment: No. For example, the product topology of $\mathbb R\times\mathbb R$ is the same as the Euclidean topology on $\mathbb R^2$, but the basis for the product topology does not contain all open subsets of $\mathbb R^2$ - they are "too boxy." In particular, an open disk in $\mathbb R^2$ can't be in $\mathcal B$.
Answer: An open set $W$ in the product topology is in the basis $\mathcal B$ if and only if:

For all $(x_1,y_1),(x_2,y_2)\in W$, we have that $(x_1,y_2),(x_2,y_1)\in W$.

But it is not hard to find, in most cases[*], that there is some pair $W_1=U_1\times V_1$ and $W_2=U_2\times V_2$ such that $W_1\cup W_2$ does not have this property.
[*] I say "in most cases," because in a few cases, like $|Y|=1$, this is not true.


Is it possible to group taxonomy list items by content type?

Question: I'm working on a website which uses a single vocabulary for three different content types. I'm looking for a way to group list items by content type.
To illustrate, I got three content types:

Manual
News
Blog

And I got lots of vocabulary terms which might be used by all three content types:

Rabbits
Cats
Dogs
Frogs

When I select a vocabulary term it will show all the relevant content, sorted by the publication date, like so:
Rabbits

Rabbit escaped from show-ground
Feeding your rabbit
Why do rabbits have such big ears?

However, I'd like to group the items by content type:
Rabbits
Manual

Feeding your rabbit

News

Rabbit escaped from show-ground

Blog

Why do rabbits have such big ears?

I've tried the default 'Taxonomy term' view but found it wouldn't quite work because it affect other vocabularies as well. I also tried the Taxonomy Display module but didn't really understand how it works (I got some configuration options but no view I could change).
Is there a function that could check the vocabulary and the list items' content types and then group them by content type?
Answer: I assume you know how to set up the view and have difficulty only with applying the view to the specific taxonomy and letting other taxonomies render by default.
Create a custom module and put this is the main module file:
<code>function MODULE_menu_alter(&$items){
  // change taxonomy view path for certain vocabularies
  $items['taxonomy/term/%taxonomy_term']['page arguments'][] = $items['taxonomy/term/%taxonomy_term']['page callback'];
  $items['taxonomy/term/%taxonomy_term']['page callback'] = 'custom_taxonomy_term_callback';
}

function custom_taxonomy_term_callback($term, $callback) {
  if ($term->vocabulary_machine_name == "SOME_TAXONOMY") {
    $view = views_get_view('CUSTOM_TERM_VIEW');
    $view->set_display('default');
    $view->set_arguments(array($term->tid));
    $view->pre_execute();
    $view->execute();
    return $view->render();
  }
  else {
    module_load_include('inc', 'taxonomy', 'taxonomy.pages');
    return $callback($term);
  }
}
</code>
This is what the code does:
It alters the path taxonomy is called on, then checks if the path is on your taxonomy that you want to special render. If it is it loads and renders the view for that taxonomy, and if not it passes the call back to the default taxonomy callback.
You need to alter the code to suit your taxonomy machine name and view name. And remember to clear the cache.
For your view you can create just the master view (ie no page with path) that accepts the tid as contextual filter. This view is custom rendered and therefore does not need to be on any path.
Comment: Many thanks - that worked. Maybe for the benefit of others struggling with this, setting up the custom view is as easy as cloning the standard _Taxonomy term_ view (disabled by default) and then changing the **Path** to the page you use to display vocabulary terms (in my case '/labels/%') and selecting the vocabulary you want to display under **Advanced**, **Content: Has taxonomy term ID (with depth)**. After that you can choose which fields you want to display, group them etc.


Are transformations to Data bad for Linear Regression model?

Question: I recently posted an article on medium where I state that a solution when we have residuals that do not follow the normal distribution is to perform non-linear transformations to the data (i.e. log transformation). Following feedback from a Statistician, he said that performing these transformations on the data causes more harm to the data than good and provided the following reasons.

The points made in the image above seem quite sensible, however I have seen such transformations to be quite common when performing Linear Regression.
Therefore, I ask whether transformations are much more harmful to Linear Regressions model than good?
Comment: This partly depends on whether your goal is to understand the relationship between **X** and **y**, or to be able to predict **y**. If you're interested in prediction, and transformation improves (out of sample) prediction, then transformation is a good thing!
Answer: It's important to distinguish between transformation of the outcome variable and transformation of predictors.
Transforming the outcome variable simply because the residuals around a regression aren't normally distributed does suffer from the problems noted. You are changing the hypothesis that you're testing, leading to the associated problems with changes in interpretation, variance, confidence intervals, etc. For example, with a log transformation of the outcome you're now saying that you expect unit changes in the linear predictor to be associated with proportional rather than additive changes in the outcome. If there is reason to suspect such an association based on your knowledge of the subject matter it might be reasonable. But nonlinear relationships between the linear predictor and the outcome are better handled by generalized linear models that take both those nonlinearities and their implications for residual variance into account.
On the other hand, transformations of predictor variables to improve the relationship between the linear predictor and outcome have important roles in modeling. For example, restricted cubic splines allow regression models (including generalized linear models) to use the data directly to find a suitable transformation of a continuous predictor variable.
Comment: Kurtis, there are many good reasons to transform a response variable, which is why it might seem common.  See, *inter alia,* https://stats.stackexchange.com/questions/298.
Comment: Thank you for your response. This aligns a lot with what i've seen from statisticians. This comes as a surprise to me as it's very common for people to perform non-linear transformations.


Interpreting experimental treatment effects on PCA output

Question: How do we interpret the effect of an experimental treatment on a principal component dimension, constructed from multiple outcomes in the experiment? Can this be interpreted substantively? What do we learn about the effect of treatment if it "causes" a principal component to decrease by 0.5?
The specific situation I am facing: I ran an experiment with one randomly assigned treatment (binary: control/treatment) and multiple outcomes of interest. I ran PCA on the outcomes. The treatment has a statistically significant effect (p<0.001) of about -0.5 on the first principal component.
The variables that load heavily in the first principal component vary together. As far as I understand, across all the PCs, the loadings times the treatment effect estimates for each PC sums to the overall treatment effect on each outcome. But I'm having trouble interpreting the effect of treatment on a single PC.
Answer: Whether it can be interpreted depends entirely on whether the PCA is measuring something meaningful or not - if you have a substantive interpretation for the 1st component (and better if that's supported in previous work in the literature) then you may be ok - if it's just that there are a bunch of very different outcomes that co-vary then you probably shouldn't put them through a PCA in the first place.


How to properly create an EF One-to-Zero-or-One relationship with navigation properties on both ends?

Question: In my model I have two objects: Lead and Work. Lead may have a related Work, but Work must have a related Lead. How do I properly express this using EF Code First and Fluent API? I've spent most of the day so far going in circles trying to do this, but I'm getting nowhere. The problem (maybe?), is that I need to have the navigation properties on both sides of the relationship. Here's how I've got my objects configured so far:
public class Lead {
    public int Id { get; set; }
    public int? WorkId { get; set; }
    public virtual Work Work { get; set; }
}

public class Work {
    public int Id { get; set; }
    //public int LeadId { get; set; } <- I think this is necessary?
    public virtual Lead Lead { get; set; }
}

// this seems to make a one-to-one relationship, but it's setting
// the column references as the Id columns on both sides, so it's wrong...
// Also causes this exception:
// A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.
this.HasOptional(t => t.Work).WithRequired(t => t.Lead);

Attempting to reverse engineer a test database yields a One-to-Many relationship, which is not what I want. I'd appreciate suggestions on how to properly configure the relationship.
Comment: Lead is the principal ?
Answer: If lead is a principal (Lead must exist first), the classes could look like this.
public class Lead {
    public int Id { get; set; }
    public virtual Work Work { get; set; }
}

public class Work {
    [Key, ForeignKey("Lead")]
    public int Id { get; set; }
    public virtual Lead Lead { get; set; }
}

Comment: This is the correct way and was very similar to what EF was producing for me, except I thought it was wrong. Either way, after some more pondering, I realized that the `Work` object was actually unnecessary, so I've removed it. But, again, for everyone else looking for a similar solution this is correct.
Comment: This approach is failing for me because my Id properties are identity columns.  EF 6 wouldn't allow me to set create a Foreign Key on an identity column (in my equivalent of the Work entity from your example above)... at least that's what the helpful error message seems to be getting at.