Tenor Banjo Tuning

Question: Have aquired a tenor banjo and do not know how I should tune it up. The nut to bridge is 23 inches in length so is completely different from my current soprano ukulele. I seek advice as to how to tune the tenor banjo.
Answer: Although your title says tenor Ukulele, I'm assuming it is a Tenor Banjo since the scale length is 23 inches. The longest scale length for a Ukulele is The Baritone Ukulele that comes in at 19 - 21.5 inches.
You can tune a Tenor Banjo a number of different ways, depending on what string gauges you use. There are string packs available for most tuning setups.
Common tuning includes:

Bottom four strings of a guitar: D G B E.
"standard" Tenor: C G D A
"Irish" Tenor: G D A E

I've met some players that tune like a 5 string banjo without the high G string: D G B D or C G C D.
Which tuning you choose may be influenced by what style of music you want to play on it. Tenor guitar tuning is useful if you already play guitar or ukulele. "Irish" tuning useful if you want to play traditional Irish tunes &c.
EDIT:
If you are interested in playing it as if it were a Ukulele, then I would suggest Baritone Ukulele tuning, which is often tuned like the bottom 4 strings of a guitar D G B E.

Tenor Banjo Tuning


Postgres Query with Date extraction

Question: I have a table with a Date field called 'run_date' in which I need to perform the following task:
get the value which has the ((most up-to-date year AND month) AND the earlier day).
Example:

run_date
2012-12-24
2012-12-31
2013-01-03
2013-01-07
2013-01-14

I need a query that returns '2013-01-03', because it follows the rules above.
My best try is:
SELECT
    run_date as val
FROM
    myTable
    WHERE  to_char(run_date, 'MM'::text) = (SELECT MAX(EXTRACT ('MONTH' FROM run_date)) FROM myTable)
    and to_char(run_date, 'YYYY'::text) = (SELECT MAX(EXTRACT ('YEAR' FROM dado_dt_data_rodada)) FROM myTable)

    ORDER BY val ASC LIMIT 1

Of course, the months cycle between 1-12, so the query above doesn't work.
I appreciate any help, thanks!
Answer: I think you want the earliest date in the most recent month.  Try this:
SELECT run_date as val
FROM myTable
ORDER BY to_char(run_date, 'YYYY-MM') desc, run_date asc
LIMIT 1

Comment: I think it works! What i want is the *earliest date in the most recent month AND year*. So you first sort it by year-month DESC, then sort again by day ASC?
Comment: @Fernando . . . Yes, that is what this does.  The first part of the `order by` puts the most recent month at the top.  The second part puts the earliest date in the month.

Postgres Query with Date extraction


push to array as long as the item does not already exist in array using javascript

Question: I have ready many post on this but none of them seem to help me out with my problem or i don't understand their answer in a way to convert it to my script. I want to add a item to an array from the input as long as it does not already exist in the array. please any help is greatly appreciated.
i would imagine i need to use a for loop and then compare the new item to the existing items in the array to check if the item already exist.
    var Fruit = ['apple', 'bannanna', 'rasberry', 'watermelon', 'grape', 'orange'];

    $('#addFruit').on('click', function(e) {
      e.preventDefault();
      var val = $('#fruitAdd').val();
      Fruit.unshift(val);
      console.log(Fruit);
    });

HTML
   <form>

      <input type="text" id="fruitAdd" class="form-control" placeholder="Search">

    <button type="submit" id="addFruit" class="btn btn-default search">Submit</button>
   </form>

Comment: Why not use an associative array? That way you can check if you already have it quickly
Comment: There are no associative arrays ?
Answer: You can check if an item exists in an array by checking for it's index:
var fruit = ['apple', 'banana'];
if (fruit.indexOf('cherry') === -1) {
    console.log('No cherries here');
}

So using that, you can write something like this:
var val = $('#fruitAdd').val();
if (Fruit.indexOf(val) === -1) {
    Fruit.push(val);
}

Comment: Since he's using jQuery, `$.inArray()` would give some additional portability.
Answer: Another approach is to declare fruit as an object literal and add properties:
fruit = {'apple': true, 'banana': true};
var val = $('#fruitAdd').val();
fruit[val] = true;

Comment: In this case looping over the values in the object is less intuitive than with an array but yeah that works.
Comment: No looping is necessary in this case.
Comment: Just try to add the property; if it exists, nothing changes.
Answer: if you want to use loop, I thinkg the code will look like it.
 var Fruit = ['apple', 'bannanna', 'rasberry', 'watermelon', 'grape', 'orange'];

$('#addFruit').on('click', function(e) {
  e.preventDefault();
  var flag = true;
  var val = $('#fruitAdd').val();
  for(var i = 0 ; i < Fruits.length ; i ++){
      if(Fruits[i] == val)
         flag = false;
  }
  if(flag)
      Fruits.push(val);
});


Como voltar de um fragment para uma activity?

Question: Eu criei uma Activity do tipo Drawer Navigation e nos ícones dessa Activity tem uma ação que me levam para um fragmento.
Meu problema é que eu não sei voltar de um fragmento para uma activity ...
como eu devo fazer para voltar com o botão voltar do onBackPressed?
Tentei simular o botão de voltar com isso mas não funcionou aqui:
Start fragment:

  public void showMyFragment(View V){
        Fragment fragment = null;
        fragment = new MyFragment();

        if (fragment != null) {
             FragmentManager fragmentManager = getFragmentManager();
             fragmentManager.beginTransaction()
                            .replace(R.id.frame_container, fragment)
                            .addToBackStack(null)
                            .commit();
        }
}

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() == 0) {
        this.finish();
    } else {
        getFragmentManager().popBackStack();
    }
}

public class MyFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
            View v=inflater.inflate(R.layout.activity_info, null);
            return v;
        }
    }

Answer: Uma forma simples de fazer isso é usar o addToBackStack(). Veja como deve ser:
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment)
    .addToBackStack("Fragment").commit();

Sendo assim, você pode colocar uma condição verificando se a cotagem de entrada de stack tem valor maior que 0. Se sim, use o método popBackStack(), que fará o usuário voltar para o fragment anterior, senão ele usa o super.onBackPressed(). Veja:
@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 0 ){
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

Um GIF vale mais que mil imagens:

Este projeto está salvo como navDrawer no GitHub.
Comment: Consegui!!!Lindo!Show!
Answer: Ao usar addToBackStack(null) está a incluir os fragments na navegação, fazendo com que o "Botão Voltar" apresente o fragment anterior.
Se não quer navegar para trás entre os fragments abertos não adicione a transanction ao backstack. Não use addToBackStack(null).
Altere
fragmentManager.beginTransaction()
               .replace(R.id.frame_container, fragment)
               .addToBackStack(null)
               .commit();

para
fragmentManager.beginTransaction()
               .replace(R.id.frame_container, fragment)
               .commit();

No entanto, se quiser manter a navegação entre fragments e, ao mesmo tempo, dar a possibilidade de retornar à Activity anterior, tem de implementar o "Botão Para Cima".
Siga os seguintes passos:

Declare qual é a Activity pai de cada Activity. Isso é feito no AndroidManifist.xml usando o atributo android:parentActivityName:
<application ... >
    ...

    <activity
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    </activity>

    <activity
        android:name="com.example.myfirstapp.MyChildActivity"
        android:label="@string/title_activity_child"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >

        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

Torne o "Botão Para Cima" disponível/visível
@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

Use o método estático navigateUpFromSameTask(), de NavUtils, para navegar para a Activity pai:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Para mais informações veja Providing Up Navigation, na documentação.
Outros tópicos para ler:

Navigation with Back and Up.
Implementing Effective Navigation.
Comment: Não entendo. O que é proposto na resposta aceite é o que você diz não querer: voltar um a um. Devemos sempre seguir o que é aconselhado pela google para que a experiência do usuário seja sempre a mesma, qualquer que seja a aplicação que esteja a utilizar. Em termos de navegação é [aconselhado](https://developer.android.com/training/design-navigation/ancestral-temporal.html) que o "botão voltar" sirva para percorrer o backstack e o "botão para cima" percorrer para níveis superiores(Activities). É o que eu tentei explicar na minha resposta.
Comment: Gostei da resposta...amanhã irei implementá-la amigo =D e te dou um retorno....
Comment: Aliás fazer isso agora. =D
Comment: Não deu certo =[
Comment: O que não deu certo? Devo ter entendido mal a sua pergunta, porque aquilo que a resposta que você aceitou sugere é o que você já fazia(usar `addToBackStack(null)`) o que obriga a navegar para trás por todos os *fragments* antes de voltar à Activity.
Comment: Seria bom se tivesse uma forma de navegar programado. tipo não voltar de um em um...
Comment: Ahhh entendi...


Passing an array as an argument in golang

Question: Why does this not work?
package main

import "fmt"

type name struct {
    X string
}

func main() {
    var a [3]name
    a[0] = name{"Abbed"}
    a[1] = name{"Ahmad"}
    a[2] = name{"Ghassan"}

    nameReader(a)
}

func nameReader(array []name) {
    for i := 0; i < len(array); i++ {
        fmt.Println(array[i].X)
    }
}

Error:
.\structtest.go:15: cannot use a (type [3]name) as type []name in function argument

Answer: You have defined your function to accept a slice as an argument, while you're trying to pass an array in the call to that function.  There are two ways you could address this:

Create a slice out of the array when calling the function.  Changing the call like this should be enough:
nameReader(a[:])

Alter the function signature to take an array instead of a slice.  For instance:
func nameReader(array [3]name) {
    ...
}

Downsides of this solution are that the function can now only accept an array of length 3, and a copy of the array will be made when calling it.

You can find a more details on arrays and slices, and common pitfalls when using them here
Comment: Upvoted, but `a := []name{"Abbed", "Ahmad", "Ghassan"}` is how I'd have defined `a` as a slice in the first place.
Comment: darn we should have `[...]type` in `func` signatures in next releases :(
Comment: That's what the second option I outline does.  But as I said, the downside is that it will only accept arrays of length 3 with that change: if you want to accept sequences of arbitrary length, you'll need to work with slices.
Comment: @YasirG.: it isn't clear how that could be done safely, given that arrays are passed by value and don't store their size (it is implicit from the type).  And we've already got slices to handle the arbitrary length sequences.
Comment: Is there a way at all to make the function accept an array?
Comment: So what's the right way to have a function take an array of `{type}` without having to know the size of the array at compile time?
Comment: So what's the right way to have a function take an array of `{type}` without having to know the size of the array at compile time?
Answer: Since @james-henstridge's answer already covered how you could make it work, I won't duplicate what he said, but I will explain why his answer works.
In Go, arrays work a bit differently than in most other languages (yes, there are arrays and slices. I'll discuss slices later). In Go, arrays are fixed-size, as you use in your code (so, [3]int is a different type than [4]int). Additionally, arrays are values. What this means is that if I copy an array from one place to another, I'm actually copying all of the elements of the array (instead of, as in most other languages, just making another reference to the same array). For example:
a := [3]int{1, 2, 3} // Array literal
b := a               // Copy the contents of a into b
a[0] = 0
fmt.Println(a)       // Prints "[0 2 3]"
fmt.Println(b)       // Prints "[1 2 3]"

However, as you noticed, Go also has slices. Slices are similar to arrays, except in two key ways. First, they're variable length (so []int is the type of a slice of any number of integers). Second, slices are references. What this means is that when I create a slice, a piece of memory is allocated to represent the contents of the slice, and the slice variable itself is really just a pointer to that memory. Then, when I copy that slice around, I'm really just copying the pointer. That means that if I copy the slice and then change one of the values, I change that value for everybody. For example:
a := []int{1, 2, 3} // Slice literal
b := a              // a and b now point to the same memory
a[0] = 0
fmt.Println(a)      // Prints "[0 2 3]"
fmt.Println(b)      // Prints "[0 2 3]"

Implementation
If that explanation was pretty easily understandable, then you might also be curious to know how this is implemented (if you had trouble understanding that, I'd stop reading here because the details will probably just be confusing).
Under the hood, Go slices are actually structs. They have a pointer to the allocated memory, like I mentioned, but they also have two other key components: length and capacity. If it were described in Go terms, it'd look something like this:
type int-slice struct {
    data *int
    len  int
    cap  int
}

The length is the length of the slice, and it's there so that you can ask for len(mySlice), and also so that Go can check to make sure you're not accessing an element that's not actually in the slice. The capacity, however, is a bit more confusing. So let's dive a bit deeper.
When you first create a slice, you give a number of elements that you want the slice to be. For example, calling make([]int, 3) would give you a slice of 3 ints. What this does is allocate space in memory for 3 ints, and then give you back a struct with a pointer to the data, the length of 3, and the capacity of 3.
However, in Go, you can do what's called slicing. This is basically where you create a new slice out of an old slice that represents only part of the old slice. You use the slc[a:b] syntax to refer to the sub-slice of slc starting at index a and ending just before index b. So, for example:
a := [5]int{1, 2, 3, 4, 5}
b := a[1:4]
fmt.Println(b) // Prints "[2 3 4]"

What this slicing operation does under the hood is to make a copy of the struct that corresponds to a, and to edit the pointer to point 1 integer forward in memory (because the new slice starts at index 1), and edit the length to be 2 shorter than before (because the old slice had length 5, while the new one has length 3). So what does this look like in memory now? Well, if we could visualize the integers laid out, it'd look something like this:
  begin     end  // a
  v         v
[ 1 2 3 4 5 ]
    ^     ^
    begin end    // b

Notice how the there's still one more int after the end of b? Well that's the capacity. See, so long as the memory's going to be sticking around for us to use, we might as well be able to use all of it. So even if you only have a slice whose length is small, it will remember that there's more capacity in case you ever want it back. So, for example:
a := []int{1, 2, 3}
b := a[0:1]
fmt.Println(b) // Prints "[1]"
b = b[0:3]
fmt.Println(b) // Prints "[1 2 3]"

See how we do b[0:3] at the end there? The length of b is actually less than 3 at this point, so the only reason we're able to do that is that Go has kept track of the fact that, in the underlying memory, we've actually got more capacity reserved. That way, when we ask for some of it back, it can happily oblige.
Comment: Or people could simply read Rob's blog article: [Arrays, slices (and strings): The mechanics of 'append'](http://blog.golang.org/slices).
Comment: You say sub-slicing `b := a[1:4]` increases the pointer by 1 and decreases the length by 2. But the capacity remains the same? Shouldn't it decrease by 1 as well?
Comment: ah, yes, that does seem more reasonable... I'd forgotten about that.
Comment: @StefanPochmann yes, `b`'s capacity is decreased by `1`, and as per the declaration of `b := a[1: 4]`, `b`'s length should be 3 and capacity should be 4. The diagram and some information in the answer is confusing and misleading, though the first part is interesting
Answer: An alternative approach
One could invoke a variadic function on the a slice to input the list of names as individual arguments to the nameReader function, eg:
package main

import "fmt"

type name struct {
    X string
}

func main() {
    a := [3]name{{"Abbed"}, {"Ahmed"}, {"Ghassan"}}
    nameReader(a[:]...)
}

func nameReader(a ...name) {
    for _, n := range a {
        fmt.Println(n.X)
    }
}

Answer: Instead of declaring a sized array, declare a slice. Allocate memory to it and fill it in. Once you have that, the original reference is still to the slice, which can be passed around to a function. Consider this simple example
package main

import "fmt"

func main() {
  // declare a slice
  var i []int

  i = make([]int, 2)
  i[0] = 3
  i[1] = 4

  // check the value - should be 3
  fmt.Printf("Val - %d\n", i[0])

  // call the function
  a(i)

  // check the value again = should be 33
  fmt.Printf("Val - %d\n", i[0])
}

func a(i []int) {
  // check the value - should be 3
  fmt.Printf("Val - %d\n", i[0])

  // change the value
  i[0] = 33

  // check the value again = should be 33
  fmt.Printf("Val - %d\n", i[0])
}

As you can see the array got passed (as a reference) and can be modified by the corresponding function.
Output looks like this:
Val - 3
Val - 3
Val - 33
Val - 33

The whole program can also be found at: http://play.golang.org/p/UBU56eWXhJ
Answer: Passing Arrays as parameters.
Arrays values are treated as a single unit. An array variable is not a pointer to a location in memory, but rather represents the entire "Block of Memory" containing the array elements.
This has the implications of creating a new copy of an array value when the array variable is reassigned or passed in as a function parameter.
Learning Go Programming, By Vladimir Vivien
This could have unwanted side effects on memory consumption for a program. You can fix this using "pointer types" to reference array values. For instance:
instead do this:
var numbers [1024*1024]int

you must do:
type numbers [1024*1024]int
var nums *numbers = new(numbers)

Remember that:

https://golang.org/pkg/builtin/#new

The new built-in function allocates memory. The first argument is a
    type, not a value, and the value returned is a pointer to a newly
    allocated zero value of that type.

Now you could pass the array pointer to the function without the side effect of memory consumption and use it as you want.
nums[0] = 10
doSomething(nums)

func doSomething(nums *numbers){
  temp := nums[0]
  ...
}

One thing to keep on mind is that array type is a low-level storage construct in Go and is used as the basis for storage primitives, where there are strict memory allocation requirements to minimize space consumption. For those cases where your requirement rely on the performance your must choose to work with arrays (like the previous example) instead of slices.
Answer: We can just use slices. Run code here: http://play.golang.org/p/WtcOvlQm01
Need to remember [3]name is an array. []name is a slice.
package main

import "fmt"

type name struct {
    X string
}

func main() {
    a := []name{name{"Abbed"}, name{"Ahmad"}, name{"Ghassan"}}
    nameReader(a)
}

func nameReader(array []name) {
    for i := 0; i < len(array); i++ {
        fmt.Println(array[i].X)
    }
}

Further reading: 50 Shades of Go: Traps, Gotchas, and Common Mistakes for New Golang Devs
Comment: Yes, It is the best method but I think the question asked was not addressing this method.


Powershell running as a another user with elevated privileges

Question: I have two scripts located in C:\setup: script.ps1 and script1.ps1.
I want to be able to run the script1.ps1 from withing script.ps1 as another user and with elevated privileges but I cannot make it work. The new powershell window opens but closes immediately ...
here is the script:
 $cspath = $MyInvocation.MyCommand.Path
 $sfolder = Split-Path $cspath
 $spath = Join-Path $sfolder "\Script1.ps1"

 $sa = "domain\user"
 $sap = "userpassword"
 $sasp = ConvertTo-SecureString -String $sap -AsPlainText -Force
 $sac = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $sa, $sasp

 Start-Process $PSHOME\powershell.exe `
            -Credential $sac `
            -ArgumentList "-Command Start-Process $PSHOME\powershell.exe -ArgumentList `"'$spath'`" -Verb Runas" -Wait

Any help will be appreciated ...
Comment: What does the script you're invoking through `Start-Process` do?
Answer: It looks like you might need to adjust your parameters for powershell.exe. Instead of using -ArgumentList, which I don't think is valid, you should use the -File parameter. Also, you will want to use the -ExecutionPolicy Bypass parameter to ensure that the script execution policy is not interfering.
Finally, I would recommend removing the single quotes from around the script path, as the Windows command interpreter does not understand single quotes to surround parameters.
Give this a try:
$ArgumentList = '-Command Start-Process -FilePath $PSHOME\powershell.exe -ArgumentList "-ExecutionPolicy Bypass -File \"{0}\"" -Verb Runas' -f $sPath;
Start-Process $PSHOME\powershell.exe `
    -Credential $sac `
    -ArgumentList $ArgumentList -Wait

Update
It seems that some quoting rules were at play here as well, since we are embedding one command inside of another. I wrote and tested a fully function script on PowerShell v4.0.
Here are the contents:
# Create test directory and script file
[void](New-Item -Path c:\test -ItemType Directory -Force);
Set-Content -Path c:\test\test1.ps1 -Value 'Add-Content -Path $PSScriptRoot\blah.txt -Value (Get-Date);';

# Get credential and define script path
$Credential = Get-Credential;
$ScriptPath = 'c:\test\test1.ps1';

# Define the command line arguments
$ArgumentList = 'Start-Process -FilePath powershell.exe -ArgumentList \"-ExecutionPolicy Bypass -File "{0}"\" -Verb Runas' -f $ScriptPath;

Start-Process -FilePath powershell.exe `
    -Credential $Credential `
    -ArgumentList $ArgumentList -Wait -NoNewWindow;

I can confirm that I get a UAC prompt, and the target script successfully executes.
Comment: `-ArgumentList` is a valid parameter for `Start-Process`, which is what he's using to invoke `powershell.exe`.
Comment: Oh, I got confused with the wrapped commands. Let me correct that.
Answer: Since you're concerned about the new session window closing, I'm guessing you want command line output.
Start-Process is working as intended. It will run the script passed in through -ArgumentList and exit the session. This means it will not hold to display command line output - the session will terminate immediately after the process completes.
If you want a persistent session, use New-PSSession. Otherwise, you could export the data you're gathering to a file.


How to set up the JsonLd @context with a custom StateProvider?

Question: To explain my problem, I set up a very simply ApiResource which use a custom state provider.
#[ApiResource(
    types: 'https://schema.org/UpdateAction',
    provider: TransitionStateProvider::class,
)]
class Transition
{
    #[ApiProperty(
        identifier: true,
        types: ['https://schema.org/identifier'],
    )]
    public int $id;
}

My state provider:
class TransitionStateProvider implements ProviderInterface
{
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
    {
        $transition = new Transition();
        $transition->id = 1;

        return $transition;
    }
}

When I send a get request, @context, @id, @types aren't set as I would like.
I got:
{
    "@context": {
        "@vocab": "https://localhost/docs.jsonld#",
        "hydra": "http://www.w3.org/ns/hydra/core#"
    },
    "@type": "Transition",
    "@id": "/.well-known/genid/66dae3d5fb3332ca13ee",
    "id": 1
}

What I want is:
{
    "@context": "/contexts/Transition",
    "@id": "/transitions/1",
    "@type": "https://schema.org/UpdateAction",
    "id": 1
}

It works with my other resources, but they are linked to a doctrine entity using stateOptions. This Transition resource is not.
I tried to set up identifier:true in ApiProperty, I tried to play with uriTemplate, urivariables and hydraContext without success.
What did I miss-configure?
Comment: Can you try with it defining custom serialization groups for your entity to achieve the desired JSON?
Answer: You could try and create a custom normalizer to modify the serialization process and make sure the @context, @id, and @type are set as you wanted.
namespace App\Serializer;

use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class TransitionNormalizer implements ContextAwareNormalizerInterface
{
    private $decorated;

    public function __construct(NormalizerInterface $decorated)
    {
        $this->decorated = $decorated;
    }

    public function normalize($object, string $format = null, array $context = [])
    {
        $data = $this->decorated->normalize($object, $format, $context);
        $data['@context'] = '/contexts/Transition';
        $data['@id'] = '/transitions/' . $object->id;
        $data['@type'] = 'https://schema.org/UpdateAction';

        return $data;
    }

    public function supportsNormalization($data, string $format = null, array $context = []): bool
    {
        return $data instanceof Transition;
    }
}

Define the custom normalizer as a service and tag it as serializer.normalizer. That will make sure it is registered within the Symfony Serializer component.
# config/services.yaml
services:
    App\Serializer\TransitionNormalizer:
        decorates: 'serializer.normalizer.object'
        tags: ['serializer.normalizer']

And update the ApiResource annotation on the Transition class to utilize the custom normalizer.
#[ApiResource(
    types: 'https://schema.org/UpdateAction',
    provider: TransitionStateProvider::class,
    normalizationContext: ['groups' => ['transition']]
)]
class Transition
{
    #[ApiProperty(
        identifier: true,
        types: ['https://schema.org/identifier'],
    )]
    public int $id;
}

You get the workflow:
+---------------+     +----------------------+     +-----------------------+     +-------------------+
| API Resource  |     | Custom Normalizer    |     |   Service Definition  |     | Desired JSON-LD   |
| Transition    | --> | TransitionNormalizer | --> | serializer.normalizer | --> |   @context Setup  |
+---------------+     +----------------------+     +-----------------------+     +-------------------+

Your updated code with the suggestions from above:
namespace App\Serializer;

use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class TransitionNormalizer implements ContextAwareNormalizerInterface
{
    private $decorated;

    public function __construct(NormalizerInterface $decorated)
    {
        $this->decorated = $decorated;
    }

    public function normalize($object, string $format = null, array $context = [])
    {
        $data = $this->decorated->normalize($object, $format, $context);
        $data['@context'] = '/contexts/Transition';
        $data['@id'] = '/transitions/' . $object->id;
        $data['@type'] = 'https://schema.org/UpdateAction';

        return $data;
    }

    public function supportsNormalization($data, string $format = null, array $context = []): bool
    {
        return $data instanceof Transition;
    }
}

// config/services.yaml
services:
    App\Serializer\TransitionNormalizer:
        decorates: 'serializer.normalizer.object'
        tags: ['serializer.normalizer']

// Your ApiResource and Provider remains the same
#[ApiResource(
    types: 'https://schema.org/UpdateAction',
    provider: TransitionStateProvider::class,
    normalizationContext: ['groups' => ['transition']]
)]
class Transition
{
    #[ApiProperty(
        identifier: true,
        types: ['https://schema.org/identifier'],
    )]
    public int $id;
}

class TransitionStateProvider implements ProviderInterface
{
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
    {
        $transition = new Transition();
        $transition->id = 1;

        return $transition;
    }
}

Comment: Thank you, @VonC ! Your code works perfectly as I expected! I only add "Groups" on other properties, because the decorated serializer was no more displaying them. You made my day! And with your explanations, I now have a better understanding of the full workflow.
Comment: @AlexandreTranchant Great, well done!


using pinverse vs gauss-jordan to solve a possibly singular system of linear equations?

Question: so i have a possibly singular coefficient matrix A . (it's sometimes singular and sometimes not !) (in the case of singularity it has many solutions we only need one)
i know using an inverse to find the answer to a system of linear equations is an awful idea .
so it seems even in  this case we should use methods like Gauss-Jordan to solve the system even when it is singular . is there any method to solve singular systems like Gauss-Jordan.(to give a answer)
and i read the matlab document on solving this types of systems and it says that we should use the pseudo-inverse function pinv  like : x = pinv(A)*b
this just looks as awful as taking the inverse (since for a non-singular matrix pseudo-inverse is same as inverse). (am I correct?)
and is it the case that we don't have any other more efficient choices of finding and answer in this case ??
Comment: Why not just use `A\b`?
Answer: It is not generally true that the pseudoinverse is the same as the inverse. In the case that a matrix is invertible, then they coincide. The pseudoinverse can be computed in different ways; pinv in MATLAB is generally good at selecting the right algorithm for the job (typically something SVD-like).
It's important to note that for a singular or otherwise ill-conditioned problem, the resulting value will not necessarily represent the solution, but rather the solution that minimizes the value $\| Ax-b\|$.
Comment: To amplify the comments of @Emily: http://math.stackexchange.com/questions/1537880/what-forms-does-the-moore-penrose-inverse-take-under-systems-with-full-rank-ful/2200203#2200203
Answer: The answer is framed using the tools in Mathematica, which are the most familiar set. The translation to MATLAB or Octave, etc., should be direct.
Given a system matrix $\mathbf{A}$ and a data vector $b$, solve the linear system
$$
 \mathbf{A} x = b
$$

The first attempt is to try a direct linear solution
x=LinearSolve[A,b]
You can trust the application, or you can specify a solution method. Current options are

banded matrix solver
Cholesky method for positive definite Hermitian matrices
iterative Krylov sparse solver
direct sparse LU decomposition

Next, try for a least squares solutions

x = LeastSquares[A, b]
This opens the door for the experts who have written the application which chooses a good method for solution.
If there is no solution, we have learned that the data vector is in the null space.

Of course, there is the pseudoinverse solution
x = PseudoInverse[A].b
As noted by @Shiyue in his post What is the best way to compute the pseudoinverse of a matrix?, the application writers use fast methods to assemble the pseudoinverse.

There are slower options. One is to construct the pseudoinverse manually.
{u,s,v}=SingularValueDecomposition[A]
x = v.PseudoInverse[s].ConjugateTranspose[u].b
The $\mathbf{QR}$ decomposition:
{q,r}=QRDecomposition[A]
x = PseudoInverse[r].Conjugate[q].b


Como inserir uma imagem e deslocar o texto ao passar o mouse no botão?

Question: Estou fazendo um menu de categorias de livros e ao passar o mouse em cada botão gostaria que o texto deslocasse para a esquerda e aparecesse uma imagem ao lado direito do botão.
Alguém poderia me ajudar?

#botao_genero {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 241px;
  height: 56px;
  border: 0;
  outline: 0;
  padding-left: 8px;
  margin: 10px;
  background: #FFFFFF;
  border-radius: 15px;
  font-size: 24px;
  box-shadow: 0px 0px 8px rgb(0 0 0 / 25%);
}
<button id="botao_genero" type="button">Aventura</button>
Answer:

#botao_genero {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 241px;
  height: 56px;
  border: 0;
  outline: 0;
  padding-left: 8px;
  margin: 10px;
  background: #FFFFFF;
  border-radius: 15px;
  font-size: 24px;
  box-shadow: 0px 0px 8px rgb(0 0 0 / 25%);
  transition: justify-content 1s;
  cursor: pointer;
}

#botao_genero:hover {
  justify-content: space-between;
}

#botao_genero img {
  display: none;
}

#botao_genero:hover img {
  display: flex;
}
<button id="botao_genero" type="button">
  Aventura
  <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTIgMmM1LjUxNCAwIDEwIDQuNDg2IDEwIDEwcy00LjQ4NiAxMC0xMCAxMC0xMC00LjQ4Ni0xMC0xMCA0LjQ4Ni0xMCAxMC0xMHptMC0yYy02LjYyNyAwLTEyIDUuMzczLTEyIDEyczUuMzczIDEyIDEyIDEyIDEyLTUuMzczIDEyLTEyLTUuMzczLTEyLTEyLTEyem02IDUuOTk5bC01LjYyMSAyLjk4NmMtLjg5OS0uMTA0LTEuODA2LjE5MS0yLjQ3NC44NTktLjY2Mi42NjMtLjk1IDEuNTYxLS44NjIgMi40MjhsLTMuMDQzIDUuNzI4IDUuNzI0LTMuMDQyYy44ODQuMDg5IDEuNzcyLS4yMDUgMi40MzItLjg2NS42MzQtLjYzNC45NjktMS41MjQuODU5LTIuNDczbDIuOTg1LTUuNjIxem0tNS45NyA3LjIyYy0uNjg5IDAtMS4yNS0uNTU5LTEuMjUtMS4yNDktLjAwMS0uNjkxLjU1OS0xLjI1MSAxLjI1LTEuMjUuNjkgMCAxLjI1LjU2IDEuMjUgMS4yNS0uMDAxLjY4OS0uNTYgMS4yNDktMS4yNSAxLjI0OXptLjc5LTkuNDA5djIuMTA4aC0uNDU3bC0uMDA0LS4wMDctLjgwMS0xLjM1NXYxLjM2MmgtLjQzNnYtMi4xMDhoLjQ1NGwuODA4IDEuMzY1di0xLjM2NWguNDM2em02LjIzNSA4LjczNHYtLjQ4aC45NTd2LS4zODRoLS45NTd2LS40MTdoMS4wNDN2LS40MTNoLTEuNTA3djIuMTA4aDEuNTI5di0uNDE0aC0xLjA2NXptLTEyLjk5OC0xLjY5NGwtLjMxNSAxLjM5NS0uMzI5LTEuMzk1aC0uNDNsLS4zMzQgMS4zNzctLjMwNC0xLjM3N2gtLjQ2NWwuNTI3IDIuMDk4LjAwMy4wMTFoLjQ2M2wuMzItMS4zNzguMzI2IDEuMzc4aC40NTVsLjUzOC0yLjEwOGgtLjQ1NXptNS4xODggOS4yMDljLjExOS4wNjYuMzU4LjEzMi42MDEuMTMyLjU4MiAwIC44NTMtLjMwMi44NTMtLjY1NyAwLS4zMDItLjE3My0uNDk3LS41NDctLjYzNi0uMjc3LS4xMDYtLjM5NC0uMTY2LS4zOTQtLjMwMiAwLS4xMDYuMTAxLS4yMDQuMzA5LS4yMDQuMjA0IDAgLjM1OC4wNi40NC4xMDFsLjEwNi0uMzg0Yy0uMTI2LS4wNi0uMjk5LS4xMDctLjU0MS0uMTA3LS40OTcgMC0uODAyLjI3NC0uODAyLjYzNiAwIC4zMTIuMjMyLjUwNy41ODUuNjMyLjI1NS4wODkuMzU1LjE2Ny4zNTUuMjk2IDAgLjE0Mi0uMTE2LjIzMy0uMzM3LjIzMy0uMjA0IDAtLjQwNS0uMDY2LS41MzEtLjEzM2wtLjA5Ny4zOTN6Ii8+PC9zdmc+">
</button>

Você pode utilizar o :hover para atribuir estilos quando o mouse passa por cima do elemento. Inicialmente a imagem vem com display: none para ficar escondida, depois mudamos isso para display: flex, e alinhamos o conteúdo nas extremidades com o justify-content: space-between.
A imagem, utilizei um SVG que achei na net, mas é trocar pela sua mesmo.
Comment: Boa Filipe, muito obrigado!!!
Só mais uma pergunta, como eu faço pra aumentar o tempo de transição?
Eu alterei no transition para 5s, mas nada aconteceu.


How to interpret negative ACF (autocorrelation function)?

Question:
So I plotted the ACF/PACF of oil returns and was expecting to see some positive autocorrelation but to my surprise I only get negative significant autocorrelation. How should I interpret the above graph?  They seem to indicate that there is a tendency for oil returns to increase when it decreased previously and vice-versa, thus the oscillating behaviour. Please correct me if I'm wrong.
Answer: Negative ACF means that a positive oil return for one observation increases the probability of having a negative oil return for another observation (depending on the lag) and vice-versa. Or you can say (for a stationary time series) if one observation is above the average the other one (depending on the lag) is below average and vice-versa. Have a look at "Interpreting a negative autocorrelation".
Comment: In practice, however, the autocorrelations you show are all very small: although some are significant at conventional levels they should not be over-interpreted. Correlations about 0.02 don't imply much predictive ability.
Comment: Would it make sense if I tried fitting an ARMA-GARCH model to this dataset?Would it make sense to use ARMA for correlation this small?I know I can just fit the return in a GARCH model but I don't want to end up with constant 0 when forecasting return.
Comment: @Stat, can you answer the above questions please? thanks
Comment: Sorry Andy, I thought I have answered them. Well, you can try both of them, and then check your models to see which one fits better to the returns and provides a reasonable forecast. But as Nick said, you don't have that much correlation, and that makes it difficult to find a good time series model.


Twitter Bootstrap carousel - move indicators

Question: I am trying to move my carousel indicators beneath the carousel. I've tried a few tips on the web to no avail.
I tried bottom with a negative value, but no good.
Any suggestions?

       ATS International Conference

       ATS International Conference

       ATS International Conference

Answer: You can insert your indicators where you want...
Bootply : http://www.bootply.com/SZqnwXVQ71
CSS:
.carousel-indicators{
    position:relative;
    background:grey;
    height:25px;
    bottom:0px;
  }
  .carousel-control{
     margin-bottom:25px;   // Same height as indicators
  }

HTML :

       ATS International Conference

       ATS International Conference

       ATS International Conference

Comment: When I do that, the indicators end up at the bottom of my page, and they are no longer clickable. here is a link: [https://store-stg.thoracic.org/index2014.php]
Comment: The gray background helps, but I don't want the indicators to show on top of the carousel slide, which they do. I want it totally beneath the carousel.


Forecast combination using optimal weights

Question: I am struggling with a case where I am supposed to calculate optimal forecast weights of two forecasts. We have fitted the models on a training set (time series) and want to calculate optimal weights by minimizing the variance of the errors. It almost seems as though we should calculate the weights using the forecast errors, but then we would in theory use previously unseen observations to calculate these weights.
Do any of you know if we should use forecast error or training error when calculating optimal weights of forecast combination?
Answer: I would not use the in-sample residuals ("training error") to calculate weights, because that would reward overfitting models.
Instead, I would divide the historical data into two batches, for instance the first 80% and the second 20%. Fit your two models to the first 80%. Forecast both out into the last 20%. Use the out-of-sample errors here to calculate weights. Finally, refit your two models on the entire historical sample, but do not update your weights. Then your weights will be based on a holdout sample, but your models will be trained using all data.
Did I write "finally"? I shouldn't have. Finally, be sure to read Claeskens et al., "The forecast combination puzzle: A simple theoretical explanation" (2016, IJF). The "forecast combination puzzle" they refer to is the possibly surprising effect that unweighted combinations often outperform "optimal" combination weights. One possible explanation is that the process of estimating (!) "optimal" weights will introduce its own variance, which will of course carry through to the variance of your forecasts, and therefore your forecast errors.
Thus, whatever you do, you should compare the approach you choose to simple unweighted combinations.
If you want to get fancy, there are a couple more articles on forecast combination in the IJF.
Comment: Thank you, this was a very good and thorough answer and I appreciate it very much! Thank you


Kruskal-Wallis vs Jonckheere-Terpstra Test

Question: If we're doing a Jonckheere-Terpstra Test and a Kruskal-Wallis test at the same significance level, which one is more likely to reject the null hypothesis when it is actually true?
From my understanding, the Jonckheere-Terpstra test tests the ordering of medians versus the Kruskal-Wallis test, that tests the equality of medians. So the former can give a significant result if the medians are actually equal, which Kruskal-Wallis will not. Hence the former is more likely to reject the null than the latter. Does this make sense? An explanation will be helpful.
Answer: You are correct that the Kruskal-Wallis test ignores ordering—making it akin to a one-way ANOVA performed on ranks. However, you are a bit off with the null hypothesis of the Kruskal-Wallis which takes the form:
$$H_{0}: P\left(X_{i} > X_{j}\right) = 0.5\\H_{A}: P\left(X_{i} > X_{j}\right) \ne 0.5$$
for all groups $i\ne j$. In plain language the null is that the probability of a randomly selected observation in one group being greater than a randomly selected observation in another group is one half.
The Kruskal-Wallis test only becomes an omnibus test for difference of unordered medians with two additional assumptions:

The distributions of each group all have the same shape—whatever that shape actually is.
The distributions of each group all have the same variance.

These two strict assumptions make Kruskal-Wallis a test for location shift (more general than a test for mean difference, or a test for median difference).
Given that the Kruskal-Wallis test ignores ordering, ceteris paribus the Jonckheere-Terpstra test will be more powerful. Indeed, Jonckheere noted that the test in balanced data was more powerful than a one-way ANOVA, which also ignores ordering.
You write "So the former can give a significant result if the medians are actually equal, which Kruskal-Wallis will not," but this is untrue: the Kruskal-Wallis test certainly can reject the null hypothesis even when it is true. In fact, when you choose $\alpha$ as a rejection criterion for this test you are selecting your preference for making exactly this kind of Type I error. Jonckheere gives a caution about using the Jonckheere-Terpstra test when the sample size in one group is large, but very small in other groups, as this will make the limiting distribution of the approximate test statistic non-normal, making inferences unreliable.
Comment: @AbominableSnowman Specifically it depends on the balance of your design (equality of sample sizes in groups), and sample sizes *for the asymptotic tests*. With small sample sizes you would just use the exact *p*-values for either test, and then your Type I error rate is just $\alpha$.
Comment: Thanks! The Jonckheere-Terpstra test will be more powerful - but does that also mean that it is more likely to reject the null when it is actually true?
Comment: @AbominableSnowman Ah... I misunderstood your question... you are concerned about Type I errors. See my edit?
Comment: Ok. So we can't say for certain whether one will always have a higher type 1 error rate than the other, and it depends on the data at hand.


Wolfram Mathematica, MATLAB or something else?

Question: I have only a little experience in math calculation tools. So please don't be strict if my question is not well defined :)
Which tool (Wolfram Mathematica, MATLAB or something else) is better to use for statistics? Where can I find quickstart guides and tutorials for it?
Comment: To prevent this question from being closed as potentially argumentative or too vague, please edit it to indicate *what* applications you contemplate and what performance criteria you have.  "Statistics" is far too broad to admit a coherent or useful set of replies.
Comment: I'm voting to close, not because it's a "bad question"...but I because it is likely that it will solicit an opinionated debate about the merits of different software. People become loyal, attached to various options.
Comment: -1 What you are stating is a problem of choice and thus a decision to be made. Doing so without providing preferences and goals to measure value of alternatives is unfortunately rather pointless or degrades to a simple matter of taste. Too bad.
Comment: The correct answer is R. Don't waste your money on proprietary tools unless you are sure you need them (which is almost never).
Answer: Wolfram Mathematica is a very capable software for doing statistics, and unlike Matlab, its statistical functionality is included in the core Mathematica.

Unlike R or Matlab it provides symbolic support for probability computations. You can peruse Probability & Statistics guide page to get an idea about the functionality.
Mathematica is often faster than R for statistical data crunching.
Mathematica has superior statistical visualization functionality. See Statistical Visualization guide page on the web.
Comment: And let's not forget, if you (the OP) will start using it, there's a [StackExchange for Mathematica](http://mathematica.stackexchange.com/)
Comment: I'd like to see a reference for this assertion: "Mathematica is often faster than R for statistical data crunching."
Comment: I guess to make it substantial we should make a comparison across the board, but my claim was based on `AbsoluteTiming[a=RandomVariate[NormalDistribution[],10^7];]` reports 072 seconds, while `system.time(a<-rnorm(10^7))` measures 1.26 seconds. Then `system.time(for(i in 1:1000) {mean(a)})` measures 32 seconds, while in _Mathematica_, `AbsoluteTiming[Do[Mean[a],{1000}]]` measures 17.15 seconds. _Mathematica_ has much faster linear algebra functions as well.
Comment: Or this one: "Mathematica has superior statistical visualization functionality". Nothing at the linked site convinces me of that. (None of which is to imply that Mathematica isn't worthwhile.)
Comment: I think if the matter of speed in Lin.Algebra comes into play, Matlab is the fastest of the 3, at least on average. Also given that R through the `Matrix` package has access to `Csparse` and `CHOLMOD` and similar is in a worst case scenario as fast as anything else when it comes to sparse matrices. (And clearly you have access to packages like `RcppEigen` that are help with small dense matrices also). Despite its merits on symbolic computation *Mathematica* is _not_ the lingua franca of Statistics, *R* is.
Comment: @Zach In addition to the comment above, here are some timing for the linear algebra. `a<-matrix(rnorm(10^6),ncol=1000);system.time(solve(a))` measures 1.7 seconds, in _Mathematica_ `a=RandomVariate[NormalDistribution[],{1000,1000}]; AbsoluteTiming[Inverse[a]; ]` measures 0.2 seconds.
Comment: I agree, Mathematica is faster than R. Not because Mathematica is very fast but because R is very slow, and it's not very well organized. But it's free.
Comment: Superior graphics ? http://gallery.r-enthusiasts.com/
Comment: @Zach: I think Sasha gave more than sufficient proof for his assertions now. Do you have a counter example to show R is as fast or faster?
Comment: @usεr11852: Now, it could very likely be argued that the *lingua franca* of statistics - and even more generally of solving problems by mathematical model is the international language of mathematics.  So one criterium of choice could then be: which tool stays closesr to mathematical notation and procedures? CAS like Mathematica and Maple certainly have a very big advantage here especially since this capability niwadays does not mean that you have to forfeit on performance!
Comment: @gwr: When referring to *lingua franca* I am concerned with computing environments here. For better or worse R is the software used more frequently in Statistics. Its depth and breadth is unparalleled. Just take a look at: https://cran.r-project.org/web/packages/available_packages_by_name.html and compare that list with the one of the 3 M's computing suites have to offer. Quality-wise R packages are on average *almost surely* worse than their M counterparts (professional devs are *almost surely* better devs than non-professional ones) but we are not examining this aspect for a *lingua franca*.
Comment: Let's not forget that ther is [RLink](http://reference.wolfram.com/language/RLink/guide/RLink.html) for *Mathematica* so all of those packages for R can be used rather easily. If your world and the problems you solve are broader than statistics, the nothing beats a package like Mathematica. Also time is limited: Why learn another language if there is some kind of *lingua franca* for mathematical problems out there?
Answer: For statistics I would recommend R - computation environment concerning statistics.
Here you can find many tutorials for R.
Comment: @Mihran R and MATLAB have a lot in common, so if you have any experience with MATLAB, I think you would do fine with R, too. Thanks for the link qmsoure, I've been looking for something like this for a few days.
Answer: There are specific tools out there for statistical analysis. For example, R, SPSS, and Minitab.
Nevertheless, both Mathematica and MATLAB are capable of doing the required computations; which is "better" is a matter of taste and application requirements, most of the time.
MATLAB doesn't ship default with many statistical subroutines. However, it does have a Statistics toolbox that contains much of the functionality found default in some other packages. It all depends on what exactly you're trying to do, statistics wise, and what your comfort level with programming is. Maybe you can elaborate more on what you're attempting.
(Of course, the man-hours spent re-programming an algorithm for, say, ANOVA is often costlier than just buying the license to the toolbox that has a stock routine outright).
Finally, to answer your question, I personally prefer MATLAB. I find that it is easier to program in and allows for easier rapid development and testing of algorithms, etc. Syntactically, I prefer MATLAB. MATLAB likes to keep things close to pseudo-code. Mathematica tries to keep things closer to mathematical notation.
You can find MATLAB tutorials all over the internet. Just google "MATLAB tutorial" and you'll have a slew of results.
Answer: Some people would say that Matlab is for numerical matrix calculations and simulations, and Mathematica for symbolic calculation.  But nowadays both can perform both things. And we should add another contender, Maple.
In my opinion Matlab is too big and needs too much resources. You should only choose it if your company or school forces you or if you need some rare simulation tool.
If not, you should choose Mathematica or Maple.  They are also very good with graphics, numeric matrixes and both have simulation tools.  But they have something much better than Matlab: symbolic and abstract mathematics.
If you can't afford commercial software or you like free software you can try R, for statistics and little bit more.


Moving the public folder outside the project laravel

Question: I want to move public folder outside of my project in laravel
-->|-Project
   |  |___app
   |  |___bootstrap
   |  |___....
   |-public

I have moved directory folder then an error occurs said
   Symfony\Component\Process\Exception\RuntimeException

  The provided cwd "C:\xampp\htdocs\site\ProjectNamexx\public" does not exist.

So I have create just empty folder called public, just to bypass error;
And in bootstrap directory, I have specified that folder public which become now in parent foder by this dirname(getcwd(), 1) and old code was dirname(__DIR__)
$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
$app->usePublicPath($app->basePath("public"));

But The ERROR: occured
In RecursiveDirectoryIterator.php line 43:

  RecursiveDirectoryIterator::__construct(): Argument #1 ($directory) cannot be empty

I have tried to solve it by just hardcoded the url and not worked as well, please if you already had this issue, or you have any idea how to solve this problem, I appreciate your help!
Answer:
Edit public/index.php

require __DIR__.'/../Project/vendor/autoload.php';

if (file_exists($maintenance = __DIR__.'/../Project/storage/framework/maintenance.php')) {
    require $maintenance;
}

$app = require_once __DIR__.'/../Project/bootstrap/app.php';

Edit bootstrap/app.php. Add before return $app;

$app->bind('path.public', function () {
    return base_path() . '/../public';
});

Create Project/.htaccess. if you're webhosting

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^(.*)$ public/$1 [L]
</IfModule>


Arguments/Advantages of Additive Model Construction Analysis in an Experimental Design

Question: Assume I perform a psychological experiment with a number of manipulations, each hypothesized to influence the dependent variable. For instance, we perform a mixed-design short-term memory experiment where:

DV = Number of letters recalled
IV1 = Number of letters
IV2 = Number of distractions
IV3 = Delay time between presentation of stimuli and recall
IV4 = Whether memory is being stored internally (biologically) or externally (i.e., pen and paper)

Assuming the presence of interactions between terms, is there any argument for constructing a number of analytical model (e.x., ~IV1*IV2, ~IV1*IV2*IV4, ~IV1*IV2*IV3*IV4) in order to best understand the phenomena? This is in the context of performing successive mixed-design ANOVA's to come to some multiple conclusions regarding the experiment. I have a basic understanding of regression/multivariate regression and recognize the folly of including unnecessary variables - but if they're all hypothesized to exert some effect, isn't the final model the most sound?
Comment: If you expect IV1-IV4 all to exert effects, it's definitely worth including them in the model. High-dimensional interactions are hard to estimate unless you have mountains of data, but if you think they exist, you might as well include them even if you are unlikely to detect a strong effect. Model checking may become harder with very complex models, but that is a problem that can be dealt with.

You might also think about whether there could be nonlinearities in these shapes that are not captured by a simple linear model, especially when there are interactions.
Answer: Yes there are several advantages to sequential model building above and beyond obtaining a better understanding of the phenomena under investigation.
First, you can obtain model diagnostics at each step of your model building process as you move from the least complex main effects model to the most complex 4-way interaction model. This may allow you to better detect issues as they arise rather than attempting to target a problem in what will be a very complex final model.
Second, you can determine whether adding a higher order interaction term significantly improves your model. Additionally, you can easily determine the amount of variance accounted for by adding a higher order interaction term, if you build and test models sequentially.
Third, as you move through your model building, when you detect significant interactions you can probe those interactions more easily right then and there so to speak. Now, there may still be higher order interaction effects that need to be considered, but having an understanding of how less complex interaction effects are operating will help you tell the story of your data.
Finally, I want to echo the comment above that high dimensional interactions are generally VERY under-powered in practice as they require large samples. Additionally, it can be difficult to offer clear interpretations of the simple effects contained within a 4-way interaction. I would just be certain that your research question/hypothesis truly requires such a complex model (for instance, would adding some variables as covariates be a better option?).


convert time to Date type nest js

Question: <code> @Cron('23 16 * * *')
  async transferData() {
    try {
      // Retrieve data from the AttendanceBulk table
      const attendanceBulkData = await this.AttendanceBulkModel.findAll();

      for (const data of attendanceBulkData) {
        const attendance = new Attendance();

        // Find the corresponding AttendanceAndBulk entry based on data.UserId
        const attendanceAndBulk = await AttendanceAndBulk.findOne({ where: { UserId: data.UserId } });

        if (attendanceAndBulk) {
          attendance.employeeId = attendanceAndBulk.employeeId;
          attendance.shiftType = data.Intime ? ShiftType.In : ShiftType.Out;
          attendance.time = new Date(`${data.Intime}`);;
          attendance.date = data.Date;
          attendance.outTime= data.Date;

          console.log(data.Intime)
          await attendance.save();
        }
      }

      this.logger.log('Data transfer completed successfully.');
    } catch (error) {
      this.logger.error('Data transfer failed:', error);
    }
  }

</code>
In above code I data.Intime is comming like 00:39:41 this. but  attendance.date variable is Date type. how can I convert time varibale(00:39:41) to Date type in nest js?
Answer: You are only receiving hour/minutes/secondes
This is not sufficient to create a date
A solution that might work would be to create the date of the day, and then set the received time on this date
<code>const [hours, minutes, seconds] = date.InTime.split(':');
const timestamp = (new Date()).setHours(hours, minutes, seconds);
const date = new Date(timestamp);
</code>
Here is the link of the documentation for the Date object, from wich we call the  setHours methods
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours
If you plan on working with date a lot, i would also advise to checkout dayjs, a very convenient library for date manipulation in javascript
https://day.js.org/

convert time to Date type nest js


Rotating an image in Photoshop causes transparent pixels on image border, how to stop this?

Question: I start with a seamless grass texture h133 w133 px, I then rotate it by 45 degrees and divide the height by 2 so i'm left with an isometric diamond shape. The background is #FF00FF that i key out when rendering my tiles.
As you can see, the diamond edges are transparent like after this process see the pic:
closeup pic of the transparent diamond edge
How to stop the transparent pixels and make them solid, thanks.
Answer: It sounds like Photoshop is automatically changing the edges when you do any transformation on any object.
Try going to Menu > Edit > Preferences > General
and select 'Image Interpolation' and under that choose "Nearest Neighbor (Preserve Hard Edges)". This will make sure that the pixels stay sharp like those 8-bit artworks.


Flat torsionfree connection in Kähler manifold

Question: If $\nabla$ is a flat torsionfree connection and $J$ is a complex structure, we define
\begin{align}
d^{\nabla}J(X,Y)=(\nabla_{X}J)Y-(\nabla_{Y}J)X.
\end{align}
Why flatness of $\nabla$ means $d^{\nabla}=0$, and $\nabla$ is torsionfree means $(d^{\nabla })^{2}(\mathrm{id})=0$?
Comment: What is the source where these meanings are used? Looks like a typo. Usually, $d^{\nabla} Id$ can be interpreted as the torsion of $\nabla$, and $d^{\nabla} \circ d^{\nabla}$ is the curvature...
Comment: I found it in this paper: http://arxiv.org/abs/hep-th/9712042 on page 4. So $d^{\nabla}(X,Y)=\nabla_{X}Y-\nabla_{Y}X-[X,Y]$?
Comment: I'm afraid that in your last equation you have made a typo again. I posted an answer hoping that it may clarify the things to you.
Comment: The formula for $\mathrm{d}^{\nabla} J$ that you give in the question holds only for torsion free connections. I have added this point to my answer.
Answer: Short answer. In general (see the extended answer), the formula for $\mathrm{d}^{\nabla} J$ would be
$$
d^{\nabla}J(X,Y)=\nabla_{X} \left( J(Y) \right) - \nabla_{Y} \left( J(X) \right) - J([X,Y])
$$
because the almost complex structure $J \colon TM \to TM$ is regarded as a $TM$-valued $1$-form (it has to satisfy $J^2 = - \mathrm{id}$ but this is irrelevant for the question we consider).
Torsion free means $T^{\nabla} = \mathrm{d}^{\nabla} \mathrm{id} = 0$, see equation (1.4) in the paper you mention.
Flat means $R^{\nabla} = \mathrm{d}^2_{\nabla} = \mathrm{d}^{\nabla} \circ \mathrm{d}^{\nabla} = 0$, see the cited paper, next line after equation (1.3)
Now, when the connection $\nabla$ is torsion free, we can use the fact that in this case the Lie bracket is expressed simply as
$$
[X,Y] = \nabla_X Y - \nabla_Y X
$$
and using (see e.g. here) the notation
$$
(\nabla_X J) Y := \nabla_X (J(Y)) - J(\nabla_X Y)
$$
the general expression for $\mathrm{d}^{\nabla} J$ is simplified to
$$
\mathrm{d}^{\nabla} J (X,Y) = (\nabla_X J) Y - (\nabla_Y J) X
$$
as it is given, for instance, in this paper, Remark 1 on p.5.
Extended answer.
The invariant formula
$$
\begin{align}
\mathrm{d} \omega(X_0,...,X_k) = & \sum_{0 \le i \le k}(-1)^{i} X_i \left(\omega(X_0, \ldots, \hat{X_i}, \ldots, X_k)\right) \\
& +\sum_{0 \le i<j \le k}(-1)^{i+j} \omega([X_i, X_j], X_0, \ldots, \hat{X_i}, \ldots, \hat{X_j}, \ldots, X_k)
\end{align}
$$
for the exterior derivative of a $k$-form $\omega \in \Omega^k(M)$ on a manifold $M$ can be used as a definition, and also it can be extended to $k$-forms with values in a vector bundle $E \to M$ almost without a change (formally):
$$
\begin{align}
\mathrm{d}^{\nabla} \omega(X_0,...,X_k) = & \sum_{0 \le i \le k}(-1)^{i} \nabla_{X_i} \left(\omega(X_0, \ldots, \hat{X_i}, \ldots, X_k)\right) \\
& +\sum_{0 \le i<j \le k}(-1)^{i+j} \omega([X_i, X_j], X_0, \ldots, \hat{X_i}, \ldots, \hat{X_j}, \ldots, X_k)
\end{align}
$$
where $\nabla \colon \Omega^0(E) \to \Omega^1(E)$ is a connection in vector bundle $E$.
Now let us make a few applications of this formula to the most basic cases.
For $\omega \in \Omega^0(E) \equiv \Gamma(E)$ we have $\mathrm{d}^{\nabla} \omega (X) = \nabla_X \omega$
When $\omega \in \Omega^1(E) \equiv \Omega^1(M) \otimes \Gamma(E)$ one gets
$$
\mathrm{d}^{\nabla} \omega (X,Y) = \nabla_X \omega(Y) - \nabla_Y \omega(X) - \omega([X,Y]) \tag{*}
$$
The identity map $\mathrm{id} \colon TM \to TM$ can be naturally seen as a $TM$-valued $1$-form, and the latter identity applied to it reads as
$$
\mathrm{d}^{\nabla} \mathrm{id} (X,Y) = \nabla_X Y - \nabla_Y X - [X,Y]
$$
where on the right hand side we see what is known as the torsion $T(X,Y) = T^{\nabla}(X,Y)$ of the connection $\nabla$
No surprise that torsion free ($T^{\nabla}(X,Y) = 0$) connections are in favour: we would like that the identity map has zero derivative!
Let us turn to the connection $\nabla$ itself. For $\omega \in \Omega^0(E)$ we regard  $\mathrm{d}^{\nabla} \omega = \nabla \omega$ as a $E$-valued $1$-form, and so we can use the identity (*) again:
$$
\begin{align}
\mathrm{d}^{\nabla} \mathrm{d}^{\nabla} \omega & = \nabla_X \mathrm{d}^{\nabla} \omega(Y) - \nabla_Y \mathrm{d}^{\nabla} \omega (X) - \mathrm{d}^{\nabla} \omega([X,Y]) \\
& = \nabla_X \nabla_Y \omega - \nabla_Y \nabla_X \omega - \nabla_{[X,Y]} \omega
\end{align}
$$
and again we recognize in RHS the curvature operator $R_{X Y}$ acting on a section $\omega \in \Gamma(E)$ of a vector bundle $E$ with a connection $\nabla$
Informally speaking, $\mathrm{d}^{\nabla} \circ \mathrm{d}^{\nabla} = R^{\nabla}$
A connection is called flat if $R^{\nabla} = \mathrm{d}^{\nabla} \circ \mathrm{d}^{\nabla} = 0$
We like flat connections because the derivatives commute nicely.
This is precisely the story that can be read off from the equation (1.3) in the cited paper
All this is, indeed, very standard stuff. A more detailed treatment with everything made precise one can find e.g. in I.Madsen, J.Torenhave "From Calculus to Cohomology".
For a gentle introduction I would recommend the Wikipedia's article and the references therein (especially the book of R.W.R. Darling "Differential forms and connections").
Of course, all this is usually mentioned in the books and lectures on Kähler geometry in the sections on background. See, for instance, W.Ballmann's "Lectures on Kähler Manifolds", p.4.


Repetir JQuery .animate() após clicar no botão

Question: Tenho o seguinte código:

$(document).ready(function(){

 $('#cadastre-se').click(function(){
     $('.icon-cracha').stop(true, true).delay(500).animate({top: "+0"},1000);
  });

});
.icon-cracha{
  width:100px;
  height: 100px;
  background-color:black;
  border-radius: 100%;
  position:absolute;
  top:-100px;
}

button{
  margin-top: 100px;
}

<button id="cadastre-se" name="submit" class="btn">Próximo</button>

jsfiddle
Gostaria que esse efeito se repetisse todas as vezes que eu clicasse no botão próximo. Pq aqui no meu projeto ele so acontece no primeiro passo do cadastro, nos demais a bolinha ja aparece direito sem efeito.
Answer: Faz assim, declara o top dele negativo, assim a animação pode aparecer sempre.
    $('#cadastre-se').click(function(){
      $('.icon-cracha').css('top','-100px');
      $('.icon-cracha').stop(true, true).delay(500).animate({top: "+0"},1000);
  });

Ve e me fala se é isso que você precisa.
Fiz um exemplo para mostrar.
https://jsfiddle.net/rboschini/ensdzre1/
Comment: Cara era exatamente isso, muito obrigado!
Comment: Precisando de ajuda, da um toque!


Can There Get Found Single Axioms for Some Subsystems of Propositional Calculus?

Question: I use Polish notation.  All systems have detachment and uniform substitution as the only primitive rules of the system.
A user named John told me in an answer "On the question of a single axiom, the answer is yes... many are known as you were pointed at above. But more generally, Tarski announced in 1930 that any system with substitution and modus ponens and that has as theorems either of the sets: {CpCqp, CpCqCCpCqrr} or {CpCqp, CpCqCCpCqrCsr} has a single axiom basis. (Adrian Rezus published a proof in 1982 of the first basis, Dolph Ulrich presented a proof of the second some years ago) John Halleck recently showed that (Cpp, CpCqCCpCqrCsr} and {CpCqp, CCpCqrCqCpr} were also suffice show that there is a single axiom basis for a system."
I'm not sure if his statement applies to any logical calculus, or just implicational calculi (and he doesn't have much activity on the stackexchange network).
Can there get found single axiom(s) for the positive implicational conjunctive calculus {CpCqp, CCpCqrCCpqCpr, CKpqp, CKpqq, CpCqKpq}?  The positive equivalential calculus... {{CpCqp, CCpCqrCCpqCpr, CEpqCpq, CEpqCqp, CCpqCCqpEpq}?  Does there exist single axiom(s) for these systems if we join Perice CCCpqpp as an axiom also? Does there exists a single axiom for the system {CpCqp, CCpCqrCCpqCpr, CCNpqCCNpNqp, CpCqKpq, CKpqp, CKpqq, CpApq, CpAqp, CCpqCCrqCAprq, CEpqCpq, CEpqCqp, CCpqCCqpEpq} where inter-definability of connectives is prohibited?
Any tips as to how to go about finding a single axiom for a logical system?
Answer: You may see this useful collection of axiom systems for propositional calculus.
Comment: A. N. Prior has a list of axiom systems also in the appendix of his Formal Logic.  Some of the systems listed include axioms for the positive implicational calculus, which has a 2-axiom basis of {CpCqp, CCpCqrCCpqCpr}.  The implication I mean to get at here comes as that if you look at say Frege's system for classical logic, you could replace {CpCqp, CCpCqrCCpqCpr} in Frege's axiom set by say a sole axiom of Meredith's CCCpqrCsCCqCrtCqt, or by a 3-axiom basis of Hilbert and get another basis for C-N classical logic.  I know that {CpCqp, CCpCqrCCpqCpr, CCNpNCqNNqp, CpCqNCpNq} is also a basis.
Comment: Also, if we have a system where a deduction theorem comes as provable, and CpCqp and CCpCqrCCpqCpr are axioms, then any axiom which is not CpCqp or CCpCqrCCpqCpr can get replaced by any of its commuted variants ({CpCqp, CCpCqrCCpqCpr} has the same theorems as {CpCqp, CCpqCCpCqrCpr}).  For example, Mendelsohn's system {CaCba, CCaCbcCCabCac, CCNaNbCCNaba} has the same theorem as {CaCba, CCaCbcCCabCac, CCNabCCNaNba} as well as {CaCba, CCabCCaCabCab, CCNaNbCCNaba} and {CaCba, CCabCCaCabCab, CCNabCCNaNba}.  Or in a C-A-K-E-N calculus CCpqCCrqCAprq could get replaced by CApqCCprCCqrr.
Comment: Also, for any system with CpCqp as one of its axioms, you can replace CpCqp with any theorem obtainable by condensed detachment in the system {CpCqp}.  For instance, the positive logic instead of getting axiomitized by {CpCqp, CCpCqrCCpqCpr} could get axiomitized by {CpCqCrp, CCpCqrCCpqCpr} or {CpCqCrCsr, CCpCqrCCpqCpr} or {CpCqCrCsCtCuCvCwCxCyCzy, CCpCqrCCpqCpr}.
Answer: "... (Cpp, CpCqCCpCqrCsr} and {CpCqp, CCpCqrCqCpr} were also suffice to show that there is a single axiom basis for a system. ... I'm not sure if his statement applies to any logical calculus, or just implicational calculi."
Short answer: True of any logical calculus that has the given theorems.
The proof is (as Rezus' proof is) a contructive proof that given either set you can package up ANY axiomatic basis of the system into a single axiom.  While the proofs are mine, they were found using approaches that are due to Dolph "Ted" Ulrich.  [And they produce shorter axioms than Rezus' techniques produce.]  To the best of my knowledge, there are currently no constructive techniques (like Rezus', or Ulrich's, or mine) that produce shortest single axioms.
Answer: Cross ref. to "Examples of mathematical discoveries which were kept as a secret" [Nov 3, 2014]
The Question was:
"What are examples of mathematical discoveries which were kept as a secret when they discovered and then became unfolded after a while by any reasons?" [asked Nov 3, '14 at 14:17, by Ali Sadegh Dagighi, edited Nov 15 '14 at 10:32] [ Examples of mathematical discoveries which were kept as a secret, commented upon by Doug Spoonwood, Nov 10 '14, etc.]
[Adrian Rezus: 20150323] Actually, Tarski's result is of 1925. It was not "kept secret", his (Polish) colleagues and collaborators (Lesniewski, Lukasiewicz, etc.) were duly informed about the finding, Tarski just did not find it interesting enough to advertise it. (Another example — more relevant, perhaps — is the so-called "Deduction Theorem", usually credited to Jacques Herbrand, cca 1930, which Tarski found already around 1921-1922, about a decade before the Frenchman; he mentioned the result in print only much later.) The original proof of the axiomatixability result was lost, indeed. As to "data retrieval", I was a able to prove the result around 1979 [in print 1982][1], not just "a few years later" (unless 1979-1925 = 54 years would count as "a few"!), by a method based on [typed] lambda-calculus. (As an aside: lambda calculus was invented by the end of the twenties, and appeared first in print in 1932-1933, while typed lambda-calculus dates of 1937-1938; so I still wonder what could have been Tarski's "original method" of proof!) Around 2010, John Halleck found another proof of Tarski's Claim (1925) by using specific software (an automated theorem prover) of his own design. [For details, see also my [notes][2] of Oct 1, 2010],
[1] "On a Theorem of Tarski", Libertas Mathematica [Arlington TX] vol 2, 1982, pp 63-97 [MR 84b:03019] [online @ https://www.academia.edu/293942/_On_a_theorem_of_Tarski_Libertas_Mathematica_Arlington_TX_vol._2_1982_pp._63-97_MR_84b_03019_]
[2] "Tarski's Claim - Thirty years later", Oct 1, 2010 [online @
https://www.academia.edu/999512/_Tarskis_Claim_Thirty_Years_Later_Preprint_Nijmegen_October_1_2010_]


Capture and encode desktop with libav in real time not giving corect images

Question: As part of a larger project I want to be able to capture and encode the desktop frame by frame in real time. I have the following test code to reproduce the issue shown in the screenshot:
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <math.h>

extern "C"
{
#include "libavdevice/avdevice.h"
#include "libavutil/channel_layout.h"
#include "libavutil/mathematics.h"
#include "libavutil/opt.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
}

/* 5 seconds stream duration */
#define STREAM_DURATION   5.0
#define STREAM_FRAME_RATE 25 /* 25 images/s */
#define STREAM_NB_FRAMES  ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
#define STREAM_PIX_FMT    AV_PIX_FMT_YUV420P /* default pix_fmt */

int videoStreamIndx;
int framerate = 30;

int width = 1920;
int height = 1080;

int encPacketCounter;

AVFormatContext* ifmtCtx;
AVCodecContext* avcodecContx;
AVFormatContext* ofmtCtx;
AVStream* videoStream;
AVCodecContext* avCntxOut;
AVPacket* avPkt;
AVFrame* avFrame;
AVFrame* outFrame;
SwsContext* swsCtx;

std::ofstream fs;

AVDictionary* ConfigureScreenCapture()
{

    AVDictionary* options = NULL;
    //Try adding "-rtbufsize 100M" as in https://stackoverflow.com/questions/6766333/capture-windows-screen-with-ffmpeg
    av_dict_set(&options, "rtbufsize", "100M", 0);
    av_dict_set(&options, "framerate", std::to_string(framerate).c_str(), 0);
    char buffer[16];
    sprintf(buffer, "%dx%d", width, height);
    av_dict_set(&options, "video_size", buffer, 0);
    return options;
}

AVCodecParameters* ConfigureAvCodec()
{
    AVCodecParameters* av_codec_par_out = avcodec_parameters_alloc();
    av_codec_par_out->width = width;
    av_codec_par_out->height = height;
    av_codec_par_out->bit_rate = 40000;
    av_codec_par_out->codec_id = AV_CODEC_ID_H264; //AV_CODEC_ID_MPEG4; //Try H.264 instead of MPEG4
    av_codec_par_out->codec_type = AVMEDIA_TYPE_VIDEO;
    av_codec_par_out->format = 0;
    return av_codec_par_out;
}

int GetVideoStreamIndex()
{
    int VideoStreamIndx = -1;
    avformat_find_stream_info(ifmtCtx, NULL);
    /* find the first video stream index . Also there is an API available to do the below operations */
    for (int i = 0; i < (int)ifmtCtx->nb_streams; i++) // find video stream position/index.
    {
        if (ifmtCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
        {
            VideoStreamIndx = i;
            break;
        }
    }

    if (VideoStreamIndx == -1)
    {
    }

    return VideoStreamIndx;
}

void CreateFrames(AVCodecParameters* av_codec_par_in, AVCodecParameters* av_codec_par_out)
{

    avFrame = av_frame_alloc();
    avFrame->width = avcodecContx->width;
    avFrame->height = avcodecContx->height;
    avFrame->format = av_codec_par_in->format;
    av_frame_get_buffer(avFrame, 0);

    outFrame = av_frame_alloc();
    outFrame->width = avCntxOut->width;
    outFrame->height = avCntxOut->height;
    outFrame->format = av_codec_par_out->format;
    av_frame_get_buffer(outFrame, 0);
}

bool Init()
{
    AVCodecParameters* avCodecParOut = ConfigureAvCodec();

    AVDictionary* options = ConfigureScreenCapture();

    AVInputFormat* ifmt = av_find_input_format("gdigrab");
    auto ifmtCtxLocal = avformat_alloc_context();
    if (avformat_open_input(&ifmtCtxLocal, "desktop", ifmt, &options) < 0)
    {
        return false;
    }
    ifmtCtx = ifmtCtxLocal;

    videoStreamIndx = GetVideoStreamIndex();

    AVCodecParameters* avCodecParIn = avcodec_parameters_alloc();
    avCodecParIn = ifmtCtx->streams[videoStreamIndx]->codecpar;

    AVCodec* avCodec = avcodec_find_decoder(avCodecParIn->codec_id);
    if (avCodec == NULL)
    {
        return false;
    }

    avcodecContx = avcodec_alloc_context3(avCodec);
    if (avcodec_parameters_to_context(avcodecContx, avCodecParIn) < 0)
    {
        return false;
    }

    //av_dict_set
    int value = avcodec_open2(avcodecContx, avCodec, NULL); //Initialize the AVCodecContext to use the given AVCodec.
    if (value < 0)
    {
        return false;
    }

    AVOutputFormat* ofmt = av_guess_format("h264", NULL, NULL);

    if (ofmt == NULL)
    {
        return false;
    }

    auto ofmtCtxLocal = avformat_alloc_context();
    avformat_alloc_output_context2(&ofmtCtxLocal, ofmt, NULL, NULL);
    if (ofmtCtxLocal == NULL)
    {
        return false;
    }
    ofmtCtx = ofmtCtxLocal;

    AVCodec* avCodecOut = avcodec_find_encoder(avCodecParOut->codec_id);
    if (avCodecOut == NULL)
    {
        return false;
    }

    videoStream = avformat_new_stream(ofmtCtx, avCodecOut);
    if (videoStream == NULL)
    {
        return false;
    }

    avCntxOut = avcodec_alloc_context3(avCodecOut);
    if (avCntxOut == NULL)
    {
        return false;
    }

    if (avcodec_parameters_copy(videoStream->codecpar, avCodecParOut) < 0)
    {
        return false;
    }

    if (avcodec_parameters_to_context(avCntxOut, avCodecParOut) < 0)
    {
        return false;
    }

    avCntxOut->gop_size = 30; //3; //Use I-Frame frame every 30 frames.
    avCntxOut->max_b_frames = 0;
    avCntxOut->time_base.num = 1;
    avCntxOut->time_base.den = framerate;

    //avio_open(&ofmtCtx->pb, "", AVIO_FLAG_READ_WRITE);

    if (avformat_write_header(ofmtCtx, NULL) < 0)
    {
        return false;
    }

    value = avcodec_open2(avCntxOut, avCodecOut, NULL); //Initialize the AVCodecContext to use the given AVCodec.
    if (value < 0)
    {
        return false;
    }

    if (avcodecContx->codec_id == AV_CODEC_ID_H264)
    {
        av_opt_set(avCntxOut->priv_data, "preset", "ultrafast", 0);
        av_opt_set(avCntxOut->priv_data, "zerolatency", "1", 0);
        av_opt_set(avCntxOut->priv_data, "tune", "ull", 0);
    }

    if ((ofmtCtx->oformat->flags & AVFMT_GLOBALHEADER) != 0)
    {
        avCntxOut->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
    }

    CreateFrames(avCodecParIn, avCodecParOut);

    swsCtx = sws_alloc_context();
    if (sws_init_context(swsCtx, NULL, NULL) < 0)
    {
        return false;
    }

    swsCtx = sws_getContext(avcodecContx->width, avcodecContx->height, avcodecContx->pix_fmt,
        avCntxOut->width, avCntxOut->height, avCntxOut->pix_fmt, SWS_FAST_BILINEAR,
        NULL, NULL, NULL);
    if (swsCtx == NULL)
    {
        return false;
    }

    return true;
}

void Encode(AVCodecContext* enc_ctx, AVFrame* frame, AVPacket* pkt)
{
    int ret;

    /* send the frame to the encoder */
    ret = avcodec_send_frame(enc_ctx, frame);
    if (ret < 0)
    {
        return;
    }

    while (ret >= 0)
    {
        ret = avcodec_receive_packet(enc_ctx, pkt);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return;
        if (ret < 0)
        {
            return;
        }

        fs.write((char*)pkt->data, pkt->size);
        av_packet_unref(pkt);
    }
}

void EncodeFrames(int noFrames)
{
    int frameCount = 0;
    avPkt = av_packet_alloc();
    AVPacket* outPacket = av_packet_alloc();
    encPacketCounter = 0;

    while (av_read_frame(ifmtCtx, avPkt) >= 0)
    {
        if (frameCount++ == noFrames)
            break;
        if (avPkt->stream_index != videoStreamIndx) continue;

        avcodec_send_packet(avcodecContx, avPkt);

        if (avcodec_receive_frame(avcodecContx, avFrame) >= 0) // Frame successfully decoded :)
        {
            outPacket->data = NULL; // packet data will be allocated by the encoder
            outPacket->size = 0;

            outPacket->pts = av_rescale_q(encPacketCounter, avCntxOut->time_base, videoStream->time_base);
            if (outPacket->dts != AV_NOPTS_VALUE)
                outPacket->dts = av_rescale_q(encPacketCounter, avCntxOut->time_base, videoStream->time_base);

            outPacket->dts = av_rescale_q(encPacketCounter, avCntxOut->time_base, videoStream->time_base);
            outPacket->duration = av_rescale_q(1, avCntxOut->time_base, videoStream->time_base);

            outFrame->pts = av_rescale_q(encPacketCounter, avCntxOut->time_base, videoStream->time_base);
            outFrame->pkt_duration = av_rescale_q(encPacketCounter, avCntxOut->time_base, videoStream->time_base);
            encPacketCounter++;

            int sts = sws_scale(swsCtx,
                avFrame->data, avFrame->linesize, 0, avFrame->height,
                outFrame->data, outFrame->linesize);

            /* make sure the frame data is writable */
            auto ret = av_frame_make_writable(outFrame);
            if (ret < 0)
                break;
            Encode(avCntxOut, outFrame, outPacket);
        }
        av_frame_unref(avFrame);
        av_packet_unref(avPkt);
    }
}

void Dispose()
{
    fs.close();

    auto ifmtCtxLocal = ifmtCtx;
    avformat_close_input(&ifmtCtx);
    avformat_free_context(ifmtCtx);
    avcodec_free_context(&avcodecContx);

}

int main(int argc, char** argv)
{
    avdevice_register_all();

    fs.open("out.h264");

    if (Init())
    {
        EncodeFrames(300);
    }
    else
    {
        std::cout << "Failed to Init \n";
    }

    Dispose();

    return 0;
}

As far as I can tell the setup of the encoding process is correct as it is largely unchanged from how the example given in the official documentation is working: https://libav.org/documentation/doxygen/master/encode__video_8c_source.html
However there is limited documentation around the desktop capture online so I am not sure if I have set that up correctly.
Comment: This is not a solution to the problem directly but a comment on the sample code. I notice that you open a output format context but then don't use it, if you are just dumping the raw packets to file (or passing them to another non-ffmpeg component) then it is wasted effort to open a format context that you don't use, you can instead just open the codec context directly.
Answer: We have to open the out.h264 as binary file.
Replace fs.open("out.h264"); with fs.open("out.h264", std::ios::binary);.

The default file type in Windows is "text file".
That means that each \n in converted to \r\n when writing, and the encoded stream get "messed up".
It took me quite a long time to figure out the problem...

There is another small issue:
There is a missing loop at the end, that flushes the remaining encoded packets.
We can use FFprobe for counting the number of encoded frames:
ffprobe -v error -select_streams v:0 -count_frames -show_entries stream=nb_read_frames -print_format csv out.h264
The result is 263 instead of 300.
The solution is adding the following loop at the end of void EncodeFrames(int noFrames) function:
int ret = 0;
avcodec_send_frame(avCntxOut, NULL);
do
{
    av_packet_unref(outPacket);
    ret = avcodec_receive_packet(avCntxOut, outPacket);
    if (!ret)
    {
        fs.write((char*)outPacket->data, outPacket->size);
    }
} while (!ret);

Comment: Hi Rotem, thanks for the answer, do you have any idea what might be causing the packets to pile up in the first place? For the example given here I write to a file for testing, however I want to be able to send each frame over the web in the final product so I dont want them to pile up and need flushing, but instead for them to send as each frame is ready.
Comment: That is because the code `av_opt_set(avCntxOut->priv_data, "zerolatency", "1", 0);` is not executed. Use the debugger to see why. Without "tuning" the default latency is relatively long.
Answer: This is not a solution to the problem directly but maybe so?
AVDictionary * pDic = NULL;
av_dict_set(&pDic, "tune", "zerolatency", 0);
avcodec_open2(avCntxOut, avCodecOut, &pDic);


time difference between 2 geographic coordinates

Question: The pre-calculus question was:
If it's 10 am in City A, $35.1667^{\circ}$S, $70.7^{\circ}$E, what time is it in city B at $24.3^{\circ}$S, $19.53^{\circ}$E.
I know that the time is based on longitude not latitude, so I found the difference between the 2 longitudes $70.7-19.53=51.17^{\circ}$. Since I know that there is $1$ hour of time difference for every $15^{\circ}$ of longitude I divided $51.17 $ by $15=3.41$ hours.  Since we were told it was ok to round, I rounded this to $3$ hours = $10-3= 7$am.
Book says $6$ am.  !!! So, I worked it the more accurate way of knowing that there is $4$ minutes of time difference for every $1 ^{\circ}$ of longitude. $51.17 * 4=204.68$ minutes.  This would indicate the same $3$ hours and $24$ mintues of time difference.  Technically, this would make it $6:36$ am in City B.  I don't see how I could possibly get $6$am unless I just drop the minutes entirely and NOT round.
Is there a proper way to do this problem, or is it subject to various methods of rounding/dropping?
Comment: Perhaps the answer may depend on just where the time zone lines are drawn - the default being uniformly spaced at intervals of longitude starting with $0$ in Greenwich. Draw a picture and place your points. Just "rounding" may not be right.
Comment: We are told this could be a test question.  I would have no idea how to draw timezones in the middle of the Indian Ocean.
Comment: As you noticed, your city A shoud be underwater in the Indian Ocean.;-)
Comment: If they do not expect you to have access to maps with time zones, then they can't expect you to get the answer exactly correct. I would say $3$ hours is a reasonable result, and mark it as correct. However, this is up to your teachers, and they may not be as lenient. Also, checking the points on a map with time zones, I do get a time difference of 3 hours (UTC+5 for point A straight north from Port-au-Francais in the Indian ocean, and UTC+2 for point B in Ukraine). Unless there are daylight savings shenanigans going on, I have no idea how they got 4 hours.
Comment: I think you need to assume that a time zone is $\pm7.5^\circ$ around $0,15,30,45,60,75^\circ$. Then city $A$ is in the $75^\circ$ zone, and $B$ is in the $15^\circ$ zone
Answer: The prime meridian is, by definition in the middle of a time zone, typically denoted the +0 time zone since there is no time offset between that zone and itself.
Because $$5 \cdot 15^\circ - 7.5^\circ = 67.5^\circ < 70.7^\circ < 82.5^\circ = 5 \cdot 15^\circ + 7.5^\circ  \text{,}  $$ city A is in the +5 time zone east of the prime meridian.  Because $$1 \cdot 15^{\circ} - 7.5^\circ  = 7.5^\circ < 19.53^\circ < 22.5^\circ = 1 \cdot 15^\circ + 7.5^\circ  \text{,}  $$ city B is in the +1 timezone to the east of the prime meridian.  So in an ideal universe without national borders and seasonal time changes, there would be 4 hours time difference between the two cities.
However, in the real world, ...
City A is in the Indian ocean, further south than most of Australia, so this city's time zone is not complicated by national borders.  City B is in Namibia, so is actually in the Central Africa time zone, a +2 time zone.  (Namibia no longer implements Winter Time, so this UTC offset is correct year-round)  Accounting for this complication, the difference in times is 3 hours.
Comment: Yes, this was a non-real-world question, a math question, not a real city question.  I think the book was looking for your first answer.  It's just that ALL of the examples they gave were to find diff in longitude and divide by 15 and round.  Your way makes sense.  Thank you.  BTW, some great photography in Namibia.


How to create an increasing color of background for 3 cells in one row?

Question: I would like to create this kind of background in my xsl-fo document:

I blurred out the sensitive info, but hopefully it is still visible enough that it should be a grey color that gets increased from cell to cell.
This is my code behind it:

            <fo:table table-layout="fixed" width="100%" background-color="#FFFFFF">
                <fo:table-body>
                    <fo:table-row>
                        <fo:table-cell margin-left="55pt" padding-after="10pt">
                            <fo:block-container xsl:use-attribute-sets="boldtext">
                                <fo:block>
                                   1st column header
                                </fo:block>
                            </fo:block-container>
                        </fo:table-cell>
                        <fo:table-cell padding-left="30pt" padding-after="10pt">
                            <fo:block-container xsl:use-attribute-sets="boldtext">
                                <fo:block>
                                     2nd column header
                                </fo:block>
                            </fo:block-container>
                        </fo:table-cell>
                        <fo:table-cell padding-left="15pt" padding-after="10pt">
                            <fo:block-container xsl:use-attribute-sets="boldtext">
                                <fo:block>
                                     3rd column header
                                </fo:block>
                            </fo:block-container>
                        </fo:table-cell>
                    </fo:table-row>
                </fo:table-body>
            </fo:table>

Comment: Create an SVG that is the triangle and use behind the table. If you want it broken like that, use a white border on the middle cell left and right.
Answer: If you use RenderX you could use their extensions to scale background images. This solution would be like this. It would scale completely to the table with the number of rows and/or the size. It is unclear in your example what else would be in the table.
<fo:table table-layout="fixed" width="100%" background-image="tri.svg" background-position="bottom left" background-repeat="no-repeat" rx:background-content-width="scale-to-fit" rx:background-content-height="scale-to-fit" rx:background-scaling="non-uniform">
            <fo:table-body >
                <fo:table-row>
                    <fo:table-cell>
                        <fo:block-container >
                            <fo:block>
                                1st column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                    <fo:table-cell border-left="5pt solid white" border-right="5pt solid white">
                        <fo:block-container >
                            <fo:block>
                                2nd column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                    <fo:table-cell>
                        <fo:block-container>
                            <fo:block>
                                3rd column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                </fo:table-row>
                <fo:table-row>
                    <fo:table-cell>
                        <fo:block-container >
                            <fo:block>
                                1st column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                    <fo:table-cell border-left="5pt solid white" border-right="5pt solid white">
                        <fo:block-container >
                            <fo:block>
                                2nd column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                    <fo:table-cell>
                        <fo:block-container>
                            <fo:block>
                                3rd column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                </fo:table-row>
                <fo:table-row>
                    <fo:table-cell>
                        <fo:block-container >
                            <fo:block>
                                1st column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                    <fo:table-cell border-left="5pt solid white" border-right="5pt solid white">
                        <fo:block-container >
                            <fo:block>
                                2nd column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                    <fo:table-cell>
                        <fo:block-container>
                            <fo:block>
                                3rd column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                </fo:table-row>
                <fo:table-row>
                    <fo:table-cell>
                        <fo:block-container >
                            <fo:block>
                                1st column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                    <fo:table-cell border-left="5pt solid white" border-right="5pt solid white">
                        <fo:block-container >
                            <fo:block>
                                2nd column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                    <fo:table-cell>
                        <fo:block-container>
                            <fo:block>
                                3rd column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                </fo:table-row>
                <fo:table-row>
                    <fo:table-cell>
                        <fo:block-container >
                            <fo:block>
                                1st column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                    <fo:table-cell border-left="5pt solid white" border-right="5pt solid white">
                        <fo:block-container >
                            <fo:block>
                                2nd column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                    <fo:table-cell>
                        <fo:block-container>
                            <fo:block>
                                3rd column header
                            </fo:block>
                        </fo:block-container>
                    </fo:table-cell>
                </fo:table-row>
            </fo:table-body>
        </fo:table>

This results in this:

If you are using FOP, it is not clear to me that such extensions exist and you would likely need to size the SVG for the table if known.
Comment: Kevin, maybe I don't understand it, because i'm new to this, sorry for that. I just wanted to let you or the next person to know what was the exact code that worked for me (because just by copy and paste, it did not give me the result I needed!), and I cannot enter my code in a comment. But next time I will not do it then.
Comment: @Meredydd You should be able to accept the answer (green check mark). You asked the question so there are two things -- upvoting a useful answer and accepting an answer. If you wish to then add additional information that is useful you can in comments or even edit your question your specific edits to the answer.


Trigonometric functions as elementary functions

Question: We know Euler's formula implies that trigonometric functions are elementary functions. However, it forms only complex exponential functions. So, can I say that it is an extension of elementary functions?
Answer: You can just call them elementary functions. It's true that in some sense it could be classified as an extension of real elementary functions, but people usually just refer to all trig functions as elementary functions (distinguishing them from something like the error function).


Given a function $f(x)$ where $x$ is uniformly distributed between $a$ and $b$, how do I find the probability density function of $f$?

Question: For example, if $f(x) = \sin x$ and $x$ is uniformly distributed on $[0, \pi]$, how is the equation found that satisfies the probability distribution function of $f(x)$? I imagine the distribution function will be greater when the derivative of $f(x)$ is closer to zero, but this is just a guess.
I apologize if this question is vague or not advanced enough, but I can't find the answer anywhere.
Answer: Note that $\sin(x)$ increases from $x = 0$ to $x = {\pi \over 2}$, then decreases from ${\pi \over 2}$ to $\pi$, in a way symmetric about ${\pi \over 2}$. So for a given $0 \leq \alpha \leq 1$, the $x \in [0,\pi]$ for which $\sin(x) \leq \alpha$ consists of two segments, $[0,\beta]$ and $[\pi - \beta, \pi]$, where $\beta$ is the number for which $\sin(\beta) = \alpha$. In other words $\beta = \arcsin(\alpha)$.
Since $x$ is uniformly distributed on $[0,\pi]$, the probability $x$ is in $[0,\beta]$ is ${\beta \over \pi}$, and the probability $x$ is in $[\pi - \beta, \pi]$ is also ${\beta \over \pi}$. So the chance that $x$ is in one of these two segments is $2{\beta \over \pi}$. This means the probability $\sin(x) \leq \alpha$ is $2{\beta \over \pi}$, or ${2 \over \pi} \arcsin(\alpha)$. Thus this gives the distribution function of $\sin(x)$. The density function is obtained by differentiating with respect to $\alpha$; the result is ${2 \over \pi \sqrt{1 - \alpha^2}}$.
Comment: Sorry for my late reply, but thank you for your answer! I finally understand this concept, and your answer has helped greatly.
Answer: in searching the solution for a nearly problem, I have been falling in your interesting discussion. But there's something I doubt about Zarrax's answer. If the probablity density function is like your result, we can find out easily there's some values of alpha which makes the distribution function greater than 1, is it physically correct?
Comment: Note that if $0 \leq \alpha \leq 1$, then $0 \leq (2/\pi)\arcsin(\alpha) \leq 1$.