问:
Django running fine outside Docker but never starts within Docker, how to find issue?
I had a working Django project that had built and deployed many images over the last few weeks. My django project kept working fine when ran as "python manage.py runserver" and the Docker images kept being built fine (all successful builds). However the django app now doesn't deploy. What could be the issue and where should I start to look for it? I've tried the logs but they only say "Starting Django" without actually starting the service

I use github and have gone back to previous versions of the code and none of them now work, even though the code is exactly the same. It also fails to deploy the Django server on AWS Elastic Beanstalk infrastructure which is my ultimate goal with this code.

start.sh:

```<code>#!/bin/bash
echo Starting Django
cd TN_API
exec python ../manage.py runserver 0.0.0.0:8000
</code>```

Dockerfile:

```<code>FROM python:2.7.13-slim

# Set the working directory to /app
WORKDIR /TN_API

# Copy the current directory contents into the container at /app
ADD . /TN_API

# COPY startup script into known file location in container
COPY start.sh /start.sh

# Install requirements
RUN pip install -r requirements.txt

# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000

# CMD specifcies the command to execute to start the server running.
CMD ["/start.sh"]
</code>```

Commands:
sudo docker run -d tn-api
sudo docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
d28115a919f9        tn-api              "/start.sh"         11 seconds ago      Up 8 seconds        8000/tcp            festive_darwin

sudo docker logs [container id]
Starting Django

(doesn't do the whole:
Performing system checks...

System check identified no issues (0 silenced).
August 06, 2017 - 20:54:36
Django version 1.10.5, using settings 'TN_API.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.)

答:
It looks like the path is wrong for the manage.py script in /start.sh.

Your start.sh:

```<code>#!/bin/bash
echo Starting Django
cd TN_API
exec python ../manage.py runserver 0.0.0.0:8000
</code>```

Seeing that you set WORKDIR to you project directory in the Dockerfile, the start.sh script is actually run from inside the project directory - which means it is actually doing this:

```<code>cd /TN_API               # WORKDIR directive in Dockerfile
echo Starting Django     # from the start.sh script
cd /TN_API/TN_API        # looking for TN_API within your current pwd
exec python /TN_API/manage.py runserver 0.0.0.0:8000  # goes up a level (..) to look for manage.py
</code>```

So it could be that your context for running runserver is off.
You can avoid this path jumping by rewriting your Dockerfile to include an CMD directive as follows:

```<code>FROM python:2.7.13-slim

# Set the working directory to /app
WORKDIR /TN_API

# Copy the current directory contents into the container at /app
ADD . /TN_API

# Install requirements
RUN pip install -r requirements.txt

# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000

# CMD specifcies the command to execute to start the server running.
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
</code>```

Here using python manage.py runserver 0.0.0.0:8000 will work since you set the WORKDIR to your project directory already. So you wouldn't need your start.sh script necessarily.

Body:
I had a working Django project that had built and deployed many images over the last few weeks. My django project kept working fine when ran as "python manage.py runserver" and the Docker images kept being built fine (all successful builds). However the django app now doesn't deploy. What could be the issue and where should I start to look for it? I've tried the logs but they only say "Starting Django" without actually starting the service

I use github and have gone back to previous versions of the code and none of them now work, even though the code is exactly the same. It also fails to deploy the Django server on AWS Elastic Beanstalk infrastructure which is my ultimate goal with this code.

start.sh:

#!/bin/bash
echo Starting Django
cd TN_API
exec python ../manage.py runserver 0.0.0.0:8000

Dockerfile:

FROM python:2.7.13-slim

# Set the working directory to /app
WORKDIR /TN_API

# Copy the current directory contents into the container at /app
ADD . /TN_API

# COPY startup script into known file location in container
COPY start.sh /start.sh

# Install requirements
RUN pip install -r requirements.txt

# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000

# CMD specifcies the command to execute to start the server running.
CMD ["/start.sh"]

Commands:
sudo docker run -d tn-api
sudo docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
d28115a919f9        tn-api              "/start.sh"         11 seconds ago      Up 8 seconds        8000/tcp            festive_darwin

sudo docker logs [container id]
Starting Django

(doesn't do the whole:
Performing system checks...

System check identified no issues (0 silenced).
August 06, 2017 - 20:54:36
Django version 1.10.5, using settings 'TN_API.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.)

Body:
It looks like the path is wrong for the manage.py script in /start.sh.

Your start.sh:

#!/bin/bash
echo Starting Django
cd TN_API
exec python ../manage.py runserver 0.0.0.0:8000

Seeing that you set WORKDIR to you project directory in the Dockerfile, the start.sh script is actually run from inside the project directory - which means it is actually doing this:

cd /TN_API               # WORKDIR directive in Dockerfile
echo Starting Django     # from the start.sh script
cd /TN_API/TN_API        # looking for TN_API within your current pwd
exec python /TN_API/manage.py runserver 0.0.0.0:8000  # goes up a level (..) to look for manage.py

So it could be that your context for running runserver is off.
You can avoid this path jumping by rewriting your Dockerfile to include an CMD directive as follows:

FROM python:2.7.13-slim

# Set the working directory to /app
WORKDIR /TN_API

# Copy the current directory contents into the container at /app
ADD . /TN_API

# Install requirements
RUN pip install -r requirements.txt

# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000

# CMD specifcies the command to execute to start the server running.
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

Here using python manage.py runserver 0.0.0.0:8000 will work since you set the WORKDIR to your project directory already. So you wouldn't need your start.sh script necessarily.


来源: stackexchange

问:
Xamarin.Forms leak on Android doing simple push/pop of page?
I'm investigating a memory leak (or leaks) which seem to be core to our Forms app.

We're using FreshMvvm, which previously had a pretty bad leak due to Pages/PageModels not being garbage collected. Michael Ridland (FreshMvvm) author) fixed that, which is great.

However, we're still seeing the figure returned by GC.GetTotalMemory() steadily increase. It does decrease, but the general trend is upwards.

I've stripped things right back so that I've just got a plain Page which pushes another page and we can then pop back to the first.

Doing this, I'm seeing GC.GetTotalMemory() generally increase by 2K - 4K every cycle. This is after forcibly calling GC.Collect();

We're running Xamarin.Forms 2.3.4.270 - I know this is quite old, but we really don't want to upgrade as we don't want to introduce 'new Forms' bugs! However, I have tried experimentally upgrading to 2.5.0.121934, and I see the same behaviour (as well as aspects of the app stop working with this version).

Short of using Profiler, are there any investigative techniques I can use to find the culprit?

My next step will be to strip more and more out!

答:
I've encountered a similar issue in the past with Xamarin.Forms memory leaks and to help figure what views/pages were the culprit this class was created:

```<code>public static class Refs
{
    private static readonly List<WeakReference> _refs = new List<WeakReference>();

    public static readonly BindableProperty IsWatchedProperty = BindableProperty.CreateAttached("IsWatched", typeof(bool), typeof(Refs), false, propertyChanged: OnIsWatchedChanged);

    public static bool GetIsWatched(BindableObject obj)
    {
        return (bool)obj.GetValue(IsWatchedProperty);
    }

    public static void SetIsWatched(BindableObject obj, bool value)
    {
        obj.SetValue(IsWatchedProperty, value);
    }

    private static void OnIsWatchedChanged(BindableObject bindable, object oldValue, object newValue)
    {
        AddRef(bindable);
    }

    public async static void AddRef(object p)
    {
        GC.Collect();
        await Task.Delay(100);
        GC.Collect();

        _refs.Add(new WeakReference(p));
        foreach (var @ref in _refs)
        {
            if (@ref.IsAlive)
            {
                var obj = @ref.Target;
                Debug.WriteLine("IsAlive: " + obj.GetType().Name);
            }
            else
            {
                Debug.WriteLine("IsAlive: False");
            }
        }
        Debug.WriteLine("---------------");
    }
}
</code>```

Then to use it you can use the IsWatched property in your pages xaml or in code behind you can just do Refs.AddRef(this); after InitializeComponent(); and just navigate to and from the page several times. If it is being gc'ed the console should print IsAlive: False if not it will print out the type.

Most often the leaks we had were fixed by clearing the BindingContext and/or setting some things to null when leaving the page.

```<code>protected override void OnParentSet()
{
    base.OnParentSet();

    if (Parent == null)
    {
        BindingContext = null;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've encountered a similar issue in the past with Xamarin.Forms memory leaks and to help figure what views/pages were the culprit this class was created:

public static class Refs
{
    private static readonly List<WeakReference> _refs = new List<WeakReference>();

    public static readonly BindableProperty IsWatchedProperty = BindableProperty.CreateAttached("IsWatched", typeof(bool), typeof(Refs), false, propertyChanged: OnIsWatchedChanged);

    public static bool GetIsWatched(BindableObject obj)
    {
        return (bool)obj.GetValue(IsWatchedProperty);
    }

    public static void SetIsWatched(BindableObject obj, bool value)
    {
        obj.SetValue(IsWatchedProperty, value);
    }

    private static void OnIsWatchedChanged(BindableObject bindable, object oldValue, object newValue)
    {
        AddRef(bindable);
    }

    public async static void AddRef(object p)
    {
        GC.Collect();
        await Task.Delay(100);
        GC.Collect();

        _refs.Add(new WeakReference(p));
        foreach (var @ref in _refs)
        {
            if (@ref.IsAlive)
            {
                var obj = @ref.Target;
                Debug.WriteLine("IsAlive: " + obj.GetType().Name);
            }
            else
            {
                Debug.WriteLine("IsAlive: False");
            }
        }
        Debug.WriteLine("---------------");
    }
}

Then to use it you can use the IsWatched property in your pages xaml or in code behind you can just do Refs.AddRef(this); after InitializeComponent(); and just navigate to and from the page several times. If it is being gc'ed the console should print IsAlive: False if not it will print out the type.

Most often the leaks we had were fixed by clearing the BindingContext and/or setting some things to null when leaving the page.

protected override void OnParentSet()
{
    base.OnParentSet();

    if (Parent == null)
    {
        BindingContext = null;
    }
}


问:
How to convert a nested lists to dataframe in R?
I'm have a nested list I would like to convert to a dataframe.

```<code>iter1 <- list(item1 = 1, item2 = "a")
iter2 <- list(item1 = 1, item2 = "b")
All <- list(iter1 = iter1, iter2 = iter2)

df <- data.frame(t(sapply(All,c))) # Convert list to dataframe
</code>```

But my problem is that df$iter1 returns a list instead of a dataframe, any idea ?

```<code>> class(df)
[1] "data.frame"

> df$item1
$iter1
[1] 1

$iter2
[1] 1
</code>```

I have the same problem when converting with do.call : df <- data.frame(do.call(rbind, All)) but I can't figure out what is wrong.

答:
I think you want the first column to be a numeric vector as 1,1 and the second column to be a character vector as "a" and "b"?

How about this:

```<code>iter1 <- list(item1 = 1, item2 = "a")
iter2 <- list(item1 = 1, item2 = "b")
All <- list(iter1 = iter1, iter2 = iter2)

extract <- function(x, listx) sapply(listx, "[[", x)

df <- lapply(1:2, extract, All)
df <- as.data.frame(df, col.names = names(All), stringsAsFactors = F)
df
</code>```

And if you want a one-liner:

```<code>df <- as.data.frame(lapply(1:2, function(x, listx) sapply(listx, "[[", x), All), col.names = names(All), stringsAsFactors = F)
df
</code>```

Body:
I'm have a nested list I would like to convert to a dataframe.

iter1 <- list(item1 = 1, item2 = "a")
iter2 <- list(item1 = 1, item2 = "b")
All <- list(iter1 = iter1, iter2 = iter2)

df <- data.frame(t(sapply(All,c))) # Convert list to dataframe

But my problem is that df$iter1 returns a list instead of a dataframe, any idea ?

> class(df)
[1] "data.frame"

> df$item1
$iter1
[1] 1

$iter2
[1] 1

I have the same problem when converting with do.call : df <- data.frame(do.call(rbind, All)) but I can't figure out what is wrong.

Body:
I think you want the first column to be a numeric vector as 1,1 and the second column to be a character vector as "a" and "b"?

How about this:

iter1 <- list(item1 = 1, item2 = "a")
iter2 <- list(item1 = 1, item2 = "b")
All <- list(iter1 = iter1, iter2 = iter2)

extract <- function(x, listx) sapply(listx, "[[", x)

df <- lapply(1:2, extract, All)
df <- as.data.frame(df, col.names = names(All), stringsAsFactors = F)
df

And if you want a one-liner:

df <- as.data.frame(lapply(1:2, function(x, listx) sapply(listx, "[[", x), All), col.names = names(All), stringsAsFactors = F)
df


问:
CSS animate one direction, flip then animate back

I am trying to animate a sailboat to go horizontally from left to right, then flip the boat and animate it back from right to left, then loop.

I've got the right to left going fine. Not sure how to handle the flip and right to left part.

```<code>.sailBoatContainer {
    position: absolute;
    width: 250px;
    animation: move 20s linear infinite;
}

@keyframes move {
    from {
        left: 0;
    }
    to {
        left: 100%;
    }
}

    <div id="sail" class="sailBoatContainer">
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 98 103.18">
        <defs>
            <style>.sail1,.sail5{fill:none;}.sail1{stroke:#e1e1e1;}.sail1,.sail5,.sail6{stroke-linecap:round;}.sail1,.sail6{stroke-linejoin:round;}.sail2,.sail6{fill:#d3dfdd;}.sail3{fill:#f4f4f4;}.sail4{fill:#f1263a;}.sail5{stroke:#ae8863;stroke-miterlimit:10;stroke-width:2px;}.sail6{stroke:#c2ccca;}.sail7{fill:#7f604c;}
            </style>
        </defs>
        <title>sailboat</title>
        <g id="rigging">
            <path id="roperight" class="sail1" d="M1.48,89s37-35.67,50-70.33" transform="translate(-0.48 0)"/>
            <path id="ropeleft" class="sail1" d="M51.48,20.33c16,37.34,46,62.67,46,62.67" transform="translate(-0.48 0)"/>
        </g>
        <g id="cabin">
            <path id="cabinbox" class="sail2" d="M51.48,82v8h27V87s-9-5-12-5ZM62,83.5h4v4H62Zm-6,1h3v3H56Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="sails">
            <path id="sailright" class="sail3" d="M86.48,72s-23-43-33-49c0-1,11,24-4,46C49.48,69,75.48,68,86.48,72Z" transform="translate(-0.48 0)"/>
            <path id="sailleft" class="sail3" d="M48.48,14s-49,35-34,66c0,1,35,0,35,0S44.48,38,48.48,14Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="flag">
            <path class="sail4" d="M52,1.5s-2,2-3,2-8-2-11,0c0,0,6,1,8,4h6Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="mast">
            <line id="mastline" class="sail5" x1="51" y1="88" x2="51" y2="1"/>
        </g>
        <g id="hull">
            <path id="hullbox" class="sail6" d="M90,101.5s-78,4-89-4v-9s79,2,97-6C97,83.5,99,90.5,90,101.5Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="hullbottom">
            <path id="hullbottombox" class="sail7" d="M91.87,99.88S21.5,104,.5,97v2s8.73,6.94,89.73,2.94Z" transform="translate(-0.48 0)"/>
        </g>
    </svg>
</div>
</code>```

Here is a Codpen

I'd appreciate it if someone could point me in the right direction.

答:
Not sure how to handle the flip and right to left part.

Start by moving from two to three "steps", 0%/50%/100% instead of from/to. Move all the way to the right at 50%, and back to 0 at 100%.

(left: calc(100% - 250px); helps to make it turn around when it reaches the right window edge, instead of going over by the ship's width and causing scrollbars ;-)

And then throw in some transform:scaleX to "mirror" it from 50% on as well.

But that will actually require inserting a fourth step - otherwise scaleX will slowly transform from -1 to 1, and he boat will end up "rotating" ... so to keep it at -1 up until we get to 50%, throw in a frame a 49.999%:

```<code>@keyframes move
{
    0% {
        left: 0;
      transform: scaleX(1);
    }
    49.999% {
      transform: scaleX(1);
    }
    50% {
      left: calc(100% - 250px);
      transform: scaleX(-1);
    }
    100% {
      left: 0%;
      transform: scaleX(-1);
    }
}
</code>```

https://codepen.io/anon/pen/ZagbXN

Body:
I am trying to animate a sailboat to go horizontally from left to right, then flip the boat and animate it back from right to left, then loop.

I've got the right to left going fine. Not sure how to handle the flip and right to left part.

.sailBoatContainer {
    position: absolute;
    width: 250px;
    animation: move 20s linear infinite;
}

@keyframes move {
    from {
        left: 0;
    }
    to {
        left: 100%;
    }
}

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 98 103.18">
        <defs>

        </defs>
        <title>sailboat</title>
        <g id="rigging">
            <path id="roperight" class="sail1" d="M1.48,89s37-35.67,50-70.33" transform="translate(-0.48 0)"/>
            <path id="ropeleft" class="sail1" d="M51.48,20.33c16,37.34,46,62.67,46,62.67" transform="translate(-0.48 0)"/>
        </g>
        <g id="cabin">
            <path id="cabinbox" class="sail2" d="M51.48,82v8h27V87s-9-5-12-5ZM62,83.5h4v4H62Zm-6,1h3v3H56Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="sails">
            <path id="sailright" class="sail3" d="M86.48,72s-23-43-33-49c0-1,11,24-4,46C49.48,69,75.48,68,86.48,72Z" transform="translate(-0.48 0)"/>
            <path id="sailleft" class="sail3" d="M48.48,14s-49,35-34,66c0,1,35,0,35,0S44.48,38,48.48,14Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="flag">
            <path class="sail4" d="M52,1.5s-2,2-3,2-8-2-11,0c0,0,6,1,8,4h6Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="mast">
            <line id="mastline" class="sail5" x1="51" y1="88" x2="51" y2="1"/>
        </g>
        <g id="hull">
            <path id="hullbox" class="sail6" d="M90,101.5s-78,4-89-4v-9s79,2,97-6C97,83.5,99,90.5,90,101.5Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="hullbottom">
            <path id="hullbottombox" class="sail7" d="M91.87,99.88S21.5,104,.5,97v2s8.73,6.94,89.73,2.94Z" transform="translate(-0.48 0)"/>
        </g>
    </svg>

Here is a Codpen

I'd appreciate it if someone could point me in the right direction.

Body:
Not sure how to handle the flip and right to left part.

Start by moving from two to three "steps", 0%/50%/100% instead of from/to. Move all the way to the right at 50%, and back to 0 at 100%.

(left: calc(100% - 250px); helps to make it turn around when it reaches the right window edge, instead of going over by the ship's width and causing scrollbars ;-)

And then throw in some transform:scaleX to "mirror" it from 50% on as well.

But that will actually require inserting a fourth step - otherwise scaleX will slowly transform from -1 to 1, and he boat will end up "rotating" ... so to keep it at -1 up until we get to 50%, throw in a frame a 49.999%:

@keyframes move
{
    0% {
        left: 0;
      transform: scaleX(1);
    }
    49.999% {
      transform: scaleX(1);
    }
    50% {
      left: calc(100% - 250px);
      transform: scaleX(-1);
    }
    100% {
      left: 0%;
      transform: scaleX(-1);
    }
}

https://codepen.io/anon/pen/ZagbXN


问:
I need to convert this code to PowerShell
I wrote this Linux Shell script in Linux now i want to write it in PowerShell

```<code>manu="$1"

sort -t';' -nrk3 auto1.dat | grep "$manu" | head -n1 | cut -d';' -f2
</code>```

I did sort like this:

```<code>$car = Import-Csv -Header "Manufacturer" , "Model" , "Price" -delimiter ';' auto.dat
$car | % { $_.Price = [int]$_.Price }
$car | Sort-Object Price -Descending
</code>```

but i can find information about how to do grep and head or cut i tried few things and it didn't work. So basically what I want is

```<code>.\car.ps1 Tesla
</code>```

this code should give me expensive model of Tesla

and auto.dat file contains cars and models and prices:

```<code>Lamborghini;Aventador;700000
Lamborghini;Urus;200000
Tesla;ModelS;180000
Tesla;ModelX;140000
Ford;Mustang;300000
Ford;Focus;20000
Audi;A8;100000
Audi;R8;500000
</code>```

答:
You want to look at Get-Help about_Functions_Advanced_Parameters and Get-Help about_Functions_Advanced.  You can make a script work like a function by removing the function statement and outer braces from it.

So, you can take this function:

```<code>function car {
[CmdletBinding()]
Param (
    [Parameter(Mandatory=$true,Position=1)]
    [String]
    $Manufacturer
)

Import-Csv -Path auto.dat -Header "Manufacturer","Model","Price" -Delimiter ';' |
    Where-Object { $_.Manufacturer -match $Manufacturer } |
    Sort-Object -Property @{e={[int]$_.Price}} -Descending |
    Select-Object -First 1
}
</code>```

And save this as .\Car.ps1:

```<code>[CmdletBinding()]
Param (
    [Parameter(Mandatory=$true,Position=1)]
    [String]
    $Manufacturer
)

Import-Csv -Path auto.dat -Header "Manufacturer","Model","Price" -Delimiter ';' |
    Where-Object { $_.Manufacturer -match $Manufacturer } |
    Sort-Object -Property @{e={[int]$_.Price}} -Descending |
    Select-Object -First 1
</code>```

Call it:

```<code>.\Car.ps1 -Manu Audi
.\Car.ps1 -M Tesla
.\Car.ps1 Ford
</code>```

Body:
I wrote this Linux Shell script in Linux now i want to write it in PowerShell

manu="$1"

sort -t';' -nrk3 auto1.dat | grep "$manu" | head -n1 | cut -d';' -f2

I did sort like this:

$car = Import-Csv -Header "Manufacturer" , "Model" , "Price" -delimiter ';' auto.dat
$car | % { $_.Price = [int]$_.Price }
$car | Sort-Object Price -Descending

but i can find information about how to do grep and head or cut i tried few things and it didn't work. So basically what I want is

.\car.ps1 Tesla

this code should give me expensive model of Tesla

and auto.dat file contains cars and models and prices:

Lamborghini;Aventador;700000
Lamborghini;Urus;200000
Tesla;ModelS;180000
Tesla;ModelX;140000
Ford;Mustang;300000
Ford;Focus;20000
Audi;A8;100000
Audi;R8;500000

Body:
You want to look at Get-Help about_Functions_Advanced_Parameters and Get-Help about_Functions_Advanced.  You can make a script work like a function by removing the function statement and outer braces from it.

So, you can take this function:

function car {
[CmdletBinding()]
Param (
    [Parameter(Mandatory=$true,Position=1)]
    [String]
    $Manufacturer
)

Import-Csv -Path auto.dat -Header "Manufacturer","Model","Price" -Delimiter ';' |
    Where-Object { $_.Manufacturer -match $Manufacturer } |
    Sort-Object -Property @{e={[int]$_.Price}} -Descending |
    Select-Object -First 1
}

And save this as .\Car.ps1:

[CmdletBinding()]
Param (
    [Parameter(Mandatory=$true,Position=1)]
    [String]
    $Manufacturer
)

Import-Csv -Path auto.dat -Header "Manufacturer","Model","Price" -Delimiter ';' |
    Where-Object { $_.Manufacturer -match $Manufacturer } |
    Sort-Object -Property @{e={[int]$_.Price}} -Descending |
    Select-Object -First 1

Call it:

.\Car.ps1 -Manu Audi
.\Car.ps1 -M Tesla
.\Car.ps1 Ford


问:
Where did this invalid object name come from?
I have a simple SQL UPDATE query which is complaining about an "invalid object name" AuditCrudFields which doesn't exist in my ASP.NET project at all. (I have already tried grepping for AuditCrudFields in my project but couldn't find matches.)

The UPDATE statement is:

```<code>UPDATE [dbo].[PartModel]
SET partOfficial = 39, updateTS = CONVERT(DATETIME, ‘2017-12-08’, 111)
WHERE partId = 298
</code>```

the error returned:

What's puzzling is that these are all the properties that exist inside PartModel. So I wonder where did AuditCrudFields come from?

```<code>public class PartModel : EntityInformation
{
    [Key]
    public Int64 partId { get; set; }

    public int partTypeId { get; set; }
    [ForeignKey("partTypeId")]
    public virtual PartTypeModel PartType { get; set; }

    public int locationId { get; set; }
    [ForeignKey("locationId")]
    public virtual LocationModel Location { get; set; }

    public int partOfficial { get; set; }
    public int partUnofficial { get; set; }
    public int partThreshold { get; set; }

    public string partImg { get; set; }
    public int partStatus { get; set; }
}
</code>```

答:
You can run this query to locate the SQL object code which is trying to use the table AuditCrudFields:

```<code>select *
from sys.objects
where object_definition(object_id) like '%AuditCrudFields%'
</code>```

I'd be very surprised if this is not inside a trigger definition.

Body:
I have a simple SQL UPDATE query which is complaining about an "invalid object name" AuditCrudFields which doesn't exist in my ASP.NET project at all. (I have already tried grepping for AuditCrudFields in my project but couldn't find matches.)

The UPDATE statement is:

UPDATE [dbo].[PartModel]
SET partOfficial = 39, updateTS = CONVERT(DATETIME, ‘2017-12-08’, 111)
WHERE partId = 298

the error returned:

What's puzzling is that these are all the properties that exist inside PartModel. So I wonder where did AuditCrudFields come from?

public class PartModel : EntityInformation
{
    [Key]
    public Int64 partId { get; set; }

    public int partTypeId { get; set; }
    [ForeignKey("partTypeId")]
    public virtual PartTypeModel PartType { get; set; }

    public int locationId { get; set; }
    [ForeignKey("locationId")]
    public virtual LocationModel Location { get; set; }

    public int partOfficial { get; set; }
    public int partUnofficial { get; set; }
    public int partThreshold { get; set; }

    public string partImg { get; set; }
    public int partStatus { get; set; }
}

Body:
You can run this query to locate the SQL object code which is trying to use the table AuditCrudFields:

select *
from sys.objects
where object_definition(object_id) like '%AuditCrudFields%'

I'd be very surprised if this is not inside a trigger definition.


问:
html input datalist get selected value and pass into method
i have an html input data list where i need to pass the selected value into javascript / angular. It needs to be passed as the datalist is going into a html table so there will be many of them. All the examples i have seen grab it in the javascript instead of passing it into a method.

I tried on-select but it did nothing. I am also using angular 1

```<code><datalist id="dataList">
 <option ng-repeat="note in linknotes" value="{{note}}">{{note}}</option>
 </datalist>
<input maxlength="50" type="text" list="dataList">

 $scope.linknotes = [
    'Note 1',
    'Note 2',
    'Note 3',
    'Note 4',
    'Note 5',
    'Note 6'
].sort();
</code>```

答: Not sure exactly what you're asking here but I'm assuming you're referring to using ($index). You can pass the selected object from ng-repeat into a function using this. Here's a link with an example.</p>

Body:
i have an html input data list where i need to pass the selected value into javascript / angular. It needs to be passed as the datalist is going into a html table so there will be many of them. All the examples i have seen grab it in the javascript instead of passing it into a method.

I tried on-select but it did nothing. I am also using angular 1

<datalist id="dataList">
 <option ng-repeat="note in linknotes" value="{{note}}">{{note}}</option>
 </datalist>
<input maxlength="50" type="text" list="dataList">

 $scope.linknotes = [
    'Note 1',
    'Note 2',
    'Note 3',
    'Note 4',
    'Note 5',
    'Note 6'
].sort();


问:
How to create a date within a Formula in Excel
So what I'm trying to do is create a formula that reflects off of two dates (Start date and end date), if its shorter than 49 days, Find the exact middle date, if it's greater than that number add 30 days to the start date. So far I have the formula down it looks like:

```<code>=IF(C3-B3>49,IF(B3+30<=C3,"Report Date: "&B3+30,"Report Date: "&C3),"Report Date: "&((C3-B3)/2)+B3)
</code>```

The C Column is the End Date, the B Column is the Start date. What currently comes out for example if the Start date is, 4/2/2017 and the end date is, 2/3/2018, It comes out with, Report Date: 42857

When I want it to actually come out as, 5/2/2017 instead. So how exactly do I go about doing this within the formula itself to automatically set the date for me?

Thanks in advance!

Maykid

答:
Format your formula cell to be a date

TEXT(formula, "d/m/yyyy"), but depends what you want to do with it. Some calculations might not work.

DATE(YEAR(formula),MONTH(formula),DAY(formula)) In my experience this doesn't give you the result you want with all Excel versions or settings.

Body:
So what I'm trying to do is create a formula that reflects off of two dates (Start date and end date), if its shorter than 49 days, Find the exact middle date, if it's greater than that number add 30 days to the start date. So far I have the formula down it looks like:

=IF(C3-B3>49,IF(B3+30<=C3,"Report Date: "&B3+30,"Report Date: "&C3),"Report Date: "&((C3-B3)/2)+B3)

The C Column is the End Date, the B Column is the Start date. What currently comes out for example if the Start date is, 4/2/2017 and the end date is, 2/3/2018, It comes out with, Report Date: 42857

When I want it to actually come out as, 5/2/2017 instead. So how exactly do I go about doing this within the formula itself to automatically set the date for me?

Thanks in advance!

Maykid


问:
Why isn't SQL ANSI-92 standard better adopted over ANSI-89?
At every company I have worked at, I have found that people are still writing their SQL queries in the ANSI-89 standard:

```<code>select a.id, b.id, b.address_1
from person a, address b
where a.id = b.id
</code>```

rather than the ANSI-92 standard:

```<code>select a.id, b.id, b.address_1
from person a
inner join address b
on a.id = b.id
</code>```

For an extremely simple query like this, there's not a big difference in readability, but for large queries I find that having my join criteria grouped in with listing out the table makes it much easier to see where I might have issues in my join, and let's me keep all my filtering in my WHERE clause.  Not to mention that I feel that outer joins are much intuitive than the (+) syntax in Oracle.

As I try to evangelize ANSI-92 to people, are there any concrete performance benefits in using ANSI-92 over ANSI-89?  I would try it on my own, but the Oracle setups we have here don't allow us to use EXPLAIN PLAN - wouldn't want people to try to optimize their code, would ya?

答:
Here are a few points comparing SQL-89, and SQL-92 and clearing up some misconceptions in other answers.

NATURAL JOINS are a horrible idea. They're implicit and they require meta-information about the table. Nothing about SQL-92 requires their use so simply ignore them. They're not relevant to this discussion.

USING is a great idea, it has two effects:

It produces only one column on the result set from an equijoin.

It's enforces a sound and sane convention. In SQL-89 you had people writing the column id on both tables. After you join the tables, this becomes and ambiguous and it requires explicit aliasing. Further, the ids on the join almost certainly had different data. If you join person to company, you now have to alias one id to person_id, and one id to company_id, without which the join would produce two ambiguous columns. Using a globally-unique identifier for the table's surrogate key is the convention the standard rewards with USING.

The SQL-89 syntax is an implicit CROSS JOIN. A CROSS JOIN doesn't reduce the set, it implicitly grows it. FROM T1,T2 is the same as FROM T1 CROSS JOIN T2, that produces a Cartesian join which is usually not what you want. Having the selectivity to reduce that removed to a distant WHERE conditional means that you're more likely to make mistakes during design.

SQL-89 , and SQL-92 explicit JOINs have different precedence. JOIN has a higher precedence. Even worse, some databases like MySQL got this wrong for a very long time.. So mixing the two styles is a bad idea, and the far more popular style today is the SQL-92 style.

OwnerDisplayName: Patrick Harrington

ContentLicense: CC BY-SA 2.5

Body:
At every company I have worked at, I have found that people are still writing their SQL queries in the ANSI-89 standard:

select a.id, b.id, b.address_1
from person a, address b
where a.id = b.id

rather than the ANSI-92 standard:

select a.id, b.id, b.address_1
from person a
inner join address b
on a.id = b.id

For an extremely simple query like this, there's not a big difference in readability, but for large queries I find that having my join criteria grouped in with listing out the table makes it much easier to see where I might have issues in my join, and let's me keep all my filtering in my WHERE clause.  Not to mention that I feel that outer joins are much intuitive than the (+) syntax in Oracle.

As I try to evangelize ANSI-92 to people, are there any concrete performance benefits in using ANSI-92 over ANSI-89?  I would try it on my own, but the Oracle setups we have here don't allow us to use EXPLAIN PLAN - wouldn't want people to try to optimize their code, would ya?

LastEditorDisplayName: Click Ok


问:
How to set maximum execution time for a Promise await?
How would you wait for a Promise to resolve/reject, for a maximum execution time ? The code below is obviously wrong, it's just to explain what I'm trying to achieve. I'm clueless.

```<code>await doSomething();
if ( executionTime > maxExecutionTime ) {
    doSomethingElse();
}
</code>```

This is not for a bluebird promise.

答:
As noahnu suggested, you can use Promise.race. You can wrap it in a function that takes a promise.

With some syntax sugar you can use thisOrThat which takes logic, a function that takes 2 functions, first and second. You can apply logic here as to try the first function and when to try the second (in our case if the first doesn't resolve within a certain time then try the second).

thisOrThat then takes an argument first that is a function returning a promise (in our case doSomething.

thisOrThat returns an object that has an or property that takes a function returning a promise. That parameter is called second and is passed to logic as second (in our case it is doSomethingElse).

var timeoutPromise =
  time    =>
  promiseFn =>
    Promise.race([
      promiseFn(),
      new Promise(
        (_,r)=>
          setTimeout(
            _=>r("timed out")
            ,time
          )
        )
    ]);

var thisOrThat =
  logic     =>
  first  => ({
    or:second=>
      logic(first)(second)
  });
var within75ms = thisOrThat
  (first=>second=>
    timeoutPromise(75)(first)
    .catch(_=>second())
  );
var within25ms = thisOrThat
  (first=>second=>
    timeoutPromise(25)(first)
    .catch(_=>second())
  );

var doSomething = () =>
  console.log("do something called")||
  new Promise(r=>setTimeout(x=>r("something"),50));
var doSomethingElse = () =>
  console.log("do something else called") ||
  new Promise(r=>setTimeout(x=>r("something else"),50));

async function someFunc() {
  const doesNotTimeOut =
    await within75ms(doSomething).or(doSomethingElse);
  console.log("within 75ms resolved to:",doesNotTimeOut);

  const doesTimeOut =
    await within25ms(doSomething).or(doSomethingElse)
  console.log("within 25ms resolved to:",doesTimeOut);
};
someFunc();```

Body:
How would you wait for a Promise to resolve/reject, for a maximum execution time ? The code below is obviously wrong, it's just to explain what I'm trying to achieve. I'm clueless.

await doSomething();
if ( executionTime > maxExecutionTime ) {
    doSomethingElse();
}

This is not for a bluebird promise.


问:
PUT/DELETE got 403 Error but GET/POST works
There's a Spring Boot application running on the back-end. I have implemented a couple of GET/POST/PUT/DELETE APIs.

The front-end(AngularJS) can do GET and POST, but it would get 403 ERROR when request PUT and DELETE.
I have added the allowed origins(POST wouldn't work without it) to solve CORS issue.

CORS Settings:

```<code>@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("https://xxx1.com", "https://xxx2.com");
        }
    };
}
</code>```

CSRF Settings:

```<code>  http.csrf().disable();
</code>```

It is disabled for now

Below is my implementation of DELETE:

```<code>   @DeleteMapping("/listings/{id}")
    public ResponseEntity<Void> deleteListings(@PathVariable Long id) {
        log.debug("REST request to delete listings : {}", id);
        this.listingsService.delete(id);
        return ResponseEntity.status(HttpStatus.OK).body(null);
    }
</code>```

Can anyone help? Really appreciated!

答:
Looks like you can chain on an allowedMethods("GET","POST","PUT","DELETE") according to the docs.

Does that helps?

Body:
There's a Spring Boot application running on the back-end. I have implemented a couple of GET/POST/PUT/DELETE APIs.

The front-end(AngularJS) can do GET and POST, but it would get 403 ERROR when request PUT and DELETE.
I have added the allowed origins(POST wouldn't work without it) to solve CORS issue.

CORS Settings:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("https://xxx1.com", "https://xxx2.com");
        }
    };
}

CSRF Settings:

  http.csrf().disable();

It is disabled for now

Below is my implementation of DELETE:

   @DeleteMapping("/listings/{id}")
    public ResponseEntity<Void> deleteListings(@PathVariable Long id) {
        log.debug("REST request to delete listings : {}", id);
        this.listingsService.delete(id);
        return ResponseEntity.status(HttpStatus.OK).body(null);
    }

Can anyone help? Really appreciated!


答:
The major difference you need to be aware of between PowerShell and bash (Unix in general) when it comes to piping, is that in PowerShell you are generally dealing with real objects, not text streams.

So the beauty of what you have done so far, is that you don't need the head and cut commands at all.

The head command, which was (presumably?) skipping your header row, is already taken care of by specifying the headers to Import-Csv.

The result of Import-Csv is an array of objects (one for each row), and each column in the CSV is a single property of the row object, with the same name as the header.

If you want the name of the model in the first row, you use this:

```<code>$car[0].Model
</code>```

Your last line sorts all the rows by price, but then it just sends that information out the pipeline.

So instead it seems what you want, is to use the parameter passed into the script (the manufacturer), to then find the most expensive model that manufacturer has.

There are lots of ways to do this, lots of ways to structure this, but I'll show you a very PowerShell way using the capabilities of the pipeline and the full objects.

Replacing your third line, I'd do something like this:

```<code>$car |
    Where-Object { $_.Manufacturer -eq $args[0] } |
    Sort-Object Price -Descending |
    Select-Object -ExpandProperty Model -First 1
</code>```

Note you can line break after a pipe, easier to read.

Here I'm going through the rows, filtering out the ones where the manufacturer matches, then sorting by price (descending), then taking the first 1 and keeping only the Model property.

I do recommend taking a proper named parameter, (as shown in Bacon Bits's answer) instead of using $args.

Title: I need to convert this code to PowerShell

Body:
The major difference you need to be aware of between PowerShell and bash (Unix in general) when it comes to piping, is that in PowerShell you are generally dealing with real objects, not text streams.

So the beauty of what you have done so far, is that you don't need the head and cut commands at all.

The head command, which was (presumably?) skipping your header row, is already taken care of by specifying the headers to Import-Csv.

The result of Import-Csv is an array of objects (one for each row), and each column in the CSV is a single property of the row object, with the same name as the header.

If you want the name of the model in the first row, you use this:

$car[0].Model

Your last line sorts all the rows by price, but then it just sends that information out the pipeline.

So instead it seems what you want, is to use the parameter passed into the script (the manufacturer), to then find the most expensive model that manufacturer has.

There are lots of ways to do this, lots of ways to structure this, but I'll show you a very PowerShell way using the capabilities of the pipeline and the full objects.

Replacing your third line, I'd do something like this:

$car |
    Where-Object { $_.Manufacturer -eq $args[0] } |
    Sort-Object Price -Descending |
    Select-Object -ExpandProperty Model -First 1

Note you can line break after a pipe, easier to read.

Here I'm going through the rows, filtering out the ones where the manufacturer matches, then sorting by price (descending), then taking the first 1 and keeping only the Model property.

I do recommend taking a proper named parameter, (as shown in Bacon Bits's answer) instead of using $args.


问:
Can't play a reversed .wav file with MediaPlayer
I've created an app that records audio, saves the sample to the sd card then plays it back, using the record and play buttons. I need to reverse this sample. I can do all this and the the reversed sample is saved on the SD card under a different name. The original sample is test.wav and the same sample reversed is save as revFile.wav. when i try play revFile.wav android says it can't play this format.

I've litterally put the sample in an array then reversed the contents, something is telling me that there could be header info at the start of the sample that needs striping first, any ideas. thanks.

Here's what i have so far.

```<code>public class recorder extends Activity  {
    MediaRecorder myRecorder = null;
    DataInputStream dis = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void onClickPlay(View v){
        Log.v("onClickplay", "play clicked");

        try{
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/test.wav");
            mp.prepare();
            mp.start();
        } catch(Exception e3) {
            e3.printStackTrace();
        }
        TextView text = (TextView)findViewById(R.id.TextView01);
        text.setText("playing");
    }

    public void onClickRecord(View v){
        Log.v("onClickRecord", "record clicked");

        File path = Environment.getExternalStorageDirectory();
        Log.v("file path", ""+path.getAbsolutePath());

        File file = new File(path, "test.wav");
        if(file.exists()){
            file.delete();
        }
        path.mkdirs();
        Log.v("file path", ""+file.getAbsolutePath());
        myRecorder = new MediaRecorder();
        myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        myRecorder.setOutputFile(file.getAbsolutePath());
        Log.i("myrecorder", "about to prepare recording");
        try{
            myRecorder.prepare();
        } catch(Exception e) {
            e.printStackTrace();
        }

        Log.i("myrecorder", "prepared");
        myRecorder.start();   // Recording is now started
        Log.i("myrecorder", "recording");
        TextView text = (TextView)findViewById(R.id.TextView01);
        text.setText("recording");
    }

    public void onClickStop(View v){
        Log.v("onClickStop", "stop clicked");

            try{
             myRecorder.stop();
             myRecorder.reset();   // You can reuse the object by going back to setAudioSource() step
             myRecorder.release(); // Now the object cannot be reused
            }catch(Exception e){}

            TextView text = (TextView)findViewById(R.id.TextView01);
             text.setText("recording stopped");

        }

public void onClickReverse(View v){
        Log.v("onClickReverse", "reverse clicked");

        File f = Environment.getExternalStorageDirectory();
        String path = f.getAbsolutePath();
        path = path + "/test.wav";
        Log.v("path = ", ""+path);
        Log.v("dir = ", ""+f.getAbsolutePath());
        Log.v("test file exists? = ", ""+f.getAbsolutePath()+"/test.wav");

        File f2 = new File(path);
        Log.v("f2 = ", ""+f2.getAbsolutePath());

        try {
            InputStream is = new FileInputStream(f2);
            BufferedInputStream bis = new BufferedInputStream(is);
            dis = new DataInputStream(bis);
        } catch (Exception e) {
            e.printStackTrace();
        }

        int fileLength = (int)f2.length();
        byte[] buffer = new byte[fileLength];

        /*File reversedFile = Environment.getExternalStorageDirectory();
          File revFile = new File(reversedFile, "reversedFile.wav");
          Log.v("reversedfile path", ""+ revFile.getAbsolutePath());

          if(revFile.exists()){
              revFile.delete();
          }

          reversedFile.mkdirs();
    */

        byte[] byteArray = new byte[fileLength +1];
        Log.v("bytearray size = ", ""+byteArray.length);

        try {
            while(dis.read(buffer) != -1 ) {
                dis.read(buffer);
                Log.v("about to read buffer", "buffer");

                byteArray = buffer;
            }

            Log.v(" buffer size = ", ""+ buffer.length);
        } catch (IOException e) {
            e.printStackTrace();
        }

          byte[] tempArray = new byte[fileLength];

          int j=0;
          for (int i=byteArray.length-1; i >=0; i--) {
              tempArray[ j++ ] = byteArray[i];
          }

          File revPath = Environment.getExternalStorageDirectory();
          Log.v("revpath path", ""+revPath.getAbsolutePath());

          File revFile = new File(revPath, "revFile.wav");
          Log.v("revfile path ", ""+revFile.getAbsolutePath());
          if(revFile.exists()){
              revFile.delete();
          }

          revPath.mkdirs();

          try {
              OutputStream os = new FileOutputStream(revFile);
              BufferedOutputStream bos = new BufferedOutputStream(os);
              DataOutputStream dos = new DataOutputStream(bos);
              Log.v("temparray size = ", ""+ tempArray.length);
              dos.write(tempArray);
              dos.flush();
              dos.close();
          } catch (Exception e) {
              e.printStackTrace();
          }

          try{
              MediaPlayer mp = new MediaPlayer();
              mp.setDataSource(Environment.getExternalStorageDirectory().getPath()
                                                                    +"/revFile.wav");

              mp.prepare();
              mp.start();
         } catch(Exception e3) {
                e3.printStackTrace();
         }
          TextView text = (TextView)findViewById(R.id.TextView01);
           text.setText("playing reversed file");
      }

}// end of onclickrev
</code>```

答:
There is a good description of the .WAV header at link text

Also note that all data in the file is stored as Little Endian order (low order byte of 1 multi byte number is stored at the lowest address....) so you can't just reverse the bytes. you need to see how many bytes wide each sample is, (usually 16, but check the header) and reverse them in chunks of that size

Body:
I've created an app that records audio, saves the sample to the sd card then plays it back, using the record and play buttons. I need to reverse this sample. I can do all this and the the reversed sample is saved on the SD card under a different name. The original sample is test.wav and the same sample reversed is save as revFile.wav. when i try play revFile.wav android says it can't play this format.

I've litterally put the sample in an array then reversed the contents, something is telling me that there could be header info at the start of the sample that needs striping first, any ideas. thanks.

Here's what i have so far.

public class recorder extends Activity  {
    MediaRecorder myRecorder = null;
    DataInputStream dis = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void onClickPlay(View v){
        Log.v("onClickplay", "play clicked");

        try{
            MediaPlayer mp = new MediaPlayer();
            mp.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/test.wav");
            mp.prepare();
            mp.start();
        } catch(Exception e3) {
            e3.printStackTrace();
        }
        TextView text = (TextView)findViewById(R.id.TextView01);
        text.setText("playing");
    }

    public void onClickRecord(View v){
        Log.v("onClickRecord", "record clicked");

        File path = Environment.getExternalStorageDirectory();
        Log.v("file path", ""+path.getAbsolutePath());

        File file = new File(path, "test.wav");
        if(file.exists()){
            file.delete();
        }
        path.mkdirs();
        Log.v("file path", ""+file.getAbsolutePath());
        myRecorder = new MediaRecorder();
        myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

        myRecorder.setOutputFile(file.getAbsolutePath());
        Log.i("myrecorder", "about to prepare recording");
        try{
            myRecorder.prepare();
        } catch(Exception e) {
            e.printStackTrace();
        }

        Log.i("myrecorder", "prepared");
        myRecorder.start();   // Recording is now started
        Log.i("myrecorder", "recording");
        TextView text = (TextView)findViewById(R.id.TextView01);
        text.setText("recording");
    }

    public void onClickStop(View v){
        Log.v("onClickStop", "stop clicked");

            try{
             myRecorder.stop();
             myRecorder.reset();   // You can reuse the object by going back to setAudioSource() step
             myRecorder.release(); // Now the object cannot be reused
            }catch(Exception e){}

            TextView text = (TextView)findViewById(R.id.TextView01);
             text.setText("recording stopped");

        }

public void onClickReverse(View v){
        Log.v("onClickReverse", "reverse clicked");

        File f = Environment.getExternalStorageDirectory();
        String path = f.getAbsolutePath();
        path = path + "/test.wav";
        Log.v("path = ", ""+path);
        Log.v("dir = ", ""+f.getAbsolutePath());
        Log.v("test file exists? = ", ""+f.getAbsolutePath()+"/test.wav");

        File f2 = new File(path);
        Log.v("f2 = ", ""+f2.getAbsolutePath());

        try {
            InputStream is = new FileInputStream(f2);
            BufferedInputStream bis = new BufferedInputStream(is);
            dis = new DataInputStream(bis);
        } catch (Exception e) {
            e.printStackTrace();
        }

        int fileLength = (int)f2.length();
        byte[] buffer = new byte[fileLength];

        /*File reversedFile = Environment.getExternalStorageDirectory();
          File revFile = new File(reversedFile, "reversedFile.wav");
          Log.v("reversedfile path", ""+ revFile.getAbsolutePath());

          if(revFile.exists()){
              revFile.delete();
          }

          reversedFile.mkdirs();
    */

        byte[] byteArray = new byte[fileLength +1];
        Log.v("bytearray size = ", ""+byteArray.length);

        try {
            while(dis.read(buffer) != -1 ) {
                dis.read(buffer);
                Log.v("about to read buffer", "buffer");

                byteArray = buffer;
            }

            Log.v(" buffer size = ", ""+ buffer.length);
        } catch (IOException e) {
            e.printStackTrace();
        }

          byte[] tempArray = new byte[fileLength];

          int j=0;
          for (int i=byteArray.length-1; i >=0; i--) {
              tempArray[ j++ ] = byteArray[i];
          }

          File revPath = Environment.getExternalStorageDirectory();
          Log.v("revpath path", ""+revPath.getAbsolutePath());

          File revFile = new File(revPath, "revFile.wav");
          Log.v("revfile path ", ""+revFile.getAbsolutePath());
          if(revFile.exists()){
              revFile.delete();
          }

          revPath.mkdirs();

          try {
              OutputStream os = new FileOutputStream(revFile);
              BufferedOutputStream bos = new BufferedOutputStream(os);
              DataOutputStream dos = new DataOutputStream(bos);
              Log.v("temparray size = ", ""+ tempArray.length);
              dos.write(tempArray);
              dos.flush();
              dos.close();
          } catch (Exception e) {
              e.printStackTrace();
          }

          try{
              MediaPlayer mp = new MediaPlayer();
              mp.setDataSource(Environment.getExternalStorageDirectory().getPath()
                                                                    +"/revFile.wav");

              mp.prepare();
              mp.start();
         } catch(Exception e3) {
                e3.printStackTrace();
         }
          TextView text = (TextView)findViewById(R.id.TextView01);
           text.setText("playing reversed file");
      }

}// end of onclickrev


问:
Datatables adding rows
I'm trying to dynamically ad rows to a blank datatable. However, it instead of the text displaying on the screen it's coming back as [object Object] in each column. I've tried multiple things, but can't figure out what's wrong with it.

my html is just a basic table

and my js looks like this

```<code>var commentTable = $('.commentTable').DataTable({
            columns: [
                {
                    class: "commentDate",
                    data: null
                    },
                {
                    class: "commentUser",
                    data:  null
                    },
                {
                    class: "commentComment",
                    data:  null
                    }
                ],
            bSort: false
        });

$('.addComment').on('click', function () {

    var newCom = $('.newCommentArea').find('input').val();
    var dateInput = moment().format("dd MM, YYYY");
    var rowNode = commentTable
        .row.add({
            "date": dateInput,
            "name": 'name',
            "comment": newCom
        })
        .draw(false)
        .node();

    commentTable.page('last').draw(false);

$(rowNode)
    .css('background-color', 'lightyellow')
    .animate({
        color: 'black'
    });
$('.newCommentArea').find('input').val('');
 });
</code>```

答:
Check out if this works for you:</p>

```<code>var commentTable = $('.commentTable').DataTable({
    aoColumns: [
        {"mData": "date", "className": "commentDate"},
        {"mData": "name", "className": "commentUser"},
        {"mData": "comment", "className": "commentComment"},
    ],
    bSort: false
});

$('.addComment').on('click', function () {

    var newCom = $('.newCommentArea').find('input').val();
    var dateInput = moment().format("dd MM, YYYY");

    var dataSet = {
        "date": dateInput,
        "name": 'name',
        "comment": newCom
    }

   commentTable.rows.add(dataSet).draw();

    ...

});
</code>```

Title: Datatables adding rows

Body:
I'm trying to dynamically ad rows to a blank datatable. However, it instead of the text displaying on the screen it's coming back as [object Object] in each column. I've tried multiple things, but can't figure out what's wrong with it.

my html is just a basic table

and my js looks like this

var commentTable = $('.commentTable').DataTable({
            columns: [
                {
                    class: "commentDate",
                    data: null
                    },
                {
                    class: "commentUser",
                    data:  null
                    },
                {
                    class: "commentComment",
                    data:  null
                    }
                ],
            bSort: false
        });

$('.addComment').on('click', function () {

    var newCom = $('.newCommentArea').find('input').val();
    var dateInput = moment().format("dd MM, YYYY");
    var rowNode = commentTable
        .row.add({
            "date": dateInput,
            "name": 'name',
            "comment": newCom
        })
        .draw(false)
        .node();

    commentTable.page('last').draw(false);

$(rowNode)
    .css('background-color', 'lightyellow')
    .animate({
        color: 'black'
    });
$('.newCommentArea').find('input').val('');
 });

Body:
Check out if this works for you:

var commentTable = $('.commentTable').DataTable({
    aoColumns: [
        {"mData": "date", "className": "commentDate"},
        {"mData": "name", "className": "commentUser"},
        {"mData": "comment", "className": "commentComment"},
    ],
    bSort: false
});

$('.addComment').on('click', function () {

    var newCom = $('.newCommentArea').find('input').val();
    var dateInput = moment().format("dd MM, YYYY");

    var dataSet = {
        "date": dateInput,
        "name": 'name',
        "comment": newCom
    }

   commentTable.rows.add(dataSet).draw();

    ...

});


问:
Except replacement in mysql?
I have to write some code in mysql but mostly I write in MS SQL and here is problem, in MS SQL I can use EXCEPT and everything is fine for me. But in MySQL there is not that simple, I tried with NOT IN and NOT EXISTS but it didn't give me same output. My MS SQL code is:

```<code>SELECT P.IDRoom, R.IDRoom, R.DateB, R.DataE
FROM Room P LEFT JOIN Reservation R ON P.IDRoom = R.IDRoom
JOIN Hotel H ON P.IDHotelu = H.IDHotelu
WHERE P.NumberOfBeds = 2 AND H.IDHotelu = 2
EXCEPT
SELECT P.IDRoom, R.IDRoom, R.DateB, R.DataE
FROM Room P JOIN Reservation R ON P.IDRoom = R.IDRoom
WHERE '2017-12-10' BETWEEN DataB AND DataE;
</code>```

Like u can see I look for hotel who have 2 beds and hotel id is 2. but I don't want to see rooms who are already booked so I use except and look for booked rooms... but it's easy in MS SQL, in MySQL nothing work for me -_-. Any ideas?

答:
I usually create a sub-query and join the outer table on to it with a LEFT JOIN. This then lets you put a WHERE column IS NULL.</p>

```<code>SELECT
    P.IDRoom
   ,R.IDRoom
   ,R.DateB
   ,R.DataE
FROM
    Room P
    LEFT JOIN Reservation R ON P.IDRoom = R.IDRoom
    INNER JOIN Hotel H ON P.IDHotelu = H.IDHotelu
LEFT JOIN (
    SELECT
        P.IDRoom AS IDRoom1
        ,R.IDRoom AS IDRoom2
        ,R.DateB
        ,R.DataE
    FROM
        Room P
        JOIN Reservation R ON P.IDRoom = R.IDRoom
    WHERE
        '2017-12-10' BETWEEN DataB AND DataE
) AS e ON  P.IDRoom = e.IDRoom1 AND R.IDRoom = e.IDRoom2 AND R.DateB = e.DateB AND R.DataE = R.DataE
WHERE
    P.NumberOfBeds = 2 AND H.IDHotelu = 2
    AND e.IDRoom1 IS NULL
</code>```

Title: Except replacement in mysql?

Body:
I have to write some code in mysql but mostly I write in MS SQL and here is problem, in MS SQL I can use EXCEPT and everything is fine for me. But in MySQL there is not that simple, I tried with NOT IN and NOT EXISTS but it didn't give me same output. My MS SQL code is:

SELECT P.IDRoom, R.IDRoom, R.DateB, R.DataE
FROM Room P LEFT JOIN Reservation R ON P.IDRoom = R.IDRoom
JOIN Hotel H ON P.IDHotelu = H.IDHotelu
WHERE P.NumberOfBeds = 2 AND H.IDHotelu = 2
EXCEPT
SELECT P.IDRoom, R.IDRoom, R.DateB, R.DataE
FROM Room P JOIN Reservation R ON P.IDRoom = R.IDRoom
WHERE '2017-12-10' BETWEEN DataB AND DataE;

Like u can see I look for hotel who have 2 beds and hotel id is 2. but I don't want to see rooms who are already booked so I use except and look for booked rooms... but it's easy in MS SQL, in MySQL nothing work for me -_-. Any ideas?

Body:
I usually create a sub-query and join the outer table on to it with a LEFT JOIN. This then lets you put a WHERE column IS NULL.

SELECT
    P.IDRoom
   ,R.IDRoom
   ,R.DateB
   ,R.DataE
FROM
    Room P
    LEFT JOIN Reservation R ON P.IDRoom = R.IDRoom
    INNER JOIN Hotel H ON P.IDHotelu = H.IDHotelu
LEFT JOIN (
    SELECT
        P.IDRoom AS IDRoom1
        ,R.IDRoom AS IDRoom2
        ,R.DateB
        ,R.DataE
    FROM
        Room P
        JOIN Reservation R ON P.IDRoom = R.IDRoom
    WHERE
        '2017-12-10' BETWEEN DataB AND DataE
) AS e ON  P.IDRoom = e.IDRoom1 AND R.IDRoom = e.IDRoom2 AND R.DateB = e.DateB AND R.DataE = R.DataE
WHERE
    P.NumberOfBeds = 2 AND H.IDHotelu = 2
    AND e.IDRoom1 IS NULL


问:
Can't open url with requests and urllib2
I try to access https://www.collinsdictionary.com/browse/english/words-starting-with-a with python requests, but get requests.exceptions.ConnectionError: ('Connection aborted.', BadStatusLine("''",)).

I tried with urllib2.urlopen, but I got different html from what I see in browser (there is no
).

What am I doing wrong?

答:
With the following code I do get the page you seem to want:

```<code>import urllib2
page =urllib2.urlopen("https://www.collinsdictionary.com/browse/english/words-starting-with-a")
print page.read()
</code>```

it does contain

Body:
With the following code I do get the page you seem to want:

import urllib2
page =urllib2.urlopen("https://www.collinsdictionary.com/browse/english/words-starting-with-a")
print page.read()

it does contain <ul class="columns2 browse-list">


问:
what is the point of 'timeline' in array or param for get_news_feed?
I went through all tutorials and docs which stream-django provided.

And there was one thing that I could't understand.

I can't find the differences between these feed_manager methods.

```<code># (1)
feed = feed_manager.get_news_feed('timeline', request.id)
# (2)
feed = feed_manager.get_news_feed(request.id)['timeline']
# (3)
feed = feed_manager.get_news_feed(request.id)
</code>```

Could you explain the difference? Are they doing exactly same thing? timeline means flat feed, then why do we put timeline in param?

Thank you

答:
timeline is the name of the feed group that you've created within Stream.

Once you create a feed group in Stream, you'll select the type of feed group ("flat" in this case, but can also be "aggregated" or "notification"), then, you'll name the feed group - common names are timeline/news_feed (a homepage feed showing activity from other users) or profile/user (a profile page feed showing all activities from a single user). There are no "reserved" words in feed group names.

Re: whether or not these methods are all doing the same thing:

feed_manager.get_news_feed('timeline', request.id) (1) is definitely correct. It'll fetch the feed activities for the specific timeline:1234 feed, where 1234 is most likely your user's ID.

(2) and (3) I'm not sure about - it's likely that they're doing the same thing as (1), but I'm not able to tell at the first glance at the docs.

Hopefully that helps!

Body:
I went through all tutorials and docs which stream-django provided.

And there was one thing that I could't understand.

I can't find the differences between these feed_manager methods.

# (1)
feed = feed_manager.get_news_feed('timeline', request.id)
# (2)
feed = feed_manager.get_news_feed(request.id)['timeline']
# (3)
feed = feed_manager.get_news_feed(request.id)

Could you explain the difference? Are they doing exactly same thing? timeline means flat feed, then why do we put timeline in param?

Thank you


问:
JS Add events to a List where rows are added dynamically

Hi,
I am inserting rows in a list dynamically. Right now that is happening on a click of button but eventually that data will come from a DB. That works fine!

What I want to do is that once the list is presented to a user, s/he will take the mouse over the desired list item. At that time the item should be highlighted.
So I want to add mouseover and mouseout event to each row.
But the event is triggered on the function declaration itself.
Please find the JSfiddle link here:
https://jsfiddle.net/indiaaditya/ycyb9dot/

The problem section is here::

```<code>function AddEventsToTableForEachRow(tableId) {
  //Get the NodeList
  alert("Function Called!");
  var nodelist = document.querySelectorAll(".classTableElement");
  var lclCntr = 0;
  alert("Elements found:" + nodelist.length);
  //Set ID's for all the elements
  var strInloop = "";
  //This loop sets the ID for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    nodelist[lclCntr].setAttribute("id", strInloop);
  }
  //This loop adds event for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    var rowElement = document.getElementById(strInloop);
    rowElement.addEventListener("onmouseover", alert("A"), false);
  }
}
</code>```

Explanation of JSFiddle code:

1. Click on Generate List button to add rows.

2. Click on GlowRecord Button to highlight the first row. Click it again to remove the highlight. This is the desired function on mouseover and mouseout.

3. Click on AddEvents to generate the events. This is the part of code that is not working

 AddEvents calls

    AddEventsToTableForEachRow('tblTestList')

function.
But this function immediately calls the alert function calls in it.

Expected result is that after calling AddEventsToTableForEachRow, the events should be attached to each row and when the mouse mover to the row, alert message should be shown.

In effect, as mentioned before the alert functions inside AddEventsToTableForEachRow are called immediately and no action on mouseover.

For those who question why I have not used jquery:
a. I am a complete novice to JS/HTML/CSS. I am from C/C++ background and have come to this side because of the ease of building the UI with HTML/CSS/JS.
b. I am learning on the fly and found DOM to be much cleaner and easier to understand.
But after spending 3 days on this issue I am ready for anything and everything. (But will be happier if I get DOM based solution!)

Thanks in advance.

Kind Regards,
Aditya

答:
Instead of adding the event listener to every row, just add it once to the table. Then, in your event handler you can use event.target to make sure the event happened on the correct element.

function mouseOverHandler(event) {
  var tr = event.target;
  while(tr) {
    if (tr.localName === 'tr') {
      break;
    }

    tr = tr.parentNode;
  }

  // tr will be null if the `<table>` was the event recipient
  if (tr) {
    console.log(tr.localName, tr.textContent);
  }
}

function AddEventsToTable(tableId) {
  var table = document.getElementById(tableId);
  if (table) {
    table.addEventListener("mouseover", mouseOverHandler, false);
  }
}

AddEventsToTable('mytable');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="mytable">
  <tr>
    <td>row 1, col 1</td>
    <td>row 1, col 2</td>
    <td>row 1, col 3</td>
    <td>row 1, col 4</td>
  </tr>
  <tr>
    <td>row 2, col 1</td>
    <td>row 2, col 2</td>
    <td>row 2, col 3</td>
    <td>row 2, col 4</td>
  </tr>
  <tr>
    <td>row 3, col 1</td>
    <td>row 3, col 2</td>
    <td>row 3, col 3</td>
    <td>row 3, col 4</td>
  </tr>
</table></code>```

This does cause the event to trigger when your mouse moves over ANY of the tables children, but I use the while loop to convert the event target to the appropriate
.

Body:
Hi,
I am inserting rows in a list dynamically. Right now that is happening on a click of button but eventually that data will come from a DB. That works fine!

What I want to do is that once the list is presented to a user, s/he will take the mouse over the desired list item. At that time the item should be highlighted.
So I want to add mouseover and mouseout event to each row.
But the event is triggered on the function declaration itself.
Please find the JSfiddle link here:
https://jsfiddle.net/indiaaditya/ycyb9dot/

The problem section is here::

function AddEventsToTableForEachRow(tableId) {
  //Get the NodeList
  alert("Function Called!");
  var nodelist = document.querySelectorAll(".classTableElement");
  var lclCntr = 0;
  alert("Elements found:" + nodelist.length);
  //Set ID's for all the elements
  var strInloop = "";
  //This loop sets the ID for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    nodelist[lclCntr].setAttribute("id", strInloop);
  }
  //This loop adds event for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    var rowElement = document.getElementById(strInloop);
    rowElement.addEventListener("onmouseover", alert("A"), false);
  }
}

Explanation of JSFiddle code:

1. Click on Generate List button to add rows.

2. Click on GlowRecord Button to highlight the first row. Click it again to remove the highlight. This is the desired function on mouseover and mouseout.

3. Click on AddEvents to generate the events. This is the part of code that is not working

 AddEvents calls

    AddEventsToTableForEachRow('tblTestList')

function.
But this function immediately calls the alert function calls in it.

Expected result is that after calling AddEventsToTableForEachRow, the events should be attached to each row and when the mouse mover to the row, alert message should be shown.

In effect, as mentioned before the alert functions inside AddEventsToTableForEachRow are called immediately and no action on mouseover.

For those who question why I have not used jquery:
a. I am a complete novice to JS/HTML/CSS. I am from C/C++ background and have come to this side because of the ease of building the UI with HTML/CSS/JS.
b. I am learning on the fly and found DOM to be much cleaner and easier to understand.
But after spending 3 days on this issue I am ready for anything and everything. (But will be happier if I get DOM based solution!)

Thanks in advance.

Kind Regards,
Aditya

Body:
Instead of adding the event listener to every row, just add it once to the table. Then, in your event handler you can use event.target to make sure the event happened on the correct element.

function mouseOverHandler(event) {
  var tr = event.target;
  while(tr) {
    if (tr.localName === 'tr') {
      break;
    }

    tr = tr.parentNode;
  }

  // tr will be null if the `<table>` was the event recipient
  if (tr) {
    console.log(tr.localName, tr.textContent);
  }
}

function AddEventsToTable(tableId) {
  var table = document.getElementById(tableId);
  if (table) {
    table.addEventListener("mouseover", mouseOverHandler, false);
  }
}

AddEventsToTable('mytable');

<table id="mytable">
  <tr>
    <td>row 1, col 1</td>
    <td>row 1, col 2</td>
    <td>row 1, col 3</td>
    <td>row 1, col 4</td>
  </tr>
  <tr>
    <td>row 2, col 1</td>
    <td>row 2, col 2</td>
    <td>row 2, col 3</td>
    <td>row 2, col 4</td>
  </tr>
  <tr>
    <td>row 3, col 1</td>
    <td>row 3, col 2</td>
    <td>row 3, col 3</td>
    <td>row 3, col 4</td>
  </tr>
</table>

This does cause the event to trigger when your mouse moves over ANY of the tables children, but I use the while loop to convert the event target to the appropriate <tr>.


问:
<column> is ambiguous in column comparison between two tables
I want this postgres function to work :

```<code>CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  returns table(match_id BIGINT)
as
$$
BEGIN
  return QUERY
  SELECT *
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';
</code>```

This stand alone query works just fine:

```<code>SELECT *
FROM sports.match_history
WHERE match_id NOT IN (SELECT match_id FROM sports.match_results);
</code>```

But when I put it into this function and try to run it like this:

```<code>select *
from difference_of_match_ids_in_match_history_and_match_results();
</code>```

I get this:

SQL Error [42702]: ERROR: column reference "match_id" is ambiguous

  Detail: It could refer to either a PL/pgSQL variable or a table
  column.   Where: PL/pgSQL function
  difference_of_match_ids_in_match_history_and_match_results() line 3 at
  RETURN QUERY

I've seen other questions with this same error, and they suggest naming the sub queries to specify which instance of a column you're referring to, however, those examples use joins and my query works fine outside of the function.

If I do need to name the column, how would I do so with only one sub-query?

If that isn't the issue, then I'm assuming that there's something wrong with the way I'm defining a function.

答:
You query is fine. The ambiguity is on the match_id in returns table(match_id BIGINT) rename it or prefix the columns with the table name in your query

```<code>CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  returns table(new_name BIGINT)
as
$$
BEGIN
  return QUERY
  SELECT *
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';
</code>```

or

```<code>CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  returns table(match_id BIGINT)
as
$$
BEGIN
  return QUERY
  SELECT sports.match_history.match_id
  FROM sports.match_history
  WHERE sports.match_history.match_id NOT IN (SELECT sports.match_results.match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';
</code>```

Didn't test the code.

Body:
I want this postgres function to work :

CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  returns table(match_id BIGINT)
as
$$
BEGIN
  return QUERY
  SELECT *
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';

This stand alone query works just fine:

SELECT *
FROM sports.match_history
WHERE match_id NOT IN (SELECT match_id FROM sports.match_results);

But when I put it into this function and try to run it like this:

select *
from difference_of_match_ids_in_match_history_and_match_results();

I get this:

SQL Error [42702]: ERROR: column reference "match_id" is ambiguous

  Detail: It could refer to either a PL/pgSQL variable or a table
  column.   Where: PL/pgSQL function
  difference_of_match_ids_in_match_history_and_match_results() line 3 at
  RETURN QUERY

I've seen other questions with this same error, and they suggest naming the sub queries to specify which instance of a column you're referring to, however, those examples use joins and my query works fine outside of the function.

If I do need to name the column, how would I do so with only one sub-query?

If that isn't the issue, then I'm assuming that there's something wrong with the way I'm defining a function.

Body:
You query is fine. The ambiguity is on the match_id in returns table(match_id BIGINT) rename it or prefix the columns with the table name in your query

CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  returns table(new_name BIGINT)
as
$$
BEGIN
  return QUERY
  SELECT *
  FROM sports.match_history
  WHERE match_id NOT IN (SELECT match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';

or

CREATE OR REPLACE FUNCTION difference_of_match_ids_in_match_history_and_match_results()
  returns table(match_id BIGINT)
as
$$
BEGIN
  return QUERY
  SELECT sports.match_history.match_id
  FROM sports.match_history
  WHERE sports.match_history.match_id NOT IN (SELECT sports.match_results.match_id
                         FROM sports.match_results);
END $$
LANGUAGE 'plpgsql';

Didn't test the code.


问:
mongodb, the second res.json error
I have some issue with the second res.json. I tried with:

```<code>res.json({500,message : 'xxxxxx'})

res.send({500,message : 'xxxxxx'})
</code>```

But still doesn't work. This my code:

```<code>import mongoose from 'mongoose';
import {Router} from 'express';
import Motor from '../model/motor';

export default({config,db}) =>{
  let api = Router();

  //  '/v1/motor/add'
  api.post('/add',(res,req) => {
    let newMotor = new Motor();
    newMotor.title = req.body.title;

    newMotor.save(err = {
       if(err){
          res.json({message : 'error'});
       }
       res.json({message : 'motor saved successfuly'});
     });
  });

  return api;
}
</code>```

And this the error message:

```<code>SyntaxError: C:/Users/Ali Baltschun/Desktop/motorDB/src/controller/motor.js: Unexpected token, expected , (17:6)
  15 |         res.json({message : 'error'});
  16 |       }
> 17 |       res.json({message : 'motor saved successfuly'});
     |       ^
  18 |     });
  19 |   });
</code>```

答:
res.json expecting a valid json object so

```<code>res.json({500,message : 'xxxxxx'})
</code>```

the above line will fail

and you should also return res.json

```<code> newMotor.save(err = {
       if(err){
          return res.json({message : 'error'});
       }
       return res.json({message : 'motor saved successfuly'});
     });
  });
</code>```

next, if you want to send 500 code server error you could do

res.status(500).json({message : 'error'})

Title: mongodb, the second res.json error

Body:
I have some issue with the second res.json. I tried with:

res.json({500,message : 'xxxxxx'})

res.send({500,message : 'xxxxxx'})

But still doesn't work. This my code:

import mongoose from 'mongoose';
import {Router} from 'express';
import Motor from '../model/motor';

export default({config,db}) =>{
  let api = Router();

  //  '/v1/motor/add'
  api.post('/add',(res,req) => {
    let newMotor = new Motor();
    newMotor.title = req.body.title;

    newMotor.save(err = {
       if(err){
          res.json({message : 'error'});
       }
       res.json({message : 'motor saved successfuly'});
     });
  });

  return api;
}

And this the error message:

SyntaxError: C:/Users/Ali Baltschun/Desktop/motorDB/src/controller/motor.js: Unexpected token, expected , (17:6)
  15 |         res.json({message : 'error'});
  16 |       }
> 17 |       res.json({message : 'motor saved successfuly'});
     |       ^
  18 |     });
  19 |   });

Body:
res.json expecting a valid json object so

res.json({500,message : 'xxxxxx'})

the above line will fail

and you should also return res.json

 newMotor.save(err = {
       if(err){
          return res.json({message : 'error'});
       }
       return res.json({message : 'motor saved successfuly'});
     });
  });

next, if you want to send 500 code server error you could do

res.status(500).json({message : 'error'})


问:
Linux editing privilege over webservice
I'm currently working on a project, which will dynamically fetch some informations of my job and display them in a html page. To accomplish this i wrote a python script, which will be invoked using a PHP webservice. The script needs to edit some files in order to work.
Basically PHP executes the script using
 $output = shell_exec('python script.py');

The problem is, that if the webservice is called, the script does not have the needed permissions to edit the files.
So the webserver should call the script using something like  $output = shell_exec('sudo python script.py');

I may need to change the permissions to the project folder but i don't know how.
Some additional informations:

I'm using a raspberry pi 3 with LAMP installation on raspian as webserver
The folder structure is the following:

 projectfolder

|

- style (containing css)

-script.py

-script2.py

-filetoedit1.txt

-filetoedit2.html

Any help is appreciated!

答:
As suggested by @wpercy you have figure out which user is executing the file. Usually that user is called  www-data !
To find out which user is calling the service use
 ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1

After you figured out the user you have to change the permission for the folder. That command schould be something like  chown -R www-data:www-data /var/www/html/Projectfolder

Special thanks to wpercy!

Title: Linux editing privilege over webservice


问:
In Swift 4, how can you get the string-representation of a data type stored in a variable of type 'Any'?
What is the easiest way to get the string-representation of a value's data type if that value is stored in an 'Any' variable?

For instance, I'm debugging code that has this...

```<code>extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        return Parse(value)

    }
}
</code>```

I'm trying to figure out what data types are being passed through the function, but if I use type(of:) I keep getting 'Any' and not the value held in it.

```<code>extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        let nameOfType = ??? <-- This is what I'm trying to figure out
        log(nameOfType)

        return Parse(value)

    }
}
</code>```

I simply want to print the data type to the debug window, not do testing with is or as, etc.  It's strictly for logging/debugging reasons.

答:
Ok, I figured it out.  It's a two-step process.

You have to:

Use type(of:) to get the type of the variable (as others have described)

Use String(describing:) to get the name of that type (that was the missing piece)

Here's an example...

```<code>let typeName = String(describing: type(of:value))
</code>```

That's what I was after. Thanks for the other answers. Hope this helps!

Body:
What is the easiest way to get the string-representation of a value's data type if that value is stored in an 'Any' variable?

For instance, I'm debugging code that has this...

extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        return Parse(value)

    }
}

I'm trying to figure out what data types are being passed through the function, but if I use type(of:) I keep getting 'Any' and not the value held in it.

extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        let nameOfType = ??? <-- This is what I'm trying to figure out
        log(nameOfType)

        return Parse(value)

    }
}

I simply want to print the data type to the debug window, not do testing with is or as, etc.  It's strictly for logging/debugging reasons.

Body:
Ok, I figured it out.  It's a two-step process.

You have to:

Use type(of:) to get the type of the variable (as others have described)

Use String(describing:) to get the name of that type (that was the missing piece)

Here's an example...

let typeName = String(describing: type(of:value))

That's what I was after. Thanks for the other answers. Hope this helps!


问:
VXML for DTMF entry of letters based on their placement on dialpad
I'm brand new to VXML (and coding in general) and apparently what I'm trying to do is... not normal, but hopefully it can be done.

I understand the principle concept of DTMF input with VXML where I use:

<grammar mode="dtmf"><![CDATA[ (*|0|1|2|3|4|5|6|7|8|9)<2-31> ]]></grammar>

  <prompt>something here</prompt>

  <noinput-nomatch-filled>conditions</noinput-nomatch-filled>

What I'm trying to do is take multiple actions to allow DTMF entry of letters based on their  placement on the dialpad.  You'd achieve this by first dialing the number that the letter is on (2-9), and the placement of that letter (1-4).

For example: "E" would be 3 and 2 on the dialpad.

I'm at a complete loss as to how this would work in VXML.  What I'd like to do is this:

1) PROMPT: Please input your THREE letter code.  Please enter your first letter.

2) Expect two DTMF inputs the first number between 2 and 9, the second number between 1 and 4. Based on this logic (33 = F, 94 = Z) the letter is set.

3) PROMPT: The letter you have entered is (INPUT).  Is this correct?  Press 1 for yes, 2 to retry.

4) Retry or go onto the next letter.  So on and so forth.

If anyone has resources so I can stumble upon the answer to this myself, that'd be great!  If anyone would like a bounty... that's an option, too!  Thank you for reading!

答: The typical approach to this problem is just accept twice the number of tones as you expect or use a pound terminated input.  Then use ECMAscript or server side code to translate the tone strings into the desired letters.</p>


问:
React-Redux-Firebase - populate item with another item
I am using react-redux-firebase.
This is how my firebase data looks like once user submit the form:

It pushes information to "contacts" and images to "uploadedFiles"(also used for file Storage path). I really want to have it as one item. Something like:

```<code>contacts = {
 kydfsdcfasdfsadf :{
   email: "user@gmail.com",
   firstName: Tom,
   lastName : "Smith",
   uploasedFiles:{
     downloadURL:"dsfsdfsdsdvsdfgdsfgds",
     fullPath:"dfsdfsdf",
     mame:"q34deser4wefwsdf"
   }
 }
}
</code>```

I feel like I should use Populate, but I can not find how to populate one item with another. Will really appreciate any suggestion  and useful links.

Here is the code:
AddContactForm.js

```<code>import { Field, reduxForm } from 'redux-form';
import { browserHistory } from 'react-router';
import Uploader from '../components/Uploader';

const capitalize = value => value.charAt(0).toUpperCase() + value.substring(1);
const lower = value => value && value.toLowerCase();

const AddContactForm = props => {
    const { handleSubmit } = props;
    return (
      <div>
          <h1> Add New Contact</h1>
          <hr />
            <form onSubmit={handleSubmit}>
              <div>
                <label htmlFor="firstName">First Name</label>
                <Field name="firstName" component="input" type="text" normalize={capitalize} />
              </div>
              <div>
                <label htmlFor="lastName">Last Name</label>
                <Field name="lastName" component="input" type="text" normalize={capitalize} />
              </div>
              <div>
                <label htmlFor="email">Email</label>
                <Field name="email" component="input" type="email" normalize={lower} />
              </div>
              <Uploader />
              <button type="submit">Submit</button>
              <button onClick={() => { browserHistory.push('/'); }} >Cancel</button>
            </form>
        </div>
    );
};

AddContactForm = reduxForm({
  // a unique name for the form
  form: 'contact'
})(AddContactForm)

export default AddContactForm;
</code>```

Uploader.js

```<code>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { compose, bindActionCreators } from 'redux';
import { firebaseConnect, dataToJS, getFirebase } from 'react-redux-firebase';
import { map } from 'lodash';
import Dropzone from 'react-dropzone';

// Path within Database for metadata (also used for file Storage path)
const filesPath = 'uploadedFiles';

class Uploader extends Component {

  onFilesDrop(files) {
      const firebase = getFirebase();
    // Uploads files and push's objects containing metadata to database at dbPath
    // uploadFiles(storagePath, files, dbPath)
    firebase.uploadFiles(filesPath, files, filesPath);
}

  onFileDelete(file, key) {
      const firebase = getFirebase();
    // Deletes file and removes metadata from database
    // deleteFile(storagePath, dbPath)
    firebase.deleteFile(file.fullPath, `${filesPath}/${key}`);
  }

  render() {
    const { uploadedFiles } = this.props
    return (
      <div>
        <Dropzone onDrop={this.onFilesDrop}>
          <div>
            Drag and drop files here
            or click to select
          </div>
        </Dropzone>
        {
          uploadedFiles &&
            <div>
              <h3>
                Uploaded file(s):
              </h3>
              {
                map(uploadedFiles, (file, key) => (
                  <div key={file.name + key}>
                    <span>{file.name}</span>
                    <button onClick={() => this.onFileDelete(file, key)}>
                      Delete File
                    </button>
                  </div>
                ))
              }
            </div>
          }
      </div>
    );
  }
}

Uploader.propTypes = {
    firebase: PropTypes.object.isRequired,
    uploadedFiles: PropTypes.object
};

export default compose(
  firebaseConnect([
    filesPath
  ]),
  connect(
    ({ firebase }) => ({
      uploadedFiles: dataToJS(firebase, filesPath)
    })
  )
)(Uploader);
</code>```

AddContact.js

```<code>import React from 'react';
import { getFirebase, firebaseConnect, dataToJS } from 'react-redux-firebase';
import { browserHistory } from 'react-router';
import { connect } from 'react-redux';
import { compose } from 'redux';
import AddContactForm from './AddContactForm';

class AddContact extends React.Component {
    submit(values) {
      const firebase = getFirebase();
      firebase
      .push('contacts', values)

    //   .push('contacts', Object.assign({}, values, { img: 'here I need to pass uploadedFiles' }))

      .then(() => {
        browserHistory.push('/');
    });
}
    render() {
            const { uploadedFiles } = this.props;
            const uploadArr = uploadedFiles&&Object.values(uploadedFiles);
            const fileToAdd = uploadedFiles&&uploadArr[uploadArr.length-1].downloadURL

            console.log('uploadedFiles!', uploadedFiles&&fileToAdd);
      return (
            <div className="container">
                <AddContactForm onSubmit={this.submit} />
            </div>
      );
    }
}

export default compose(
  firebaseConnect([
    { path: 'contacts', queryParams: ['orderByValue'] },
    { path: 'uploadedFiles', queryParams: ['orderByValue'] }
  ]),
  connect(
    (state) => ({
      uploadedFiles: dataToJS(state.firebase, 'uploadedFiles')
    }),
  )
)(AddContact)
</code>```

答:
I would suggest to follow the React Redux "Way" of dealing with Firebase and that to create an Action that deals with Firebase which i am not sure if i am missing it in your code or not. However, when you upload the files in storage you need to set the URI into your Firebase database reference. you should get a URI as a result when you upload a file into the Firebase Storage.</p>

```<code>export function createAccount(data, picture) {
  const { fname, lname, email, password, image } = data;

      storage.child(`/${picture.name}/${new Date().getTime()}`).put(image[0]).then((snapshot) => {
        database.ref('contacts').child(youruserID).set({
         email: "user@gmail.com",
   firstName: Tom,
   lastName : "Smith",
          uploadedfile: snapshot.metadata.downloadURLs[0]
        });
      });

}
</code>```

Body:
I am using react-redux-firebase.
This is how my firebase data looks like once user submit the form:

It pushes information to "contacts" and images to "uploadedFiles"(also used for file Storage path). I really want to have it as one item. Something like:

contacts = {
 kydfsdcfasdfsadf :{
   email: "user@gmail.com",
   firstName: Tom,
   lastName : "Smith",
   uploasedFiles:{
     downloadURL:"dsfsdfsdsdvsdfgdsfgds",
     fullPath:"dfsdfsdf",
     mame:"q34deser4wefwsdf"
   }
 }
}

I feel like I should use Populate, but I can not find how to populate one item with another. Will really appreciate any suggestion  and useful links.

Here is the code:
AddContactForm.js

import { Field, reduxForm } from 'redux-form';
import { browserHistory } from 'react-router';
import Uploader from '../components/Uploader';

const capitalize = value => value.charAt(0).toUpperCase() + value.substring(1);
const lower = value => value && value.toLowerCase();

const AddContactForm = props => {
    const { handleSubmit } = props;
    return (

 Add New Contact

            <form onSubmit={handleSubmit}>

                First Name
                <Field name="firstName" component="input" type="text" normalize={capitalize} />

                Last Name
                <Field name="lastName" component="input" type="text" normalize={capitalize} />

                Email
                <Field name="email" component="input" type="email" normalize={lower} />

              <Uploader />
              <button type="submit">Submit</button>
              <button onClick={() => { browserHistory.push('/'); }} >Cancel</button>
            </form>

    );
};

AddContactForm = reduxForm({
  // a unique name for the form
  form: 'contact'
})(AddContactForm)

export default AddContactForm;

Uploader.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { compose, bindActionCreators } from 'redux';
import { firebaseConnect, dataToJS, getFirebase } from 'react-redux-firebase';
import { map } from 'lodash';
import Dropzone from 'react-dropzone';

// Path within Database for metadata (also used for file Storage path)
const filesPath = 'uploadedFiles';

class Uploader extends Component {

  onFilesDrop(files) {
      const firebase = getFirebase();
    // Uploads files and push's objects containing metadata to database at dbPath
    // uploadFiles(storagePath, files, dbPath)
    firebase.uploadFiles(filesPath, files, filesPath);
}

  onFileDelete(file, key) {
      const firebase = getFirebase();
    // Deletes file and removes metadata from database
    // deleteFile(storagePath, dbPath)
    firebase.deleteFile(file.fullPath, `${filesPath}/${key}`);
  }

  render() {
    const { uploadedFiles } = this.props
    return (

        <Dropzone onDrop={this.onFilesDrop}>

            Drag and drop files here
            or click to select

        </Dropzone>
        {
          uploadedFiles &&

                Uploaded file(s):

              {
                map(uploadedFiles, (file, key) => (

                    {file.name}
                    <button onClick={() => this.onFileDelete(file, key)}>
                      Delete File
                    </button>

                ))
              }

          }

    );
  }
}

Uploader.propTypes = {
    firebase: PropTypes.object.isRequired,
    uploadedFiles: PropTypes.object
};

export default compose(
  firebaseConnect([
    filesPath
  ]),
  connect(
    ({ firebase }) => ({
      uploadedFiles: dataToJS(firebase, filesPath)
    })
  )
)(Uploader);

AddContact.js

import React from 'react';
import { getFirebase, firebaseConnect, dataToJS } from 'react-redux-firebase';
import { browserHistory } from 'react-router';
import { connect } from 'react-redux';
import { compose } from 'redux';
import AddContactForm from './AddContactForm';

class AddContact extends React.Component {
    submit(values) {
      const firebase = getFirebase();
      firebase
      .push('contacts', values)

    //   .push('contacts', Object.assign({}, values, { img: 'here I need to pass uploadedFiles' }))

      .then(() => {
        browserHistory.push('/');
    });
}
    render() {
            const { uploadedFiles } = this.props;
            const uploadArr = uploadedFiles&&Object.values(uploadedFiles);
            const fileToAdd = uploadedFiles&&uploadArr[uploadArr.length-1].downloadURL

            console.log('uploadedFiles!', uploadedFiles&&fileToAdd);
      return (

                <AddContactForm onSubmit={this.submit} />

      );
    }
}

export default compose(
  firebaseConnect([
    { path: 'contacts', queryParams: ['orderByValue'] },
    { path: 'uploadedFiles', queryParams: ['orderByValue'] }
  ]),
  connect(
    (state) => ({
      uploadedFiles: dataToJS(state.firebase, 'uploadedFiles')
    }),
  )
)(AddContact)

Body:
I would suggest to follow the React Redux "Way" of dealing with Firebase and that to create an Action that deals with Firebase which i am not sure if i am missing it in your code or not. However, when you upload the files in storage you need to set the URI into your Firebase database reference. you should get a URI as a result when you upload a file into the Firebase Storage.

export function createAccount(data, picture) {
  const { fname, lname, email, password, image } = data;

      storage.child(`/${picture.name}/${new Date().getTime()}`).put(image[0]).then((snapshot) => {
        database.ref('contacts').child(youruserID).set({
         email: "user@gmail.com",
   firstName: Tom,
   lastName : "Smith",
          uploadedfile: snapshot.metadata.downloadURLs[0]
        });
      });

}