问:
Bash: Gathering all inputs at once, without waiting for the process to end
I have been writing a bash script in which the process depends on the user's input, but it is a 1min process, and if the user wants to do it more than once, he will have to wait for the loop to finish.
Here is the code:

```<code>while [[ ! "$addstr" =~ ^[Nn](.*)?$ ]]; do
    read -p "[*] String to permute around: " string
    echo; sleep 0.1s

    while [[ ! "$string" =~ ^[0-9a-zA-Z]+$ ]]; do
        echo "[!] Only alphanumeric strings are allowed!"; sleep 0.1s
        read -p "=> " string
        echo; sleep 0.1s
    done

    ## PROCESS ##

    echo "[?] Do you want to permute around another string?"; sleep 0.1s
    read -p "=> " addstr
    echo; sleep 0.1s

    while [[ ! "$addstr" =~ ^[YyNn](.*)?$ ]]; do
        echo "[!] Type again:"
        read -p "=> " addstr
        echo; sleep 0.1s
    done
done
</code>```

What i want to do is to allow the user to enter all strings AT ONCE, storing the variables for each of them and running the process as many times as it needs... I tryed a lot of things, even appending a "$counter" after "$string" but couldn't make this work, i believe it's something very simple and i just don't have the knowledge..

答:
Alter the script to read input from stdin. Then the user can redirect from a file.

Your script then becomes:

```<code>while IFS= read -r string; do
    if [[ ! "$string" =~ ^[0-9a-zA-Z]+$ ]]; do
        echo "[!] Only alphanumeric strings are allowed! $string"
        continue
    fi

    ## PROCESS ##
done
</code>```

And the user types something like

```<code>./yourscript < file.with.strings
</code>```

or various other ways to feed data to your script's stdin.

Another thought: gather all the inputs up front:

```<code>inputs=()
while true; do
    read -p "[*] String to permute around: " string
    echo; sleep 0.1s

    while [[ ! "$string" =~ ^[[:alnum:]]+$ ]]; do
        echo "[!] Only alphanumeric strings are allowed!"; sleep 0.1s
        read -p "=> " string
        echo; sleep 0.1s
    done

    # store the user input
    inputs+=( "$string" )

    echo "[?] Do you want to permute around another string?"; sleep 0.1s
    read -p "=> " addstr
    echo; sleep 0.1s

    while [[ ! "$addstr" =~ ^[[:blank:]]*[YyNn] ]]; do
        echo "[!] Type again:"
        read -p "=> " addstr
        echo; sleep 0.1s
    done

    [[ "$addstr" =~ ^[[:blank:]]*[Nn] ]] && break
done

## PROCESS ##
for string in "${inputs[@]}"; do
    process "$string"
done
</code>```

Body:
I have been writing a bash script in which the process depends on the user's input, but it is a 1min process, and if the user wants to do it more than once, he will have to wait for the loop to finish.
Here is the code:

while [[ ! "$addstr" =~ ^[Nn](.*)?$ ]]; do
    read -p "[*] String to permute around: " string
    echo; sleep 0.1s

    while [[ ! "$string" =~ ^[0-9a-zA-Z]+$ ]]; do
        echo "[!] Only alphanumeric strings are allowed!"; sleep 0.1s
        read -p "=> " string
        echo; sleep 0.1s
    done

    ## PROCESS ##

    echo "[?] Do you want to permute around another string?"; sleep 0.1s
    read -p "=> " addstr
    echo; sleep 0.1s

    while [[ ! "$addstr" =~ ^[YyNn](.*)?$ ]]; do
        echo "[!] Type again:"
        read -p "=> " addstr
        echo; sleep 0.1s
    done
done

What i want to do is to allow the user to enter all strings AT ONCE, storing the variables for each of them and running the process as many times as it needs... I tryed a lot of things, even appending a "$counter" after "$string" but couldn't make this work, i believe it's something very simple and i just don't have the knowledge..

Body:
Alter the script to read input from stdin. Then the user can redirect from a file.

Your script then becomes:

while IFS= read -r string; do
    if [[ ! "$string" =~ ^[0-9a-zA-Z]+$ ]]; do
        echo "[!] Only alphanumeric strings are allowed! $string"
        continue
    fi

    ## PROCESS ##
done

And the user types something like

./yourscript < file.with.strings

or various other ways to feed data to your script's stdin.

Another thought: gather all the inputs up front:

inputs=()
while true; do
    read -p "[*] String to permute around: " string
    echo; sleep 0.1s

    while [[ ! "$string" =~ ^[[:alnum:]]+$ ]]; do
        echo "[!] Only alphanumeric strings are allowed!"; sleep 0.1s
        read -p "=> " string
        echo; sleep 0.1s
    done

    # store the user input
    inputs+=( "$string" )

    echo "[?] Do you want to permute around another string?"; sleep 0.1s
    read -p "=> " addstr
    echo; sleep 0.1s

    while [[ ! "$addstr" =~ ^[[:blank:]]*[YyNn] ]]; do
        echo "[!] Type again:"
        read -p "=> " addstr
        echo; sleep 0.1s
    done

    [[ "$addstr" =~ ^[[:blank:]]*[Nn] ]] && break
done

## PROCESS ##
for string in "${inputs[@]}"; do
    process "$string"
done


来源: stackexchange

问:
Self publish a Chrome extension with one-click install
The Chrome Web Store installs extensions with one click.  From an extension's Chrome Web Store page, you simply click the INSTALL button and are not required to confirm or take any additional actions.  Is it possible to replicate this exact experience outside of the Chrome Web Store?

I know you can link to the Web Store page, but that's two clicks.  Or you can link directly to the extension packages, but that requires a second confirmation click for install.

Thanks.

答:
If you host your own extensions you can link on it

```<code><a href="your_extenison_or_app_or_theme.crx">Install</a>
</code>```

You have to pack it with Chrome new page tab's extension packer. This is the nearest you can get.

ContentLicense: CC BY-SA 2.5

Body:
If you host your own extensions you can link on it

<a href="your_extenison_or_app_or_theme.crx">Install</a>

You have to pack it with Chrome new page tab's extension packer. This is the nearest you can get.


问:
Highcharts: Draw line from data markers to axis?
I'm trying to make this combination chart in Highcharts:

So I'm wondering how to draw that dashed line from the data points out to the axes.

The Y-Axis is a percentage, and the X-axis is a date.

Currently, I'm combining a spline chart, area chart, and stacked column chart.

My series data currently looks like this:

```<code>series: [{
    type: 'spline',
    name: 'Average',
    data: [0, 50, 85, 95, 95, 95, 97],
    dashStyle: 'shortdash',
    marker: {
      radius: 8,
      lineWidth: 2,
      lineColor: 'skyblue',
      fillColor: 'white',
      symbol: 'triangle'
    }
  },
  {
    type: 'area',
    name: ' ',
    color: '#D8E1E8',
    data: [0, 0, 15, 25, 25],
    marker: {
      radius: 8,
      fillColor: 'skyblue',
      symbol: 'triangle'
    }
  },

  {
    type: 'area',
    name: ' ',
    color: '#FFFFCB',
    data: [0, 0, 15, 15, 15],
    marker: {
      radius: 1,
    },
    dataLabels: {
      enabled: false
    }
  },
  {
    type: 'area',
    name: ' ',
    color: '#B5E9FF',
    data: [0, 50, 55, 55, 55],
    marker: {
      radius: 1,
    },

  },
  {
    name: 'John',
    color: '#990000',
    data: [0, 13, 0]
  }, {
    name: 'Jane',
    color: '#FFB900',
    data: [0, 12, 0]
  }, {
    name: 'Joe',
    color: '#647D2D',
    data: [0, 24, 0]
  }
]
</code>```

答:
Use renderer.path to create an svg path which has 3 points - start, middle point and stop.

A function for creating a path:

```<code>function drawDashLine (chart, point, dashLine) {
  const xAxis = chart.xAxis[0]
  const yAxis = chart.yAxis[0]

  const x = Math.round(xAxis.toPixels(point[0]))
  const y = Math.round(yAxis.toPixels(point[1]))
  const d = ['M', xAxis.left, y, 'L', x, y, 'L', x, yAxis.top + yAxis.height]

  return dashLine
    ? dashLine.attr({ d })
    : chart.renderer.path(d).attr({ 'stroke-dasharray': '3,1', 'stroke': 'skyblue', 'stroke-width': 2, zIndex: 1 }).add()
}
</code>```

Call the function on load - to create the lines, and on redraw to recalculate the position of the lines.

```<code> chart: {
    events: {
      load: function () {
        this.dashLines = dashLines.map(point => drawDashLine(this, point))
      },
      redraw: function () {
        this.dashLines.forEach((line, i) => drawDashLine(this, dashLines[i], line))
      }
    }
  },
</code>```

live example: https://jsfiddle.net/em7e9o2t/

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make this combination chart in Highcharts:

So I'm wondering how to draw that dashed line from the data points out to the axes.

The Y-Axis is a percentage, and the X-axis is a date.

Currently, I'm combining a spline chart, area chart, and stacked column chart.

My series data currently looks like this:

series: [{
    type: 'spline',
    name: 'Average',
    data: [0, 50, 85, 95, 95, 95, 97],
    dashStyle: 'shortdash',
    marker: {
      radius: 8,
      lineWidth: 2,
      lineColor: 'skyblue',
      fillColor: 'white',
      symbol: 'triangle'
    }
  },
  {
    type: 'area',
    name: ' ',
    color: '#D8E1E8',
    data: [0, 0, 15, 25, 25],
    marker: {
      radius: 8,
      fillColor: 'skyblue',
      symbol: 'triangle'
    }
  },

  {
    type: 'area',
    name: ' ',
    color: '#FFFFCB',
    data: [0, 0, 15, 15, 15],
    marker: {
      radius: 1,
    },
    dataLabels: {
      enabled: false
    }
  },
  {
    type: 'area',
    name: ' ',
    color: '#B5E9FF',
    data: [0, 50, 55, 55, 55],
    marker: {
      radius: 1,
    },

  },
  {
    name: 'John',
    color: '#990000',
    data: [0, 13, 0]
  }, {
    name: 'Jane',
    color: '#FFB900',
    data: [0, 12, 0]
  }, {
    name: 'Joe',
    color: '#647D2D',
    data: [0, 24, 0]
  }
]

Body:
Use renderer.path to create an svg path which has 3 points - start, middle point and stop.

A function for creating a path:

function drawDashLine (chart, point, dashLine) {
  const xAxis = chart.xAxis[0]
  const yAxis = chart.yAxis[0]

  const x = Math.round(xAxis.toPixels(point[0]))
  const y = Math.round(yAxis.toPixels(point[1]))
  const d = ['M', xAxis.left, y, 'L', x, y, 'L', x, yAxis.top + yAxis.height]

  return dashLine
    ? dashLine.attr({ d })
    : chart.renderer.path(d).attr({ 'stroke-dasharray': '3,1', 'stroke': 'skyblue', 'stroke-width': 2, zIndex: 1 }).add()
}

Call the function on load - to create the lines, and on redraw to recalculate the position of the lines.

 chart: {
    events: {
      load: function () {
        this.dashLines = dashLines.map(point => drawDashLine(this, point))
      },
      redraw: function () {
        this.dashLines.forEach((line, i) => drawDashLine(this, dashLines[i], line))
      }
    }
  },

live example: https://jsfiddle.net/em7e9o2t/


问:
Use clipping to round corners of ViewGroup
I have a RelativeLayout that needs to have rounded upper left and upper right corners. I can do this with a drawable background defined in XML with corners topLeftRadius and topRightRadius. But... This RelativeLayout also need to have a background that is a layer-list with a tiled bitmap and shape combo, and the tiled bitmap does not have a corners parameter in the drawable XML. So my idea was to to make a RelativeLayout with the following code:

```<code>@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    path.reset();
    rect.set(0, 0, w, h);
    path.addRoundRect(rect, radius, radius, Path.Direction.CW);
    path.close();
}

@Override
protected void dispatchDraw(Canvas canvas) {
    int save = canvas.save();
    canvas.clipPath(path);
    super.dispatchDraw(canvas);
    canvas.restoreToCount(save);
}</code>```

Sadly no clipping is happening, I was expecting it to clip all four corners of my RelativeLayout, but nothing is happening. The "onSizeChanged" and "dispatchDraw" methods are both called, I tested that. I have also tried to turn off hardware acceleration, but it does nothing.

My RelativeLayout is part of a larger layout, and that layout is inflated in a subclass of FrameLayout, and that subclass is then used a a row in a RecyclerView, if that changes anything.

答:
Having defined this layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent">

    <com.playground.RoundedRelativeLayout
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:background="@color/colorPrimary" />

</FrameLayout>
</code>```

Where RoundedRelativeLayout has following implementation:

```
<code>
    public class RoundedRelativeLayout extends RelativeLayout {

        private RectF rectF;
        private Path path = new Path();
        private float cornerRadius = 15;

        public RoundedRelativeLayout(Context context) {
            super(context);
        }

        public RoundedRelativeLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public RoundedRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            rectF = new RectF(0, 0, w, h);
            resetPath();
        }

        @Override
        public void draw(Canvas canvas) {
            int save = canvas.save();
            canvas.clipPath(path);
            super.draw(canvas);
            canvas.restoreToCount(save);
        }

        @Override
        protected void dispatchDraw(Canvas canvas) {
            int save = canvas.save();
            canvas.clipPath(path);
            super.dispatchDraw(canvas);
            canvas.restoreToCount(save);
        }

        private void resetPath() {
            path.reset();
            path.addRoundRect(rectF, cornerRadius, cornerRadius, Path.Direction.CW);
            path.close();
        }
    }
</code>
```

You'll get following output:

The implementation is shamelessly stolen from RoundKornerLayouts project.

Body:
I have a RelativeLayout that needs to have rounded upper left and upper right corners. I can do this with a drawable background defined in XML with corners topLeftRadius and topRightRadius. But... This RelativeLayout also need to have a background that is a layer-list with a tiled bitmap and shape combo, and the tiled bitmap does not have a corners parameter in the drawable XML. So my idea was to to make a RelativeLayout with the following code:

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);

    path.reset();
    rect.set(0, 0, w, h);
    path.addRoundRect(rect, radius, radius, Path.Direction.CW);
    path.close();
}

@Override
protected void dispatchDraw(Canvas canvas) {
    int save = canvas.save();
    canvas.clipPath(path);
    super.dispatchDraw(canvas);
    canvas.restoreToCount(save);
}

Sadly no clipping is happening, I was expecting it to clip all four corners of my RelativeLayout, but nothing is happening. The "onSizeChanged" and "dispatchDraw" methods are both called, I tested that. I have also tried to turn off hardware acceleration, but it does nothing.

My RelativeLayout is part of a larger layout, and that layout is inflated in a subclass of FrameLayout, and that subclass is then used a a row in a RecyclerView, if that changes anything.

Body:
Having defined this layout:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent">

    <com.playground.RoundedRelativeLayout
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:background="@color/colorPrimary" />

</FrameLayout>

Where RoundedRelativeLayout has following implementation:

    public class RoundedRelativeLayout extends RelativeLayout {

        private RectF rectF;
        private Path path = new Path();
        private float cornerRadius = 15;

        public RoundedRelativeLayout(Context context) {
            super(context);
        }

        public RoundedRelativeLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public RoundedRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {
            super.onSizeChanged(w, h, oldw, oldh);
            rectF = new RectF(0, 0, w, h);
            resetPath();
        }

        @Override
        public void draw(Canvas canvas) {
            int save = canvas.save();
            canvas.clipPath(path);
            super.draw(canvas);
            canvas.restoreToCount(save);
        }

        @Override
        protected void dispatchDraw(Canvas canvas) {
            int save = canvas.save();
            canvas.clipPath(path);
            super.dispatchDraw(canvas);
            canvas.restoreToCount(save);
        }

        private void resetPath() {
            path.reset();
            path.addRoundRect(rectF, cornerRadius, cornerRadius, Path.Direction.CW);
            path.close();
        }
    }

You'll get following output:

The implementation is shamelessly stolen from RoundKornerLayouts project.


问:
Delete rows older than 14 days in MySQL

Summary

I need to purge the history of a table from rows that are older than 14 days.

Being no MySQL Expert, my searches lead me to this:

```<code>delete
    from SYS_VERROUS_POLICE
    where idModificationPolice not in (
                select distinct idModificationPolice
                    from SYS_VERROUS_POLICE
                    where date(dateHeureModification)
                            between curdate() and curdate() - interval 14 day
            );
</code>```

Thrown Exception

But then I'm stuck with this error message:

Error Code: 1093. You can't specify target table 'SYS_VERROUS_POLICE' for update in FROM clause.

What the...

Context

MySQL seems to be operating in safe mode, so I just won't be able to perform a DELETE where matching dates.

In safe-mode, if I try to delete using only the date field, it doesn't comply.

```<code>delete
  from SYS_VERROUS_POLICE
 where date(dateHeureModification) < curdate() - interval 14 day

Error Code: 1175. You are using safe update mode and you tried to update a table without a
WHERE that uses a KEY column
To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
0,00071 sec
</code>```

Am I missing something?

答:
I understand your point about using safe mode. If you try to use UPDATE or DELETE against a non-indexed expression, it complains, because it can't make an estimate of whether you will accidentally delete your whole table.

Using an expression on DATE(dateHeureModification) > ...
 is naturally unindexed. MySQL can't do an index lookup against the result of a function.

You can use LIMIT in your delete query to make it satisfy the safe-updates mode. MySQL treats it as sufficient protection against accidentally deleting all the rows in the table, if you use LIMIT.

```<code>DELETE
    FROM SYS_VERROUS_POLICE
    WHERE DATE(dateHeureModification) < (curdate() - INTERVAL 14 DAY)
    LIMIT 1000;
</code>```

It's a good idea to run the delete in limited-size batches anyway, so it doesn't create too many locks or add too much to the undo segment.

Just keep doing DELETE in a loop, deleting batches of 1000 rows at a time, and check rows-affected after each batch. Stop the loop when rows-affected reaches 0.

Another idea: I don't think you really need the DATE() function in your WHERE clause. So you might be able to do the DELETE like below, and it will be able to use an index. Besides, it should be faster to the query to check for any rows if you have an index on dateHeureModification.

```<code>DELETE
    FROM SYS_VERROUS_POLICE
    WHERE dateHeureModification < (curdate() - INTERVAL 14 DAY)
    LIMIT 1000;
</code>```

Title: Delete rows older than 14 days in MySQL

Body:
Summary

I need to purge the history of a table from rows that are older than 14 days.

Being no MySQL Expert, my searches lead me to this:

delete
    from SYS_VERROUS_POLICE
    where idModificationPolice not in (
                select distinct idModificationPolice
                    from SYS_VERROUS_POLICE
                    where date(dateHeureModification)
                            between curdate() and curdate() - interval 14 day
            );

Thrown Exception

But then I'm stuck with this error message:

Error Code: 1093. You can't specify target table 'SYS_VERROUS_POLICE' for update in FROM clause.

What the...

Context

MySQL seems to be operating in safe mode, so I just won't be able to perform a DELETE where matching dates.

In safe-mode, if I try to delete using only the date field, it doesn't comply.

delete
  from SYS_VERROUS_POLICE
 where date(dateHeureModification) < curdate() - interval 14 day

Error Code: 1175. You are using safe update mode and you tried to update a table without a
WHERE that uses a KEY column
To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
0,00071 sec

Am I missing something?

Body:
I understand your point about using safe mode. If you try to use UPDATE or DELETE against a non-indexed expression, it complains, because it can't make an estimate of whether you will accidentally delete your whole table.

Using an expression on DATE(dateHeureModification) > ...
 is naturally unindexed. MySQL can't do an index lookup against the result of a function.

You can use LIMIT in your delete query to make it satisfy the safe-updates mode. MySQL treats it as sufficient protection against accidentally deleting all the rows in the table, if you use LIMIT.

DELETE
    FROM SYS_VERROUS_POLICE
    WHERE DATE(dateHeureModification) < (curdate() - INTERVAL 14 DAY)
    LIMIT 1000;

It's a good idea to run the delete in limited-size batches anyway, so it doesn't create too many locks or add too much to the undo segment.

Just keep doing DELETE in a loop, deleting batches of 1000 rows at a time, and check rows-affected after each batch. Stop the loop when rows-affected reaches 0.

Another idea: I don't think you really need the DATE() function in your WHERE clause. So you might be able to do the DELETE like below, and it will be able to use an index. Besides, it should be faster to the query to check for any rows if you have an index on dateHeureModification.

DELETE
    FROM SYS_VERROUS_POLICE
    WHERE dateHeureModification < (curdate() - INTERVAL 14 DAY)
    LIMIT 1000;


问:
Missing metadata driver in Symfony 3.4 BETA 4
After upgrading my project from Symfony 3.4.0 BETA 2 to 3.4.0 BETA 4 I get the following error in every request and every cli command:

```<code>[Doctrine\ORM\ORMException]
It's a requirement to specify a Metadata Driver and pass it to Doctrine\ORM\Configuration::setMetadataDriverImpl().

Exception trace:
Doctrine\ORM\ORMException::missingMappingDriverImpl() at D:\jinya-gallery-cms\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php:830
Doctrine\ORM\EntityManager::create() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:952
Container3xxrjsx\appDevDebugProjectContainer->getDoctrine_Orm_DefaultEntityManagerService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:2164
Container3xxrjsx\appDevDebugProjectContainer->getJinyaGallery_Monolog_MySqlHandlerService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:2299
Container3xxrjsx\appDevDebugProjectContainer->getMonolog_Logger_CacheService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:1508
Container3xxrjsx\appDevDebugProjectContainer->getCache_AnnotationsService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:1409
Container3xxrjsx\appDevDebugProjectContainer->getAnnotationReaderService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:940
Container3xxrjsx\appDevDebugProjectContainer->getDoctrine_Orm_DefaultEntityManagerService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:2164
Container3xxrjsx\appDevDebugProjectContainer->getJinyaGallery_Monolog_MySqlHandlerService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:2330
Container3xxrjsx\appDevDebugProjectContainer->getMonolog_Logger_EventService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:1703
Container3xxrjsx\appDevDebugProjectContainer->getDebug_EventDispatcherService() at D:\jinya-gallery-cms\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Container.php:299
Symfony\Component\DependencyInjection\Container->get() at D:\jinya-gallery-cms\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:65
Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at D:\jinya-gallery-cms\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:129
Symfony\Component\Console\Application->run() at D:\jinya-gallery-cms\bin\console:27
</code>```

After checking the generated cache code I found out, that the code that instantiates the EntityManager is completely different than in BETA 2.

This is the code from BETA 2:

```<code><?php

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;

// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
// Returns the public 'doctrine.orm.default_entity_manager' shared service.

$a = ${($_ = isset($this->services['annotation_reader']) ? $this->services['annotation_reader'] : $this->load(__DIR__.'/getAnnotationReaderService.php')) && false ?: '_'};

$b = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($a, array(0 => 'D:\\jinya-gallery-cms\\src\\HelperBundle\\Entity', 1 => 'D:\\jinya-gallery-cms\\src\\DataBundle\\Entity'));

$c = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();
$c->addDriver($b, 'HelperBundle\\Entity');
$c->addDriver($b, 'DataBundle\\Entity');
$c->addDriver(new \Doctrine\ORM\Mapping\Driver\XmlDriver(new \Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator(array('D:\\jinya-gallery-cms\\vendor\\friendsofsymfony\\user-bundle\\Resources\\config\\doctrine-mapping' => 'FOS\\UserBundle\\Model'), '.orm.xml')), 'FOS\\UserBundle\\Model');

$d = new \Doctrine\ORM\Configuration();
$d->setEntityNamespaces(array('HelperBundle' => 'HelperBundle\\Entity', 'DataBundle' => 'DataBundle\\Entity'));
$d->setMetadataCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_metadata_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_metadata_cache'] : $this->load(__DIR__.'/getDoctrineCache_Providers_Doctrine_Orm_DefaultMetadataCacheService.php')) && false ?: '_'});
$d->setQueryCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_query_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_query_cache'] : $this->load(__DIR__.'/getDoctrineCache_Providers_Doctrine_Orm_DefaultQueryCacheService.php')) && false ?: '_'});
$d->setResultCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_result_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_result_cache'] : $this->load(__DIR__.'/getDoctrineCache_Providers_Doctrine_Orm_DefaultResultCacheService.php')) && false ?: '_'});
$d->setMetadataDriverImpl($c);
$d->setProxyDir(($this->targetDirs[0].'/doctrine/orm/Proxies'));
$d->setProxyNamespace('Proxies');
$d->setAutoGenerateProxyClasses(true);
$d->setClassMetadataFactoryName('Doctrine\\ORM\\Mapping\\ClassMetadataFactory');
$d->setDefaultRepositoryClassName('Doctrine\\ORM\\EntityRepository');
$d->setNamingStrategy(new \Doctrine\ORM\Mapping\UnderscoreNamingStrategy());
$d->setQuoteStrategy(new \Doctrine\ORM\Mapping\DefaultQuoteStrategy());
$d->setEntityListenerResolver(${($_ = isset($this->services['doctrine.orm.default_entity_listener_resolver']) ? $this->services['doctrine.orm.default_entity_listener_resolver'] : $this->load(__DIR__.'/getDoctrine_Orm_DefaultEntityListenerResolverService.php')) && false ?: '_'});

$this->services['doctrine.orm.default_entity_manager'] = $instance = \Doctrine\ORM\EntityManager::create(${($_ = isset($this->services['doctrine.dbal.default_connection']) ? $this->services['doctrine.dbal.default_connection'] : $this->load(__DIR__.'/getDoctrine_Dbal_DefaultConnectionService.php')) && false ?: '_'}, $d);

${($_ = isset($this->services['doctrine.orm.default_manager_configurator']) ? $this->services['doctrine.orm.default_manager_configurator'] : $this->services['doctrine.orm.default_manager_configurator'] = new \Doctrine\Bundle\DoctrineBundle\ManagerConfigurator(array(), array())) && false ?: '_'}->configure($instance);

return $instance;
</code>```

This is the code from BETA 4

```<code><?php

namespace ContainerXo2t2t9;

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;

/**
 * This class has been auto-generated
 * by the Symfony Dependency Injection Component.
 *
 * @final since Symfony 3.3
 */
class appDevDebugProjectContainer extends Container
{
/**
     * Gets the public 'doctrine.orm.default_entity_manager' shared service.
     *
     * @return \Doctrine\ORM\EntityManager
     */
    protected function getDoctrine_Orm_DefaultEntityManagerService($lazyLoad = true)
    {
        $a = ${($_ = isset($this->services['doctrine.dbal.default_connection']) ? $this->services['doctrine.dbal.default_connection'] : $this->getDoctrine_Dbal_DefaultConnectionService()) && false ?: '_'};
        $b = ${($_ = isset($this->services['annotation_reader']) ? $this->services['annotation_reader'] : $this->getAnnotationReaderService()) && false ?: '_'};

        if (isset($this->services['doctrine.orm.default_entity_manager'])) {
            return $this->services['doctrine.orm.default_entity_manager'];
        }

        $c = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($b, array(0 => 'D:\\jinya-gallery-cms\\src\\HelperBundle\\Entity', 1 => 'D:\\jinya-gallery-cms\\src\\DataBundle\\Entity'));

        $d = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();

        $e = new \Doctrine\ORM\Configuration();

        $this->services['doctrine.orm.default_entity_manager'] = $instance = \Doctrine\ORM\EntityManager::create($a, $e);

        $d->addDriver($c, 'HelperBundle\\Entity');
        $d->addDriver($c, 'DataBundle\\Entity');
        $d->addDriver(new \Doctrine\ORM\Mapping\Driver\XmlDriver(new \Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator(array('D:\\jinya-gallery-cms\\vendor\\friendsofsymfony\\user-bundle\\Resources\\config\\doctrine-mapping' => 'FOS\\UserBundle\\Model'), '.orm.xml')), 'FOS\\UserBundle\\Model');
        $e->setEntityNamespaces(array('HelperBundle' => 'HelperBundle\\Entity', 'DataBundle' => 'DataBundle\\Entity'));
        $e->setMetadataCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_metadata_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_metadata_cache'] : $this->getDoctrineCache_Providers_Doctrine_Orm_DefaultMetadataCacheService()) && false ?: '_'});
        $e->setQueryCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_query_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_query_cache'] : $this->getDoctrineCache_Providers_Doctrine_Orm_DefaultQueryCacheService()) && false ?: '_'});
        $e->setResultCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_result_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_result_cache'] : $this->getDoctrineCache_Providers_Doctrine_Orm_DefaultResultCacheService()) && false ?: '_'});
        $e->setMetadataDriverImpl($d);
        $e->setProxyDir(($this->targetDirs[0].'/doctrine/orm/Proxies'));
        $e->setProxyNamespace('Proxies');
        $e->setAutoGenerateProxyClasses(true);
        $e->setClassMetadataFactoryName('Doctrine\\ORM\\Mapping\\ClassMetadataFactory');
        $e->setDefaultRepositoryClassName('Doctrine\\ORM\\EntityRepository');
        $e->setNamingStrategy(new \Doctrine\ORM\Mapping\UnderscoreNamingStrategy());
        $e->setQuoteStrategy(new \Doctrine\ORM\Mapping\DefaultQuoteStrategy());
        $e->setEntityListenerResolver(${($_ = isset($this->services['doctrine.orm.default_entity_listener_resolver']) ? $this->services['doctrine.orm.default_entity_listener_resolver'] : $this->services['doctrine.orm.default_entity_listener_resolver'] = new \Doctrine\Bundle\DoctrineBundle\Mapping\ContainerAwareEntityListenerResolver($this)) && false ?: '_'});

        ${($_ = isset($this->services['doctrine.orm.default_manager_configurator']) ? $this->services['doctrine.orm.default_manager_configurator'] : $this->services['doctrine.orm.default_manager_configurator'] = new \Doctrine\Bundle\DoctrineBundle\ManagerConfigurator(array(), array())) && false ?: '_'}->configure($instance);

        return $instance;
    }
}
</code>```

The result is, that in BETA 4 the EntityManager is created before the config values are set. Does anyone know how I can affect the cache generation to create a working cache?

答:
The solution which worked for me:

Install Lazy Services with composer require ocramius/proxy-manager

For each listener set additional parameter lazy: true in tags

```<code>app.service_doctrine.foo_listerner:
class: AppBundle\Service\Doctrine\FooListener
...
tags:
    - { name: doctrine.orm.entity_listener, entity_manager: default, lazy: true }
</code>```

Body:
After upgrading my project from Symfony 3.4.0 BETA 2 to 3.4.0 BETA 4 I get the following error in every request and every cli command:

[Doctrine\ORM\ORMException]
It's a requirement to specify a Metadata Driver and pass it to Doctrine\ORM\Configuration::setMetadataDriverImpl().

Exception trace:
Doctrine\ORM\ORMException::missingMappingDriverImpl() at D:\jinya-gallery-cms\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php:830
Doctrine\ORM\EntityManager::create() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:952
Container3xxrjsx\appDevDebugProjectContainer->getDoctrine_Orm_DefaultEntityManagerService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:2164
Container3xxrjsx\appDevDebugProjectContainer->getJinyaGallery_Monolog_MySqlHandlerService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:2299
Container3xxrjsx\appDevDebugProjectContainer->getMonolog_Logger_CacheService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:1508
Container3xxrjsx\appDevDebugProjectContainer->getCache_AnnotationsService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:1409
Container3xxrjsx\appDevDebugProjectContainer->getAnnotationReaderService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:940
Container3xxrjsx\appDevDebugProjectContainer->getDoctrine_Orm_DefaultEntityManagerService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:2164
Container3xxrjsx\appDevDebugProjectContainer->getJinyaGallery_Monolog_MySqlHandlerService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:2330
Container3xxrjsx\appDevDebugProjectContainer->getMonolog_Logger_EventService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:1703
Container3xxrjsx\appDevDebugProjectContainer->getDebug_EventDispatcherService() at D:\jinya-gallery-cms\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Container.php:299
Symfony\Component\DependencyInjection\Container->get() at D:\jinya-gallery-cms\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:65
Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at D:\jinya-gallery-cms\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:129
Symfony\Component\Console\Application->run() at D:\jinya-gallery-cms\bin\console:27

After checking the generated cache code I found out, that the code that instantiates the EntityManager is completely different than in BETA 2.

This is the code from BETA 2:

<?php

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;

// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
// Returns the public 'doctrine.orm.default_entity_manager' shared service.

$a = ${($_ = isset($this->services['annotation_reader']) ? $this->services['annotation_reader'] : $this->load(__DIR__.'/getAnnotationReaderService.php')) && false ?: '_'};

$b = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($a, array(0 => 'D:\\jinya-gallery-cms\\src\\HelperBundle\\Entity', 1 => 'D:\\jinya-gallery-cms\\src\\DataBundle\\Entity'));

$c = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();
$c->addDriver($b, 'HelperBundle\\Entity');
$c->addDriver($b, 'DataBundle\\Entity');
$c->addDriver(new \Doctrine\ORM\Mapping\Driver\XmlDriver(new \Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator(array('D:\\jinya-gallery-cms\\vendor\\friendsofsymfony\\user-bundle\\Resources\\config\\doctrine-mapping' => 'FOS\\UserBundle\\Model'), '.orm.xml')), 'FOS\\UserBundle\\Model');

$d = new \Doctrine\ORM\Configuration();
$d->setEntityNamespaces(array('HelperBundle' => 'HelperBundle\\Entity', 'DataBundle' => 'DataBundle\\Entity'));
$d->setMetadataCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_metadata_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_metadata_cache'] : $this->load(__DIR__.'/getDoctrineCache_Providers_Doctrine_Orm_DefaultMetadataCacheService.php')) && false ?: '_'});
$d->setQueryCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_query_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_query_cache'] : $this->load(__DIR__.'/getDoctrineCache_Providers_Doctrine_Orm_DefaultQueryCacheService.php')) && false ?: '_'});
$d->setResultCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_result_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_result_cache'] : $this->load(__DIR__.'/getDoctrineCache_Providers_Doctrine_Orm_DefaultResultCacheService.php')) && false ?: '_'});
$d->setMetadataDriverImpl($c);
$d->setProxyDir(($this->targetDirs[0].'/doctrine/orm/Proxies'));
$d->setProxyNamespace('Proxies');
$d->setAutoGenerateProxyClasses(true);
$d->setClassMetadataFactoryName('Doctrine\\ORM\\Mapping\\ClassMetadataFactory');
$d->setDefaultRepositoryClassName('Doctrine\\ORM\\EntityRepository');
$d->setNamingStrategy(new \Doctrine\ORM\Mapping\UnderscoreNamingStrategy());
$d->setQuoteStrategy(new \Doctrine\ORM\Mapping\DefaultQuoteStrategy());
$d->setEntityListenerResolver(${($_ = isset($this->services['doctrine.orm.default_entity_listener_resolver']) ? $this->services['doctrine.orm.default_entity_listener_resolver'] : $this->load(__DIR__.'/getDoctrine_Orm_DefaultEntityListenerResolverService.php')) && false ?: '_'});

$this->services['doctrine.orm.default_entity_manager'] = $instance = \Doctrine\ORM\EntityManager::create(${($_ = isset($this->services['doctrine.dbal.default_connection']) ? $this->services['doctrine.dbal.default_connection'] : $this->load(__DIR__.'/getDoctrine_Dbal_DefaultConnectionService.php')) && false ?: '_'}, $d);

${($_ = isset($this->services['doctrine.orm.default_manager_configurator']) ? $this->services['doctrine.orm.default_manager_configurator'] : $this->services['doctrine.orm.default_manager_configurator'] = new \Doctrine\Bundle\DoctrineBundle\ManagerConfigurator(array(), array())) && false ?: '_'}->configure($instance);

return $instance;

This is the code from BETA 4

<?php

namespace ContainerXo2t2t9;

use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;

/**
 * This class has been auto-generated
 * by the Symfony Dependency Injection Component.
 *
 * @final since Symfony 3.3
 */
class appDevDebugProjectContainer extends Container
{
/**
     * Gets the public 'doctrine.orm.default_entity_manager' shared service.
     *
     * @return \Doctrine\ORM\EntityManager
     */
    protected function getDoctrine_Orm_DefaultEntityManagerService($lazyLoad = true)
    {
        $a = ${($_ = isset($this->services['doctrine.dbal.default_connection']) ? $this->services['doctrine.dbal.default_connection'] : $this->getDoctrine_Dbal_DefaultConnectionService()) && false ?: '_'};
        $b = ${($_ = isset($this->services['annotation_reader']) ? $this->services['annotation_reader'] : $this->getAnnotationReaderService()) && false ?: '_'};

        if (isset($this->services['doctrine.orm.default_entity_manager'])) {
            return $this->services['doctrine.orm.default_entity_manager'];
        }

        $c = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($b, array(0 => 'D:\\jinya-gallery-cms\\src\\HelperBundle\\Entity', 1 => 'D:\\jinya-gallery-cms\\src\\DataBundle\\Entity'));

        $d = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();

        $e = new \Doctrine\ORM\Configuration();

        $this->services['doctrine.orm.default_entity_manager'] = $instance = \Doctrine\ORM\EntityManager::create($a, $e);

        $d->addDriver($c, 'HelperBundle\\Entity');
        $d->addDriver($c, 'DataBundle\\Entity');
        $d->addDriver(new \Doctrine\ORM\Mapping\Driver\XmlDriver(new \Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator(array('D:\\jinya-gallery-cms\\vendor\\friendsofsymfony\\user-bundle\\Resources\\config\\doctrine-mapping' => 'FOS\\UserBundle\\Model'), '.orm.xml')), 'FOS\\UserBundle\\Model');
        $e->setEntityNamespaces(array('HelperBundle' => 'HelperBundle\\Entity', 'DataBundle' => 'DataBundle\\Entity'));
        $e->setMetadataCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_metadata_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_metadata_cache'] : $this->getDoctrineCache_Providers_Doctrine_Orm_DefaultMetadataCacheService()) && false ?: '_'});
        $e->setQueryCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_query_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_query_cache'] : $this->getDoctrineCache_Providers_Doctrine_Orm_DefaultQueryCacheService()) && false ?: '_'});
        $e->setResultCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_result_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_result_cache'] : $this->getDoctrineCache_Providers_Doctrine_Orm_DefaultResultCacheService()) && false ?: '_'});
        $e->setMetadataDriverImpl($d);
        $e->setProxyDir(($this->targetDirs[0].'/doctrine/orm/Proxies'));
        $e->setProxyNamespace('Proxies');
        $e->setAutoGenerateProxyClasses(true);
        $e->setClassMetadataFactoryName('Doctrine\\ORM\\Mapping\\ClassMetadataFactory');
        $e->setDefaultRepositoryClassName('Doctrine\\ORM\\EntityRepository');
        $e->setNamingStrategy(new \Doctrine\ORM\Mapping\UnderscoreNamingStrategy());
        $e->setQuoteStrategy(new \Doctrine\ORM\Mapping\DefaultQuoteStrategy());
        $e->setEntityListenerResolver(${($_ = isset($this->services['doctrine.orm.default_entity_listener_resolver']) ? $this->services['doctrine.orm.default_entity_listener_resolver'] : $this->services['doctrine.orm.default_entity_listener_resolver'] = new \Doctrine\Bundle\DoctrineBundle\Mapping\ContainerAwareEntityListenerResolver($this)) && false ?: '_'});

        ${($_ = isset($this->services['doctrine.orm.default_manager_configurator']) ? $this->services['doctrine.orm.default_manager_configurator'] : $this->services['doctrine.orm.default_manager_configurator'] = new \Doctrine\Bundle\DoctrineBundle\ManagerConfigurator(array(), array())) && false ?: '_'}->configure($instance);

        return $instance;
    }
}

The result is, that in BETA 4 the EntityManager is created before the config values are set. Does anyone know how I can affect the cache generation to create a working cache?

Body:
The solution which worked for me:

Install Lazy Services with composer require ocramius/proxy-manager

For each listener set additional parameter lazy: true in tags

app.service_doctrine.foo_listerner:
class: AppBundle\Service\Doctrine\FooListener
...
tags:
    - { name: doctrine.orm.entity_listener, entity_manager: default, lazy: true }


问:
How to fix unhandled exception access violation
I have written a logic to find out common elements from two arrays. But the program breaks at the if condition giving an exception saying Access violation reading location 0x00000002.

```<code>#include<stdio.h>
void intersect(int[2][2],int[2][2],int,int);
int main()
{
    int arr1[2][2]={{2,5},{6,8}};
    int arr2[2][2]={{1,2},{8,8}};
row = (sizeof(arr1)/sizeof(arr1[0]));
     col = (sizeof(arr1[0])/sizeof(arr1[0][1]));
intersect(arr1,arr2,row,col);
}

void intersect(int **ptr1, int **ptr2,int row, int col)
{
    int i = 0, j= 0, x = 0, y = 0;

    for(i = 0; i <row ; i++)
    {
        for(j = 0 ; j < col ; j++)
        {
                for(x = 0; x < row ; x++)
                {
                    for(y = 0; y < col ; y++)
                    {
                        if(ptr1[i][j] == ptr2[x][y])
                            printf("%d\t",ptr1[i][j]);

                    }
                }
        }
    }
}
</code>```

This is what it says in detail: First-chance exception at 0x002b1572 in Array.exe: 0xC0000005: Access violation reading location 0x00000002. Unhandled exception at 0x002b1572 in Array.exe: 0xC0000005: Access violation reading location 0x00000002.

答:
when you are passing 2D array as a argument to function, you should catch with pointer to an array not with double pointer because 2D array and double pointer are not same..

```<code>    #define r 2
    #define c 2

    void intersect(int (*ptr1)[r], int (*ptr2)[c],int row, int col)
    {
           //function body
    }
</code>```

Body:
I have written a logic to find out common elements from two arrays. But the program breaks at the if condition giving an exception saying Access violation reading location 0x00000002.

#include<stdio.h>
void intersect(int[2][2],int[2][2],int,int);
int main()
{
    int arr1[2][2]={{2,5},{6,8}};
    int arr2[2][2]={{1,2},{8,8}};
row = (sizeof(arr1)/sizeof(arr1[0]));
     col = (sizeof(arr1[0])/sizeof(arr1[0][1]));
intersect(arr1,arr2,row,col);
}

void intersect(int **ptr1, int **ptr2,int row, int col)
{
    int i = 0, j= 0, x = 0, y = 0;

    for(i = 0; i <row ; i++)
    {
        for(j = 0 ; j < col ; j++)
        {
                for(x = 0; x < row ; x++)
                {
                    for(y = 0; y < col ; y++)
                    {
                        if(ptr1[i][j] == ptr2[x][y])
                            printf("%d\t",ptr1[i][j]);

                    }
                }
        }
    }
}

This is what it says in detail: First-chance exception at 0x002b1572 in Array.exe: 0xC0000005: Access violation reading location 0x00000002. Unhandled exception at 0x002b1572 in Array.exe: 0xC0000005: Access violation reading location 0x00000002.

Body:
when you are passing 2D array as a argument to function, you should catch with pointer to an array not with double pointer because 2D array and double pointer are not same..

    #define r 2
    #define c 2

    void intersect(int (*ptr1)[r], int (*ptr2)[c],int row, int col)
    {
           //function body
    }


问:
SQL statement, delete records where 2 fields do not match 2 fields from different table
SQL newbie here:  I have a temp table called work1 with the following fields:

company3, dept.  (and other fields that are n/a to the question)

I have a manager association table 'deptmgrassoc' that has the following fields that identify which combination of department & company a manager is over:

company3, dept, mgrid.

Let's say work1 has the following records:

company3, dept

1, a

1, b

1, c

2, a

2, b

2, c

How do I delete records from work1 where the company3 & dept combination are not in the list of company & dept combinations in the association table for Tom where his records are:

company3, dept, mgrid

1, a, tom

1, b, tom

2, a, tom

2, b, tom

The sql should delete records with 1, c & 2, c since those combinations are not in the association table.

答:
The not exists operator should do the trick:

```<code>DELETE FROM work1 w
WHERE  NOT EXISTS (SELECT *
                   FROM   deptmgrassoc d
                   WHERE  w.company3 = d.company3 AND
                          w.dept = d.dept)
</code>```

Body:
The not exists operator should do the trick:

DELETE FROM work1 w
WHERE  NOT EXISTS (SELECT *
                   FROM   deptmgrassoc d
                   WHERE  w.company3 = d.company3 AND
                          w.dept = d.dept)


问:
Removing stand-alone numbers from string in Python
There are a lot of similar questions, but I have not found a solution for my problem. I have a data frame with the following structure/form:

```<code>   col_1
0  BULKA TARTA 500G KAJO 1
1  CUKIER KRYSZTAL 1KG KSC 4
2  KASZA JĘCZMIENNA 4*100G 2 0.92
3  LEWIATAN MAKARON WSTĄŻKA 1 0.89
</code>```

However, I want to achieve the effect:

```<code>   col_1
0  BULKA TARTA 500G KAJO
1  CUKIER KRYSZTAL 1KG KSC
2  KASZA JĘCZMIENNA 4*100G
3  LEWIATAN MAKARON WSTĄŻKA
</code>```

So I want to remove the independent natural and decimal numbers, but leave the numbers in the string with the letters.

I tried to use df.col_1.str.isdigit().replace([True, False],[np.nan, df.col_1]) , but it only works on comparing the entire cell whether it is a number or not.

You have some ideas how to do it? Or maybe it would be good to break the column with spaces and then compare?

答:
Yes you can

```<code>def no_nums(col):
    return ' '.join(filter(lambda word:word.replace('.','').isdigit()==False, col.split()))
df.col_1.apply(no_nums)
</code>```

This filters out words from each value which are completely made of digits,

And maybe contains a decimal point.

If you want to filter out numbers like 1,000, simply add another replace for ','

Body:
There are a lot of similar questions, but I have not found a solution for my problem. I have a data frame with the following structure/form:

   col_1
0  BULKA TARTA 500G KAJO 1
1  CUKIER KRYSZTAL 1KG KSC 4
2  KASZA JĘCZMIENNA 4*100G 2 0.92
3  LEWIATAN MAKARON WSTĄŻKA 1 0.89

However, I want to achieve the effect:

   col_1
0  BULKA TARTA 500G KAJO
1  CUKIER KRYSZTAL 1KG KSC
2  KASZA JĘCZMIENNA 4*100G
3  LEWIATAN MAKARON WSTĄŻKA

So I want to remove the independent natural and decimal numbers, but leave the numbers in the string with the letters.

I tried to use df.col_1.str.isdigit().replace([True, False],[np.nan, df.col_1]) , but it only works on comparing the entire cell whether it is a number or not.

You have some ideas how to do it? Or maybe it would be good to break the column with spaces and then compare?

Body:
Yes you can

def no_nums(col):
    return ' '.join(filter(lambda word:word.replace('.','').isdigit()==False, col.split()))
df.col_1.apply(no_nums)

This filters out words from each value which are completely made of digits,

And maybe contains a decimal point.

If you want to filter out numbers like 1,000, simply add another replace for ','


问:
Sort a dictionary by key, and then take values from a particular key
So I have some storm data that I've sorted into dictionaries, with the key being the year the storm occurred. The value of the main dictionary is actually another dictionary, with the storm name as the key for the inner dictionary.

After I've created all the dictionaries, I ask the user for an input, and store that input as the variable year which gets passed to the function that I want to use to display the data, let's call it display_info(dictionary, year).

Sidenote: I have a main() function that actually takes the input for year, and other functions that edit and return the dictionary, so what I have here isn't complete, it's just this one function that I need help with.

```<code>year = input("Input a year: ")

def display_info(dictionary, year):
    '''Displays the storm info for the year input'''

    for k,v in dictionary.items():
        if k == year:
            print(k, v)
</code>```

I've tried a few different variations of this, but none seem to get the job done.

答:
Id just do:

```<code>if year in dictionary:
   print(year, dictionary[year])
</code>```

also, if your dictionary keys consist of type int, you will need to something like:

```<code>year = int(year)
</code>```

before running that logic.

I would not do:

int(input()) because if you input something non numeric it will raise a ValueError

Further exploiting .get(), which has a second argument which can be used to assign default values, you could just do:

```<code>print(year, dictionary.get(year, 'No entry found for year: %s' % year)
</code>```

This would print 'No entry found for year x' if the key (year) is missing from the dictionary.

Body:
So I have some storm data that I've sorted into dictionaries, with the key being the year the storm occurred. The value of the main dictionary is actually another dictionary, with the storm name as the key for the inner dictionary.

After I've created all the dictionaries, I ask the user for an input, and store that input as the variable year which gets passed to the function that I want to use to display the data, let's call it display_info(dictionary, year).

Sidenote: I have a main() function that actually takes the input for year, and other functions that edit and return the dictionary, so what I have here isn't complete, it's just this one function that I need help with.

year = input("Input a year: ")

def display_info(dictionary, year):
    '''Displays the storm info for the year input'''

    for k,v in dictionary.items():
        if k == year:
            print(k, v)

I've tried a few different variations of this, but none seem to get the job done.

Body:
Id just do:

if year in dictionary:
   print(year, dictionary[year])

also, if your dictionary keys consist of type int, you will need to something like:

year = int(year)

before running that logic.

I would not do:

int(input()) because if you input something non numeric it will raise a ValueError

Further exploiting .get(), which has a second argument which can be used to assign default values, you could just do:

print(year, dictionary.get(year, 'No entry found for year: %s' % year)

This would print 'No entry found for year x' if the key (year) is missing from the dictionary.

ContentLicense: CC BY-SA 4.0


问:
Django with MySQL deploy on aws ec2
I want to deploy my django with MySQL db for production on aws ec2. Files and db are present on the server.</p>

答: follow the official docs http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html, start directly at "Configure Your Django Application for Elastic Beanstalk", since you have already developed your app </p>

Title: Django with MySQL deploy on aws ec2


问:
Pattern matching higher-kinded parameter
I have a domain model with an ADT with 4 subcases, e.g.

```<code>sealed trait Param

case class A(...) extends Param
case class B(...) extends Param
case class C(...) extends Param
case class D(...) extends Param
</code>```

And various type parameterised on this Param, e.g.

```<code>case class Config[T <: Param](...)
case class Parser[T <: Param](...)
case class Price[T <: Param](...)
</code>```

I would love to be able to pattern match each of those:

```<code>val config: Config[T] = ???
//Assuming T <: Param, as defined above
config match {
  case confA: Config[A] =>
  case confB: Config[B] =>
  case confC: Config[C] =>
  case confD: Config[D] =>
}
</code>```

But as we know type erasure makes this a pain...

Do notice though that I always need to match a higher-kinded F[T <: Param].

Any neat ideas? I have seen shapeless typeable, but not sure it how I could use it in my case. Switching to typelevel scala (which I think solves type parameter matching, woohoo) is not an option.

Any neat ideas people? :D

EDIT:
Here is an approach I tried but run into compiler issues:

```<code>sealed trait Param

case class A() extends Param
case class B() extends Param
case class C() extends Param
case class D() extends Param

sealed trait ForParam[F[T <: Param], T <:Param] {
  def value: F[T]
}
case class ForParamA[F[_]](value: F[A]) extends ForParam[F, A]
case class ForParamB[F[_]](value: F[B]) extends ForParam[F, B]
case class ForParamC[F[_]](value: F[C]) extends ForParam[F, C]
case class ForParamD[F[_]](value: F[D]) extends ForParam[F, D]

object ForParam {
  case class Example[T <: Param](f: T => String)

  val exampleFormParam: ForParam[Example, _] = ???
  //The below does not compile:
  //  [error]      constructor cannot be instantiated to expected type;
  //  [error]       found   : ForParamD[F]
  //  [error]       required: ForParam[ForParam.Example,_$2] where type _$2
//  I think I run into issue related to https://github.com/scala/scala/pull/6069
  exampleFormParam match {
    case ForParamA(value) =>
    case ForParamB(value) =>
    case ForParamC(value) =>
    case ForParamD(value) =>
  }

}
</code>```

答:
You lost bound for type parameter in ForParamA etc.

The following code compiles:

```<code>  sealed trait Param

  case class A() extends Param
  case class B() extends Param
  case class C() extends Param
  case class D() extends Param

  sealed trait ForParam[F[_ <: Param], T <: Param] {
    def value: F[T]
  }
  case class ForParamA[F[_ <: Param]](value: F[A]) extends ForParam[F, A]
  case class ForParamB[F[_ <: Param]](value: F[B]) extends ForParam[F, B]
  case class ForParamC[F[_ <: Param]](value: F[C]) extends ForParam[F, C]
  case class ForParamD[F[_ <: Param]](value: F[D]) extends ForParam[F, D]

  object ForParam {
    case class Example[T <: Param](f: T => String)

    val exampleFormParam: ForParam[Example, _] = ???
    exampleFormParam match {
      case ForParamA(value) => ???
      case ForParamB(value) => ???
      case ForParamC(value) => ???
      case ForParamD(value) => ???
    }

  }
</code>```

Body:
I have a domain model with an ADT with 4 subcases, e.g.

sealed trait Param

case class A(...) extends Param
case class B(...) extends Param
case class C(...) extends Param
case class D(...) extends Param

And various type parameterised on this Param, e.g.

case class Config[T <: Param](...)
case class Parser[T <: Param](...)
case class Price[T <: Param](...)

I would love to be able to pattern match each of those:

val config: Config[T] = ???
//Assuming T <: Param, as defined above
config match {
  case confA: Config[A] =>
  case confB: Config[B] =>
  case confC: Config[C] =>
  case confD: Config[D] =>
}

But as we know type erasure makes this a pain...

Do notice though that I always need to match a higher-kinded F[T <: Param].

Any neat ideas? I have seen shapeless typeable, but not sure it how I could use it in my case. Switching to typelevel scala (which I think solves type parameter matching, woohoo) is not an option.

Any neat ideas people? :D

EDIT:
Here is an approach I tried but run into compiler issues:

sealed trait Param

case class A() extends Param
case class B() extends Param
case class C() extends Param
case class D() extends Param

sealed trait ForParam[F[T <: Param], T <:Param] {
  def value: F[T]
}
case class ForParamA[F[_]](value: F[A]) extends ForParam[F, A]
case class ForParamB[F[_]](value: F[B]) extends ForParam[F, B]
case class ForParamC[F[_]](value: F[C]) extends ForParam[F, C]
case class ForParamD[F[_]](value: F[D]) extends ForParam[F, D]

object ForParam {
  case class Example[T <: Param](f: T => String)

  val exampleFormParam: ForParam[Example, _] = ???
  //The below does not compile:
  //  [error]      constructor cannot be instantiated to expected type;
  //  [error]       found   : ForParamD[F]
  //  [error]       required: ForParam[ForParam.Example,_$2] where type _$2
//  I think I run into issue related to https://github.com/scala/scala/pull/6069
  exampleFormParam match {
    case ForParamA(value) =>
    case ForParamB(value) =>
    case ForParamC(value) =>
    case ForParamD(value) =>
  }

}

Body:
You lost bound for type parameter in ForParamA etc.

The following code compiles:

  sealed trait Param

  case class A() extends Param
  case class B() extends Param
  case class C() extends Param
  case class D() extends Param

  sealed trait ForParam[F[_ <: Param], T <: Param] {
    def value: F[T]
  }
  case class ForParamA[F[_ <: Param]](value: F[A]) extends ForParam[F, A]
  case class ForParamB[F[_ <: Param]](value: F[B]) extends ForParam[F, B]
  case class ForParamC[F[_ <: Param]](value: F[C]) extends ForParam[F, C]
  case class ForParamD[F[_ <: Param]](value: F[D]) extends ForParam[F, D]

  object ForParam {
    case class Example[T <: Param](f: T => String)

    val exampleFormParam: ForParam[Example, _] = ???
    exampleFormParam match {
      case ForParamA(value) => ???
      case ForParamB(value) => ???
      case ForParamC(value) => ???
      case ForParamD(value) => ???
    }

  }


问:
Execute automaticaly the script on extension
I have a script that executes  a script, but in my case the script only runs when I click on the icon: I need in my case to automatically run/inject the script when the pages loads.

My code:

```<code>chrome.browserAction.onClicked.addListener(function (tab) {
    // for the current tab, inject the "inject.js" file & execute it
    chrome.tabs.executeScript(tab.ib, {
        file: 'inject.js'
    });
});
</code>```

答:
So after looking more closer i found this solution:</p>

```<code>chrome.tabs.onUpdated.addListener(
  function ( tabId, changeInfo, tab )
  {
    if ( changeInfo.status === "complete" )
    {
      chrome.tabs.executeScript({
      file: 'inject.js'
    });
  }
});
</code>```

Body:
I have a script that executes  a script, but in my case the script only runs when I click on the icon: I need in my case to automatically run/inject the script when the pages loads.

My code:

chrome.browserAction.onClicked.addListener(function (tab) {
    // for the current tab, inject the "inject.js" file & execute it
    chrome.tabs.executeScript(tab.ib, {
        file: 'inject.js'
    });
});

Body:
So after looking more closer i found this solution:

chrome.tabs.onUpdated.addListener(
  function ( tabId, changeInfo, tab )
  {
    if ( changeInfo.status === "complete" )
    {
      chrome.tabs.executeScript({
      file: 'inject.js'
    });
  }
});


问:
How to add new column from list column value
How to unlist list column and add new column from unlist column value in data frame.Can you please find my df below.

My data Frame.

```<code>Status       AuditResult                                               Deship                                        Item

Active    list(DDID=c("2","First"),Dvalue=c("Bpin","67"))  list(UserID=1,Add="Stet,Bpin")  list(Menu=1,Bill=9,Deship =list(list(IDesc ="A",vendor=5)))

Inactive  list(DDID=c("Second","8"),Dvalue=c("CA","98"))   list(UserID=2,Add="Stet,Bpin")  list(Menu=1,Bill=8,Deship =list(list(IDesc ="B,N,O",vendor=4)))

OnHold    list(DDID=c("78","8",NA),Dvalue=c("UK","76"))   list(UserID=1,Add="Stet,Bpin")  list(Menu=1,Bill=7,Deship =list(list(IDesc ="L,q",vendor=2)))
</code>```

Expected data frame.

```<code>Status   DDID          Dvalue         UserID    Add         Menu  Bill  IDesc    vendor

Active   "2","First"   "Bpin","67"    1       "Stet,Bpin"    1     9     "A"        5

Inactive "Second","8"  "CA","98"      2       "Stet,Bpin"    1     8     "B,N,O"    4

OnHold   "78","8",NA   "UK","76"      1       "Stet,Bpin"    1     7     "L,q"      2
</code>```

please suggest me if any unstructured code.

Dput.

```<code>structure(list(Status = c("Active", "Inactive", "OnHold"), AuditResult = list(
    structure(list(DDID = c(2, "First"), Dvalue = c("Bpin",
    67)), .Names = c("DDID", "Dvalue"), class = "data.frame", row.names = 1:2),
    structure(list(DDID = c("Second", 8), Dvalue = c("CA",
    98)), .Names = c("DDID", "Dvalue"), class = "data.frame", row.names = 1:2),
    structure(list(DDID = c("78","8",NA), Dvalue = c("UK",
    76)), .Names = c("DDID", "Dvalue"), class = "data.frame", row.names = 1:2)),
    Deship = list(structure(list(UserID = 1, Add = "Stet, Bpin"), .Names = c("UserID",
    "Add"), class = "data.frame", row.names = 1L), structure(list(
        UserID = 2, Add = "Stet, Bpin"), .Names = c("UserID",
    "Add"), class = "data.frame", row.names = 1L), structure(list(
        UserID = 1, Add = "Stet, Bpin"), .Names = c("UserID",
    "Add"), class = "data.frame", row.names = 1L)), Item = list(
structure(list(Menu = 1, Bill = 9.0, Deship = list(
            structure(list(IDesc = "A", vendor = 5), .Names = c("IDesc",
            "vendor"), class = "data.frame", row.names = 1L))), .Names = c("Menu",
        "Bill", "Deship"), class = "data.frame", row.names = 1L),
        structure(list(Menu = 1, Bill = 8.0, Deship = list(
            structure(list(IDesc = "B,N,O", vendor = 4), .Names = c("IDesc",
            "vendor"), class = "data.frame", row.names = 1L))), .Names = c("Menu",
        "Bill", "Deship"), class = "data.frame", row.names = 1L),
        structure(list(Menu = 1, Bill = 7.0, Deship = list(
            structure(list(IDesc = "L,q", vendor = 2), .Names = c("IDesc",
            "vendor"), class = "data.frame", row.names = 1L))), .Names = c("Menu",
        "Bill", "Deship"), class = "data.frame", row.names = 1L))), .Names = c("Status",
"AuditResult", "Deship", "Item"), row.names = c(NA,
3L), class = "data.frame")
</code>```

答:
As each of the list columns has a different structure, you'll have to deal with them in different ways.

With base R:

```<code>dfnew <- data.frame(df$Status,
                    do.call(rbind, lapply(df$AuditResult, function(x) sapply(x, toString))),
                    do.call(rbind, df$Deship),
                    do.call(rbind, lapply(df$Item, unlist)))
names(dfnew) <- sub('^.*\\.','',names(dfnew))
</code>```

which gives:

```<code>> dfnew
    Status      DDID   Dvalue UserID        Add Menu Bill IDesc vendor
1   Active  2, First Bpin, 67      1 Stet, Bpin    1    9     A      5
2 Inactive Second, 8   CA, 98      2 Stet, Bpin    1    8 B,N,O      4
3   OnHold 78, 8, NA   UK, 76      1 Stet, Bpin    1    7   L,q      2
</code>```

Body:
How to unlist list column and add new column from unlist column value in data frame.Can you please find my df below.

My data Frame.

Status       AuditResult                                               Deship                                        Item

Active    list(DDID=c("2","First"),Dvalue=c("Bpin","67"))  list(UserID=1,Add="Stet,Bpin")  list(Menu=1,Bill=9,Deship =list(list(IDesc ="A",vendor=5)))

Inactive  list(DDID=c("Second","8"),Dvalue=c("CA","98"))   list(UserID=2,Add="Stet,Bpin")  list(Menu=1,Bill=8,Deship =list(list(IDesc ="B,N,O",vendor=4)))

OnHold    list(DDID=c("78","8",NA),Dvalue=c("UK","76"))   list(UserID=1,Add="Stet,Bpin")  list(Menu=1,Bill=7,Deship =list(list(IDesc ="L,q",vendor=2)))

Expected data frame.

Status   DDID          Dvalue         UserID    Add         Menu  Bill  IDesc    vendor

Active   "2","First"   "Bpin","67"    1       "Stet,Bpin"    1     9     "A"        5

Inactive "Second","8"  "CA","98"      2       "Stet,Bpin"    1     8     "B,N,O"    4

OnHold   "78","8",NA   "UK","76"      1       "Stet,Bpin"    1     7     "L,q"      2

please suggest me if any unstructured code.

Dput.

structure(list(Status = c("Active", "Inactive", "OnHold"), AuditResult = list(
    structure(list(DDID = c(2, "First"), Dvalue = c("Bpin",
    67)), .Names = c("DDID", "Dvalue"), class = "data.frame", row.names = 1:2),
    structure(list(DDID = c("Second", 8), Dvalue = c("CA",
    98)), .Names = c("DDID", "Dvalue"), class = "data.frame", row.names = 1:2),
    structure(list(DDID = c("78","8",NA), Dvalue = c("UK",
    76)), .Names = c("DDID", "Dvalue"), class = "data.frame", row.names = 1:2)),
    Deship = list(structure(list(UserID = 1, Add = "Stet, Bpin"), .Names = c("UserID",
    "Add"), class = "data.frame", row.names = 1L), structure(list(
        UserID = 2, Add = "Stet, Bpin"), .Names = c("UserID",
    "Add"), class = "data.frame", row.names = 1L), structure(list(
        UserID = 1, Add = "Stet, Bpin"), .Names = c("UserID",
    "Add"), class = "data.frame", row.names = 1L)), Item = list(
structure(list(Menu = 1, Bill = 9.0, Deship = list(
            structure(list(IDesc = "A", vendor = 5), .Names = c("IDesc",
            "vendor"), class = "data.frame", row.names = 1L))), .Names = c("Menu",
        "Bill", "Deship"), class = "data.frame", row.names = 1L),
        structure(list(Menu = 1, Bill = 8.0, Deship = list(
            structure(list(IDesc = "B,N,O", vendor = 4), .Names = c("IDesc",
            "vendor"), class = "data.frame", row.names = 1L))), .Names = c("Menu",
        "Bill", "Deship"), class = "data.frame", row.names = 1L),
        structure(list(Menu = 1, Bill = 7.0, Deship = list(
            structure(list(IDesc = "L,q", vendor = 2), .Names = c("IDesc",
            "vendor"), class = "data.frame", row.names = 1L))), .Names = c("Menu",
        "Bill", "Deship"), class = "data.frame", row.names = 1L))), .Names = c("Status",
"AuditResult", "Deship", "Item"), row.names = c(NA,
3L), class = "data.frame")

Body:
As each of the list columns has a different structure, you'll have to deal with them in different ways.

With base R:

dfnew <- data.frame(df$Status,
                    do.call(rbind, lapply(df$AuditResult, function(x) sapply(x, toString))),
                    do.call(rbind, df$Deship),
                    do.call(rbind, lapply(df$Item, unlist)))
names(dfnew) <- sub('^.*\\.','',names(dfnew))

which gives:

> dfnew
    Status      DDID   Dvalue UserID        Add Menu Bill IDesc vendor
1   Active  2, First Bpin, 67      1 Stet, Bpin    1    9     A      5
2 Inactive Second, 8   CA, 98      2 Stet, Bpin    1    8 B,N,O      4
3   OnHold 78, 8, NA   UK, 76      1 Stet, Bpin    1    7   L,q      2


问:
R ggplot2: geom_text error (object not found)... aes() clashing?
I just want to add Kruskal-Wallis test results that I compute outside the plot, at the top of some boxplots. I know I could calculate kruskal.test in the same geom_text line, but in this case I'd rather keep it outside since I already have it.

Please check the following MWE:

```<code>library(reshape2)
library(ggplot2)
data(iris)
iris$treatment <- rep(c("A","B"), length(iris$Species)/2)
mydf <- melt(iris, measure.vars=names(iris)[1:4])
head(mydf)
mydf$both <- factor(paste(mydf$treatment, mydf$variable, sep=' -- '), levels=(unique(paste(mydf$treatment, mydf$variable, sep=' -- '))))

##Signif levels comparing treatments per Species (regardless of variable)
addkw1 <- as.data.frame(mydf %>% group_by(Species) %>%
                       summarize(p.value = wilcox.test(value ~ treatment)$p.value)) #no need for kruskal, only 2 treatments
##Signif levels comparing variable per Species (regardless of treatment)
addkw2 <- as.data.frame(mydf %>% group_by(Species) %>%
                       summarize(p.value = kruskal.test(value ~ variable)$p.value))
##Signif levels comparing treatment+variable per Species
addkw3 <- as.data.frame(mydf %>% group_by(Species) %>%
                        summarize(p.value = kruskal.test(value ~ both)$p.value))
addkw1$TEST <- "Treatment"
addkw2$TEST <- "Variable"
addkw3$TEST <- "Treat:Var"
addkw <- rbind(addkw1, addkw2, addkw3)
addkw$p.adjust <- p.adjust(addkw$p.value, "BH")
addkw

sp <- "setosa"
addkw0 <- subset(addkw, Species==sp)
df0 <- subset(mydf, Species==sp)

pdf(file="test.df", height=15, width=15)
print(
  ggplot(df0, aes(x=both, y=value, fill=both)) + geom_boxplot() +
    stat_summary(fun.y=mean, geom="point", shape=5, size=4) +
    geom_text(data=addkw0,aes(x=0, y=0, label=p.adjust))
)
dev.off()
</code>```

As you can see, I just want to plot the boxplots for setosa, for which I have 3 Kruskal-Wallis p-values. I would like 3 lines at the top of the boxplot, like:

```<code>KW p-value Treatment = 9.96e01
KW p-value Variable = 1.92e39
KW p-value Treat:Var = 1.18e36
</code>```

However, I get the following error which I do not know how to solve... my guess is there might be some clashing between the ggplot aes() and the geom_text aes().

Error in FUN(X[[i]], ...) : object 'both' not found

EDIT

Thanks to @baptiste's comment, I managed to avoid the error, but I still struggle at printing the 3 lines with the 3 KW values... Any help?

This is the new code:

```<code>png(filename="test.png")
print(
  ggplot(df0, aes(x=both, y=value)) + geom_boxplot(aes(fill=both)) +
  stat_summary(fun.y=mean, geom="point", shape=5, size=4) +
  geom_text(data=addkw0, aes(x=0, y=0, label=paste0("KW pv = ", formatC(p.adjust, format="e", digits=2))), hjust=0)
)
dev.off()
</code>```

which produces this:

答:
To control the position of geom_text you need to specify the coordinates of each label. Since for all three strings you have specified x = 0 and y = 0 in the geom_text call they overlap.

```<code>ggplot(df0, aes(x = both, y = value)) + geom_boxplot(aes(fill = both)) +
  stat_summary(fun.y = mean, geom = "point", shape = 5, size = 4) +
  geom_text(data = addkw0, aes(x = 7, y = c(4.5, 5, 5.5),
                               label = paste0("KW pv = ", formatC(p.adjust, format="e", digits=2))), hjust = 0)
</code>```

for other applications, like labeling with text on top of each bar, one would need to calculate the appropriate coordinates before hand and incorporate them in  a data frame corresponding to addkw0.

Body:
I just want to add Kruskal-Wallis test results that I compute outside the plot, at the top of some boxplots. I know I could calculate kruskal.test in the same geom_text line, but in this case I'd rather keep it outside since I already have it.

Please check the following MWE:

library(reshape2)
library(ggplot2)
data(iris)
iris$treatment <- rep(c("A","B"), length(iris$Species)/2)
mydf <- melt(iris, measure.vars=names(iris)[1:4])
head(mydf)
mydf$both <- factor(paste(mydf$treatment, mydf$variable, sep=' -- '), levels=(unique(paste(mydf$treatment, mydf$variable, sep=' -- '))))

##Signif levels comparing treatments per Species (regardless of variable)
addkw1 <- as.data.frame(mydf %>% group_by(Species) %>%
                       summarize(p.value = wilcox.test(value ~ treatment)$p.value)) #no need for kruskal, only 2 treatments
##Signif levels comparing variable per Species (regardless of treatment)
addkw2 <- as.data.frame(mydf %>% group_by(Species) %>%
                       summarize(p.value = kruskal.test(value ~ variable)$p.value))
##Signif levels comparing treatment+variable per Species
addkw3 <- as.data.frame(mydf %>% group_by(Species) %>%
                        summarize(p.value = kruskal.test(value ~ both)$p.value))
addkw1$TEST <- "Treatment"
addkw2$TEST <- "Variable"
addkw3$TEST <- "Treat:Var"
addkw <- rbind(addkw1, addkw2, addkw3)
addkw$p.adjust <- p.adjust(addkw$p.value, "BH")
addkw

sp <- "setosa"
addkw0 <- subset(addkw, Species==sp)
df0 <- subset(mydf, Species==sp)

pdf(file="test.df", height=15, width=15)
print(
  ggplot(df0, aes(x=both, y=value, fill=both)) + geom_boxplot() +
    stat_summary(fun.y=mean, geom="point", shape=5, size=4) +
    geom_text(data=addkw0,aes(x=0, y=0, label=p.adjust))
)
dev.off()

As you can see, I just want to plot the boxplots for setosa, for which I have 3 Kruskal-Wallis p-values. I would like 3 lines at the top of the boxplot, like:

KW p-value Treatment = 9.96e01
KW p-value Variable = 1.92e39
KW p-value Treat:Var = 1.18e36

However, I get the following error which I do not know how to solve... my guess is there might be some clashing between the ggplot aes() and the geom_text aes().

Error in FUN(X[[i]], ...) : object 'both' not found

EDIT

Thanks to @baptiste's comment, I managed to avoid the error, but I still struggle at printing the 3 lines with the 3 KW values... Any help?

This is the new code:

png(filename="test.png")
print(
  ggplot(df0, aes(x=both, y=value)) + geom_boxplot(aes(fill=both)) +
  stat_summary(fun.y=mean, geom="point", shape=5, size=4) +
  geom_text(data=addkw0, aes(x=0, y=0, label=paste0("KW pv = ", formatC(p.adjust, format="e", digits=2))), hjust=0)
)
dev.off()

which produces this:

Body:
To control the position of geom_text you need to specify the coordinates of each label. Since for all three strings you have specified x = 0 and y = 0 in the geom_text call they overlap.

ggplot(df0, aes(x = both, y = value)) + geom_boxplot(aes(fill = both)) +
  stat_summary(fun.y = mean, geom = "point", shape = 5, size = 4) +
  geom_text(data = addkw0, aes(x = 7, y = c(4.5, 5, 5.5),
                               label = paste0("KW pv = ", formatC(p.adjust, format="e", digits=2))), hjust = 0)

for other applications, like labeling with text on top of each bar, one would need to calculate the appropriate coordinates before hand and incorporate them in  a data frame corresponding to addkw0.


问:
Garble JavaScript code before sending to client-side
How can I garble JavaScript code before sending it to client-side? I don't want to expose functionalities. The code is already compressed using jsmin.

答: A word of warning: most obfuscated JS on the internet is security hole exploit code. You risk being mistaken for a sploit, particularly by the more paranoid anti-virus scanners.</p>

OwnerDisplayName: Rakesh

OwnerDisplayName: bobince


问:
DIV height like having some text inside
On one of my web pages I have a DIV element, containing string of text inside, which is of, say, 1.1em size. For example:

```<code><div id="displaydiv">
    <b>Hello World</b>
</div>
</code>```

Another page has the same DIV element, but with no text inside it at all. And that's why this DIV has the visual height of less value than the one on the first page.

```<code><div id="displaydiv">

</div>
</code>```

What is the recommended way of keeping the DIV element on the second page of the same height as on the first one?

答:
If you would like it to be the same height as on the other page, you could do this by passing a parameter to the next page, like with $_GET in PHP.

You could use jQuery to exactly measure the height of your div (with .height()). Then, when going to your new page, you should do something like: myDomain.com/newPage?height=500. Use PHP to evaluate your new height in the new page.

Title: DIV height like having some text inside

Body:
On one of my web pages I have a DIV element, containing string of text inside, which is of, say, 1.1em size. For example:

    Hello World

Another page has the same DIV element, but with no text inside it at all. And that's why this DIV has the visual height of less value than the one on the first page.

What is the recommended way of keeping the DIV element on the second page of the same height as on the first one?


问:
How to use require_relative with an rspec test?
I have an rspec test, i.e. describe and an it

I want to add before :all and before :each behavior

I can add it by putting in the test spec file directly, i.e.

```<code>describe "test" do
  before :all do
    CONTINUE_SPEC= true
  end

  around :each do |example|
    if CONTINUE_SPEC
      CONTINUE_SPEC = false
      example.run
      CONTINUE_SPEC = true unless example.exception
    else
      example.skip
    end
  end
  ... actual tests...
</code>```

However I want to have it in nearly every spec so I thought I could use a require_relative statement to make it easy.  However when I transfer the code to a file using require_relative with

```<code>require_relative '../../support/continue_test_if_passing'
</code>```

I get

```<code>Failure/Error:
  before :all do
    CONTINUE_SPEC= true
  end

NoMethodError:
  undefined method `before' for main:Object
</code>```

答:
Just add this to your spec_helper.rb in the RSpec.configure block:

```<code>RSpec.configure do |config|
  config.before :all do
    CONTINUE_SPEC= true
  end

  config.around :each do |example|
    if CONTINUE_SPEC
      CONTINUE_SPEC = false
      example.run
      CONTINUE_SPEC = true unless example.exception
    else
      example.skip
    end
  end

  # ...
end
</code>```

Body:
I have an rspec test, i.e. describe and an it

I want to add before :all and before :each behavior

I can add it by putting in the test spec file directly, i.e.

describe "test" do
  before :all do
    CONTINUE_SPEC= true
  end

  around :each do |example|
    if CONTINUE_SPEC
      CONTINUE_SPEC = false
      example.run
      CONTINUE_SPEC = true unless example.exception
    else
      example.skip
    end
  end
  ... actual tests...

However I want to have it in nearly every spec so I thought I could use a require_relative statement to make it easy.  However when I transfer the code to a file using require_relative with

require_relative '../../support/continue_test_if_passing'

I get

Failure/Error:
  before :all do
    CONTINUE_SPEC= true
  end

NoMethodError:
  undefined method `before' for main:Object

Body:
Just add this to your spec_helper.rb in the RSpec.configure block:

RSpec.configure do |config|
  config.before :all do
    CONTINUE_SPEC= true
  end

  config.around :each do |example|
    if CONTINUE_SPEC
      CONTINUE_SPEC = false
      example.run
      CONTINUE_SPEC = true unless example.exception
    else
      example.skip
    end
  end

  # ...
end


问:
Eclipse doesn't report errors until runtime
I was trying to do some messy tricks to carry in an IMarker a ProblemDescriptor object.

ProblemDescriptor problem = new ProblemDescriptor(... my arguments...);
marker.setAttribute("PROBLEM_DESCRIPTOR", problem);

Later on I wanted to check if the attribute is set, make use of the informations from it.

The error is not reported while developing but at runtime I get the error:

The attribute value type is com.localhost.problems.ProblemDescription and expected is one of java.lang.String, Boolean, Integer

Is it a special case/a bad implementation in that code or I should get used with those kinds of errors reported only at runtime?

答:
The setAttribute method you are using is

```<code>public void setAttribute(String attributeName, Object value)
</code>```

Since the second argument is Object no check for correctness can be done at compile time, however the Javadoc for this clearly says:

Sets the attribute with the given name. The value must be null or an
  instance of one of the following classes: String, Integer, or Boolean.
  If the value is null, the attribute is considered to be undefined.

The attribute value cannot be a String whose UTF encoding exceeds 65535
  bytes. On persistent markers this limit is enforced by an assertion.

An alternative design would have been to replace this with 3 methods with a String, Integer and Boolean second argument but the API designers decided not to do that.

Body:
The setAttribute method you are using is

public void setAttribute(String attributeName, Object value)

Since the second argument is Object no check for correctness can be done at compile time, however the Javadoc for this clearly says:

Sets the attribute with the given name. The value must be null or an
  instance of one of the following classes: String, Integer, or Boolean.
  If the value is null, the attribute is considered to be undefined.

The attribute value cannot be a String whose UTF encoding exceeds 65535
  bytes. On persistent markers this limit is enforced by an assertion.

An alternative design would have been to replace this with 3 methods with a String, Integer and Boolean second argument but the API designers decided not to do that.


问:
How to restrict buffering in video steaming in android
I want to restrict buffering after pausing a video in android. When I pause the video player, the video stops but buffering does not. It continues to consume data. I want to stop data to be consumed.
Thanks in advance.</p>

答: With a standard mp4/webm, you can’t. It’s totally up the the browser. If you use fragmented mp4 and feed the buffer via MSE and Ajax, you can do whatever you want. But it’s a thousand time more work on your part. </p>


问:
Can't import the HashAlgorithmProviders nor the CryptographicBuffer Class
I'm trying to create an MD hash using the following code I found from Alireza Noori. But I cannot import both the HashAlgorithmProviders nor the CryptographicBuffer Classes. Even when I try to manually add them using the following packages:

```<code>using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage;
</code>```

How come I cannot import these classes do they need to be installed?

答:
It's apparent your using statements are incorrect, they should look something like:

```<code>using System.Windows.Security.Cryptography; // CryptographicBuffer Class package
using System.Windows.Security.Cryptography.Core; // HashAlgorithmProviders Class package
using Windows.Storage.Streams;
</code>```

You have to manually either of these .dlll frameworks, depending on your .Net Framework version
Goto:

Project >> Add Reference >> Framework >> Add System.Web.ApplicationServices +
 (.Net 4.5+)

or

Project >> Add Reference >> Framework >> Add System.Web.Security - (.Net 4.0)

Body:
I'm trying to create an MD hash using the following code I found from Alireza Noori. But I cannot import both the HashAlgorithmProviders nor the CryptographicBuffer Classes. Even when I try to manually add them using the following packages:

using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage;

How come I cannot import these classes do they need to be installed?

Body:
It's apparent your using statements are incorrect, they should look something like:

using System.Windows.Security.Cryptography; // CryptographicBuffer Class package
using System.Windows.Security.Cryptography.Core; // HashAlgorithmProviders Class package
using Windows.Storage.Streams;

You have to manually either of these .dlll frameworks, depending on your .Net Framework version
Goto:

Project >> Add Reference >> Framework >> Add System.Web.ApplicationServices +
 (.Net 4.5+)

or

Project >> Add Reference >> Framework >> Add System.Web.Security - (.Net 4.0)


问:
invalid initialization of non-const reference of type ‘std::string& from an rvalue of type ‘std::basic_string<char>
```<code>bool hasWord(int y, int x, string &word) {
    if(!inRange(y, x)) return false;
    if(board[y][x] != word[0])  return false;
    if(word.size() == 1) return true;
    for(int direction = 0; direction < 8; direction++) {
        int nextX = x + dx[direction];
        int nextY = y + dy[direction];
        if(hasWord(nextY, nextX, word.substr(1)))  // <--- This
            return true;
    }
return false; }
</code>```

error: invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ from an rvalue of type ‘std::basic_string’
   if(hasWord(nextY, nextX, word.substr(1)))

why the reason I was wrong?

答:
The error message says it all: invalid initialization of non-const reference of type std::string {aka std::basic_string} from an rvalue of type std::basic_string.

I.e. a reference to non-const cannot be bound to a temporary object (aka r-value). That temporary object is created by word.substr(1) expression.

In declaration:

```<code>bool hasWord(int y, int x, string &word)
</code>```

Make it string const& word, since you do not need a modifiable word.

Body:
bool hasWord(int y, int x, string &word) {
    if(!inRange(y, x)) return false;
    if(board[y][x] != word[0])  return false;
    if(word.size() == 1) return true;
    for(int direction = 0; direction < 8; direction++) {
        int nextX = x + dx[direction];
        int nextY = y + dy[direction];
        if(hasWord(nextY, nextX, word.substr(1)))  // <--- This
            return true;
    }
return false; }

error: invalid initialization of non-const reference of type ‘std::string& {aka std::basic_string&}’ from an rvalue of type ‘std::basic_string’
   if(hasWord(nextY, nextX, word.substr(1)))

why the reason I was wrong?

Body:
The error message says it all: invalid initialization of non-const reference of type std::string {aka std::basic_string} from an rvalue of type std::basic_string.

I.e. a reference to non-const cannot be bound to a temporary object (aka r-value). That temporary object is created by word.substr(1) expression.

In declaration:

bool hasWord(int y, int x, string &word)

Make it string const& word, since you do not need a modifiable word.


问:
Converting milliseconds to Timestamp in Java
I am using System.currentTimeMillis() and adding the value of a day/week/month based on user input. How can I convert this to java.sql.Timestamp so I can save it in mysql? Thanks.</p>

答:
This code snippet is used to convert timestamp in milliseconds to Unix based java.sql.Timestamp   </p>

```<code>/**
     * Convert the epoch time to TimeStamp
     *
     * @param timestampInString timestamp as string
     * @return date as timestamp
     */
    public static Timestamp getTimestamp(String timestampInString) {
        if (StringUtils.isNotBlank(timestampInString) && timestampInString != null) {
            Date date = new Date(Long.parseLong(timestampInString));
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
            String formatted = format.format(date);
            Timestamp timeStamp = Timestamp.valueOf(formatted);
            return timeStamp;
        } else {
            return null;
        }
    }
</code>```

Body:
This code snippet is used to convert timestamp in milliseconds to Unix based java.sql.Timestamp

/**
     * Convert the epoch time to TimeStamp
     *
     * @param timestampInString timestamp as string
     * @return date as timestamp
     */
    public static Timestamp getTimestamp(String timestampInString) {
        if (StringUtils.isNotBlank(timestampInString) && timestampInString != null) {
            Date date = new Date(Long.parseLong(timestampInString));
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
            String formatted = format.format(date);
            Timestamp timeStamp = Timestamp.valueOf(formatted);
            return timeStamp;
        } else {
            return null;
        }
    }


问:
AJAX timing in IE
Chrome has its developer tools that times ajax latency, firefox has firebug, but what do you do in IE? I would have thought firebug lite, but apparently it doesn't time ajax calls (at least not in IE6). How do you do it?</p>

答:
You can always write your own timing code.  Grab the start time before your Ajax call and get the end time from your callback function.

```<code>startTime = new Date().getTime();
//Make your Ajax call

function someCallback() {
  endTime = new Date().getTime();
}

alert((endTime - startTime) + " millis have elapsed.");
</code>```

If you are using jQuery you can use the .ajaxSend and .ajaxComplete functions to register event handlers that can do the timings.

Title: AJAX timing in IE

Body:
You can always write your own timing code.  Grab the start time before your Ajax call and get the end time from your callback function.

startTime = new Date().getTime();
//Make your Ajax call

function someCallback() {
  endTime = new Date().getTime();
}

alert((endTime - startTime) + " millis have elapsed.");

If you are using jQuery you can use the .ajaxSend and .ajaxComplete functions to register event handlers that can do the timings.


问:
How to connect to newly installed Oracle XE instance?
I have installed Oracle XE on Win7 x64 machine. Installation completed successfully without problem, or perhaps installer didn't tell about them. But after installation I can't connect to database; its web interface is not working. I have looked through list of open ports, and there is no 8080 port as was noted during installation. Also I can't connect via SQLPlus.

```<code>SQL> connect SYSTEM
Enter password:
ERROR:
ORA-12638: Credential retrieval failed
</code>```

Somewhere in the web it was told to edit sqlnet.ora file, I have changed it in the following way:

```<code># SQLNET.AUTHENTICATION_SERVICES = (NTS)
SQLNET.AUTHENTICATION_SERVICES = (NONE)
</code>```

and now I get next error

```<code>SQL> connect SYSTEM
Enter password:
ERROR:
ORA-01034: ORACLE not available
ORA-27101: shared memory realm does not exist
</code>```

What do I need to change so that I can connect to it?

答:
Sorry for answering this YEARS old question, but I managed to make it work...

Make sqlnet.ora change.

Run StopDB.bat

Run MakeDB.bat

This will create a demo database, reset the password to 'oracle', and will also allow you to connect without error.

Body:
I have installed Oracle XE on Win7 x64 machine. Installation completed successfully without problem, or perhaps installer didn't tell about them. But after installation I can't connect to database; its web interface is not working. I have looked through list of open ports, and there is no 8080 port as was noted during installation. Also I can't connect via SQLPlus.

SQL> connect SYSTEM
Enter password:
ERROR:
ORA-12638: Credential retrieval failed

Somewhere in the web it was told to edit sqlnet.ora file, I have changed it in the following way:

# SQLNET.AUTHENTICATION_SERVICES = (NTS)
SQLNET.AUTHENTICATION_SERVICES = (NONE)

and now I get next error

SQL> connect SYSTEM
Enter password:
ERROR:
ORA-01034: ORACLE not available
ORA-27101: shared memory realm does not exist

What do I need to change so that I can connect to it?


问:
Close someone else's code review TFS 2015
I am in charge of a team of developers that has experienced a high rate of turnover.  I have 100 some code reviews in "requested" status because the developer didn't close them before leaving the company.  I took ownership of these in TFS by right clicking and assigning to myself, but it is not giving me the option of closing.

According to this link I should be able to download an excel sheet and do a "bulk" update:

Please try this workaround: create a work query to get all that user’s Code Review Request work items which in Requested state, save this work item query and open this query in Excel, then edit them work items in Excel to change the state to Closed, then click Publish button to publish the updates to TFS Server.

I do not see any way to do this either.

What are my options here?

答:
All code review requests are in fact a TFS work item. You can close them in bulk by bulk updating them using Excel, just as you would do for any other work item.

The way to do is to open your code reviews query from the link on the top right of Code Reviews section in Team Explorer

Once you are in query mode, click on "Save query" to save your code review query. Now click on the "Open query in Excel" button

This would open up an excel sheet for you. Change the State of each of code review work item that you would like to update. Then click on the the Team menu and use the "Publish" button to make your changes in TFS.


问:
Append data frames from multiple files in a for loop
I have a script that creates a data frame from a *xlsx file. Now I would like to add a loop on top of the script that will read multiple files and append the data frames together by row. All of the column names will match. I have sample code below with what I have so far. From what I can tell, the script is reading both files but each file is writing over the previous one instead of appending to the previous. Any help would be appreciated!</p>

```<code>filenames <- Sys.glob("*.xlsx")
data.files = list.files(pattern = "*.xlsx")

datalist = list()

for( title in c(paste(filenames , sep="."))) {
    # ... make some data (final table named "Stats")
    df <- data.frame(Stats)
    df$title <- title    # to keep track of file
    datalist[[title]] <- df    # add it to your list
}

big_data = do.call(rbind, datalist)
</code>```

答:
Why don't you try to append data.frames in a loop? Something like:

```<code>final.df <- data.frame()
for( title in c(paste(filenames , sep="."))) {
    # ... make some data (final table named "Stats")
    df <- data.frame(Stats)
    final.df <- rbind(final.df, df)
}

big_data <- final.df
</code>```

There may be some problems with columns, but you can recognize first data frame and just substitute final.df with the first one.

Body:
I have a script that creates a data frame from a *xlsx file. Now I would like to add a loop on top of the script that will read multiple files and append the data frames together by row. All of the column names will match. I have sample code below with what I have so far. From what I can tell, the script is reading both files but each file is writing over the previous one instead of appending to the previous. Any help would be appreciated!

filenames <- Sys.glob("*.xlsx")
data.files = list.files(pattern = "*.xlsx")

datalist = list()

for( title in c(paste(filenames , sep="."))) {
    # ... make some data (final table named "Stats")
    df <- data.frame(Stats)
    df$title <- title    # to keep track of file
    datalist[[title]] <- df    # add it to your list
}

big_data = do.call(rbind, datalist)

Body:
Why don't you try to append data.frames in a loop? Something like:

final.df <- data.frame()
for( title in c(paste(filenames , sep="."))) {
    # ... make some data (final table named "Stats")
    df <- data.frame(Stats)
    final.df <- rbind(final.df, df)
}

big_data <- final.df

There may be some problems with columns, but you can recognize first data frame and just substitute final.df with the first one.