问:
php namespace and autoload
I have some class

/library/QPF/Loader.php

```<code>namespace QPF;

class Loader
{
    protected static $loader = null;

    public function __construct()
    {
        spl_autoload_register('QPF\Loader::_autoload');
    }

    public static function init()
    {
        if (null === self::$loader) {
            self::$loader = new Loader();
        }
        return self::$loader;
    }

    public function _autoload($class)
    {
        //if (class_exists($class)) return true;

        $classFile = str_replace('\\', '/', $class) . '.php';
        require_once $classFile;
        if (!class_exists($class)) throw new Extension('Not found class');

    }
}
</code>```

/library/Version.php

```<code>namespace QPF;

class Version
{
    public function getVersion()
    {
        return '0.1';
    }
}
</code>```

/public/index.php

```<code>set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../library');
define('APPLICATION_PATH', dirname(__FILE__) . '/../application');

require_once 'QPF/Loader.php';
QPF\Loader::init();

echo 'start';

use QPF;

$v = new QPF\Version();
var_dump($v);

echo 'ss';
</code>```

Version class loading, but var_dump show what it's empty class without function getVersion();

```<code>startobject(QPF\Version)#2 (0) { } ss
</code>```

答: Methods do not show up in var_dump or print_r output, as they are not part of the state of the object. Try calling the method; it should work as expected.

Title: php namespace and autoload

Body:
I have some class

/library/QPF/Loader.php

namespace QPF;

class Loader
{
    protected static $loader = null;

    public function __construct()
    {
        spl_autoload_register('QPF\Loader::_autoload');
    }

    public static function init()
    {
        if (null === self::$loader) {
            self::$loader = new Loader();
        }
        return self::$loader;
    }

    public function _autoload($class)
    {
        //if (class_exists($class)) return true;

        $classFile = str_replace('\\', '/', $class) . '.php';
        require_once $classFile;
        if (!class_exists($class)) throw new Extension('Not found class');

    }
}

/library/Version.php

namespace QPF;

class Version
{
    public function getVersion()
    {
        return '0.1';
    }
}

/public/index.php

set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/../library');
define('APPLICATION_PATH', dirname(__FILE__) . '/../application');

require_once 'QPF/Loader.php';
QPF\Loader::init();

echo 'start';

use QPF;

$v = new QPF\Version();
var_dump($v);

echo 'ss';

Version class loading, but var_dump show what it's empty class without function getVersion();

startobject(QPF\Version)#2 (0) { } ss


来源: stackexchange

问:
OdbcParameter error - size of 0 for varchar(MAX) output parameter
I'm using:

Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
  Dec 28 2012 20:23:12

  Copyright (c) Microsoft Corporation   Enterprise Edition (64-bit) on Windows NT 6.2  (Build 9200: ) (Hypervisor)

I have a stored procedure which has a varchar(MAX) output parameter.

I'm calling it via an OdbcCommand and I've created a VarChar output parameter and added it to the OdbcCommand Parameters list:

```<code>new OdbcParameter("@MaxField", OdbcType.VarChar)
    { Direction = ParameterDirection.Output, Size = -1 })
</code>```

While debugging I can see that the Size field on the parameter is still -1 but when I run the query using OdbcCommand.ExecuteNonQuery() I get the following exception:

System.InvalidOperationException was unhandled

  HResult=-2146233079

  Message=String[2]: the Size property has an invalid size of 0.

  Source=System.Data

  StackTrace:

         at System.Data.Odbc.OdbcParameter.GetParameterSize(Object value, Int32 offset, Int32 ordinal)

         at System.Data.Odbc.OdbcParameter.PrepareForBind(OdbcCommand command, Int16 ordinal, Int32& parameterBufferSize)

         at System.Data.Odbc.OdbcParameterCollection.CalcParameterBufferSize(OdbcCommand
  command)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader, Object[] methodArguments,
  SQL_API odbcApiMethod)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader)

         at System.Data.Odbc.OdbcCommand.ExecuteNonQuery()

I tried using the OdbcCommandBuilder.DeriveParameters(odbcCommand); to examine the parameter information derived from the stored procedure and it said that the parameter had a Size of 2147483647 - however, if I try and use that value I get a different exception telling me

System.Data.Odbc.OdbcException was unhandled

  ErrorCode=-2146232009

  HResult=-2146232009

  Message=ERROR [42000] [Microsoft][ODBC SQLServer Driver][SQL Server]Invalid parameter 2 (''):  Data type 0x23 is
  a deprecated large object, or LOB, but is marked as output parameter.
  Deprecated types are not supported as output parameters.  Use current
  large object types instead.   Source=SQLSRV32.DLL   StackTrace:

         at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader, Object[] methodArguments,
  SQL_API odbcApiMethod)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader)

         at System.Data.Odbc.OdbcCommand.ExecuteNonQuery()

How should I configure my OdbcCommand output parameter to receive this output from the stored procedure?

This is on an existing, in-production database so trying to change the datatype of the field is sadly the absolute last resort. The field that is being selected is varchar(max).

Edit: If the actual answer is "You just can't" then that would be acceptable - at least I would know for sure.

答:
If you want to stick with System.Data.Odbc then the following workaround might suffice. For the stored procedure

CREATE PROCEDURE [dbo].[HodorSpeaks]
    @repeat int = 1,
    @response varchar(max) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @whatHeSaid varchar(max);
    SET @whatHeSaid = 'HODOR! ';
    SELECT @response = REPLICATE(@whatHeSaid, @repeat);
END
```

<p>the C# code</p>

<pre class="lang-cs prettyprint-override"><code>using (var cmd = new OdbcCommand())
{
    cmd.Connection = conn;
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText =
        "SET NOCOUNT ON; " +
        "DECLARE @out varchar(max); " +
        "EXEC dbo.HodorSpeaks @repeat=?, @response=@out OUTPUT; " +
        "SELECT @out;";
    cmd.Parameters.Add("?", OdbcType.Int).Value = 10000;
    string resp = cmd.ExecuteScalar().ToString();
    Console.WriteLine("{0} characters were returned", resp.Length);

}
</code>```

tells me that

70000 characters were returned
```

ContentLicense: CC BY-SA 3.0

Body:
I'm using:

Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
  Dec 28 2012 20:23:12

  Copyright (c) Microsoft Corporation   Enterprise Edition (64-bit) on Windows NT 6.2  (Build 9200: ) (Hypervisor)

I have a stored procedure which has a varchar(MAX) output parameter.

I'm calling it via an OdbcCommand and I've created a VarChar output parameter and added it to the OdbcCommand Parameters list:

new OdbcParameter("@MaxField", OdbcType.VarChar)
    { Direction = ParameterDirection.Output, Size = -1 })

While debugging I can see that the Size field on the parameter is still -1 but when I run the query using OdbcCommand.ExecuteNonQuery() I get the following exception:

System.InvalidOperationException was unhandled

  HResult=-2146233079

  Message=String[2]: the Size property has an invalid size of 0.

  Source=System.Data

  StackTrace:

         at System.Data.Odbc.OdbcParameter.GetParameterSize(Object value, Int32 offset, Int32 ordinal)

         at System.Data.Odbc.OdbcParameter.PrepareForBind(OdbcCommand command, Int16 ordinal, Int32& parameterBufferSize)

         at System.Data.Odbc.OdbcParameterCollection.CalcParameterBufferSize(OdbcCommand
  command)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader, Object[] methodArguments,
  SQL_API odbcApiMethod)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader)

         at System.Data.Odbc.OdbcCommand.ExecuteNonQuery()

I tried using the OdbcCommandBuilder.DeriveParameters(odbcCommand); to examine the parameter information derived from the stored procedure and it said that the parameter had a Size of 2147483647 - however, if I try and use that value I get a different exception telling me

System.Data.Odbc.OdbcException was unhandled

  ErrorCode=-2146232009

  HResult=-2146232009

  Message=ERROR [42000] [Microsoft][ODBC SQLServer Driver][SQL Server]Invalid parameter 2 (''):  Data type 0x23 is
  a deprecated large object, or LOB, but is marked as output parameter.
  Deprecated types are not supported as output parameters.  Use current
  large object types instead.   Source=SQLSRV32.DLL   StackTrace:

         at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader, Object[] methodArguments,
  SQL_API odbcApiMethod)

         at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior
  behavior, String method, Boolean needReader)

         at System.Data.Odbc.OdbcCommand.ExecuteNonQuery()

How should I configure my OdbcCommand output parameter to receive this output from the stored procedure?

This is on an existing, in-production database so trying to change the datatype of the field is sadly the absolute last resort. The field that is being selected is varchar(max).

Edit: If the actual answer is "You just can't" then that would be acceptable - at least I would know for sure.

Body:
If you want to stick with System.Data.Odbc then the following workaround might suffice. For the stored procedure

CREATE PROCEDURE [dbo].[HodorSpeaks]
    @repeat int = 1,
    @response varchar(max) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @whatHeSaid varchar(max);
    SET @whatHeSaid = 'HODOR! ';
    SELECT @response = REPLICATE(@whatHeSaid, @repeat);
END

the C# code

using (var cmd = new OdbcCommand())
{
    cmd.Connection = conn;
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText =
        "SET NOCOUNT ON; " +
        "DECLARE @out varchar(max); " +
        "EXEC dbo.HodorSpeaks @repeat=?, @response=@out OUTPUT; " +
        "SELECT @out;";
    cmd.Parameters.Add("?", OdbcType.Int).Value = 10000;
    string resp = cmd.ExecuteScalar().ToString();
    Console.WriteLine("{0} characters were returned", resp.Length);

}

tells me that

70000 characters were returned


问:
Manipulation of antd calendar in react js
How can i highlight the specific dates in the antd calendar..? i can able to hide the dates using "Date.now()" and "current" but can't able to access those dates for customization.<img src="https://i.stack.imgur.com/07QQL.png" alt="enter image description here"> </p>

答:
You can control how to render each cell using dateFullCellRender event. Example

```<code>function onFullRender(date){
  const day = date.day();
  let style;
  if(day === 1) {
   style = { border: "1px solid #d9d9d9"};
  }
  else {
   style = { border: "1px solid red"};
  }
  return <div style={style}>{day}</div>;
}
</code>```

https://codepen.io/anon/pen/RjgWgL?editors=0010

Body:
You can control how to render each cell using dateFullCellRender event. Example

function onFullRender(date){
  const day = date.day();
  let style;
  if(day === 1) {
   style = { border: "1px solid #d9d9d9"};
  }
  else {
   style = { border: "1px solid red"};
  }
  return <div style={style}>{day}</div>;
}

https://codepen.io/anon/pen/RjgWgL?editors=0010


问:
read line by line with awk and parse variables
I have a script that read log files and parse the data to insert them to mysql table..

My script looks like

```<code>while read x;do
var=$(echo ${x}|cut -d+ -f1)
var2=$(echo ${x}|cut -d_ -f3)
...
echo "$var,$var2,.." >> mysql.infile
done<logfile
</code>```

The Problem is that log files are thousands of lines and taking hours....

I read that awk is better, I tried, but don't know the syntax to parse the variables...

EDIT:
inputs are structure firewall logs so they are pretty large files like

@timestamp $HOST reason="idle Timeout" source-address="x.x.x.x"
  source-port="19219" destination-address="x.x.x.x"
  destination-port="53" service-name="dns-udp" application="DNS"....

So I'm using a lot of grep for ~60 variables e.g

```<code>sourceaddress=$(echo ${x}|grep -P -o '.{0,0}
source-address=\".{0,50}'|cut -d\" -f2)
</code>```

if you think perl will be better I'm open to suggestions and maybe a hint how to script it...

答:
To answer your question, I assume the following rules of the game:

each line contains various variables

each variable can be found by a different delimiter.

This gives you the following awk script :

```<code>awk 'BEGIN{OFS=","}
     { FS="+"; $0=$0; var=$1;
       FS="_"; $0=$0; var2=$3;
               ...
       print var1,var2,... >> "mysql.infile"
     }' logfile
</code>```

It basically does the following :

set the output separator to ,

read line

set the field separator to +, re-parse the line ($0=$0) and determine the first variable

set the field separator to '_', re-parse the line ($0=$0) and determine the second variable

... continue for all variables

print the line to the output file.

ContentLicense: CC BY-SA 4.0

Body:
I have a script that read log files and parse the data to insert them to mysql table..

My script looks like

while read x;do
var=$(echo ${x}|cut -d+ -f1)
var2=$(echo ${x}|cut -d_ -f3)
...
echo "$var,$var2,.." >> mysql.infile
done<logfile

The Problem is that log files are thousands of lines and taking hours....

I read that awk is better, I tried, but don't know the syntax to parse the variables...

EDIT:
inputs are structure firewall logs so they are pretty large files like

@timestamp $HOST reason="idle Timeout" source-address="x.x.x.x"
  source-port="19219" destination-address="x.x.x.x"
  destination-port="53" service-name="dns-udp" application="DNS"....

So I'm using a lot of grep for ~60 variables e.g

sourceaddress=$(echo ${x}|grep -P -o '.{0,0}
source-address=\".{0,50}'|cut -d\" -f2)

if you think perl will be better I'm open to suggestions and maybe a hint how to script it...

Body:
To answer your question, I assume the following rules of the game:

each line contains various variables

each variable can be found by a different delimiter.

This gives you the following awk script :

awk 'BEGIN{OFS=","}
     { FS="+"; $0=$0; var=$1;
       FS="_"; $0=$0; var2=$3;
               ...
       print var1,var2,... >> "mysql.infile"
     }' logfile

It basically does the following :

set the output separator to ,

read line

set the field separator to +, re-parse the line ($0=$0) and determine the first variable

set the field separator to '_', re-parse the line ($0=$0) and determine the second variable

... continue for all variables

print the line to the output file.


问:
Name grid-template-rows in SASS
Just writing grid-template-columns: [first] 15% [second] 100fr  [third] 15% works if we do it in pure CSS but when I do it in SASS I get an error.
But if I check the SASS docs and search for "grid" the first hit is a line that explains that I should be able to use brackets… But there are no examples showing the exact syntax that should be used and I can't figure it out.

答:
Try that way:

grid-template-columns: unquote("[first] 15% [second] 100fr [third] 15%");

Title: Name grid-template-rows in SASS


问:
Angular Drag and Drop from table to table
I have two tables. Table A has more data than Table B. In the JSON data structure that I am using for table A - I am not showing all of the data in table A, as it's reserved for Table B. Basically what I want to do, is drag and drop a row from table A to Table B, but when the drop is complete, the data looks completely different from when I started dragging from A. Lets say I'm not displaying object.colorRed in Table A but the data is there. I then move that row to Table B and now I can view object.colorRed.

What really needs to happen is a row from Table A needs to be split into two. Dividing the data and placing it in two rows in Table B. I'm not sure how to go about this.

-- Angular 4

Thanks

答:
I do something similar with one of my Angular projects, and use the ng2-dnd library.  Unlike other drag-n-drop libraries, ng2-dnd doesn't manipulate the dom, and instead sends the object data to the dropped container.

Here is a link to their online documentation.  The premise is pretty simple, and you do something like this:

(on the table you want to drag)

```<code><tr *ngFor="let thing of things" dnd-draggable [dragEnabled]="true" [dragData]=
"myDragData">
</code>```

(on the table/div you want to drop)

```<code><tbody dnd-droppable (onDropSuccess)="handleDrop($event)">
</code>```

Body:
I do something similar with one of my Angular projects, and use the ng2-dnd library.  Unlike other drag-n-drop libraries, ng2-dnd doesn't manipulate the dom, and instead sends the object data to the dropped container.

Here is a link to their online documentation.  The premise is pretty simple, and you do something like this:

(on the table you want to drag)

<tr *ngFor="let thing of things" dnd-draggable [dragEnabled]="true" [dragData]=
"myDragData">

(on the table/div you want to drop)

<tbody dnd-droppable (onDropSuccess)="handleDrop($event)">


问:
How do I convert the items in a list from integers to '.' and ' '?
I have this code that works for the integers in my list

```<code>def draw_beautiful(n):
    ps = list(gen(n))
    max = len(' '.join(map(str,ps[-1])))
    for p in ps:
        print(' '.join(map(str,p)).center(max)+'\n')
</code>```

the list is generated like pascals triangle, but every odd is a 1 and every even is a 0.

```<code>def gen(n,r=[]):
    for x in range(n):
        l = len(r)
        r = [1 if i == 0 or i == l else (r[i=1]+r[i])%2 for i in range(l+1)]
        yield r
</code>```

as is, it prints a nice triangle made of ones and zeros, but I need the ones to be dots and the zeros to be spaces.

答:
Something like this to change the values in the list</p>

```<code>p = [1, 1, 1, 1, 0, 0, 0, 0]
o = []

for x in p:
    if x == 1:
        o.append('.')
    if x == 0:
        o.append(' ')
</code>```

Body:
I have this code that works for the integers in my list

def draw_beautiful(n):
    ps = list(gen(n))
    max = len(' '.join(map(str,ps[-1])))
    for p in ps:
        print(' '.join(map(str,p)).center(max)+'\n')

the list is generated like pascals triangle, but every odd is a 1 and every even is a 0.

def gen(n,r=[]):
    for x in range(n):
        l = len(r)
        r = [1 if i == 0 or i == l else (r[i=1]+r[i])%2 for i in range(l+1)]
        yield r

as is, it prints a nice triangle made of ones and zeros, but I need the ones to be dots and the zeros to be spaces.

Body:
Something like this to change the values in the list

p = [1, 1, 1, 1, 0, 0, 0, 0]
o = []

for x in p:
    if x == 1:
        o.append('.')
    if x == 0:
        o.append(' ')


问:
Is Multinomial logistic regression appropriate for this dataset?
I have the following dataset shown below. Any value between 500 & 900 were categorized as A, while values between 900 & ~1500 were mixed between A and B.  I want to find the probability of getting A, B, and C at any value of x where x is my independent variable and A,B,C are my dependent variables. It seems to be a good fit for multinomial logistic regression. I believe the number of observations for each dependent variable is sufficient. If multinomial log regression is appropriate, I wish to uses Python's scikit learn logistic regression module to obtain my probability of A, B, and C at any value of x but I am not sure how to approach this using that module.

答:
Personally, it looks like an all right candidate for logistic regression, but the fact that it looks 1-dimensional with overlapping may make it hard to separate along those parts. I’m mainly here to answer the second part of your question which can be generalized to pretty much any other classifier within scikit-learn.

I recommend looking at the scikit-learn section on SGDClassifier since it has a simple example right below the attribute list, but replace the SGDClassifier part with the LogisticRegression class instead.
http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html#sklearn.linear_model.SGDClassifier

Here’s also the documentation for LogisticRegression: http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression


问:
Attached property of type list but without an encolsed tag
I'm following this answer, but when I comment out the container

```<code>            <tly:MyDataGridHelper.HiddenCols>
                <!--  <tly:LabelCollection>  -->
                    <Label Name="SomeProp"/>
                    <Label Name="DisplayName"/>
                <!--</tly:LabelCollection>  -->
            </tly:MyDataGridHelper.HiddenCols>
</code>```

and I change only the name of the string passed to RegisterAttached

```<code>    public static readonly DependencyProperty HiddenColsProperty =
        DependencyProperty.RegisterAttached("HiddenColsInternal", typeof(LabelCollection), typeof(MyDataGridHelper), new PropertyMetadata
        {
            PropertyChangedCallback = (obj, e) =>
            {
                var grid = (DataGrid)obj;
                if (grid != null) {
                    var arr = ((LabelCollection)e.NewValue).Cast<Label>().ToArray();
                    hidden[grid.Name] = (arr ?? new Label[0]).Select(l => l.Name).ToArray();
               }
            }
        });
</code>```

but if I have to initialize the collection in the getter

```<code>    public static LabelCollection GetHiddenCols(DependencyObject obj)
    {
        var collection = (LabelCollection)obj.GetValue(HiddenColsProperty);
        if (collection == null) {
            collection = new LabelCollection();
            obj.SetValue(HiddenColsProperty, collection);
        }
        return collection;
    }
</code>```

then my values (my label names: "SomeProp" and "DisplayName" for example) are lost. What am I doing wrong? How am I supposed to get them?

At the moment my workaround is to keep the envelop <tly:LabelCollection> (and everything works in this case)

答:
If you want to avoid to create the LabelCollection in your XAML or in your getter, you need to use a generic ObservableCollection as the property type of the HiddenCols property.
Then with "some" reflection:

```<code>public static readonly DependencyProperty HiddenColsProperty =
    DependencyProperty.RegisterAttached("HiddenColsInternal", typeof(ObservableCollection<Label>), typeof(MyDataGridHelper), new PropertyMetadata
    {
        DefaultValue = GetObservableCollectionDefaultValueFactory(),
        PropertyChangedCallback = (obj, e) =>
        {
            var grid = (DataGrid)obj;
            if (grid != null)
            {
                var arr = ((LabelCollection)e.NewValue).Cast<Label>().ToArray();
                hidden[grid.Name] = (arr ?? new Label[0]).Select(l => l.Name).ToArray();
            }
        }

private static object GetObservableCollectionDefaultValueFactory()
{
    Type type = Type.GetType("MS.Internal.ObservableCollectionDefaultValueFactory`1, WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
    Type closedType = type.MakeGenericType(typeof(Label));
    ConstructorInfo constructorInfo = closedType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
    return constructorInfo.Invoke(null);
}
</code>```

I hope it helps.

Body:
I'm following this answer, but when I comment out the container

            <tly:MyDataGridHelper.HiddenCols>

            </tly:MyDataGridHelper.HiddenCols>

and I change only the name of the string passed to RegisterAttached

    public static readonly DependencyProperty HiddenColsProperty =
        DependencyProperty.RegisterAttached("HiddenColsInternal", typeof(LabelCollection), typeof(MyDataGridHelper), new PropertyMetadata
        {
            PropertyChangedCallback = (obj, e) =>
            {
                var grid = (DataGrid)obj;
                if (grid != null) {
                    var arr = ((LabelCollection)e.NewValue).Cast().ToArray();
                    hidden[grid.Name] = (arr ?? new Label[0]).Select(l => l.Name).ToArray();
               }
            }
        });

but if I have to initialize the collection in the getter

    public static LabelCollection GetHiddenCols(DependencyObject obj)
    {
        var collection = (LabelCollection)obj.GetValue(HiddenColsProperty);
        if (collection == null) {
            collection = new LabelCollection();
            obj.SetValue(HiddenColsProperty, collection);
        }
        return collection;
    }

then my values (my label names: "SomeProp" and "DisplayName" for example) are lost. What am I doing wrong? How am I supposed to get them?

At the moment my workaround is to keep the envelop <tly:LabelCollection> (and everything works in this case)

Body:
If you want to avoid to create the LabelCollection in your XAML or in your getter, you need to use a generic ObservableCollection as the property type of the HiddenCols property.
Then with "some" reflection:

public static readonly DependencyProperty HiddenColsProperty =
    DependencyProperty.RegisterAttached("HiddenColsInternal", typeof(ObservableCollection<Label>), typeof(MyDataGridHelper), new PropertyMetadata
    {
        DefaultValue = GetObservableCollectionDefaultValueFactory(),
        PropertyChangedCallback = (obj, e) =>
        {
            var grid = (DataGrid)obj;
            if (grid != null)
            {
                var arr = ((LabelCollection)e.NewValue).Cast<Label>().ToArray();
                hidden[grid.Name] = (arr ?? new Label[0]).Select(l => l.Name).ToArray();
            }
        }

private static object GetObservableCollectionDefaultValueFactory()
{
    Type type = Type.GetType("MS.Internal.ObservableCollectionDefaultValueFactory`1, WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
    Type closedType = type.MakeGenericType(typeof(Label));
    ConstructorInfo constructorInfo = closedType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
    return constructorInfo.Invoke(null);
}

I hope it helps.


问:
How to use Grails Spring Security Plugin to require logging in before access an action?
I know that I can use annotation or Request mapping to restrict access to an ACTION by some specific ROLES. But now I have a different circumstance.

My scenario is: every user of my site can create posts, and they can make their own post public, private, or only share to some other users. I implement sharing post by a database table PERMISSION, which specify if a user have the right to view a post or not.

The problem arises here is that when a customer access a post through a direct link, how can I determine he/she have the privilege to view it? There's 3 circumstances:

The post is public, so it can be viewed by anyone (include not-login
  user)

The post is private, so only the login-owner can view it

The post is sharing, it means only the login-user that is shared and the
  owner can view it.

I want to process like this:

If the requested post is public: ok.

If the requested post is private/sharing: I want to redirect
  the customer to the login page; after
  logging in, the user will be re-direct
  to the page he wants to see.

The problem here is that I can redirect the user to login controller/ auth action, but after that I don't know how to redirect it back. The link to every post is different by post_id, so I can't use SpringSecurityUtils.securityConfig.successHandler.defaultTargetUrl

Could anyone know a way to do this?

答: I think you could add your own filter that will be executed before the action is called and do the verification of the post permissions there. You can find more information about Grails Filters here.</p>

ContentLicense: CC BY-SA 2.5


问:
Letting touch events go to the view pager behind collapsing toolbar
I have a view pager nested inside a collapsing toolbar. I want to detect when that view pager is clicked. I am trying to add a simple onclick listener but it doesn't work. However I am able to swipe through the view pager. Below is the layout code :

```<code><android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/app_bar_height"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:toolbarId="@+id/toolbar">

        <android.support.v4.view.ViewPager
            android:id="@+id/pager_introduction"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            tools:listitem="@layout/pager_item"
            app:layout_collapseMode="parallax"
            android:clickable="true"/>

        <android.support.v7.widget.Toolbar
            android:id="@+id/detail_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"/>

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView
    android:id="@+id/item_detail_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"

        // Some code

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

<LinearLayout
    android:id="@+id/viewPagerCountDots"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    app:layout_anchor="@+id/item_detail_container"
    app:layout_anchorGravity="top|center"
    android:orientation="horizontal"
    android:gravity="center"/>
</code>```

答:
Toolbar consumes clicks, so you will have to subclass it. See my answer here for a way to do that.
Apart from toolbar, the other views in your layout may consume clicks in a similar way </p>

Body:
I have a view pager nested inside a collapsing toolbar. I want to detect when that view pager is clicked. I am trying to add a simple onclick listener but it doesn't work. However I am able to swipe through the view pager. Below is the layout code :

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="@dimen/app_bar_height"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:toolbarId="@+id/toolbar">

        <android.support.v4.view.ViewPager
            android:id="@+id/pager_introduction"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            tools:listitem="@layout/pager_item"
            app:layout_collapseMode="parallax"
            android:clickable="true"/>

        <android.support.v7.widget.Toolbar
            android:id="@+id/detail_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin"/>

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView
    android:id="@+id/item_detail_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"

        // Some code

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

<LinearLayout
    android:id="@+id/viewPagerCountDots"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    app:layout_anchor="@+id/item_detail_container"
    app:layout_anchorGravity="top|center"
    android:orientation="horizontal"
    android:gravity="center"/>


答:
In draw_beautiful, try replacing

```<code>ps = list(gen(n))
</code>```

by

```<code>ps = [[' .'[x] for x in row] for row in gen(n)]
</code>```

This will turn 0 to ' ' and 1 to '.'.

Title: How do I convert the items in a list from integers to '.' and ' '?

Body:
In draw_beautiful, try replacing

ps = list(gen(n))

by

ps = [[' .'[x] for x in row] for row in gen(n)]

This will turn 0 to ' ' and 1 to '.'.


问:
Slicing Pandas Dataframe based on a value present in a column which is a list of lists
I have a Pandas Dataframe with a million rows (ids) with one of the columns as a list of lists.
e.g.

df = pd.DataFrame({'id' : [1,2,3,4] ,'token_list' : [['a','b','c'],['c','d'],['a','e','f'],['c','f']]})

I want to create a dictionary of all the unique tokens - 'a', 'b', 'c', 'e', 'f' (which i already have as a separate list) as keys and all the ids that each key is associated with. For eg, {'a' : [1,3], 'b': [1], 'c': [1,  2,4]..} and so on.

My problem is there are 12000 such tokens, and I do not want to use loops to run through each row in the first frame. And is in does not seem to work.

答:
Use np.repeat with numpy.concatenate for flattening first and thengroupby with list and last to_dict:

```<code>a = np.repeat(df['id'], df['token_list'].str.len())
b = np.concatenate(df['token_list'].values)

d = a.groupby(b).apply(list).to_dict()
print (d)

{'c': [1, 2, 4], 'a': [1, 3], 'b': [1], 'd': [2], 'e': [3], 'f': [3, 4]}
</code>```

Detail:

```<code>print (a)
0    1
0    1
0    1
1    2
1    2
2    3
2    3
2    3
3    4
3    4
Name: id, dtype: int64

print (b)
['a' 'b' 'c' 'c' 'd' 'a' 'e' 'f' 'c' 'f']
</code>```

Body:
Use np.repeat with numpy.concatenate for flattening first and thengroupby with list and last to_dict:

a = np.repeat(df['id'], df['token_list'].str.len())
b = np.concatenate(df['token_list'].values)

d = a.groupby(b).apply(list).to_dict()
print (d)

{'c': [1, 2, 4], 'a': [1, 3], 'b': [1], 'd': [2], 'e': [3], 'f': [3, 4]}

Detail:

print (a)
0    1
0    1
0    1
1    2
1    2
2    3
2    3
2    3
3    4
3    4
Name: id, dtype: int64

print (b)
['a' 'b' 'c' 'c' 'd' 'a' 'e' 'f' 'c' 'f']


问:
Access to a network disk PHPExcel
I was looking for an easy way to read and treat a *.xls file, and I found PHPExcel. All worked perfectly until I tried to access to a file which was in another Network Disk.
I now use this to access to my *.xls file :

```<code>$objPHPExcel = PHPExcel_IOFactory::load('//NetworkDisk2/Stuff/.../SomeFile.xls');
</code>```

But, as I said, this ain't working. And I don't know why. When the file and the *.php pages were in the same disk, no problems, all worked just fine.

Could anyone please help me (may be I'm wrong with my path or I don't know) or at least redirect me to another way to do the treatment?

Can it be because of the firewall?

Thanks.

答:
Don't know why, don't know how, but I can't have access with my website to another network disk. I couldn't execute a script all morning same time because the hours of treatments change with the day (never the same twice) so I modify a macro which was use to treat the Excel file and have the good information, so when my coworkers'll execute the macro, a copy of the file created will be paste to the network disk I have access too.

So the answer is to my question is no, we can't have access to a network disk with PHPExcel.

Topic closed guys, you can go home, thanks for all of you.

Title: Access to a network disk PHPExcel

Body:
I was looking for an easy way to read and treat a *.xls file, and I found PHPExcel. All worked perfectly until I tried to access to a file which was in another Network Disk.
I now use this to access to my *.xls file :

$objPHPExcel = PHPExcel_IOFactory::load('//NetworkDisk2/Stuff/.../SomeFile.xls');

But, as I said, this ain't working. And I don't know why. When the file and the *.php pages were in the same disk, no problems, all worked just fine.

Could anyone please help me (may be I'm wrong with my path or I don't know) or at least redirect me to another way to do the treatment?

Can it be because of the firewall?

Thanks.


问:
How to check which user Phusion Passenger chooses to run node.js?
What is the best practice for using Phusion Passenger with a version of node installed my nvm?

In this tutorial on using Passenger to run a Meteor app, I read:

[Y]our Meteor application is run as ... the owner of the
  main.js file (when deploying a Meteor bundle), unless you configure it
  otherwise. Of course you still have to make sure that each of your
  applications is owned by another user.

Meteor 1.6 works with Node.js v8.8.1, so I have used nvm to install node. I created a special meteor user to run the nvm installation of node and nvm. Node was therefore installed at /home/meteor/.nvm/versions/node/v8.8.1/bin/node, and /home/meteor/.nvm/versions/node/v8.8.1/bin/ was added to the $PATH variable for my meteor user. As a result, calling node -v as the meteor user showed that v8.8.1 was installed and accessible.

I followed this tutorial to deploy my Meteor app to my server.

As the meteor user from within the bundle/programs/server directory, I ran npm install --production. I made meteor the owner of everthing inside bundle/.

I had expected that Passenger would launch node as the meteor user, and that everything would run smoothly. Instead, Passenger showed a useful alert page, apologising that "something went wrong".

To work around this, I created a symlink at /usr/bin/node to point at /home/meteor/.nvm/versions/node/v8.8.1/bin/node, and now Passenger was happy to launch the bundled app.

This suggests to me that Passenger was not running main.js as the meteor user. Or is there another reason why the meteor user was not able to see its own version of node?

The quote above suggests that it is possible to configure which user Passenger uses. How do I do that?

In a nutshell: what is the official Passenger method for working with a version of node installed by nvm?

答:
You'll want to set the version of node to the full path to the nvm node: https://www.phusionpassenger.com/library/config/standalone/reference/#--nodejs-nodejs

As for the user-switching, you can set the log-level to 7 (https://www.phusionpassenger.com/library/config/standalone/reference/#--log-level-log_level) in order to debug that and either go through the startup logs yourself or post them here.


问:
Why does C manage the heap, instead of the operating system?
In other words, why doesn't free() just return the memory to the operating system, and malloc simply request memory from the operating system?

This unpacks to three closely related questions:

Why does C need to manage its own heap? (Is it because the OS will only allow you to allocate and free contiguous memory of a minimum size?)

Assuming what I wrote in parentheses is true, why is it?

Can this problem affect the operating system itself, so that it's unable to allocate blocks of memory to any running processes?

答:
Why does C need to manage its own heap? (Is it because the OS will only allow you to allocate and free contiguous memory of a minimum size?)

Operating systems manage memory in pages. Allocating and freeing pages has a high overhead. Most allocations in C tend to be much smaller than a page size.


问:
Apache Transaction:write file transactionally - how to use resourceId
If anybody implemented transactional writing to file,please, assist me.

Related topic was discussed in earlier thread(transactional write).

Use case is following:

if writing to log file is failed,that appropriate DB transaction shoud be rolled back.

So the writinig to file should be performed in transactional way.

I've chosen Apache Commons Transaction lib.

And have issue,that doesn't let me go further,because haven't found appropriate documentation or examples.

I have created instance of FileResourceManager:

FileResourceManager frm = new
  FileResourceManager("c:\cur",
  "c:\cur", true, logger);

As I understand from this Apache Commons Transaction tutorial,i should implement following steps:

start transaction:
 frm.start();

get transaction Id for it:
 transactionId = frm.generatedUniqueTxId();

call method, that is needed, e.g. writeResource with transactionId and resourceId:
frm.writeResource(transactionId, resourceId);

And here is ambiguity:

a) how can I connect resourceId with real resource,that I should write transactioanally?

b) how do my file,that I will write transactionally will now about resourceId?

Thank you for advise.

答:
As far nobody answers, I try do that from my latest experience.

Useful documentataion:

example2(.ppt)

Simplified algorithm looks like(actually,depicted in example2):

1. initialize FileResourceManager

2. start FileResourceManager

3. get transaction Id from FileResourceManager instance

4. start transaction with transaction Id from step 3

5. write resource you need  - here is mentioned write it transactionally
,so looks like it's the major step!

6. commit or rollback transaction

Note: resourceId,about i asked in ,my question, is simply name of transactional file.
This naming doesn't depict very good this attribute.

Code, I used:

```<code>private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(FileAppender.class);
private static LoggerFacade loggerFacade = new Log4jLogger(logger);

private static String tempDir = (String) System.getProperties().get("java.io.tmpdir");

private FileResourceManager frm = new FileResourceManager(tempDir, tempDir, false, loggerFacade);
private static OutputStream outputStream;

public void writeOut(E event) throws IOException {
    Object txId = null;
    try {
        frm.start();
        txId = frm.generatedUniqueTxId();
        frm.startTransaction(txId);
        outputStream = frm.writeResource(txId, fileName, true);
        frm.commitTransaction(txId);

    }

    catch (Exception e) {
        throw new IOException("DB rollback");
    }
}
</code>```

Body:
As far nobody answers, I try do that from my latest experience.

Useful documentataion:

example2(.ppt)

Simplified algorithm looks like(actually,depicted in example2):

1. initialize FileResourceManager

2. start FileResourceManager

3. get transaction Id from FileResourceManager instance

4. start transaction with transaction Id from step 3

5. write resource you need  - here is mentioned write it transactionally
,so looks like it's the major step!

6. commit or rollback transaction

Note: resourceId,about i asked in ,my question, is simply name of transactional file.
This naming doesn't depict very good this attribute.

Code, I used:

private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(FileAppender.class);
private static LoggerFacade loggerFacade = new Log4jLogger(logger);

private static String tempDir = (String) System.getProperties().get("java.io.tmpdir");

private FileResourceManager frm = new FileResourceManager(tempDir, tempDir, false, loggerFacade);
private static OutputStream outputStream;

public void writeOut(E event) throws IOException {
    Object txId = null;
    try {
        frm.start();
        txId = frm.generatedUniqueTxId();
        frm.startTransaction(txId);
        outputStream = frm.writeResource(txId, fileName, true);
        frm.commitTransaction(txId);

    }

    catch (Exception e) {
        throw new IOException("DB rollback");
    }
}


问:
Add Legend and change Colour on grouped bar plot
I created a plot like this;

```<code>library("ggplot2")
ggplot(data = diamonds) +
      geom_bar(mapping = aes(x = color, y = ..prop.., group = 2)) +
      scale_y_continuous(labels=scales::percent) +
      facet_grid(~cut)
</code>```

Now I want to add a legend for the variable "color", also I want to change the colour of the bars. The graph is exactly how I want it to be, and if possible I don't want change the structure of the dataset, just add a legend and change colours.

I could not find example that fit for this "percentage"-style graphics.

答:
```<code>ggplot(data = diamonds, aes(x = color, y = ..prop.., group = cut)) +
  geom_bar(aes(fill = factor(..x.., labels = LETTERS[seq(from = 4, to = 10 )]))) +
  labs(fill = "color") +
  scale_y_continuous(labels = scales::percent) +
  facet_grid(~ cut)
</code>```

Body:
I created a plot like this;

library("ggplot2")
ggplot(data = diamonds) +
      geom_bar(mapping = aes(x = color, y = ..prop.., group = 2)) +
      scale_y_continuous(labels=scales::percent) +
      facet_grid(~cut)

Now I want to add a legend for the variable "color", also I want to change the colour of the bars. The graph is exactly how I want it to be, and if possible I don't want change the structure of the dataset, just add a legend and change colours.

I could not find example that fit for this "percentage"-style graphics.


问:
I need to print divs and appending array contents inside of them in Javascript. How do i do that?
I have a div like this

```<code>    <div id="news" class="col-sm-6 col-md-4 col-lg-4 pb-70">
  <div class="post-prev-img">
      <a href="blog-single-sidebar-right.html"><img src="images/blog/post-prev-1.jpg" alt="img"></a>
    </div>

    <div class="post-prev-title">
      <h3><a href="blog-single-sidebar-right.html">TIME FOR MINIMALISM</a></h3>
    </div>

    <div class="post-prev-info">
      JULE 10<span class="slash-divider">/</span><a href="http://themeforest.net/user/abcgomel/portfolio?ref=abcgomel">JOHN DOE</a>
    </div>

    <div class="post-prev-text">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae, nostrum, cumque culpa provident aliquam commodi assumenda laudantium magnam illo nostrum.
    </div>

    <div class="post-prev-more-cont clearfix">
      <div class="post-prev-more left">
        <a href="blog-single-sidebar-right.html" class="blog-more">READ MORE</a>
      </div>
      <div class="right" >
        <a href="blog-single-sidebar-right.html#comments" class="post-prev-count"><span aria-hidden="true" class="icon_comment_alt"></span><span class="icon-count">21</span></a>
        <a href="http://themeforest.net/user/abcgomel/portfolio?ref=abcgomel" class="post-prev-count"><span aria-hidden="true" class="icon_heart_alt"></span><span class="icon-count">53</span></a>
        <a href="#" class="post-prev-count dropdown-toggle" data-toggle="dropdown" aria-expanded="false" >
          <span aria-hidden="true" class="social_share"></span>
        </a>
        <ul class="social-menu dropdown-menu dropdown-menu-right" role="menu">
          <li><a href="#"><span aria-hidden="true" class="social_facebook"></span></a>
          </li>
          <li><a href="#"><span aria-hidden="true" class="social_twitter"></span></a></li>
          <li><a href="#"><span aria-hidden="true" class="social_dribbble"></span></a></li>
        </ul>
      </div>
    </div>
</div>
</code>```

I need this to be my "skeleton" for my other divs.
Now i want to make a for and append the content of my array inside of it and print every div inside an HTML page. How do i do that?

Thanks

答:
You do this as follows,

make a template in your html and hide using css #template, make a div to show all the items that we are going to dynamically make #list

```<code><div id="list">
</div>

<div id="template">
<div class="col-sm-6 col-md-4 col-lg-4 pb-70">
  <div class="post-prev-img">
      <a href="blog-single-sidebar-right.html"><img src="{{img}}"  alt="img"></a>
    </div>

    <div class="post-prev-title">
      <h3><a href="blog-single-sidebar-right.html">{{name}}</a></h3>
    </div>

    <div class="post-prev-info">
      JULE 10<span class="slash-divider">/</span><a href="http://themeforest.net/user/abcgomel/portfolio?ref=abcgomel">JOHN DOE</a>
    </div>

    <div class="post-prev-text">
     {{info}}
    </div>

    <div class="post-prev-more-cont clearfix">
      <div class="post-prev-more left">
        <a href="blog-single-sidebar-right.html" class="blog-more">READ MORE</a>
      </div>
      <div class="right" >
        <a href="blog-single-sidebar-right.html#comments" class="post-prev-count"><span aria-hidden="true" class="icon_comment_alt"></span><span class="icon-count">21</span></a>
        <a href="http://themeforest.net/user/abcgomel/portfolio?ref=abcgomel" class="post-prev-count"><span aria-hidden="true" class="icon_heart_alt"></span><span class="icon-count">53</span></a>
        <a href="#" class="post-prev-count dropdown-toggle" data-toggle="dropdown" aria-expanded="false" >
          <span aria-hidden="true" class="social_share"></span>
        </a>
        <ul class="social-menu dropdown-menu dropdown-menu-right" role="menu">
          <li><a href="#"><span aria-hidden="true" class="social_facebook"></span></a>
          </li>
          <li><a href="#"><span aria-hidden="true" class="social_twitter"></span></a></li>
          <li><a href="#"><span aria-hidden="true" class="social_dribbble"></span></a></li>
        </ul>
      </div>
    </div>
</div>
</div>
</code>```

CSS to hide the template

```<code>#template {
  display: none;
}
</code>```

Then make an array of all your needed object data circle it with a loop and replace the data holders.

Then insert the new html into the dom

```<code>var assets= [
{

name: "Time for JS",
img: "http://via.placeholder.com/350x150",
link: "",
info:"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae, nostrum, cumque culpa provident aliquam commodi assumenda laudantium magnam illo nostrum.",
},
{

name: "Time for CSS",
img: "http://via.placeholder.com/350x150",
link: "",
info:"ipsum dolor sit amet, consectetur adipisicing elit. Recusandae, nostrum, cumque culpa provident aliquam commodi assumenda laudantium magnam illo nostrum .consectetur adipisicing",
},
{

name: "Time for HTML",
img: "http://via.placeholder.com/350x150",
link: "",
info:"consectetur adipisicing consectetur adipisicing elit. Recusandae, nostrum, cumque culpa provident aliquam commodi assumenda laudantium magnam illo nostrum .consectetur adipisicing",
}

];

var html=""

assets.forEach(buildTemplate);
document.getElementById("list").innerHTML=html;

function buildTemplate(item) {
var template = document.getElementById("template").innerHTML;
template = template.replace("{{name}}", item.name);
template = template.replace("{{info}}", item.info);
template = template.replace("{{img}}", item.img);
html+=template;
}
</code>```

Here it is in action, it's that simple no jquery ultra fast hardcode JS.

https://jsfiddle.net/5yeh38LL/

There is a much easier way use a js template engine there are lots on google but this demonstrates how this is done and how effectively a template system will work.

Body:
I have a div like this

TIME FOR MINIMALISM

      JULE 10/JOHN DOE

      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae, nostrum, cumque culpa provident aliquam commodi assumenda laudantium magnam illo nostrum.

        READ MORE

        21
        53

I need this to be my "skeleton" for my other divs.
Now i want to make a for and append the content of my array inside of it and print every div inside an HTML page. How do i do that?

Thanks

Body:
You do this as follows,

make a template in your html and hide using css #template, make a div to show all the items that we are going to dynamically make #list

<div id="list">
</div>

<div id="template">
<div class="col-sm-6 col-md-4 col-lg-4 pb-70">
  <div class="post-prev-img">
      <a href="blog-single-sidebar-right.html"><img src="{{img}}"  alt="img"></a>
    </div>

    <div class="post-prev-title">
      <h3><a href="blog-single-sidebar-right.html">{{name}}</a></h3>
    </div>

    <div class="post-prev-info">
      JULE 10<span class="slash-divider">/</span><a href="http://themeforest.net/user/abcgomel/portfolio?ref=abcgomel">JOHN DOE</a>
    </div>

    <div class="post-prev-text">
     {{info}}
    </div>

    <div class="post-prev-more-cont clearfix">
      <div class="post-prev-more left">
        <a href="blog-single-sidebar-right.html" class="blog-more">READ MORE</a>
      </div>
      <div class="right" >
        <a href="blog-single-sidebar-right.html#comments" class="post-prev-count"><span aria-hidden="true" class="icon_comment_alt"></span><span class="icon-count">21</span></a>
        <a href="http://themeforest.net/user/abcgomel/portfolio?ref=abcgomel" class="post-prev-count"><span aria-hidden="true" class="icon_heart_alt"></span><span class="icon-count">53</span></a>
        <a href="#" class="post-prev-count dropdown-toggle" data-toggle="dropdown" aria-expanded="false" >
          <span aria-hidden="true" class="social_share"></span>
        </a>
        <ul class="social-menu dropdown-menu dropdown-menu-right" role="menu">
          <li><a href="#"><span aria-hidden="true" class="social_facebook"></span></a>
          </li>
          <li><a href="#"><span aria-hidden="true" class="social_twitter"></span></a></li>
          <li><a href="#"><span aria-hidden="true" class="social_dribbble"></span></a></li>
        </ul>
      </div>
    </div>
</div>
</div>

CSS to hide the template

#template {
  display: none;
}

Then make an array of all your needed object data circle it with a loop and replace the data holders.

Then insert the new html into the dom

var assets= [
{

name: "Time for JS",
img: "http://via.placeholder.com/350x150",
link: "",
info:"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae, nostrum, cumque culpa provident aliquam commodi assumenda laudantium magnam illo nostrum.",
},
{

name: "Time for CSS",
img: "http://via.placeholder.com/350x150",
link: "",
info:"ipsum dolor sit amet, consectetur adipisicing elit. Recusandae, nostrum, cumque culpa provident aliquam commodi assumenda laudantium magnam illo nostrum .consectetur adipisicing",
},
{

name: "Time for HTML",
img: "http://via.placeholder.com/350x150",
link: "",
info:"consectetur adipisicing consectetur adipisicing elit. Recusandae, nostrum, cumque culpa provident aliquam commodi assumenda laudantium magnam illo nostrum .consectetur adipisicing",
}

];

var html=""

assets.forEach(buildTemplate);
document.getElementById("list").innerHTML=html;

function buildTemplate(item) {
var template = document.getElementById("template").innerHTML;
template = template.replace("{{name}}", item.name);
template = template.replace("{{info}}", item.info);
template = template.replace("{{img}}", item.img);
html+=template;
}

Here it is in action, it's that simple no jquery ultra fast hardcode JS.

https://jsfiddle.net/5yeh38LL/

There is a much easier way use a js template engine there are lots on google but this demonstrates how this is done and how effectively a template system will work.


问:
Javascript String.replace(/\$/,str) works weirdly in jsp file
For simplicity, i have the following file named test.jsp:

```<code><script language="javascript">
    alert("a$b".replace(/\$/g,"k"));
</script>
</code>```

I put this file in my local server, then display it using firefox:  http://localhost:8080/myproj/test.jsp. It works okay, the result alert string is:

```<code> akb
</code>```

But when i put this file in a remote server and use the same firefox to display, it output is: a$bk which is incorrect for me.

Then i change the test.jsp content to:

```<code><script language="javascript">
    alert("a$b".replace(/\\$/g,"k"));
</script>
</code>```

Note here i add two slashes instead of one. In this case it works in the remote server but not in local one.

Then i rename the file from test.jsp to test.html, but the content is the same as my first case, i.e.:

```<code><script language="javascript">
    alert("a$b".replace(/\$/g,"k"));
</script>
</code>```

By using the same firefox, it works okay in both servers.

But my file needs to embed the javascript in jsp file. it is not allowed to use .html suffix for my file. What should I do to write a portable javascript in this scenario?

My local server uses tomcat-5.5.26; remote server uses tomcat-5.0.28. Firefox version is  3.0.4.

答:
Peter's got it, and Simon's suggestion is also a good idea.

Additionally, you don't need to use regex to do a simple static-string replace. The JS idiom would be:

```<code>alert('a$b'.split('$').join('k'));
</code>```

OwnerDisplayName: jscoot

Body:
For simplicity, i have the following file named test.jsp:

I put this file in my local server, then display it using firefox:  http://localhost:8080/myproj/test.jsp. It works okay, the result alert string is:

 akb

But when i put this file in a remote server and use the same firefox to display, it output is: a$bk which is incorrect for me.

Then i change the test.jsp content to:

Note here i add two slashes instead of one. In this case it works in the remote server but not in local one.

Then i rename the file from test.jsp to test.html, but the content is the same as my first case, i.e.:

By using the same firefox, it works okay in both servers.

But my file needs to embed the javascript in jsp file. it is not allowed to use .html suffix for my file. What should I do to write a portable javascript in this scenario?

My local server uses tomcat-5.5.26; remote server uses tomcat-5.0.28. Firefox version is  3.0.4.

LastEditorDisplayName: jscoot

Body:
Peter's got it, and Simon's suggestion is also a good idea.

Additionally, you don't need to use regex to do a simple static-string replace. The JS idiom would be:

alert('a$b'.split('$').join('k'));

OwnerDisplayName: bobince


问:
Tips and tricks to increase productivity / efficiency with Team Foundation Server
I have to use Team Foundation Server 2010 at my company and I'm not very happy with it.
There are so many features or just default behavior I'd expect from a CVS that TFS seems to lack (compared to svn, git or perforce, which I have experience with), so my question is: which tricks do you know, which hidden features are out there to make TFS easier to use / more convenient?

Perhaps I should elaborate a bit and list what I think could be better:

The default check-in action when associated with a task is "resolve", though in 99% of all check-ins, I only want to "associate" my commit with the task. There's only 1 commit (the last) that "resolves" the task, so why is that the default? Can I change that?

In the check-in dialog, when double-clicking a file, Notepad is launched and shows the contents of the file. Notepad. Seriously? What about the Visual Studio editor? Anyway, I'd like to see the differences to review the changes I've made, not the contents of the file. The diff tool is hidden in a submenu. This might seem trivial, but when I have to check 10+ files it's just annoying to always right-click, open submenu, click to diff.

The diff tool. Merging with it isn't really straightforward, also the conflict detection mechanism is somewhat lacking. The (Tortoise-)SVN / Git merge tools or that of Perforce are way better here.

Speed. Creating a new file, opening a file for the first time, comparing a file with a previous version etc takes forever (that is, 3-10+ seconds). Our TFS server is in-house and has absolutely no load - also why does Visual Studio have to contact the TFS server when I just create a new file (which I might not even check in)? Is there perhaps an option to turn that off?

Readonly files. All files are read-only when checked-in and become writeable when edited for the first time. This is really annyoing when the application crashes because of that. Windows Azure for example modifies a web.config file and fails whenever I check out because the file is read-only then.

These are just the most prominent things that I think are really annoying and unnecessary.
I didn't have the pleasure to branch and merge yet, but from what I've heard so far it won't be very enjoyable as well...

So again: If you know some tricks, settings, featuers that make working with TFS less inconvenient, please share them.

答:
TFS Power Tools might be a useful extension for you.

http://visualstudiogallery.msdn.microsoft.com/en-us/c255a1e4-04ba-4f68-8f4e-cd473d6b971f

For #2, are you using the "pending changes" window in Visual Studio to keep track of files that are modified?  Double clicking on a file there keeps you in the Visual Studio editor.

For #5, make sure Tools->Options->Environment->Documents "Allow Editing of read-only files; warn when attempt to save" is checked.

TFS is hella frustrating.  Good luck!


问:
Remove spacing between two paragraphs when displaying WYSIWIGS with ckeditor 4 in Angular
I'm using Angular 4 with ckeditor 4.x for WYSIWYG.

So when I'm displaying the code from database, the view is not the same in ckeditor, even if there's no style applying with paragraph.

I've tryed to reduce the line-height with CSS but no-way, it's the same result.

I removed the margin between lines but the same matters.

This is the code of the CSS where I've tryed to solve the problem:

p, p + p{
    color:rgb(51, 51, 51);
    display:block;
    font-family:sans-serif, Arial, Verdana, "Trebuchet MS";
    font-size:13px;
    line-height:normal;
    margin: 0;
    word-wrap:break-word;
    -webkit-margin-after:0px;
    -webkit-margin-before:0px;
    -webkit-margin-end:0px;
    -webkit-margin-start:0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>This one line</p>
<p>this is the second lines</p>
<p>And another one</p>
<p>And a last lines</p></code>```

This is the view:

Here's the computed code in dev tools

答:
try this : remove height:</p>

```<code>p{
    color:rgb(51, 51, 51);
    display:block;
    font-family:sans-serif, Arial, Verdana, "Trebuchet MS";
    font-size:13px;

    line-height:1.2;
    margin: 0;
    word-wrap:break-word;
margin-bottom:10px

}
</code>```

Body:
I'm using Angular 4 with ckeditor 4.x for WYSIWYG.

So when I'm displaying the code from database, the view is not the same in ckeditor, even if there's no style applying with paragraph.

I've tryed to reduce the line-height with CSS but no-way, it's the same result.

I removed the margin between lines but the same matters.

This is the code of the CSS where I've tryed to solve the problem:

p, p + p{
    color:rgb(51, 51, 51);
    display:block;
    font-family:sans-serif, Arial, Verdana, "Trebuchet MS";
    font-size:13px;
    line-height:normal;
    margin: 0;
    word-wrap:break-word;
    -webkit-margin-after:0px;
    -webkit-margin-before:0px;
    -webkit-margin-end:0px;
    -webkit-margin-start:0px;
}

This one line

this is the second lines

And another one

And a last lines

This is the view:

Here's the computed code in dev tools

Body:
try this : remove height:

p{
    color:rgb(51, 51, 51);
    display:block;
    font-family:sans-serif, Arial, Verdana, "Trebuchet MS";
    font-size:13px;

    line-height:1.2;
    margin: 0;
    word-wrap:break-word;
margin-bottom:10px

}


问:
SplashScreen with Vector stretched full screen
I did my splash screen with this tutorial and it works great:

https://www.bignerdranch.com/blog/splash-screens-the-right-way/

Basically I set up a splascreen through theme:

```<code><style name="ThemeSplash" parent="Theme.AppCompat.NoActionBar">
    <item name="android:windowBackground">@drawable/drawable_splashcreen</item>
</style>
</code>```

I wanted to put a vector image inside like this: (drawable_splashcreen)

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/color_background_splash_screen" />
    <item android:drawable="@drawable/vector_najdiflet_logo" />
</layer-list>
</code>```

The image will streched through the full screen. On API 23 it works like it should have. But on older devices it just streches. I tried width, height and even messed up with viewports but no success.

答:
I do not think this is possible to do with vectors, for devices < API 23, since it is not possible to set the attributes android:height and android:width on the drawable.

To implement my splash screen with a centered icon, I had to export the vector of my logo to .png's for each screen size, and embed a bitmap within the layer-list:

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:opacity="opaque">
    <item android:drawable="@drawable/splash_screen_background" />

    <item
        android:left="20dp"
        android:right="20dp">
        <bitmap
            android:gravity="center"
            android:scaleType="centerInside"
            android:src="@drawable/logo_rasterised" />
    </item>

</layer-list>
</code>```

Ideally I would not like to have any bitmap images at all in my resources, but at least the splash screen is the only place where I have had to use bitmaps.

Body:
I did my splash screen with this tutorial and it works great:

https://www.bignerdranch.com/blog/splash-screens-the-right-way/

Basically I set up a splascreen through theme:

I wanted to put a vector image inside like this: (drawable_splashcreen)

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/color_background_splash_screen" />
    <item android:drawable="@drawable/vector_najdiflet_logo" />
</layer-list>

The image will streched through the full screen. On API 23 it works like it should have. But on older devices it just streches. I tried width, height and even messed up with viewports but no success.

Body:
I do not think this is possible to do with vectors, for devices < API 23, since it is not possible to set the attributes android:height and android:width on the drawable.

To implement my splash screen with a centered icon, I had to export the vector of my logo to .png's for each screen size, and embed a bitmap within the layer-list:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:opacity="opaque">
    <item android:drawable="@drawable/splash_screen_background" />

    <item
        android:left="20dp"
        android:right="20dp">
        <bitmap
            android:gravity="center"
            android:scaleType="centerInside"
            android:src="@drawable/logo_rasterised" />
    </item>

</layer-list>

Ideally I would not like to have any bitmap images at all in my resources, but at least the splash screen is the only place where I have had to use bitmaps.


问:
Analysing a data frame that contains a time series using stargazer
I have a panel data set of 10 obs. and 3 variables.
(# of obs. 30 = 10 rows (= countries) * 2 columns  (= migration parameters) * 1col for the respective year.
My data frame consists of 3 annual data frames, so to say.

How can I apply stargazer on the whole period of time by taking into account that it is a panel data set (so max N=10)? That is, R should start over after every 11th row. I'd like to get the pretty table for descriptive statistics

The data set for the first three years:

```<code>structure(list(Population = c(21759420, 8696916, 1946351, 14689726,
8212264, 491723, 18907008, 4345386, 11133861, 657229, 22549547,
8944706, 1979882, 15141099, 8489031, 496963, 19432541, 4404230,
11502786, 673252, 23369131, 9199259, 2014866, 15605217, 8766930,
502384, 19970495, 4448525, 11887202, 689692), Distance..km. = c(7243L,
4290L, 9500L, 3789L, 6452L, 2211L, 4667L, 5036L, 4047L, 9140L,
7243L, 4290L, 9500L, 3789L, 6452L, 2211L, 4667L, 5036L, 4047L,
9140L, 7243L, 4290L, 9500L, 3789L, 6452L, 2211L, 4667L, 5036L,
4047L, 9140L), year = c(2008, 2008, 2008, 2008, 2008, 2008, 2008,
2008, 2008, 2008, 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009,
2009, 2009, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010,
2010)), .Names = c("Population", "Distance..km.", "year"), row.names = c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 50L, 51L, 52L, 53L, 54L,
55L, 56L, 57L, 58L, 59L, 99L, 100L, 101L, 102L, 103L, 104L, 105L,
106L, 107L, 108L), class = "data.frame")
</code>```

I still get descriptive statistics from N=30, but it should N=10, since I'm looking for the descriptive statistics of the whole period of three years and each yearly data frame needs to be considered isolated for that.
Hope I expressed the problem comprehensibly

Body:
I have a panel data set of 10 obs. and 3 variables.
(# of obs. 30 = 10 rows (= countries) * 2 columns  (= migration parameters) * 1col for the respective year.
My data frame consists of 3 annual data frames, so to say.

How can I apply stargazer on the whole period of time by taking into account that it is a panel data set (so max N=10)? That is, R should start over after every 11th row. I'd like to get the pretty table for descriptive statistics

The data set for the first three years:

structure(list(Population = c(21759420, 8696916, 1946351, 14689726,
8212264, 491723, 18907008, 4345386, 11133861, 657229, 22549547,
8944706, 1979882, 15141099, 8489031, 496963, 19432541, 4404230,
11502786, 673252, 23369131, 9199259, 2014866, 15605217, 8766930,
502384, 19970495, 4448525, 11887202, 689692), Distance..km. = c(7243L,
4290L, 9500L, 3789L, 6452L, 2211L, 4667L, 5036L, 4047L, 9140L,
7243L, 4290L, 9500L, 3789L, 6452L, 2211L, 4667L, 5036L, 4047L,
9140L, 7243L, 4290L, 9500L, 3789L, 6452L, 2211L, 4667L, 5036L,
4047L, 9140L), year = c(2008, 2008, 2008, 2008, 2008, 2008, 2008,
2008, 2008, 2008, 2009, 2009, 2009, 2009, 2009, 2009, 2009, 2009,
2009, 2009, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010,
2010)), .Names = c("Population", "Distance..km.", "year"), row.names = c(1L,
2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 50L, 51L, 52L, 53L, 54L,
55L, 56L, 57L, 58L, 59L, 99L, 100L, 101L, 102L, 103L, 104L, 105L,
106L, 107L, 108L), class = "data.frame")

I still get descriptive statistics from N=30, but it should N=10, since I'm looking for the descriptive statistics of the whole period of three years and each yearly data frame needs to be considered isolated for that.
Hope I expressed the problem comprehensibly

Body:
You can either use split + lapply from base R:

library(stargazer)

lapply(split(df, df$year), stargazer, type = "text")

or by:

by(df, df$year, stargazer, type = 'text')

Result:

===============================================================
Statistic     N      Mean        St. Dev.      Min      Max
---------------------------------------------------------------
Population    10 9,083,988.000 7,541,970.000 491,723 21,759,420
Distance..km. 10   5,637.500     2,385.941    2,211    9,500
year          10   2,008.000       0.000      2,008    2,008
---------------------------------------------------------------

===============================================================
Statistic     N      Mean        St. Dev.      Min      Max
---------------------------------------------------------------
Population    10 9,361,404.000 7,798,880.000 496,963 22,549,547
Distance..km. 10   5,637.500     2,385.941    2,211    9,500
year          10   2,009.000       0.000      2,009    2,009
---------------------------------------------------------------

===============================================================
Statistic     N      Mean        St. Dev.      Min      Max
---------------------------------------------------------------
Population    10 9,645,370.000 8,065,676.000 502,384 23,369,131
Distance..km. 10   5,637.500     2,385.941    2,211    9,500
year          10   2,010.000       0.000      2,010    2,010
---------------------------------------------------------------
df$year: 2008
[1] ""
[2] "==============================================================="
[3] "Statistic     N      Mean        St. Dev.      Min      Max    "
[4] "---------------------------------------------------------------"
[5] "Population    10 9,083,988.000 7,541,970.000 491,723 21,759,420"
[6] "Distance..km. 10   5,637.500     2,385.941    2,211    9,500   "
[7] "year          10   2,008.000       0.000      2,008    2,008   "
[8] "---------------------------------------------------------------"
--------------------------------------------------------------------------
df$year: 2009
[1] ""
[2] "==============================================================="
[3] "Statistic     N      Mean        St. Dev.      Min      Max    "
[4] "---------------------------------------------------------------"
[5] "Population    10 9,361,404.000 7,798,880.000 496,963 22,549,547"
[6] "Distance..km. 10   5,637.500     2,385.941    2,211    9,500   "
[7] "year          10   2,009.000       0.000      2,009    2,009   "
[8] "---------------------------------------------------------------"
--------------------------------------------------------------------------
df$year: 2010
[1] ""
[2] "==============================================================="
[3] "Statistic     N      Mean        St. Dev.      Min      Max    "
[4] "---------------------------------------------------------------"
[5] "Population    10 9,645,370.000 8,065,676.000 502,384 23,369,131"
[6] "Distance..km. 10   5,637.500     2,385.941    2,211    9,500   "
[7] "year          10   2,010.000       0.000      2,010    2,010   "
[8] "---------------------------------------------------------------"

The disadvantage of these two methods is that they print out the tables twice (once from stargazer output, another from lapply/by). To get around this, you can use walk form purrr to only call stargazer for it's side-effects:

library(dplyr)
library(purrr)

df %>%
  split(.$year) %>%
  walk(~ stargazer(., type = "text"))

Result:

===============================================================
Statistic     N      Mean        St. Dev.      Min      Max
---------------------------------------------------------------
Population    10 9,083,988.000 7,541,970.000 491,723 21,759,420
Distance..km. 10   5,637.500     2,385.941    2,211    9,500
year          10   2,008.000       0.000      2,008    2,008
---------------------------------------------------------------

===============================================================
Statistic     N      Mean        St. Dev.      Min      Max
---------------------------------------------------------------
Population    10 9,361,404.000 7,798,880.000 496,963 22,549,547
Distance..km. 10   5,637.500     2,385.941    2,211    9,500
year          10   2,009.000       0.000      2,009    2,009
---------------------------------------------------------------

===============================================================
Statistic     N      Mean        St. Dev.      Min      Max
---------------------------------------------------------------
Population    10 9,645,370.000 8,065,676.000 502,384 23,369,131
Distance..km. 10   5,637.500     2,385.941    2,211    9,500
year          10   2,010.000       0.000      2,010    2,010
---------------------------------------------------------------

Note:

All methods above works for latex output (type = "latex"). I only set type = "text" for demonstrative purposes.


问:
Perl - "Complex" Data Structure
I'm trying to get a workable data structure that I can pull the element values from in a sensible fashion. Just having great difficulty working with the data once its in the structure. This is how the struct is built:

```<code>sub hopCompare
{

    my %count;
    my %master;
    my $index = 0;

    foreach my $objPath (@latest)    #get Path object out of master array
    {
            my @path = @{$objPath->_getHopList()}; #dereferencing
            my $iter = 0;
            foreach my $hop (@path)
            {

                    ++$count{$hop}->{FREQ};
                    $count{$hop}->{INDEX} = $index;
                    $count{$hop}->{NODE} = $hop;

                    $index++;

            }
            $index = 0;
    }
    foreach my $element( keys %count )
    {
            if (defined($count{$element}->{NODE}))
            {
                    my $curr = $count{$element}->{INDEX};
                    my $freq = $count{$element}->{FREQ};
                    if (($freq > 1) || ($count{$element}->{INDEX} =~ /[0-1]/))
                    {
                            push @{ $master{$curr} }, {$count{$element}->{NODE}, {FREQ => $count{$element}->{FREQ}}};
                    }
                    print "$element = $count{$element}\n";
                    print "$element Index = $count{$element}->{INDEX}\n";
            }
    }
    print "\n Master contains: \n" . Dumper (%master);
    if (%master){return %master;} else {die "NO FINAL HOPS MATCHED";}
</code>```

}

Producing this structure:

%Master contains:

```<code>$VAR1 = '4';
$VAR2 = [
      {
        '1.1.1.2' => {
                              'FREQ' => 2
                            }
      }
    ];
$VAR3 = '1';
$VAR4 = [
      {
        '1.1.1.9' => {
                              'FREQ' => 5
                            }
      },
      {
        '1.1.1.8' => {
                              'FREQ' => 1
                            }
      }
    ];

    {truncated}
</code>```

Although ideally the structure should look like this but I had even less joy trying to pull data out at sub identifyNode:

```<code>$VAR1 = {
      '1' => [
               {
                 '1.1.1.9' => {
                                       'FREQ' => 5
                                     }
               },
               {
                 '1.1.5.8' => {
                                       'FREQ' => 1
                                     }
               }
             ],
</code>```

Then to get back at the data in another method I'm using:

```<code> sub identifyNode
 {
    my %hops = %{$_[0]};
    my $i = 0;

    foreach my $h ( keys %hops )                   #The HOP-INDEX is the key
    {
            print "\n\$h looks like \n" . Dumper ($hops{$h});
            my %host = %{ $hops{$h}[0] };           #Push the first HASH in INDEX to the %host HASH
            foreach my $hip (keys %host)
            {
                            my $corelink = `corelinks $hip`;

                            my ($node) = $corelink =~ /([a-z0-9-]+),[a-z0-9-\/]+,$hip/s;
                            print "\n\t\t\tHostname is $node\n";
            }
            $i++;
    }

}
</code>```

This then generates:

```<code>$h looks like
$VAR1 = [
      {
        '1.1.1.2' => {
                              'FREQ' => 2
                            }
      }
    ];

                    Hostname is blabla-bla-a1

$h looks like
$VAR1 = [
      {
        '1.1.1.9' => {
                              'FREQ' => 5
                            }
      },
      {
        '1.1.1.8' => {
                              'FREQ' => 1
                            }
      }
    ];

                    Hostname is somew-some-a1
</code>```

So for each hash in $h only the topmost host gets evaluated and hostname returned. This is because it is told to do so by the [0] in line:

```<code>my %host = %{ $hops{$h}[0] };
</code>```

I've played around with different data structures and de-referencing the structure a multitude of ways and this is the only halfway house I've found...

(The IPs have been obfuscated so are not consistent in my examples)

答:
Thanks for your advice it got me halfway there. It works now (in still somewhat a convoluted fashion!) :

```<code>sub identifyNode
{
    my %hops = %{$_[0]};
    my $i = 0;
    my @fin_nodes;
    my $hindex;

    foreach my $h ( keys %hops )                   #The HOP-INDEX is the key
    {
            $hindex = $h;

            foreach my $e (@{$hops{$h}})       #first part of solution credit Zdim
            {
                    my @host = %{ $e };      #second part of solution
                    my $hip = $host[0];
                    my $corelink = `corelinks $hip`;
                    my ($node) = $corelink =~ /([a-z0-9-]+),[a-z0-9-\/]+,$hip/s;
                    print "\n\t\t\tHostname is $node\n";

                    push (@fin_nodes, [$node, $hindex, $e->{$hip}->{FREQ}]);
            }
            $i++;
    }
    return (\@fin_nodes);
}
</code>```

Am I brave enough to add  the data as a hash to @fin_nodes.. hmm

Title: Perl - "Complex" Data Structure

Body:
I'm trying to get a workable data structure that I can pull the element values from in a sensible fashion. Just having great difficulty working with the data once its in the structure. This is how the struct is built:

sub hopCompare
{

    my %count;
    my %master;
    my $index = 0;

    foreach my $objPath (@latest)    #get Path object out of master array
    {
            my @path = @{$objPath->_getHopList()}; #dereferencing
            my $iter = 0;
            foreach my $hop (@path)
            {

                    ++$count{$hop}->{FREQ};
                    $count{$hop}->{INDEX} = $index;
                    $count{$hop}->{NODE} = $hop;

                    $index++;

            }
            $index = 0;
    }
    foreach my $element( keys %count )
    {
            if (defined($count{$element}->{NODE}))
            {
                    my $curr = $count{$element}->{INDEX};
                    my $freq = $count{$element}->{FREQ};
                    if (($freq > 1) || ($count{$element}->{INDEX} =~ /[0-1]/))
                    {
                            push @{ $master{$curr} }, {$count{$element}->{NODE}, {FREQ => $count{$element}->{FREQ}}};
                    }
                    print "$element = $count{$element}\n";
                    print "$element Index = $count{$element}->{INDEX}\n";
            }
    }
    print "\n Master contains: \n" . Dumper (%master);
    if (%master){return %master;} else {die "NO FINAL HOPS MATCHED";}

}

Producing this structure:

%Master contains:

$VAR1 = '4';
$VAR2 = [
      {
        '1.1.1.2' => {
                              'FREQ' => 2
                            }
      }
    ];
$VAR3 = '1';
$VAR4 = [
      {
        '1.1.1.9' => {
                              'FREQ' => 5
                            }
      },
      {
        '1.1.1.8' => {
                              'FREQ' => 1
                            }
      }
    ];

    {truncated}

Although ideally the structure should look like this but I had even less joy trying to pull data out at sub identifyNode:

$VAR1 = {
      '1' => [
               {
                 '1.1.1.9' => {
                                       'FREQ' => 5
                                     }
               },
               {
                 '1.1.5.8' => {
                                       'FREQ' => 1
                                     }
               }
             ],

Then to get back at the data in another method I'm using:

 sub identifyNode
 {
    my %hops = %{$_[0]};
    my $i = 0;

    foreach my $h ( keys %hops )                   #The HOP-INDEX is the key
    {
            print "\n\$h looks like \n" . Dumper ($hops{$h});
            my %host = %{ $hops{$h}[0] };           #Push the first HASH in INDEX to the %host HASH
            foreach my $hip (keys %host)
            {
                            my $corelink = `corelinks $hip`;

                            my ($node) = $corelink =~ /([a-z0-9-]+),[a-z0-9-\/]+,$hip/s;
                            print "\n\t\t\tHostname is $node\n";
            }
            $i++;
    }

}

This then generates:

$h looks like
$VAR1 = [
      {
        '1.1.1.2' => {
                              'FREQ' => 2
                            }
      }
    ];

                    Hostname is blabla-bla-a1

$h looks like
$VAR1 = [
      {
        '1.1.1.9' => {
                              'FREQ' => 5
                            }
      },
      {
        '1.1.1.8' => {
                              'FREQ' => 1
                            }
      }
    ];

                    Hostname is somew-some-a1

So for each hash in $h only the topmost host gets evaluated and hostname returned. This is because it is told to do so by the [0] in line:

my %host = %{ $hops{$h}[0] };

I've played around with different data structures and de-referencing the structure a multitude of ways and this is the only halfway house I've found...

(The IPs have been obfuscated so are not consistent in my examples)

Body:
Thanks for your advice it got me halfway there. It works now (in still somewhat a convoluted fashion!) :

sub identifyNode
{
    my %hops = %{$_[0]};
    my $i = 0;
    my @fin_nodes;
    my $hindex;

    foreach my $h ( keys %hops )                   #The HOP-INDEX is the key
    {
            $hindex = $h;

            foreach my $e (@{$hops{$h}})       #first part of solution credit Zdim
            {
                    my @host = %{ $e };      #second part of solution
                    my $hip = $host[0];
                    my $corelink = `corelinks $hip`;
                    my ($node) = $corelink =~ /([a-z0-9-]+),[a-z0-9-\/]+,$hip/s;
                    print "\n\t\t\tHostname is $node\n";

                    push (@fin_nodes, [$node, $hindex, $e->{$hip}->{FREQ}]);
            }
            $i++;
    }
    return (\@fin_nodes);
}

Am I brave enough to add  the data as a hash to @fin_nodes.. hmm


问:
I need help in this query mongodb with nodejs
The query is returning double value, can you help me with this?
the problem stay in unwind ?

is a consultation that consolidates the debits and credits of the db...

with aggregate...

Code:

My DAO ( MongoDB + NodeJS ) :

```<code>ListarDebitosDAO.prototype.consolidado = function(usuario,res,req){

this._connection.open(function(err, mongoclient){
    mongoclient.collection("contas", function(err, collection){
        collection.aggregate([{
            $match : {usuario : usuario}},{
            $unwind: "$debitos"
        },{
            $unwind: "$creditos"
        }, {
            $group: {
                "_id" : usuario,
                "debitos": {
                    $sum: "$debitos.debito"
                },
                "creditos" : {
                    $sum: "$creditos.credito"
                }

            }
        }])
        .toArray(function(error, results){

            console.log(results)

            var debitoConsolidado = results[0].debitos;
            var creditoConsolidado = results[0].creditos;

            res.render('dashboard', {debitoConsolidado,nome_usuario: req.session.nome,creditoConsolidado})

        });
        // mongoclient.close();
    });
});
</code>```

}

My collection ( exemple ) :

```<code>{
"_id" : ObjectId("5a09113b42e54fb49230fa37"),
"usuario" : "sara",
"creditos" : [
    {
        "nome_do_credito" : "credito inicial",
        "credito" : 0
    },
    {
        "nome_do_credito" : "salario",
        "credito" : 1200
    }
],
"debitos" : [
    {
        "nome_do_debito" : "debito inicial",
        "debito" : 0
    },
    {
        "nome_do_debito" : "Vivo",
        "debito" : 200
    },
    {
        "nome_do_debito" : "Vivo",
        "debito" : 600
    }
]
</code>```

}

My atual output:

```<code>{ "_id" : null, "debitos" : 1600, "creditos" : 3600 }
</code>```

I need :

```<code>{ "_id" : null, "debitos" : 800, "creditos" : 1200 }
enter code here
</code>```

答:
The problem is that you are trying to use both unwind simultaneously, it is creating duplicate entries hence the sum of credit and debit is coming wrong.

I guess what you can do is do sequential unwind and grouping for both credit and debit

```<code>collection.aggregate([{
        $match : {usuario : usuario}},{
        $unwind: "$debitos"
    }, {
        $group: {
            "_id" : usuario,
            "debitos": {
                $sum: "$debitos.debito"
            },
            "creditos" : "$creditos"
        }
    },
    {
        $unwind: "$creditos"
    },
    {
        $group: {
            "_id" : usuario,
            "creditos" : {
                $sum: "$creditos.credito"
            }
            "debitos": "$debitos"
        }
    }
])
</code>```

I am sure either this or some variant should work for you.

Body:
The query is returning double value, can you help me with this?
the problem stay in unwind ?

is a consultation that consolidates the debits and credits of the db...

with aggregate...

Code:

My DAO ( MongoDB + NodeJS ) :

ListarDebitosDAO.prototype.consolidado = function(usuario,res,req){

this._connection.open(function(err, mongoclient){
    mongoclient.collection("contas", function(err, collection){
        collection.aggregate([{
            $match : {usuario : usuario}},{
            $unwind: "$debitos"
        },{
            $unwind: "$creditos"
        }, {
            $group: {
                "_id" : usuario,
                "debitos": {
                    $sum: "$debitos.debito"
                },
                "creditos" : {
                    $sum: "$creditos.credito"
                }

            }
        }])
        .toArray(function(error, results){

            console.log(results)

            var debitoConsolidado = results[0].debitos;
            var creditoConsolidado = results[0].creditos;

            res.render('dashboard', {debitoConsolidado,nome_usuario: req.session.nome,creditoConsolidado})

        });
        // mongoclient.close();
    });
});

}

My collection ( exemple ) :

{
"_id" : ObjectId("5a09113b42e54fb49230fa37"),
"usuario" : "sara",
"creditos" : [
    {
        "nome_do_credito" : "credito inicial",
        "credito" : 0
    },
    {
        "nome_do_credito" : "salario",
        "credito" : 1200
    }
],
"debitos" : [
    {
        "nome_do_debito" : "debito inicial",
        "debito" : 0
    },
    {
        "nome_do_debito" : "Vivo",
        "debito" : 200
    },
    {
        "nome_do_debito" : "Vivo",
        "debito" : 600
    }
]

}

My atual output:

{ "_id" : null, "debitos" : 1600, "creditos" : 3600 }

I need :

{ "_id" : null, "debitos" : 800, "creditos" : 1200 }
enter code here

Body:
The problem is that you are trying to use both unwind simultaneously, it is creating duplicate entries hence the sum of credit and debit is coming wrong.

I guess what you can do is do sequential unwind and grouping for both credit and debit

collection.aggregate([{
        $match : {usuario : usuario}},{
        $unwind: "$debitos"
    }, {
        $group: {
            "_id" : usuario,
            "debitos": {
                $sum: "$debitos.debito"
            },
            "creditos" : "$creditos"
        }
    },
    {
        $unwind: "$creditos"
    },
    {
        $group: {
            "_id" : usuario,
            "creditos" : {
                $sum: "$creditos.credito"
            }
            "debitos": "$debitos"
        }
    }
])

I am sure either this or some variant should work for you.


问:
Mass rename of files in linux
I have files i linux that are in format :

```<code>img_1234563_@_12345.XX-FFF-123334-35370-122232-12342.gif
img_1234fdfd3_fd12345.XX-FdFF-1233343-35370-145232-d12342.gif
</code>```

that I would like to rename to the something like

```<code>img_1234fdfd3_fd12345.jpg
</code>```

So cut all after first dot and put jpg at the end

I have tried to use for and  rename with pattern like img_/\S[//^.]+
but without much success :(

答:
You can use the String split to divide your file names. When having a variable s you can retain the shortest match of a pattern from the beginning using ${MYVAR/%pattern}.

I do not know if you are processing all the entries on a directory so I suppose you have a variable files containing all the file names you need to rename. Otherwise you just need to change the loop bound to fit your list of files.

```<code>#!/bin/bash

files="img_1234563_@_12345.XX-FFF-123334-35370-122232-12342.gif img_1234fdfd3_fd12345.XX-FdFF-1233343-35370-145232-d12342.gif"

for file in $files; do
        name="${file/%.*}"
        fullName="${name}.jpg"
        mv "$file" "$fullName"
done
</code>```

Title: Mass rename of files in linux

Body:
I have files i linux that are in format :

img_1234563_@_12345.XX-FFF-123334-35370-122232-12342.gif
img_1234fdfd3_fd12345.XX-FdFF-1233343-35370-145232-d12342.gif

that I would like to rename to the something like

img_1234fdfd3_fd12345.jpg

So cut all after first dot and put jpg at the end

I have tried to use for and  rename with pattern like img_/\S[//^.]+
but without much success :(

Body:
You can use the String split to divide your file names. When having a variable s you can retain the shortest match of a pattern from the beginning using ${MYVAR/%pattern}.

I do not know if you are processing all the entries on a directory so I suppose you have a variable files containing all the file names you need to rename. Otherwise you just need to change the loop bound to fit your list of files.

#!/bin/bash

files="img_1234563_@_12345.XX-FFF-123334-35370-122232-12342.gif img_1234fdfd3_fd12345.XX-FdFF-1233343-35370-145232-d12342.gif"

for file in $files; do
        name="${file/%.*}"
        fullName="${name}.jpg"
        mv "$file" "$fullName"
done


问:
How do i change the src of an html5 video via javascript without either crashing chrome or leak memory?
I'm working on an application running on Chrome only.

I need to be able to switch the source from a playing video.

I've used javascript (&jQuery) to change the src attribute :

```<code>$fullscreenVideo.get(0).src = '/video/' + name + '.mp4'; // crash here
$fullscreenVideo.get(0).load();
$fullscreenVideo.get(0).play();
</code>```

It works a few times but my chrome (tried beta & dev channels) ends up crashing (page become unresponsive).

If i try to create a new element prepending last codeblock with :

```<code>$fullscreenVideo.remove();
$fullscreenVideo = $('<video id="video-fullscreen" width="800" height="600" loop="loop"></video>').appendTo("#page-fullscreen > div.fullscreen");
</code>```

Every video switch increase RAM by 20Mo without ever getting back down.

Is there a way to trace/prevent chrome crash en src update ?
Is there a way to force free memory ?

答:
I've been the same problem.

I read in some foruns that is a chrome's bug with memory leaks (some people say that just happens in chrome 8 and in chrome 6 works fine, but i didn't test it).

I also read that using a sleep helps. I tried and it is true, if i put a sleep before change url atribute and call load() the crashes number decreases. But still continues to crash after many changes.

Then, i tried to use setTimeout (unlike sleep, it doesn't bloq CPU, leaving it free to chrome's work).

And it is working now.
Try to see if my code helps.

```<code>var videoChangingPending = false;
function changeMovieSource(url, title){

        var $video = $('#video');
        try {
            document.getElementById('video').src = url;
        }
        catch (e) {
            alert(e);
        }

        $video.attr('autoplay', 'true');
        $video.data('currentTitle', title);

        document.getElementById('video').load();

        videoChangingPending = false;
}

function startPlayer(url, title) {

        if(videoChangingPending == true)
            return;

        document.getElementById('video').pause();

        videoChangingPending = true;
        var changeMovieCallback = function(){ changeMovieSource(url, title);}
        var t = setTimeout(changeMovieCallback, 800);

}
</code>```

Body:
I'm working on an application running on Chrome only.

I need to be able to switch the source from a playing video.

I've used javascript (&jQuery) to change the src attribute :

$fullscreenVideo.get(0).src = '/video/' + name + '.mp4'; // crash here
$fullscreenVideo.get(0).load();
$fullscreenVideo.get(0).play();

It works a few times but my chrome (tried beta & dev channels) ends up crashing (page become unresponsive).

If i try to create a new element prepending last codeblock with :

$fullscreenVideo.remove();
$fullscreenVideo = $('<video id="video-fullscreen" width="800" height="600" loop="loop"></video>').appendTo("#page-fullscreen > div.fullscreen");

Every video switch increase RAM by 20Mo without ever getting back down.

Is there a way to trace/prevent chrome crash en src update ?
Is there a way to force free memory ?

Body:
I've been the same problem.

I read in some foruns that is a chrome's bug with memory leaks (some people say that just happens in chrome 8 and in chrome 6 works fine, but i didn't test it).

I also read that using a sleep helps. I tried and it is true, if i put a sleep before change url atribute and call load() the crashes number decreases. But still continues to crash after many changes.

Then, i tried to use setTimeout (unlike sleep, it doesn't bloq CPU, leaving it free to chrome's work).

And it is working now.
Try to see if my code helps.

var videoChangingPending = false;
function changeMovieSource(url, title){

        var $video = $('#video');
        try {
            document.getElementById('video').src = url;
        }
        catch (e) {
            alert(e);
        }

        $video.attr('autoplay', 'true');
        $video.data('currentTitle', title);

        document.getElementById('video').load();

        videoChangingPending = false;
}

function startPlayer(url, title) {

        if(videoChangingPending == true)
            return;

        document.getElementById('video').pause();

        videoChangingPending = true;
        var changeMovieCallback = function(){ changeMovieSource(url, title);}
        var t = setTimeout(changeMovieCallback, 800);

}